<commit_before>import { slice, concat, without, reduce, remove, assign, find, forEach, union, filter, uniqBy } from 'lodash';

import {  ERROR, AUTH_CONNECTED, Socket, SearchMessage, DiscoverIndicesMessage, DiscoverFieldsMessage } from '../utils/index';

import {  INDICES_RECEIVE, INDICES_REQUEST } from '../modules/indices/index';
import {  FIELDS_RECEIVE, FIELDS_REQUEST } from '../modules/fields/index';
import {  NODES_DELETE, NODES_HIGHLIGHT, NODE_UPDATE, NODE_SELECT, NODES_SELECT, NODES_DESELECT, SELECTION_CLEAR } from '../modules/graph/index';
import {  SEARCH_DELETE, ITEMS_RECEIVE, ITEMS_REQUEST } from '../modules/search/index';
import {  TABLE_COLUMN_ADD, TABLE_COLUMN_REMOVE, INDEX_ADD, INDEX_DELETE, FIELD_ADD, FIELD_DELETE, DATE_FIELD_ADD, DATE_FIELD_DELETE, NORMALIZATION_ADD, NORMALIZATION_DELETE, INITIAL_STATE_RECEIVE } from '../modules/data/index';

import { normalize, fieldLocator } from '../helpers/index';

export const defaultState = {
    isFetching: false,
    noMoreHits: false,
    didInvalidate: false,
    connected: false,
    total: 0,
    node: [],
    highlight_nodes: [],
    columns: [],
    fields: [],
    date_fields: [],
    normalizations: [],
    indexes: [],
    items: [],
    searches: [],
    nodes: [], // all nodes
    links: [], // relations between nodes
    errors: null
};

export default function entries(state = defaultState, action) {
    switch (action.type) {
        case SELECTION_CLEAR:
            return Object.assign({}, state, {
                node: [],
            });
        case INDEX_DELETE:
            const index = find(state.indexes, (i) => {
                return (i.id == action.index);
            });

            var indexes = without(state.indexes, index);
            return Object.assign({}, state, {
                indexes: indexes,
            });
        case NODES_DELETE:
            var items = concat(state.items);
            var node = concat(state.node);
            var nodes = concat(state.nodes);
            var links = concat(state.links);

            // remove from selection as well
            remove(node, (p) => {
                return find(action.nodes, (o) => {
                    return o.id == p.id;
                });
            });

            remove(nodes, (p) => {
                return find(action.nodes, (o) => {
                    return o.id == p.id;
                });
            });

            remove(links, (p) => {
                return find(action.nodes, (o) => {
                    return p.source == o.id || p.target == o.id;
                });
            });

            return Object.assign({}, state, {
                items: items,
                node: node,
                nodes: nodes,
                links: links
            });
        case SEARCH_DELETE:
            var searches = without(state.searches, action.search);

            var items = concat(state.items);
            remove(items, (p) => {
                return (p.q === action.search.q);
            });

            // todo(nl5887): remove related nodes and links

            return Object.assign({}, state, {
                searches: searches,
                items: items
            });
        case TABLE_COLUMN_ADD:
            return Object.assign({}, state, {
                columns: concat(state.columns, action.field),
            });
        case TABLE_COLUMN_REMOVE:
            return Object.assign({}, state, {
                columns: without(state.columns, action.field)
            });
        case FIELD_ADD:
            return Object.assign({}, state, {
                fields: concat(state.fields, action.field)
            });
        case FIELD_DELETE:
            return Object.assign({}, state, {
                fields: without(state.fields, action.field)
            });
        case NORMALIZATION_ADD:
            let normalization = action.normalization;
            normalization.re = new RegExp(normalization.regex, "i");
            return Object.assign({}, state, {
                normalizations: concat(state.normalizations, normalization)
            });
        case NORMALIZATION_DELETE:
            return Object.assign({}, state, {
                normalizations: without(state.normalizations, action.normalization)
            });
        case DATE_FIELD_ADD:
            return Object.assign({}, state, {
                date_fields: concat(state.date_fields, action.field)
            });
        case DATE_FIELD_DELETE:
            return Object.assign({}, state, {
                date_fields: without(state.date_fields, action.field)
            });
        case NODES_HIGHLIGHT:
            return Object.assign({}, state, {
                highlight_nodes: action.highlight_nodes
            });
        case NODES_SELECT:
            return Object.assign({}, state, {
                node: concat(action.nodes)
            });
        case NODES_DESELECT:
            return Object.assign({}, state, {
                node: filter(state.node, (o) => {
                    return !find(action.nodes, o);
                })
            });
        case NODE_UPDATE:
            let nodes = concat(state.nodes, []);

            let n = find(nodes, {id: action.node_id });
            if (n) {
                n = assign(n, action.params);
            }

            return Object.assign({}, state, {
                nodes: nodes
            });
        case NODE_SELECT:
            return Object.assign({}, state, {
                node: concat(state.node, action.node)
            });
        case ERROR:
            console.debug(action);
            return Object.assign({}, state, {
                errors: action.errors
            });
        case AUTH_CONNECTED:
            return Object.assign({}, state, {
                isFetching: false,
                didInvalidate: false,
                ...action
            });
        case ITEMS_REQUEST: {
            // if we searched before, just retrieve extra results for query
            const search = find(state.searches, (o) => o.q == action.query) || { items: [] };

            let from = search.items.length || 0;

            let message = {query: action.query, index: action.index, from: from, size: action.size, color: action.color, host: action.index};
            Socket.ws.postMessage(message);

            return Object.assign({}, state, {
                isFetching: true,
                didInvalidate: false
            });
        }
        case ITEMS_RECEIVE: {
            var searches = concat(state.searches, []);

            // should we update existing search, or add new, do we still need items?
            let search = find(state.searches, (o) => o.q == action.items.query);
            if (search) {
                search.items = concat(search.items, action.items.results);
            } else {
                searches.push({
                    q: action.items.query,
                    color: action.items.color,
                    items: action.items.results
                });
            }

            // let search = find(searches, (o) => return o.q == action.items.query) {

            const { normalizations } = state;

            // todo(nl5887): should we start a webworker here, the webworker can have its own permanent cache?

            // update nodes and links
            var items = action.items.results;

            var nodes = concat(state.nodes, []);
            var links = concat(state.links, []);

            let nodeCache = {};
            for (let node of nodes) {
                nodeCache[node.id] = node;
            }

            let linkCache = {};
            for (let link of links) {
                linkCache[link.source + link.target] = link;
            }

            const fields = state.fields;
            forEach(items, (d, i) => {
                forEach(fields, (source) => {
                    let sourceValue = fieldLocator(d.fields, source.path);
                    if (sourceValue === null) {
                        return;
                    }

                    if (!Array.isArray(sourceValue)) {
                        sourceValue = [sourceValue];
                    }

                    for (let sv of sourceValue) {
                        switch (typeof sv) {
                        case "boolean":
                            sv = (sv?"true":"false");
                        }

                        const normalizedSourceValue = normalize(normalizations, sv);

                        let n = nodeCache[normalizedSourceValue];
                        if (n) {
                            if (n.items.indexOf(d.id) == -1){
                                n.items.push(d.id);
                            }

                            if (n.fields.indexOf(source.path) == -1){
                                n.fields.push(source.path);
                            }

                            n.queries.push(action.items.query);
                        } else {
                            let n = {
                                id: normalizedSourceValue,
                                queries: [action.items.query],
                                items: [d.id],
                                name: normalizedSourceValue,
                                description: '',
                                icon: source.icon,
                                fields: [source.path],
                            };

                            nodeCache[n.id] = n;
                            nodes.push(n);
                        }

                        forEach(fields, (target) => {
                            let targetValue = fieldLocator(d.fields, target.path);
                            if (targetValue === null) {
                                return;
                            }

                            if (!Array.isArray(targetValue)) {
                                targetValue = [targetValue];
                            }

                            // todo(nl5887): issue with normalizing is if we want to use it as name as well.
                            // for example we don't want to have the first name only as name.
                            //
                            // we need to keep track of the fields the value is in as well.
                            for (let tv of targetValue) {
                                switch (typeof tv) {
                                case "boolean":
                                    tv = (tv?"true":"false");
                                }

                                const normalizedTargetValue = normalize(normalizations, tv);

                                let n = nodeCache[normalizedTargetValue];
                                if (n) {
                                    if (n.items.indexOf(d.id) == -1){
                                        n.items.push(d.id);
                                    }

                                    if (n.fields.indexOf(target.path) == -1){
                                        n.fields.push(target.path);
                                    }

                                    // should add counter instead of thousands same query being added
                                    n.queries.push(action.items.query);
                                } else {
                                    let n = {
                                        id: normalizedTargetValue,
                                        queries: [action.items.query],
                                        items: [d.id],
                                        name: normalizedTargetValue,
                                        description: '',
                                        icon: [target.icon],
                                        fields: [target.path],
                                    };

                                    nodeCache[n.id] = n;
                                    nodes.push(n);
                                }

                                if (sourceValue.length > 1) {
                                    // we don't want all individual arrays to be linked together
                                    // those individual arrays being linked are (I assume) irrelevant
                                    // otherwise this needs to be a configuration option
                                    continue;
                                }

                                if (linkCache[normalizedSourceValue + normalizedTargetValue]) {
                                    // link already exists
                                    continue;
                                }

                                const link = {
                                    source: normalizedSourceValue,
                                    target: normalizedTargetValue,
                                    color: '#ccc'
                                };

                                links.push(link);
                                linkCache[link.source + link.target] = link;
                            }
                        });
                    }
                });
            });

            return Object.assign({}, state, {
                errors: null,
                nodes: nodes,
                links: links,
                items: concat(state.items, items),
                searches: searches,
                isFetching: false,
                didInvalidate: false
            });
        }
        case INDICES_REQUEST:
            Socket.ws.postMessage(
                {
                    host: [action.payload.server]
                },
                INDICES_REQUEST
            );

            return Object.assign({}, state, {
                isFetching: true,
                didInvalidate: false
            });

        case INDICES_RECEIVE:
            const indices = uniqBy(union(state.indexes, action.payload.indices.map((index) => {
                return {
		    id: `${action.payload.server}${index}`,
		    server: action.payload.server,
		    name: index
		};
            })), (i) => i.id);

            return Object.assign({}, state, {
                indexes: indices,
                isFetching: false
            });

        case FIELDS_REQUEST:
            return Object.assign({}, state, {
                isFetching: true
            });

        case FIELDS_RECEIVE:
            return Object.assign({}, state, {
                isFetching: false
            });

        case INITIAL_STATE_RECEIVE:
            return Object.assign({}, state, {});

        default:
            return state;
    }
}
<commit_msg>fixed indentation<commit_after>import { slice, concat, without, reduce, remove, assign, find, forEach, union, filter, uniqBy } from 'lodash';

import {  ERROR, AUTH_CONNECTED, Socket, SearchMessage, DiscoverIndicesMessage, DiscoverFieldsMessage } from '../utils/index';

import {  INDICES_RECEIVE, INDICES_REQUEST } from '../modules/indices/index';
import {  FIELDS_RECEIVE, FIELDS_REQUEST } from '../modules/fields/index';
import {  NODES_DELETE, NODES_HIGHLIGHT, NODE_UPDATE, NODE_SELECT, NODES_SELECT, NODES_DESELECT, SELECTION_CLEAR } from '../modules/graph/index';
import {  SEARCH_DELETE, ITEMS_RECEIVE, ITEMS_REQUEST } from '../modules/search/index';
import {  TABLE_COLUMN_ADD, TABLE_COLUMN_REMOVE, INDEX_ADD, INDEX_DELETE, FIELD_ADD, FIELD_DELETE, DATE_FIELD_ADD, DATE_FIELD_DELETE, NORMALIZATION_ADD, NORMALIZATION_DELETE, INITIAL_STATE_RECEIVE } from '../modules/data/index';

import { normalize, fieldLocator } from '../helpers/index';

export const defaultState = {
    isFetching: false,
    noMoreHits: false,
    didInvalidate: false,
    connected: false,
    total: 0,
    node: [],
    highlight_nodes: [],
    columns: [],
    fields: [],
    date_fields: [],
    normalizations: [],
    indexes: [],
    items: [],
    searches: [],
    nodes: [], // all nodes
    links: [], // relations between nodes
    errors: null
};

export default function entries(state = defaultState, action) {
    switch (action.type) {
        case SELECTION_CLEAR:
            return Object.assign({}, state, {
                node: [],
            });
        case INDEX_DELETE:
            const index = find(state.indexes, (i) => {
                return (i.id == action.index);
            });

            var indexes = without(state.indexes, index);
            return Object.assign({}, state, {
                indexes: indexes,
            });
        case NODES_DELETE:
            var items = concat(state.items);
            var node = concat(state.node);
            var nodes = concat(state.nodes);
            var links = concat(state.links);

            // remove from selection as well
            remove(node, (p) => {
                return find(action.nodes, (o) => {
                    return o.id == p.id;
                });
            });

            remove(nodes, (p) => {
                return find(action.nodes, (o) => {
                    return o.id == p.id;
                });
            });

            remove(links, (p) => {
                return find(action.nodes, (o) => {
                    return p.source == o.id || p.target == o.id;
                });
            });

            return Object.assign({}, state, {
                items: items,
                node: node,
                nodes: nodes,
                links: links
            });
        case SEARCH_DELETE:
            var searches = without(state.searches, action.search);

            var items = concat(state.items);
            remove(items, (p) => {
                return (p.q === action.search.q);
            });

            // todo(nl5887): remove related nodes and links

            return Object.assign({}, state, {
                searches: searches,
                items: items
            });
        case TABLE_COLUMN_ADD:
            return Object.assign({}, state, {
                columns: concat(state.columns, action.field),
            });
        case TABLE_COLUMN_REMOVE:
            return Object.assign({}, state, {
                columns: without(state.columns, action.field)
            });
        case FIELD_ADD:
            return Object.assign({}, state, {
                fields: concat(state.fields, action.field)
            });
        case FIELD_DELETE:
            return Object.assign({}, state, {
                fields: without(state.fields, action.field)
            });
        case NORMALIZATION_ADD:
            let normalization = action.normalization;
            normalization.re = new RegExp(normalization.regex, "i");
            return Object.assign({}, state, {
                normalizations: concat(state.normalizations, normalization)
            });
        case NORMALIZATION_DELETE:
            return Object.assign({}, state, {
                normalizations: without(state.normalizations, action.normalization)
            });
        case DATE_FIELD_ADD:
            return Object.assign({}, state, {
                date_fields: concat(state.date_fields, action.field)
            });
        case DATE_FIELD_DELETE:
            return Object.assign({}, state, {
                date_fields: without(state.date_fields, action.field)
            });
        case NODES_HIGHLIGHT:
            return Object.assign({}, state, {
                highlight_nodes: action.highlight_nodes
            });
        case NODES_SELECT:
            return Object.assign({}, state, {
                node: concat(action.nodes)
            });
        case NODES_DESELECT:
            return Object.assign({}, state, {
                node: filter(state.node, (o) => {
                    return !find(action.nodes, o);
                })
            });
        case NODE_UPDATE:
            let nodes = concat(state.nodes, []);

            let n = find(nodes, {id: action.node_id });
            if (n) {
                n = assign(n, action.params);
            }

            return Object.assign({}, state, {
                nodes: nodes
            });
        case NODE_SELECT:
            return Object.assign({}, state, {
                node: concat(state.node, action.node)
            });
        case ERROR:
            console.debug(action);
            return Object.assign({}, state, {
                errors: action.errors
            });
        case AUTH_CONNECTED:
            return Object.assign({}, state, {
                isFetching: false,
                didInvalidate: false,
                ...action
            });
        case ITEMS_REQUEST: {
            // if we searched before, just retrieve extra results for query
            const search = find(state.searches, (o) => o.q == action.query) || { items: [] };

            let from = search.items.length || 0;

            let message = {query: action.query, index: action.index, from: from, size: action.size, color: action.color, host: action.index};
            Socket.ws.postMessage(message);

            return Object.assign({}, state, {
                isFetching: true,
                didInvalidate: false
            });
        }
        case ITEMS_RECEIVE: {
            var searches = concat(state.searches, []);

            // should we update existing search, or add new, do we still need items?
            let search = find(state.searches, (o) => o.q == action.items.query);
            if (search) {
                search.items = concat(search.items, action.items.results);
            } else {
                searches.push({
                    q: action.items.query,
                    color: action.items.color,
                    items: action.items.results
                });
            }

            // let search = find(searches, (o) => return o.q == action.items.query) {

            const { normalizations } = state;

            // todo(nl5887): should we start a webworker here, the webworker can have its own permanent cache?

            // update nodes and links
            var items = action.items.results;

            var nodes = concat(state.nodes, []);
            var links = concat(state.links, []);

            let nodeCache = {};
            for (let node of nodes) {
                nodeCache[node.id] = node;
            }

            let linkCache = {};
            for (let link of links) {
                linkCache[link.source + link.target] = link;
            }

            const fields = state.fields;
            forEach(items, (d, i) => {
                forEach(fields, (source) => {
                    let sourceValue = fieldLocator(d.fields, source.path);
                    if (sourceValue === null) {
                        return;
                    }

                    if (!Array.isArray(sourceValue)) {
                        sourceValue = [sourceValue];
                    }

                    for (let sv of sourceValue) {
                        switch (typeof sv) {
                        case "boolean":
                            sv = (sv?"true":"false");
                        }

                        const normalizedSourceValue = normalize(normalizations, sv);

                        let n = nodeCache[normalizedSourceValue];
                        if (n) {
                            if (n.items.indexOf(d.id) == -1){
                                n.items.push(d.id);
                            }

                            if (n.fields.indexOf(source.path) == -1){
                                n.fields.push(source.path);
                            }

                            n.queries.push(action.items.query);
                        } else {
                            let n = {
                                id: normalizedSourceValue,
                                queries: [action.items.query],
                                items: [d.id],
                                name: normalizedSourceValue,
                                description: '',
                                icon: source.icon,
                                fields: [source.path],
                            };

                            nodeCache[n.id] = n;
                            nodes.push(n);
                        }

                        forEach(fields, (target) => {
                            let targetValue = fieldLocator(d.fields, target.path);
                            if (targetValue === null) {
                                return;
                            }

                            if (!Array.isArray(targetValue)) {
                                targetValue = [targetValue];
                            }

                            // todo(nl5887): issue with normalizing is if we want to use it as name as well.
                            // for example we don't want to have the first name only as name.
                            //
                            // we need to keep track of the fields the value is in as well.
                            for (let tv of targetValue) {
                                switch (typeof tv) {
                                case "boolean":
                                    tv = (tv?"true":"false");
                                }

                                const normalizedTargetValue = normalize(normalizations, tv);

                                let n = nodeCache[normalizedTargetValue];
                                if (n) {
                                    if (n.items.indexOf(d.id) == -1){
                                        n.items.push(d.id);
                                    }

                                    if (n.fields.indexOf(target.path) == -1){
                                        n.fields.push(target.path);
                                    }

                                    // should add counter instead of thousands same query being added
                                    n.queries.push(action.items.query);
                                } else {
                                    let n = {
                                        id: normalizedTargetValue,
                                        queries: [action.items.query],
                                        items: [d.id],
                                        name: normalizedTargetValue,
                                        description: '',
                                        icon: [target.icon],
                                        fields: [target.path],
                                    };

                                    nodeCache[n.id] = n;
                                    nodes.push(n);
                                }

                                if (sourceValue.length > 1) {
                                    // we don't want all individual arrays to be linked together
                                    // those individual arrays being linked are (I assume) irrelevant
                                    // otherwise this needs to be a configuration option
                                    continue;
                                }

                                if (linkCache[normalizedSourceValue + normalizedTargetValue]) {
                                    // link already exists
                                    continue;
                                }

                                const link = {
                                    source: normalizedSourceValue,
                                    target: normalizedTargetValue,
                                    color: '#ccc'
                                };

                                links.push(link);
                                linkCache[link.source + link.target] = link;
                            }
                        });
                    }
                });
            });

            return Object.assign({}, state, {
                errors: null,
                nodes: nodes,
                links: links,
                items: concat(state.items, items),
                searches: searches,
                isFetching: false,
                didInvalidate: false
            });
        }
        case INDICES_REQUEST:
            Socket.ws.postMessage(
                {
                    host: [action.payload.server]
                },
                INDICES_REQUEST
            );

            return Object.assign({}, state, {
                isFetching: true,
                didInvalidate: false
            });

        case INDICES_RECEIVE:
            const indices = uniqBy(union(state.indexes, action.payload.indices.map((index) => {
                return {
                    id: `${action.payload.server}${index}`,
                    server: action.payload.server,
                    name: index
                };
            })), (i) => i.id);

            return Object.assign({}, state, {
                indexes: indices,
                isFetching: false
            });

        case FIELDS_REQUEST:
            return Object.assign({}, state, {
                isFetching: true
            });

        case FIELDS_RECEIVE:
            return Object.assign({}, state, {
                isFetching: false
            });

        case INITIAL_STATE_RECEIVE:
            return Object.assign({}, state, {});

        default:
            return state;
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2012, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

function parseLines(lines, callback) {
    var re = /^\<stdin\>:([0-9]+):([0-9]+):\s+(.*)/;
    $.each(lines.split('\n'), function(_, line) {
        line = line.trim();
        if (line != "") {
            var match = line.match(re);
            if (match) {
                callback(parseInt(match[1]), match[3]);
            } else {
                callback(null, line);
            }
        }
    });
}
function clearBackground(cm) {
    for (var i = 0; i < cm.lineCount(); ++i) {
        cm.setLineClass(i, null, null);
    }
}

function Compiler(domRoot, origFilters, windowLocalPrefix, onChangeCallback) {
    var compilersByExe = {};
    var pendingTimeout = null;
    var asmCodeMirror = null;
    var cppEditor = null;
    var lastRequest = null;
    var currentAssembly = null;
    var filters = origFilters;
    var ignoreChanges = true; // Horrible hack to avoid onChange doing anything on first starting, ie before we've set anything up.

    cppEditor = CodeMirror.fromTextArea(domRoot.find(".editor textarea")[0], {
        lineNumbers: true,
              matchBrackets: true,
              useCPP: true,
              mode: "text/x-c++src",
              onChange: onChange
    });
    asmCodeMirror = CodeMirror.fromTextArea(domRoot.find(".asm textarea")[0], {
        lineNumbers: true,
                  matchBrackets: true,
                  mode: "text/x-asm",
                  readOnly: true
    });

    function getSetting(name) {
        return window.localStorage[windowLocalPrefix + "." + name];
    }
    function setSetting(name, value) {
        window.localStorage[windowLocalPrefix + "." + name] = value;
    }

    if (getSetting('code')) cppEditor.setValue(getSetting('code'));
    domRoot.find('.compiler').change(onCompilerChange);
    domRoot.find('.compiler_options').change(onChange).keyup(onChange);
    ignoreChanges = false;

    if (getSetting('compilerOptions')) {
        domRoot.find('.compiler_options').val(getSetting('compilerOptions'));
    }

    function onCompileResponse(data) {
        var stdout = data.stdout || "";
        var stderr = data.stderr || "";
        if (data.code == 0) {
            stdout += "\nCompiled ok";
        } else {
            stderr += "\nCompilation failed";
        }
        $('.result .output :visible').remove();
        var highlightLine = (data.asm == null);
        for (var i = 0; i < cppEditor.lineCount(); ++i) cppEditor.setMarker(i);
        parseLines(stderr + stdout, function(lineNum, msg) {
            var elem = $('.result .output .template').clone().appendTo('.result .output').removeClass('template');
            if (lineNum) {
                cppEditor.setMarker(lineNum - 1, null, "error");
                elem.html($('').append(lineNum + " : " + msg)).click(function() {
                    cppEditor.setSelection({line: lineNum - 1, ch: 0}, {line: lineNum, ch: 0});
                    return false;
                });
            } else {
                elem.text(msg);
            }
        });
        currentAssembly = data.asm || "[no output]";
        updateAsm();
    }

    function numberUsedLines(asm) {
        var sourceLines = {};
        $.each(asm, function(_, x) { if (x.source) sourceLines[x.source - 1] = true; });
        var ordinal = 0;
        $.each(sourceLines, function(k, _) { sourceLines[k] = ordinal++; });
        var asmLines = {};
        $.each(asm, function(index, x) { if (x.source) asmLines[index] = sourceLines[x.source - 1]; });
        return { source: sourceLines, asm: asmLines };
    }

    var lastUpdatedAsm = null;
    function updateAsm(forceUpdate) {
        if (!currentAssembly) return;
        var hashedUpdate = JSON.stringify({
            asm: currentAssembly,
            filter: filters
        });
        if (!forceUpdate && lastUpdatedAsm == hashedUpdate) { return; }
        lastUpdatedAsm = hashedUpdate;

        var asm = processAsm(currentAssembly, filters);
        var asmText = $.map(asm, function(x){ return x.text; }).join("\n");
        var numberedLines = numberUsedLines(asm);
        asmCodeMirror.setValue(asmText);

        clearBackground(cppEditor);
        clearBackground(asmCodeMirror);
        if (filters.colouriseAsm) {
            $.each(numberedLines.source, function(line, ordinal) {
                cppEditor.setLineClass(parseInt(line), null, "rainbow-" + (ordinal & 7));
            });
            $.each(numberedLines.asm, function(line, ordinal) {
                asmCodeMirror.setLineClass(parseInt(line), null, "rainbow-" + (ordinal & 7));
            });
        }
    }

    function onChange() {
        if (ignoreChanges) return;  // Ugly hack during startup.
        if (pendingTimeout) clearTimeout(pendingTimeout);
        pendingTimeout = setTimeout(function() {
            var data = {
                source: cppEditor.getValue(),
                compiler: $('.compiler').val(),
                options: $('.compiler_options').val(),
                filters: filters
            };
            setSetting('compiler', data.compiler);
            setSetting('compilerOptions', data.options);
            if (data == lastRequest) return;
            lastRequest = data;
            $.ajax({
                type: 'POST',
                url: '/compile',
                dataType: 'json',
                data: data,
                success: onCompileResponse});
        }, 750);
        setSetting('code', cppEditor.getValue());
        updateAsm();
        onChangeCallback();
    }

    function setSource(code) {
        cppEditor.setValue(code);
    }

    function getSource() {
        return cppEditor.getValue();
    }

    function serialiseState() {
        var state = {
            source: cppEditor.getValue(),
            compiler: domRoot.find('.compiler').val(),
            options: domRoot.find('.compiler_options').val(),
        };
        return state;
    }

    function deserialiseState(state) {
        cppEditor.setValue(state.source);
        domRoot.find('.compiler').val(state.compiler);
        domRoot.find('.compiler_options').val(state.options);
        // Somewhat hackily persist compiler into local storage else when the ajax response comes in
        // with the list of compilers it can splat over the deserialized version.
        // The whole serialize/hash/localStorage code is a mess! TODO(mg): fix
        setSetting('compiler', state.compiler);
        updateAsm(true);  // Force the update to reset colours after calling cppEditor.setValue
        return true;
    }

    function onCompilerChange() {
        onChange();
        var compiler = compilersByExe[$('.compiler').val()];
        domRoot.find('.filter button.btn[value="intel"]').toggleClass("disabled", !compiler.supportedOpts["-masm"]);
    }

    function setCompilers(compilers) {
        domRoot.find('.compiler option').remove();
        compilersByExe = {};
        $.each(compilers, function(index, arg) {
            compilersByExe[arg.exe] = arg;
            domRoot.find('.compiler').append($('<option value="' + arg.exe + '">' + arg.version + '</option>'));
        });
        if (getSetting('compiler')) {
            domRoot.find('.compiler').val(getSetting('compiler'));
        }
        onCompilerChange();
    }

    function setFilters(f) {
        filters = f;
        updateAsm();
    }

    return {
        serialiseState: serialiseState,
        deserialiseState: deserialiseState,
        setCompilers: setCompilers,
        getSource: getSource,
        setSource: setSource,
        setFilters: setFilters
    };
}
<commit_msg>Prevent redundant sending of filter changes that happen only on the client<commit_after>// Copyright (c) 2012, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

function parseLines(lines, callback) {
    var re = /^\<stdin\>:([0-9]+):([0-9]+):\s+(.*)/;
    $.each(lines.split('\n'), function(_, line) {
        line = line.trim();
        if (line != "") {
            var match = line.match(re);
            if (match) {
                callback(parseInt(match[1]), match[3]);
            } else {
                callback(null, line);
            }
        }
    });
}
function clearBackground(cm) {
    for (var i = 0; i < cm.lineCount(); ++i) {
        cm.setLineClass(i, null, null);
    }
}

function Compiler(domRoot, origFilters, windowLocalPrefix, onChangeCallback) {
    var compilersByExe = {};
    var pendingTimeout = null;
    var asmCodeMirror = null;
    var cppEditor = null;
    var lastRequest = null;
    var currentAssembly = null;
    var filters = origFilters;
    var ignoreChanges = true; // Horrible hack to avoid onChange doing anything on first starting, ie before we've set anything up.

    cppEditor = CodeMirror.fromTextArea(domRoot.find(".editor textarea")[0], {
        lineNumbers: true,
              matchBrackets: true,
              useCPP: true,
              mode: "text/x-c++src",
              onChange: onChange
    });
    asmCodeMirror = CodeMirror.fromTextArea(domRoot.find(".asm textarea")[0], {
        lineNumbers: true,
                  matchBrackets: true,
                  mode: "text/x-asm",
                  readOnly: true
    });

    function getSetting(name) {
        return window.localStorage[windowLocalPrefix + "." + name];
    }
    function setSetting(name, value) {
        window.localStorage[windowLocalPrefix + "." + name] = value;
    }

    if (getSetting('code')) cppEditor.setValue(getSetting('code'));
    domRoot.find('.compiler').change(onCompilerChange);
    domRoot.find('.compiler_options').change(onChange).keyup(onChange);
    ignoreChanges = false;

    if (getSetting('compilerOptions')) {
        domRoot.find('.compiler_options').val(getSetting('compilerOptions'));
    }

    function onCompileResponse(data) {
        var stdout = data.stdout || "";
        var stderr = data.stderr || "";
        if (data.code == 0) {
            stdout += "\nCompiled ok";
        } else {
            stderr += "\nCompilation failed";
        }
        $('.result .output :visible').remove();
        var highlightLine = (data.asm == null);
        for (var i = 0; i < cppEditor.lineCount(); ++i) cppEditor.setMarker(i);
        parseLines(stderr + stdout, function(lineNum, msg) {
            var elem = $('.result .output .template').clone().appendTo('.result .output').removeClass('template');
            if (lineNum) {
                cppEditor.setMarker(lineNum - 1, null, "error");
                elem.html($('').append(lineNum + " : " + msg)).click(function() {
                    cppEditor.setSelection({line: lineNum - 1, ch: 0}, {line: lineNum, ch: 0});
                    return false;
                });
            } else {
                elem.text(msg);
            }
        });
        currentAssembly = data.asm || "[no output]";
        updateAsm();
    }

    function numberUsedLines(asm) {
        var sourceLines = {};
        $.each(asm, function(_, x) { if (x.source) sourceLines[x.source - 1] = true; });
        var ordinal = 0;
        $.each(sourceLines, function(k, _) { sourceLines[k] = ordinal++; });
        var asmLines = {};
        $.each(asm, function(index, x) { if (x.source) asmLines[index] = sourceLines[x.source - 1]; });
        return { source: sourceLines, asm: asmLines };
    }

    var lastUpdatedAsm = null;
    function updateAsm(forceUpdate) {
        if (!currentAssembly) return;
        var hashedUpdate = JSON.stringify({
            asm: currentAssembly,
            filters: filters
        });
        if (!forceUpdate && lastUpdatedAsm == hashedUpdate) { return; }
        lastUpdatedAsm = hashedUpdate;

        var asm = processAsm(currentAssembly, filters);
        var asmText = $.map(asm, function(x){ return x.text; }).join("\n");
        var numberedLines = numberUsedLines(asm);
        asmCodeMirror.setValue(asmText);

        clearBackground(cppEditor);
        clearBackground(asmCodeMirror);
        if (filters.colouriseAsm) {
            $.each(numberedLines.source, function(line, ordinal) {
                cppEditor.setLineClass(parseInt(line), null, "rainbow-" + (ordinal & 7));
            });
            $.each(numberedLines.asm, function(line, ordinal) {
                asmCodeMirror.setLineClass(parseInt(line), null, "rainbow-" + (ordinal & 7));
            });
        }
    }

    function pickOnlyRequestFilters(filters) {
        return {intel: !!filters.intel };
    }

    function onChange() {
        if (ignoreChanges) return;  // Ugly hack during startup.
        if (pendingTimeout) clearTimeout(pendingTimeout);
        pendingTimeout = setTimeout(function() {
            var data = {
                source: cppEditor.getValue(),
                compiler: $('.compiler').val(),
                options: $('.compiler_options').val(),
                filters: pickOnlyRequestFilters(filters)
            };
            setSetting('compiler', data.compiler);
            setSetting('compilerOptions', data.options);
            if (JSON.stringify(data) == JSON.stringify(lastRequest)) return;
            lastRequest = data;
            $.ajax({
                type: 'POST',
                url: '/compile',
                dataType: 'json',
                data: data,
                success: onCompileResponse});
        }, 750);
        setSetting('code', cppEditor.getValue());
        updateAsm();
        onChangeCallback();
    }

    function setSource(code) {
        cppEditor.setValue(code);
    }

    function getSource() {
        return cppEditor.getValue();
    }

    function serialiseState() {
        var state = {
            source: cppEditor.getValue(),
            compiler: domRoot.find('.compiler').val(),
            options: domRoot.find('.compiler_options').val(),
        };
        return state;
    }

    function deserialiseState(state) {
        cppEditor.setValue(state.source);
        domRoot.find('.compiler').val(state.compiler);
        domRoot.find('.compiler_options').val(state.options);
        // Somewhat hackily persist compiler into local storage else when the ajax response comes in
        // with the list of compilers it can splat over the deserialized version.
        // The whole serialize/hash/localStorage code is a mess! TODO(mg): fix
        setSetting('compiler', state.compiler);
        updateAsm(true);  // Force the update to reset colours after calling cppEditor.setValue
        return true;
    }

    function onCompilerChange() {
        onChange();
        var compiler = compilersByExe[$('.compiler').val()];
        domRoot.find('.filter button.btn[value="intel"]').toggleClass("disabled", !compiler.supportedOpts["-masm"]);
    }

    function setCompilers(compilers) {
        domRoot.find('.compiler option').remove();
        compilersByExe = {};
        $.each(compilers, function(index, arg) {
            compilersByExe[arg.exe] = arg;
            domRoot.find('.compiler').append($('<option value="' + arg.exe + '">' + arg.version + '</option>'));
        });
        if (getSetting('compiler')) {
            domRoot.find('.compiler').val(getSetting('compiler'));
        }
        onCompilerChange();
    }

    function setFilters(f) {
        filters = f;
        onChange();  // used to just update ASM, but things like "Intel syntax" need a new request
    }

    return {
        serialiseState: serialiseState,
        deserialiseState: deserialiseState,
        setCompilers: setCompilers,
        getSource: getSource,
        setSource: setSource,
        setFilters: setFilters
    };
}
<|endoftext|>


<commit_before>//send the clients time zone to the server
$(document).ready(function() {
	var visitortimezone = (-new Date().getTimezoneOffset()/60);
	$.ajax({
		type: "GET",
		url: OC.filePath('files', 'ajax', 'timezone.php'),
		data: 'time='+ visitortimezone,
		success: function(){
			location.reload();
		}
	});
});<commit_msg>remove timezone.js<commit_after><|endoftext|>


<commit_before> 'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;
var generateCode = require('../../utils/code-generator');

var TransferOutDoc = BateeqModels.inventory.TransferOutDoc;
var TransferOutItem = BateeqModels.inventory.TransferOutItem;

const moduleId = "EFR-KB/ALT";

module.exports = class ALterationOutManager {
    constructor(db, user){
        this.db = db;
        this.user = user;
        this.transferOutDocCollection = this.db.use(map.inventory.TransferOutDoc);

        var TransferOutDocManager = require('./transfer-out-doc-manager');
        this.transferOutDocManager = new TransferOutDocManager(db,user);

        var FinishingTerimaBarangReturManager = require('./efr-tb-bjr-manager');
        this.finishingTerimaBarangReturManager = new FinishingTerimaBarangReturManager(db,user);

        var TransferInDocManager = require('./transfer-in-doc-manager');
        this.transferInDocManager = new TransferInDocManager(db,user);

        var ModuleManager = require('../core/module-manager');
        this.moduleManager = new ModuleManager(db,user);
    }

    read(paging){
        var _paging = Object.assign({
            page : 1,
            size : 20,
            order: "_id",
            asc : true
        },paging);

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false,
                code: {
                        '$regex': new RegExp("^[A-Z0-9]+\/" + moduleId + "\/[0-9]{2}\/[0-9]{4}$","i")}
            };

            var query = _paging.keyword ? {
                '$and': [deleted]
            } : deleted;

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterCode = {
                    'code': {
                        '$regex': regex
                    }
                };
                var $or = {
                    '$or': [filterCode]
                };
                query['$and'].push($or);
            }

            this.transferOutDocCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(transferOutDocs => {
                    resolve(transferOutDocs);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getByCode(code) {
        return new Promise((resolve, reject) => {
            var query = {
                code: code,
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getByReference(ref) {
        return new Promise((resolve, reject) => {
            var query = {
                reference: ref,
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQuery(query) {
        return new Promise((resolve, reject) => {
            this.transferOutDocCollection
                .single(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    create(transferOutDoc) {
        return new Promise((resolve, reject) => {

            this._validate(transferOutDoc)
                .then(validTransferOutDoc => {
                    validTransferOutDoc.code = generateCode(moduleId)
                    this.transferOutDocManager.create(validTransferOutDoc)
                        .then(id => {
                                resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    update(transferOutDoc){
        return new Promise((resolve,reject) =>{

        });
    }

    _validate(transferOutDoc){
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = transferOutDoc;
            this.moduleManager.getByCode(moduleId)
            .then(module => {
                var config = module.config;
                valid.source = config.source;
                valid.sourceId = config.source.value.toString();
                valid.destination = config.destination;
                valid.destinationId = config.destination.value.toString();

                var getbjrInByCode =  this.finishingTerimaBarangReturManager.getByCode(valid.reference);
                var getAltOutByRef = this.getByReference(valid.reference);

                Promise.all([getbjrInByCode,getAltOutByRef])
                .then(results =>{
                    var bjrTransferIn = results[0];
                    var altTransferOut = results[1];
                    if(bjrTransferIn){
                        if (valid.items && valid.items.length > 0) {

                        var itemErrors = [];
                            for(var item of valid.items){
                                var itemError = {};
                                for(var item2 of bjrTransferIn.items){
                                    if(item.articleVariantId == item2.articleVariantId){
                                        if(item.quantity > item2.quantity){
                                            itemError["articleVariantId"] = "item retur harus lebih kecil atau sama dengan";
                                        }
                                    }
                                }
                                itemErrors.push(itemError);
                            }

                            for (var itemError of itemErrors) {
                                for (var prop in itemError) {
                                    errors.items = itemErrors;
                                    break;
                                }
                                if (errors.items)
                                    break;
                            }
                        }else{
                            errors["items"] = "items is required";
                        }
                    }else{
                            errors["reference"] = "reference not found";
                    }

                    if(altTransferOut){
                            errors["reference"] = "reference already used";
                    }

                    // 2c. begin: check if data has any error, reject if it has.

                    for (var prop in errors) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                });

            })
            .catch(e => {
                reject(new Error(`Unable to load module:${moduleId}`));
            });
        });
    }
}<commit_msg>ganti single jadi singleordefault untuk getbycode<commit_after> 'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;
var generateCode = require('../../utils/code-generator');

var TransferOutDoc = BateeqModels.inventory.TransferOutDoc;
var TransferOutItem = BateeqModels.inventory.TransferOutItem;

const moduleId = "EFR-KB/ALT";

module.exports = class ALterationOutManager {
    constructor(db, user){
        this.db = db;
        this.user = user;
        this.transferOutDocCollection = this.db.use(map.inventory.TransferOutDoc);

        var TransferOutDocManager = require('./transfer-out-doc-manager');
        this.transferOutDocManager = new TransferOutDocManager(db,user);

        var FinishingTerimaBarangReturManager = require('./efr-tb-bjr-manager');
        this.finishingTerimaBarangReturManager = new FinishingTerimaBarangReturManager(db,user);

        var TransferInDocManager = require('./transfer-in-doc-manager');
        this.transferInDocManager = new TransferInDocManager(db,user);

        var ModuleManager = require('../core/module-manager');
        this.moduleManager = new ModuleManager(db,user);
    }

    read(paging){
        var _paging = Object.assign({
            page : 1,
            size : 20,
            order: "_id",
            asc : true
        },paging);

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false,
                code: {
                        '$regex': new RegExp("^[A-Z0-9]+\/" + moduleId + "\/[0-9]{2}\/[0-9]{4}$","i")}
            };

            var query = _paging.keyword ? {
                '$and': [deleted]
            } : deleted;

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterCode = {
                    'code': {
                        '$regex': regex
                    }
                };
                var $or = {
                    '$or': [filterCode]
                };
                query['$and'].push($or);
            }

            this.transferOutDocCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(transferOutDocs => {
                    resolve(transferOutDocs);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getByCode(code) {
        return new Promise((resolve, reject) => {
            var query = {
                code: code,
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getByReference(ref) {
        return new Promise((resolve, reject) => {
            var query = {
                reference: ref,
                _deleted: false
            };
            this.getSingleOrDefaultByQuery(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQuery(query) {
        return new Promise((resolve, reject) => {
            this.transferOutDocCollection
                .single(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleOrDefaultByQuery(query) {
        return new Promise((resolve, reject) => {
            this.transferOutDocCollection
                .singleOrDefault(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    create(transferOutDoc) {
        return new Promise((resolve, reject) => {

            this._validate(transferOutDoc)
                .then(validTransferOutDoc => {
                    validTransferOutDoc.code = generateCode(moduleId)
                    this.transferOutDocManager.create(validTransferOutDoc)
                        .then(id => {
                                resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    update(transferOutDoc){
        return new Promise((resolve,reject) =>{

        });
    }

    _validate(transferOutDoc){
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = transferOutDoc;
            this.moduleManager.getByCode(moduleId)
            .then(module => {
                var config = module.config;
                valid.source = config.source;
                valid.sourceId = config.source.value.toString();
                valid.destination = config.destination;
                valid.destinationId = config.destination.value.toString();

                var getbjrInByCode =  this.finishingTerimaBarangReturManager.getByCode(valid.reference);
                var getAltOutByRef = this.getByReference(valid.reference);

                Promise.all([getbjrInByCode,getAltOutByRef])
                .then(results =>{
                    var bjrTransferIn = results[0];
                    var altTransferOut = results[1];
                    if(bjrTransferIn){
                        if (valid.items && valid.items.length > 0) {

                        var itemErrors = [];
                            for(var item of valid.items){
                                var itemError = {};
                                for(var item2 of bjrTransferIn.items){
                                    if(item.articleVariantId == item2.articleVariantId){
                                        if(item.quantity > item2.quantity){
                                            itemError["articleVariantId"] = "item retur harus lebih kecil atau sama dengan";
                                        }
                                    }
                                }
                                itemErrors.push(itemError);
                            }

                            for (var itemError of itemErrors) {
                                for (var prop in itemError) {
                                    errors.items = itemErrors;
                                    break;
                                }
                                if (errors.items)
                                    break;
                            }
                        }else{
                            errors["items"] = "items is required";
                        }
                    }else{
                            errors["reference"] = "reference not found";
                    }

                    // if(altTransferOut){
                    //         errors["reference"] = "reference already used";
                    // }

                    // 2c. begin: check if data has any error, reject if it has.

                    for (var prop in errors) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                });

            })
            .catch(e => {
                reject(new Error(`Unable to load module:${moduleId}`));
            });
        });
    }
}<|endoftext|>


<commit_before>import { PI2 } from 'math/Constants.js';

export default class Rotation {

    constructor (transform, rotation = 0) {

        this.transform = transform;
        this._v = rotation;
        this.fast = rotation % PI2;

        this.sr = 0;
        this.cr = 0;

    }

    getValue () {
        return this._v;
    }

    setValue (value) {

        if (this._v !== value)
        {
            this._v = value;
            this.fast = value % PI2;

            if (this.fast)
            {
                //  Update the cache if the rotation != 0
                this.sr = Math.sin(value);
                this.cr = Math.cos(value);
            }

            this.transform.setDirty();
        }

    }

    setTransform (transform) {

        this.transform = transform;

    }

    addProperties (target) {

        Object.defineProperties(target, {

            'rotation': {
                enumerable: true,
                get: () => this.getValue(),
                set: (value) => this.setValue(value)
            }

        });

    }

    destroy () {

        this._v = undefined;
        this.transform = undefined;

    }

}
<commit_msg>Added isFast getter. Moved 'fast' property to [1]. Moved _v to [0] to bring inline with the other components.<commit_after>import { PI2 } from 'math/Constants.js';

export default class Rotation {

    constructor (transform, rotation = 0) {

        this.transform = transform;

        this[0] = rotation;
        this[1] = rotation % PI2;

        this.sr = 0;
        this.cr = 0;

    }

    getValue () {

        return this[0];

    }

    setValue (value) {

        if (this[0] !== value)
        {
            this[0] = value;
            this[1] = value % PI2;

            if (this[1])
            {
                //  Update the cache if the rotation != 0
                this.sr = Math.sin(value);
                this.cr = Math.cos(value);
            }

            this.transform.setDirty();
        }

    }

    get isFast () {

        return (this[1] === 0);

    }

    setTransform (transform) {

        this.transform = transform;

    }

    addProperties (target) {

        Object.defineProperties(target, {

            'rotation': {
                enumerable: true,
                get: () => this.getValue(),
                set: (value) => this.setValue(value)
            }

        });

    }

    destroy () {

        this.transform = undefined;

    }

}
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'

import ExpandableList from './ExpandableList'
import List from './List'
import Close, { CloseIcon } from './Close'

import { focus } from './utility/focus'

// `PureComponent` is only available in React >= 15.3.0.
const PureComponent = React.PureComponent || React.Component

export default class ExpandableMenu extends PureComponent
{
	static propTypes =
	{
		// Component CSS class
		className  : PropTypes.string,

		// CSS style object
		style      : PropTypes.object,

		// `aria-label` for the "Close" button
		// (which is an "x" visible in fullscreen mode).
		closeLabel : PropTypes.string,

		// The "x" button icon that closes the `<Select/>`
		// in fullscreen mode on mobile devices.
		closeButtonIcon : PropTypes.oneOfType([PropTypes.func, PropTypes.oneOf([false])]).isRequired,

		// Must accept a `ref`.
		// Receives properties: `onClick`, `onKeyDown`, `onBlur`, `aria-expanded`.
		button : PropTypes.elementType,
		buttonProps : PropTypes.object,
		buttonClassName : PropTypes.string,

		toggleElement : PropTypes.node,

		// (deprecated, use `button` component instead)
		toggler : PropTypes.func,

		// (deprecated, use `buttonProps` instead)
		togglerAriaLabel : PropTypes.string,

		// (deprecated, use `buttonProps` instead)
		togglerAriaHasPopup : PropTypes.string,

		// (deprecated, use `buttonProps` instead)
		togglerClassName : PropTypes.string,

		title: PropTypes.string,
		disabled: PropTypes.bool
	}

	static defaultProps =
	{
		// The "x" button icon that closes the `<Select/>`
		// in fullscreen mode on mobile devices.
		closeButtonIcon : CloseIcon
	}

	state = {}

	onExpand = () => this.setState({ isExpanded: true })

	onCollapse = ({ focusOut }) => {
		if (!focusOut) {
			this.focus()
		}
		this.setState({ isExpanded: false })
	}

	// `this.toggler` is deprecated.
	focus = () => focus(this.toggler || this.togglerNode)

	expand   = () => this.list.expand()
	collapse = () => this.list.collapse()
	toggle   = () => this.list.toggle()

	onFocusOut = () => {
		// `window.rruiCollapseOnFocusOut` can be used
		// for debugging expandable contents.
		if (window.rruiCollapseOnFocusOut !== false) {
			this.collapse()
		}
	}

	storeListRef = (ref) => this.list = ref

	// (legacy) (deprecated)
	// Is used to focus legacy togglers.
	storeTogglerRef = (ref) => this.toggler = ref

	// `this.togglerNode` is only used to determine
	// whether the focus is "inside" the component or "outside" of it.
	storeTogglerNode = (node) => this.togglerNode = node
	getTogglerNode = () => this.togglerNode

	render()
	{
		const
		{
			title,
			disabled,
			style,
			className,
			toggler,
			button,
			buttonProps,
			buttonClassName,
			toggleElement,
			togglerAriaLabel,
			togglerAriaHasPopup,
			togglerClassName,
			children,
			...rest
		}
		= this.props

		const { isExpanded } = this.state

		let menuToggler
		let menuItems

		if (toggler || button || toggleElement) {
			// "button" string is used instead of a `DefaultTogglerButton`
			// so that the `ref` is the `<button/>` DOM Element.
			// (`.focus()`, `.contains()`).
			const TogglerButton = button || 'button'
			const togglerElement = toggleElement || (toggler ? React.createElement(toggler) : null)
			menuItems = children
			menuToggler = (
				<TogglerButton
					type={button ? undefined : 'button'}
					aria-haspopup={ togglerAriaHasPopup }
					aria-label={ togglerAriaLabel }
					className={ classNames(togglerClassName, buttonClassName, {
						'rrui__button-reset': toggleElement,
						'rrui__outline': toggleElement
					}) }
					{...buttonProps}
					ref={ this.storeTogglerNode }
					onClick={ this.onClick }
					onKeyDown={ this.onKeyDown }
					onBlur={ this.onBlur }
					aria-expanded={ isExpanded ? true : false }
					title={ title }
					disabled={ disabled }>
					{ togglerElement }
				</TogglerButton>
			)
		} else {
			menuItems = React.Children.toArray(children)
			menuToggler = menuItems.shift()
			menuToggler = (
				<div
					ref={ this.storeTogglerNode }
					onClick={ this.onClick }
					onKeyDown={ this.onKeyDown }
					onBlur={ this.onBlur }>
					{ React.cloneElement(menuToggler, { ref : this.storeTogglerRef }) }
				</div>
			)
		}

		return (
			<div
				style={ style }
				className={ classNames('rrui__menu', className) }>

				{menuToggler}

				<ExpandableList
					{...rest}
					animation="fade-up"
					ref={this.storeListRef}
					aria-label={this.props['aria-label']}
					tabbable={false}
					scrollMaxItems={0}
					onCollapse={this.onCollapse}
					onExpand={this.onExpand}
					onFocusOut={this.onFocusOut}
					getTogglerNode={this.getTogglerNode}
					focusSelectedItem={false}
					className="rrui__shadow">
					{menuItems}
				</ExpandableList>
			</div>
		)
	}

	onBlur = (event) => this.list && this.list.onBlur(event)

	onClick = (event) => this.toggle()

	onKeyDown = (event) =>
	{
		if (event.defaultPrevented) {
			return
		}

		if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
			return
		}

		switch (event.keyCode)
		{
			// "Up" arrow.
			// Select the previous item (if present).
			case 38:
			// "Down" arrow.
			// Select the next item (if present).
			case 40:
				return this.list.onKeyDown(event)

			// "Enter".
			case 13:
				// Submit containing `<form/>`.
				// Expand otherwise.
				this.expand()
				return event.preventDefault()
		}
	}
}<commit_msg>title -> buttonTitle<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'

import ExpandableList from './ExpandableList'
import List from './List'
import Close, { CloseIcon } from './Close'

import { focus } from './utility/focus'

// `PureComponent` is only available in React >= 15.3.0.
const PureComponent = React.PureComponent || React.Component

export default class ExpandableMenu extends PureComponent
{
	static propTypes =
	{
		// Component CSS class
		className  : PropTypes.string,

		// CSS style object
		style      : PropTypes.object,

		// `aria-label` for the "Close" button
		// (which is an "x" visible in fullscreen mode).
		closeLabel : PropTypes.string,

		// The "x" button icon that closes the `<Select/>`
		// in fullscreen mode on mobile devices.
		closeButtonIcon : PropTypes.oneOfType([PropTypes.func, PropTypes.oneOf([false])]).isRequired,

		// Must accept a `ref`.
		// Receives properties: `onClick`, `onKeyDown`, `onBlur`, `aria-expanded`.
		button : PropTypes.elementType,
		buttonProps : PropTypes.object,
		buttonClassName : PropTypes.string,

		toggleElement : PropTypes.node,

		// (deprecated, use `button` component instead)
		toggler : PropTypes.func,

		// (deprecated, use `buttonProps` instead)
		togglerAriaLabel : PropTypes.string,

		// (deprecated, use `buttonProps` instead)
		togglerAriaHasPopup : PropTypes.string,

		// (deprecated, use `buttonProps` instead)
		togglerClassName : PropTypes.string,

		buttonTitle: PropTypes.string,
		disabled: PropTypes.bool
	}

	static defaultProps =
	{
		// The "x" button icon that closes the `<Select/>`
		// in fullscreen mode on mobile devices.
		closeButtonIcon : CloseIcon
	}

	state = {}

	onExpand = () => this.setState({ isExpanded: true })

	onCollapse = ({ focusOut }) => {
		if (!focusOut) {
			this.focus()
		}
		this.setState({ isExpanded: false })
	}

	// `this.toggler` is deprecated.
	focus = () => focus(this.toggler || this.togglerNode)

	expand   = () => this.list.expand()
	collapse = () => this.list.collapse()
	toggle   = () => this.list.toggle()

	onFocusOut = () => {
		// `window.rruiCollapseOnFocusOut` can be used
		// for debugging expandable contents.
		if (window.rruiCollapseOnFocusOut !== false) {
			this.collapse()
		}
	}

	storeListRef = (ref) => this.list = ref

	// (legacy) (deprecated)
	// Is used to focus legacy togglers.
	storeTogglerRef = (ref) => this.toggler = ref

	// `this.togglerNode` is only used to determine
	// whether the focus is "inside" the component or "outside" of it.
	storeTogglerNode = (node) => this.togglerNode = node
	getTogglerNode = () => this.togglerNode

	render()
	{
		const
		{
			buttonTitle,
			disabled,
			style,
			className,
			toggler,
			button,
			buttonProps,
			buttonClassName,
			toggleElement,
			togglerAriaLabel,
			togglerAriaHasPopup,
			togglerClassName,
			children,
			...rest
		}
		= this.props

		const { isExpanded } = this.state

		let menuToggler
		let menuItems

		if (toggler || button || toggleElement) {
			// "button" string is used instead of a `DefaultTogglerButton`
			// so that the `ref` is the `<button/>` DOM Element.
			// (`.focus()`, `.contains()`).
			const TogglerButton = button || 'button'
			const togglerElement = toggleElement || (toggler ? React.createElement(toggler) : null)
			menuItems = children
			menuToggler = (
				<TogglerButton
					type={button ? undefined : 'button'}
					aria-haspopup={ togglerAriaHasPopup }
					aria-label={ togglerAriaLabel }
					className={ classNames(togglerClassName, buttonClassName, {
						'rrui__button-reset': toggleElement,
						'rrui__outline': toggleElement
					}) }
					{...buttonProps}
					ref={ this.storeTogglerNode }
					onClick={ this.onClick }
					onKeyDown={ this.onKeyDown }
					onBlur={ this.onBlur }
					aria-expanded={ isExpanded ? true : false }
					title={ buttonTitle }
					disabled={ disabled }>
					{ togglerElement }
				</TogglerButton>
			)
		} else {
			menuItems = React.Children.toArray(children)
			menuToggler = menuItems.shift()
			menuToggler = (
				<div
					ref={ this.storeTogglerNode }
					onClick={ this.onClick }
					onKeyDown={ this.onKeyDown }
					onBlur={ this.onBlur }>
					{ React.cloneElement(menuToggler, { ref : this.storeTogglerRef }) }
				</div>
			)
		}

		return (
			<div
				style={ style }
				className={ classNames('rrui__menu', className) }>

				{menuToggler}

				<ExpandableList
					{...rest}
					animation="fade-up"
					ref={this.storeListRef}
					aria-label={this.props['aria-label']}
					tabbable={false}
					scrollMaxItems={0}
					onCollapse={this.onCollapse}
					onExpand={this.onExpand}
					onFocusOut={this.onFocusOut}
					getTogglerNode={this.getTogglerNode}
					focusSelectedItem={false}
					className="rrui__shadow">
					{menuItems}
				</ExpandableList>
			</div>
		)
	}

	onBlur = (event) => this.list && this.list.onBlur(event)

	onClick = (event) => this.toggle()

	onKeyDown = (event) =>
	{
		if (event.defaultPrevented) {
			return
		}

		if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
			return
		}

		switch (event.keyCode)
		{
			// "Up" arrow.
			// Select the previous item (if present).
			case 38:
			// "Down" arrow.
			// Select the next item (if present).
			case 40:
				return this.list.onKeyDown(event)

			// "Enter".
			case 13:
				// Submit containing `<form/>`.
				// Expand otherwise.
				this.expand()
				return event.preventDefault()
		}
	}
}<|endoftext|>


<commit_before>// @flow
import React, {PropTypes} from 'react'
import {
  StyleSheet,
  View,
  ListView,
  Platform,
  Text,
  Navigator,
  TouchableHighlight,
  RefreshControl,
} from 'react-native'

import delay from 'delay'

import Icon from 'react-native-vector-icons/Ionicons'
import type {StoryType} from './types'
import LoadingView from '../components/loading'
import * as c from '../components/colors'

let Entities = require('html-entities').AllHtmlEntities
const entities = new Entities()

export default class NewsContainer extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
    navigator: PropTypes.instanceOf(Navigator).isRequired,
    route: PropTypes.object.isRequired,
    url: PropTypes.string.isRequired,
  }

  state = {
    dataSource: new ListView.DataSource({
      rowHasChanged: (r1: StoryType, r2: StoryType) => r1.title != r2.title,
    }),
    refreshing: false,
    loaded: false,
    error: false,
    noNews: false,
  }

  componentWillMount() {
    this.refresh()
  }

  fetchData = async () => {
    try {
      let response = await fetch(this.props.url).then(r => r.json())
      let entries = response.responseData.feed.entries
      if (!entries.length) {
        this.setState({noNews: true})
      }
      this.setState({dataSource: this.state.dataSource.cloneWithRows(entries)})
    } catch (error) {
      this.setState({error: true})
      console.error(error)
    }

    this.setState({loaded: true})
  }

  refresh = async () => {
    let start = Date.now()
    this.setState(() => ({refreshing: true}))

    await this.fetchData()

    // wait 0.5 seconds – if we let it go at normal speed, it feels broken.
    let elapsed = start - Date.now()
    if (elapsed < 500) {
      await delay(500 - elapsed)
    }
    this.setState(() => ({refreshing: false}))
  }

  renderRow = (story: StoryType) => {
    let title = entities.decode(story.title)
    let snippet = entities.decode(story.contentSnippet)
    return (
      <TouchableHighlight underlayColor={'#ebebeb'} onPress={() => this.onPressNews(title, story)}>
        <View style={[styles.row]}>
          <View style={[styles.rowContainer]}>
            <Text style={styles.itemTitle} numberOfLines={1}>{title}</Text>
            <Text style={styles.itemPreview} numberOfLines={2}>{snippet}</Text>
          </View>
          <Icon style={[styles.arrowIcon]} name='ios-arrow-forward' />
        </View>
      </TouchableHighlight>
    )
  }

  onPressNews = (title: string, story: StoryType) => {
    this.props.navigator.push({
      id: 'NewsItemView',
      index: this.props.route.index + 1,
      title: title,
      backButtonTitle: this.props.name,
      props: {story},
    })
  }

  render() {
    if (!this.state.loaded) {
      return <LoadingView />
    }

    if (this.state.noNews) {
      return (
        <View style={{
          flex: 1,
          justifyContent: 'center',
          alignItems: 'center',
          backgroundColor: '#ffffff',
        }}>
          <Text>
            No news.
          </Text>
        </View>
      )
    }

    return (
      <ListView
        style={styles.listContainer}
        contentInset={{bottom: Platform.OS === 'ios' ? 49 : 0}}
        dataSource={this.state.dataSource}
        renderRow={this.renderRow}
        pageSize={5}
        refreshControl={
          <RefreshControl
            refreshing={this.state.refreshing}
            onRefresh={this.refresh}
          />
        }
      />
    )
  }
}

const styles = StyleSheet.create({
  listContainer: {
    paddingBottom: 50,
    backgroundColor: '#ffffff',
  },
  row: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#ebebeb',
    marginLeft: 20,
    paddingRight: 10,
    paddingTop: 8,
    paddingBottom: 8,
  },
  arrowIcon: {
    color: c.iosDisabledText,
    fontSize: 20,
    marginRight: 6,
    marginLeft: 6,
    marginTop: 0,
  },
  rowContainer: {
    flex: 1,
    flexDirection: 'column',
  },
  itemTitle: {
    color: c.black,
    paddingBottom: 3,
    fontSize: 16,
    textAlign: 'left',
  },
  itemPreview: {
    color: c.iosDisabledText,
    fontSize: 13,
    textAlign: 'left',
  },
})
<commit_msg>simplify NewsContainer<commit_after>// @flow
import React, {PropTypes} from 'react'
import {
  StyleSheet,
  View,
  ListView,
  Platform,
  Text,
  Navigator,
  TouchableHighlight,
  RefreshControl,
} from 'react-native'

import delay from 'delay'

import Icon from 'react-native-vector-icons/Ionicons'
import type {StoryType} from './types'
import LoadingView from '../components/loading'
import {NoticeView} from '../components/notice'
import * as c from '../components/colors'

let Entities = require('html-entities').AllHtmlEntities
const entities = new Entities()

export default class NewsContainer extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
    navigator: PropTypes.instanceOf(Navigator).isRequired,
    route: PropTypes.object.isRequired,
    url: PropTypes.string.isRequired,
  }

  state = {
    dataSource: new ListView.DataSource({
      rowHasChanged: (r1: StoryType, r2: StoryType) => r1 != r2,
    }),
    refreshing: false,
    loaded: false,
    error: false,
  }

  componentWillMount() {
    this.refresh()
  }

  fetchData = async () => {
    try {
      let response = await fetch(this.props.url).then(r => r.json())
      let entries = response.responseData.feed.entries
      this.setState({dataSource: this.state.dataSource.cloneWithRows(entries)})
    } catch (error) {
      this.setState({error: true})
      console.error(error)
    }

    this.setState({loaded: true})
  }

  refresh = async () => {
    let start = Date.now()
    this.setState(() => ({refreshing: true}))

    await this.fetchData()

    // wait 0.5 seconds – if we let it go at normal speed, it feels broken.
    let elapsed = start - Date.now()
    if (elapsed < 500) {
      await delay(500 - elapsed)
    }
    this.setState(() => ({refreshing: false}))
  }

  renderRow = (story: StoryType) => {
    let title = entities.decode(story.title)
    let snippet = entities.decode(story.contentSnippet)
    return (
      <TouchableHighlight underlayColor={'#ebebeb'} onPress={() => this.onPressNews(title, story)}>
        <View style={[styles.row]}>
          <View style={[styles.rowContainer]}>
            <Text style={styles.itemTitle} numberOfLines={1}>{title}</Text>
            <Text style={styles.itemPreview} numberOfLines={2}>{snippet}</Text>
          </View>
          <Icon style={[styles.arrowIcon]} name='ios-arrow-forward' />
        </View>
      </TouchableHighlight>
    )
  }

  onPressNews = (title: string, story: StoryType) => {
    this.props.navigator.push({
      id: 'NewsItemView',
      index: this.props.route.index + 1,
      title: title,
      backButtonTitle: this.props.name,
      props: {story},
    })
  }

  render() {
    if (!this.state.loaded) {
      return <LoadingView />
    }

    if (!this.state.dataSource.getRowCount()) {
      return <NoticeView text='No news.' />
    }

    return (
      <ListView
        style={styles.listContainer}
        contentInset={{bottom: Platform.OS === 'ios' ? 49 : 0}}
        dataSource={this.state.dataSource}
        renderRow={this.renderRow}
        pageSize={5}
        refreshControl={
          <RefreshControl
            refreshing={this.state.refreshing}
            onRefresh={this.refresh}
          />
        }
      />
    )
  }
}

const styles = StyleSheet.create({
  listContainer: {
    paddingBottom: 50,
    backgroundColor: '#ffffff',
  },
  row: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#ebebeb',
    marginLeft: 20,
    paddingRight: 10,
    paddingTop: 8,
    paddingBottom: 8,
  },
  arrowIcon: {
    color: c.iosDisabledText,
    fontSize: 20,
    marginRight: 6,
    marginLeft: 6,
    marginTop: 0,
  },
  rowContainer: {
    flex: 1,
    flexDirection: 'column',
  },
  itemTitle: {
    color: c.black,
    paddingBottom: 3,
    fontSize: 16,
    textAlign: 'left',
  },
  itemPreview: {
    color: c.iosDisabledText,
    fontSize: 13,
    textAlign: 'left',
  },
})
<|endoftext|>


<commit_before>/*
** copay-shell - launch
*/

var color    = require('cli-color');
var path     = require('path');
var appPath  = path.normalize(__dirname + '/../../');
var execPath = path.normalize(__dirname + '/../bin/' + process.platform);
var spawn    = require('child_process').spawn;

// update execPath with platform specific binary locations
switch (process.platform) {
  case 'linux':
    execPath += '/atom';
    break;
  case 'darwin':
    execPath += '/Atom.app/Contents/MacOS/Atom';
    break;
  case 'win32':
    execPath += '\\atom.exe'
    break;
  default:
    console.log('Platform not supported.');
    process.exit();
}

var copay = spawn(execPath, [appPath]);

copay.stdout.on('data', function (data) {
  console.log(data);
});

copay.stderr.on('data', function (data) {
  console.log(color.red(data));
});

copay.on('close', function (code) {
  console.log('child process exited with code ' + code);
});
<commit_msg>fixes #826<commit_after>/*
 ** copay-shell - launch
 */

var color = require('cli-color');
var path = require('path');
var appPath = path.normalize(__dirname + '/../../');
var execPath = path.normalize(__dirname + '/../bin/' + process.platform);
var spawn = require('child_process').spawn;

// update execPath with platform specific binary locations
switch (process.platform) {
  case 'linux':
    execPath += '/atom';
    break;
  case 'darwin':
    execPath += '/Atom.app/Contents/MacOS/Atom';
    break;
  case 'win32':
    execPath += '\\atom.exe'
    break;
  default:
    console.log('Platform not supported.');
    process.exit();
}

var copay = spawn(execPath, [appPath]);

copay.stdout.on('data', function(data) {
  console.log(data);
});

copay.stderr.on('data', function(data) {
  console.log("STDERR:" + data);
});

copay.on('close', function(code) {
  console.log('child process exited with code ' + code);
});
<|endoftext|>


<commit_before>/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Stores arrays of file paths keyed by page output paths
// to be consumed by the CSS transformer
const pagesInlineCss = new Map();

/**
 * Adds a CSS file path to a map in production or inserts
 * a <link> element to that file during development
 * @this ShortcodeContext
 * @param {string} cssPath Path to a CSS file in dist
 */
function InlineCss(cssPath) {
  console.log(this);
  const css = pagesInlineCss.get(this.ctx.page.outputPath) || [];
  css.push(cssPath);
  pagesInlineCss.set(this.ctx.page.outputPath, css);

  // For non-production environments we never want to inline,
  // but link the CSS instead to enable hot-reloading et. al.
  if (process.env.NODE_ENV !== 'production') {
    return `<link rel="stylesheet" href=${cssPath}>`;
  }

  return '';
}

module.exports = {InlineCss, pagesInlineCss};
<commit_msg>chore: remove debug console log<commit_after>/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Stores arrays of file paths keyed by page output paths
// to be consumed by the CSS transformer
const pagesInlineCss = new Map();

/**
 * Adds a CSS file path to a map in production or inserts
 * a <link> element to that file during development
 * @this ShortcodeContext
 * @param {string} cssPath Path to a CSS file in dist
 */
function InlineCss(cssPath) {
  const css = pagesInlineCss.get(this.ctx.page.outputPath) || [];
  css.push(cssPath);
  pagesInlineCss.set(this.ctx.page.outputPath, css);

  // For non-production environments we never want to inline,
  // but link the CSS instead to enable hot-reloading et. al.
  if (process.env.NODE_ENV !== 'production') {
    return `<link rel="stylesheet" href=${cssPath}>`;
  }

  return '';
}

module.exports = {InlineCss, pagesInlineCss};
<|endoftext|>