<commit_before>/**
 * @file TreeNode component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component, Fragment} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import CircularLoading from '../CircularLoading';
import Theme from '../Theme';
import IconButton from '../IconButton';
import Radio from '../Radio';
import Checkbox from '../Checkbox';

import SelectMode from '../_statics/SelectMode';

import Util from '../_vendors/Util';
import Calculation from '../_vendors/Calculation';

class TreeNode extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            collapsed: false
        };

    }

    toggleTreeNode = e => {

        e && e.stopPropagation();

        const {onNodeToggleStart} = this.props;
        onNodeToggleStart && onNodeToggleStart();

        this.setState({
            collapsed: !this.state.collapsed
        }, () => {
            const {onNodeToggleEnd} = this.props;
            onNodeToggleEnd && onNodeToggleEnd();
        });

    };

    checkboxChangeHandler = e => {

        const {data, path, value, onSelect, onDeselect} = this.props;

        if (!Calculation.isItemChecked(data, value, this.props)) {
            onSelect && onSelect(data, path, e);
        } else {
            onDeselect && onDeselect(data, path, e);
        }

    };

    radioChangeHandler = e => {
        const {data, path, onSelect} = this.props;
        onSelect && onSelect(data, path, e);
    };

    clickHandler = e => {

        const {data, path, disabled, isLoading, readOnly} = this.props;

        if (disabled || isLoading || readOnly || data.disabled || data.isLoading || data.readOnly) {
            return;
        }

        const {onClick} = this.props;
        onClick && onClick(data, path, e);

        const {selectMode} = this.props;

        switch (selectMode) {
            case SelectMode.MULTI_SELECT:
                this.checkboxChangeHandler(e);
                return;
            case SelectMode.SINGLE_SELECT:
                this.radioChangeHandler(e);
                return;
        }

    };

    render() {

        const {

                index, depth, path, theme, selectTheme, selectMode, data, value,
                disabled, isLoading, readOnly, allowCollapse, isSelectRecursive,
                valueField, displayField, descriptionField,

                collapsedIconCls, expandedIconCls, radioUncheckedIconCls, radioCheckedIconCls,
                checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls,

                renderer, onMouseEnter, onMouseLeave

            } = this.props,
            {collapsed} = this.state,

            checked = Calculation.isItemChecked(data, value, this.props),
            indeterminate = Calculation.isNodeIndeterminate(data, value, this.props),

            isNodeLoading = data.isLoading || isLoading,
            isNodeDisabled = data.disabled || disabled || isNodeLoading,

            nodeClassName = classNames('tree-node', {
                [`theme-${theme}`]: theme,
                [data.className]: data.className
            }),
            nodeStyle = {
                ...data.style,
                paddingLeft: (depth + 1) * 20
            },

            childrenClassName = classNames('tree-node-children', {
                collapsed
            }),

            loadingIconPosition = (data.rightIconCls && !data.iconCls) ? 'right' : 'left';

        return (
            <Fragment>

                        {
                            allowCollapse && data.children && data.children.length > 0 ?
                                <IconButton className="tree-node-collapse-icon"
                                            iconCls={collapsed ?
                                                data.collapsedIconCls || collapsedIconCls
                                                :
                                                data.expandedIconCls || expandedIconCls}
                                            onClick={this.toggleTreeNode}/>
                                :
                                null
                        }

                        {
                            selectMode === SelectMode.SINGLE_SELECT && (radioUncheckedIconCls || radioCheckedIconCls) ?
                                <Radio className="tree-node-select"
                                       theme={selectTheme}
                                       checked={checked}
                                       disabled={isNodeDisabled}
                                       uncheckedIconCls={data.radioUncheckedIconCls || radioUncheckedIconCls}
                                       checkedIconCls={data.radioCheckedIconCls || radioCheckedIconCls}
                                       disableTouchRipple={true}/>
                                :
                                null
                        }

                        {
                            selectMode === SelectMode.MULTI_SELECT ?
                                <Checkbox className="tree-node-select"
                                          theme={selectTheme}
                                          checked={checked}
                                          indeterminate={isSelectRecursive ? indeterminate : false}
                                          disabled={isNodeDisabled}
                                          uncheckedIconCls={data.checkboxUncheckedIconCls || checkboxUncheckedIconCls}
                                          checkedIconCls={data.checkboxCheckedIconCls || checkboxCheckedIconCls}
                                          indeterminateIconCls={data.checkboxIndeterminateIconCls || checkboxIndeterminateIconCls}
                                          disableTouchRipple={true}/>
                                :
                                null
                        }

                        {
                            isNodeLoading && loadingIconPosition === 'left' ?

                                    <CircularLoading className="button-loading-icon"
                                                     size="small"/>

                                :
                                (
                                    data.iconCls ?
                                        <i className={`button-icon button-icon-left ${data.iconCls}`}
                                           aria-hidden="true">
                                        :
                                        null
                                )
                        }

                        {
                            data.itemRenderer && typeof data.itemRenderer === 'function' ?
                                data.itemRenderer(data, index)
                                :
                                (
                                    renderer && typeof renderer === 'function' ?
                                        renderer(data, index)
                                        :
                                        (
                                            data[descriptionField] ?

                                                        {Util.getTextByDisplayField(data, displayField, valueField)}

                                                        {data[descriptionField]}

                                                :
                                                Util.getTextByDisplayField(data, displayField, valueField)
                                        )
                                )
                        }

                        {
                            isNodeLoading && loadingIconPosition === 'right' ?
                                <CircularLoading className="button-icon button-icon-right button-loading-icon"
                                                 size="small"/>
                                :
                                (
                                    data.rightIconCls ?
                                        <i className={`button-icon button-icon-right ${data.rightIconCls}`}
                                           aria-hidden="true">
                                        :
                                        null
                                )
                        }

                {
                    data.children && data.children.length > 0 ?

                            {
                                data.children.map((item, index) =>
                                    <TreeNode {...this.props}
                                              key={index}
                                              data={item}
                                              index={index}
                                              depth={depth + 1}
                                              path={
                                                  path ?
                                                      [...path, {index, node: item}]
                                                      :
                                                      [{index, node: item}]
                                              }/>
                                )
                            }

                        :
                        null
                }

            </Fragment>
        );

    }
}

TreeNode.propTypes = {

    index: PropTypes.number,
    depth: PropTypes.number,
    path: PropTypes.array,

    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    data: PropTypes.object,
    value: PropTypes.any,

    valueField: PropTypes.string,
    displayField: PropTypes.string,
    descriptionField: PropTypes.string,

    disabled: PropTypes.bool,
    isLoading: PropTypes.bool,
    readOnly: PropTypes.bool,
    allowCollapse: PropTypes.bool,
    isNodeToggling: PropTypes.bool,
    isSelectRecursive: PropTypes.bool,

    renderer: PropTypes.func,

    collapsedIconCls: PropTypes.string,
    expandedIconCls: PropTypes.string,
    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    onClick: PropTypes.func,
    onSelect: PropTypes.func,
    onDeselect: PropTypes.func,
    onMouseEnter: PropTypes.func,
    onMouseLeave: PropTypes.func,
    onNodeToggleStart: PropTypes.func,
    onNodeToggleEnd: PropTypes.func

};

TreeNode.defaultProps = {

    index: 0,
    depth: 0,

    theme: Theme.DEFAULT,

    selectTheme: Theme.DEFAULT,
    selectMode: SelectMode.SINGLE_SELECT,

    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',

    disabled: false,
    isLoading: false,
    readOnly: false,
    allowCollapse: true,
    isNodeToggling: false,
    isSelectRecursive: false,

    collapsedIconCls: 'fas fa-caret-right',
    expandedIconCls: 'fas fa-caret-down',
    checkboxUncheckedIconCls: 'far fa-square',
    checkboxCheckedIconCls: 'fas fa-check-square',
    checkboxIndeterminateIconCls: 'fas fa-minus-square'

};

export default TreeNode;<commit_msg>update TreeNode<commit_after>/**
 * @file TreeNode component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component, Fragment} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import CircularLoading from '../CircularLoading';
import Theme from '../Theme';
import IconButton from '../IconButton';
import Radio from '../Radio';
import Checkbox from '../Checkbox';

import SelectMode from '../_statics/SelectMode';

import Util from '../_vendors/Util';
import Calculation from '../_vendors/Calculation';

class TreeNode extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            collapsed: false
        };

    }

    toggleTreeNode = e => {

        e && e.stopPropagation();

        const {onNodeToggleStart} = this.props;
        onNodeToggleStart && onNodeToggleStart();

        this.setState({
            collapsed: !this.state.collapsed
        }, () => {
            const {onNodeToggleEnd} = this.props;
            onNodeToggleEnd && onNodeToggleEnd();
        });

    };

    checkboxChangeHandler = e => {

        const {data, path, value, onSelect, onDeselect} = this.props;

        if (!Calculation.isItemChecked(data, value, this.props)) {
            onSelect && onSelect(data, path, e);
        } else {
            onDeselect && onDeselect(data, path, e);
        }

    };

    radioChangeHandler = e => {
        const {data, path, onSelect} = this.props;
        onSelect && onSelect(data, path, e);
    };

    clickHandler = e => {

        const {data, path, disabled, isLoading, readOnly} = this.props;

        if (disabled || isLoading || readOnly || data.disabled || data.isLoading || data.readOnly) {
            return;
        }

        const {onClick} = this.props;
        onClick && onClick(data, path, e);

        const {selectMode} = this.props;

        switch (selectMode) {
            case SelectMode.MULTI_SELECT:
                this.checkboxChangeHandler(e);
                return;
            case SelectMode.SINGLE_SELECT:
                this.radioChangeHandler(e);
                return;
        }

    };

    render() {

        const {

                index, depth, path, theme, selectTheme, selectMode, data, value,
                disabled, isLoading, readOnly, allowCollapse, isSelectRecursive,
                valueField, displayField, descriptionField, filter,

                collapsedIconCls, expandedIconCls, radioUncheckedIconCls, radioCheckedIconCls,
                checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls,

                renderer, onMouseEnter, onMouseLeave

            } = this.props,
            {collapsed} = this.state,

            checked = Calculation.isItemChecked(data, value, this.props),
            indeterminate = Calculation.isNodeIndeterminate(data, value, this.props),

            isNodeLoading = data.isLoading || isLoading,
            isNodeDisabled = data.disabled || disabled || isNodeLoading,

            isNodeMatched = data && !!data[displayField]
                && data[displayField].toString().toUpperCase().includes(filter.toUpperCase()),

            nodeClassName = classNames('tree-node', {
                [`theme-${theme}`]: theme,
                [data.className]: data.className
            }),
            nodeStyle = {
                ...data.style,
                paddingLeft: (depth + 1) * 20
            },

            childrenClassName = classNames('tree-node-children', {
                collapsed
            }),

            loadingIconPosition = (data.rightIconCls && !data.iconCls) ? 'right' : 'left';

        return (
            <Fragment>

                {
                    isNodeMatched ?

                                {
                                    allowCollapse && data.children && data.children.length > 0 ?
                                        <IconButton className="tree-node-collapse-icon"
                                                    iconCls={collapsed ?
                                                        data.collapsedIconCls || collapsedIconCls
                                                        :
                                                        data.expandedIconCls || expandedIconCls}
                                                    onClick={this.toggleTreeNode}/>
                                        :
                                        null
                                }

                                {
                                    selectMode === SelectMode.SINGLE_SELECT && (radioUncheckedIconCls || radioCheckedIconCls) ?
                                        <Radio className="tree-node-select"
                                               theme={selectTheme}
                                               checked={checked}
                                               disabled={isNodeDisabled}
                                               uncheckedIconCls={data.radioUncheckedIconCls || radioUncheckedIconCls}
                                               checkedIconCls={data.radioCheckedIconCls || radioCheckedIconCls}
                                               disableTouchRipple={true}/>
                                        :
                                        null
                                }

                                {
                                    selectMode === SelectMode.MULTI_SELECT ?
                                        <Checkbox className="tree-node-select"
                                                  theme={selectTheme}
                                                  checked={checked}
                                                  indeterminate={isSelectRecursive ? indeterminate : false}
                                                  disabled={isNodeDisabled}
                                                  uncheckedIconCls={data.checkboxUncheckedIconCls || checkboxUncheckedIconCls}
                                                  checkedIconCls={data.checkboxCheckedIconCls || checkboxCheckedIconCls}
                                                  indeterminateIconCls={data.checkboxIndeterminateIconCls || checkboxIndeterminateIconCls}
                                                  disableTouchRipple={true}/>
                                        :
                                        null
                                }

                                {
                                    isNodeLoading && loadingIconPosition === 'left' ?

                                            <CircularLoading className="button-loading-icon"
                                                             size="small"/>

                                        :
                                        (
                                            data.iconCls ?
                                                <i className={`button-icon button-icon-left ${data.iconCls}`}
                                                   aria-hidden="true">
                                                :
                                                null
                                        )
                                }

                                {
                                    data.itemRenderer && typeof data.itemRenderer === 'function' ?
                                        data.itemRenderer(data, index)
                                        :
                                        (
                                            renderer && typeof renderer === 'function' ?
                                                renderer(data, index)
                                                :
                                                (
                                                    data[descriptionField] ?

                                                                {Util.getTextByDisplayField(data, displayField, valueField)}

                                                                {data[descriptionField]}

                                                        :
                                                        Util.getTextByDisplayField(data, displayField, valueField)
                                                )
                                        )
                                }

                                {
                                    isNodeLoading && loadingIconPosition === 'right' ?
                                        <CircularLoading className="button-icon button-icon-right button-loading-icon"
                                                         size="small"/>
                                        :
                                        (
                                            data.rightIconCls ?
                                                <i className={`button-icon button-icon-right ${data.rightIconCls}`}
                                                   aria-hidden="true">
                                                :
                                                null
                                        )
                                }

                        :
                        null
                }

                {
                    data.children && data.children.length > 0 ?

                            {
                                data.children.map((item, index) =>
                                    <TreeNode {...this.props}
                                              key={index}
                                              data={item}
                                              index={index}
                                              depth={depth + 1}
                                              path={
                                                  path ?
                                                      [...path, {index, node: item}]
                                                      :
                                                      [{index, node: item}]
                                              }/>
                                )
                            }

                        :
                        null
                }

            </Fragment>
        );

    }
}

TreeNode.propTypes = {

    index: PropTypes.number,
    depth: PropTypes.number,
    path: PropTypes.array,

    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    data: PropTypes.object,
    value: PropTypes.any,

    valueField: PropTypes.string,
    displayField: PropTypes.string,
    descriptionField: PropTypes.string,

    disabled: PropTypes.bool,
    isLoading: PropTypes.bool,
    readOnly: PropTypes.bool,
    allowCollapse: PropTypes.bool,
    isNodeToggling: PropTypes.bool,
    isSelectRecursive: PropTypes.bool,

    renderer: PropTypes.func,

    collapsedIconCls: PropTypes.string,
    expandedIconCls: PropTypes.string,
    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    onClick: PropTypes.func,
    onSelect: PropTypes.func,
    onDeselect: PropTypes.func,
    onMouseEnter: PropTypes.func,
    onMouseLeave: PropTypes.func,
    onNodeToggleStart: PropTypes.func,
    onNodeToggleEnd: PropTypes.func

};

TreeNode.defaultProps = {

    index: 0,
    depth: 0,

    theme: Theme.DEFAULT,

    selectTheme: Theme.DEFAULT,
    selectMode: SelectMode.SINGLE_SELECT,

    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',

    disabled: false,
    isLoading: false,
    readOnly: false,
    allowCollapse: true,
    isNodeToggling: false,
    isSelectRecursive: false,

    collapsedIconCls: 'fas fa-caret-right',
    expandedIconCls: 'fas fa-caret-down',
    checkboxUncheckedIconCls: 'far fa-square',
    checkboxCheckedIconCls: 'fas fa-check-square',
    checkboxIndeterminateIconCls: 'fas fa-minus-square'

};

export default TreeNode;<|endoftext|>


<commit_before>/**
 * @module
 * @prototype {Function} __touchHandler
 */

import { SmoothScrollbar } from '../smooth-scrollbar';
import { GLOBAL_ENV } from '../shared/';

const MIN_VELOCITY = 100;

let activeScrollbar = null;

/**
 * @method
 * @internal
 * Touch event handlers builder
 */
function __touchHandler() {
    const {
        targets,
        movementLocked,
        __touchRecord,
    } = this;

    const {
        container,
    } = targets;

    this.__addEvent(container, 'touchstart', (evt) => {
        if (this.__isDrag || this.__eventFromChildScrollbar(evt)) return;

        const { __timerID, movement } = this;

        // stop scrolling but keep movement for overscrolling
        cancelAnimationFrame(__timerID.scrollTo);
        if (!this.__willOverscroll('x')) movement.x = 0;
        if (!this.__willOverscroll('y')) movement.y = 0;

        // start records
        __touchRecord.track(evt);
        this.__autoLockMovement();

        activeScrollbar = this;
    });

    this.__addEvent(container, 'touchmove', (evt) => {
        if (!activeScrollbar) activeScrollbar = this;
        if (activeScrollbar !== this || this.__isDrag) return;

        __touchRecord.update(evt);

        let { x, y } = __touchRecord.getDelta();

        if (this.__shouldPropagateMovement(x, y)) {
            return this.__updateThrottle();
        }

        const { movement, MAX_OVERSCROLL, options } = this;

        if (movement.x && this.__willOverscroll('x', x)) {
            let factor = 2;

            if (options.overscrollEffect === 'bounce') {
                factor += Math.abs(10 * movement.x / MAX_OVERSCROLL);
            }

            if (Math.abs(movement.x) >= MAX_OVERSCROLL) {
                x = 0;
            } else {
                x /= factor;
            }
        }
        if (movement.y && this.__willOverscroll('y', y)) {
            let factor = 2;

            if (options.overscrollEffect === 'bounce') {
                factor += Math.abs(10 * movement.y / MAX_OVERSCROLL);
            }

            if (Math.abs(movement.y) >= MAX_OVERSCROLL) {
                y = 0;
            } else {
                y /= factor;
            }
        }

        this.__autoLockMovement();

        evt.preventDefault();

        this.__addMovement(x, y);
    });

    this.__addEvent(container, 'touchcancel touchend', (evt) => {
        if (this.__isDrag || this.__eventFromChildScrollbar(evt)) return;

        const { speed } = this.options;

        let { x, y } = __touchRecord.getVelocity();

        x = movementLocked.x ? 0 : Math.min(x * GLOBAL_ENV.EASING_MULTIPLIER, 1000);
        y = movementLocked.y ? 0 : Math.min(y * GLOBAL_ENV.EASING_MULTIPLIER, 1000);

        this.__addMovement(
            Math.abs(x) > MIN_VELOCITY ? (x * speed) : 0,
            Math.abs(y) > MIN_VELOCITY ? (y * speed) : 0
        );

        this.__unlockMovement();
        __touchRecord.release(evt);
        activeScrollbar = null;
    });
};

Object.defineProperty(SmoothScrollbar.prototype, '__touchHandler', {
    value: __touchHandler,
    writable: true,
    configurable: true,
});
<commit_msg>fix(touch): fix nested scrollbar switching<commit_after>/**
 * @module
 * @prototype {Function} __touchHandler
 */

import { SmoothScrollbar } from '../smooth-scrollbar';
import { GLOBAL_ENV } from '../shared/';

const MIN_VELOCITY = 100;

let activeScrollbar = null;

/**
 * @method
 * @internal
 * Touch event handlers builder
 */
function __touchHandler() {
    const {
        targets,
        movementLocked,
        __touchRecord,
    } = this;

    const {
        container,
    } = targets;

    this.__addEvent(container, 'touchstart', (evt) => {
        if (this.__isDrag) return;

        const { __timerID, movement } = this;

        // stop scrolling but keep movement for overscrolling
        cancelAnimationFrame(__timerID.scrollTo);
        if (!this.__willOverscroll('x')) movement.x = 0;
        if (!this.__willOverscroll('y')) movement.y = 0;

        // start records
        __touchRecord.track(evt);
        this.__autoLockMovement();
    });

    this.__addEvent(container, 'touchmove', (evt) => {
        if (this.__isDrag) return;
        if (activeScrollbar && activeScrollbar !== this) return;

        __touchRecord.update(evt);

        let { x, y } = __touchRecord.getDelta();

        if (this.__shouldPropagateMovement(x, y)) {
            return this.__updateThrottle();
        }

        const { movement, MAX_OVERSCROLL, options } = this;

        if (movement.x && this.__willOverscroll('x', x)) {
            let factor = 2;

            if (options.overscrollEffect === 'bounce') {
                factor += Math.abs(10 * movement.x / MAX_OVERSCROLL);
            }

            if (Math.abs(movement.x) >= MAX_OVERSCROLL) {
                x = 0;
            } else {
                x /= factor;
            }
        }
        if (movement.y && this.__willOverscroll('y', y)) {
            let factor = 2;

            if (options.overscrollEffect === 'bounce') {
                factor += Math.abs(10 * movement.y / MAX_OVERSCROLL);
            }

            if (Math.abs(movement.y) >= MAX_OVERSCROLL) {
                y = 0;
            } else {
                y /= factor;
            }
        }

        this.__autoLockMovement();

        evt.preventDefault();

        this.__addMovement(x, y);
        activeScrollbar = this;
    });

    this.__addEvent(container, 'touchcancel touchend', (evt) => {
        if (this.__isDrag) return;

        const { speed } = this.options;

        let { x, y } = __touchRecord.getVelocity();

        x = movementLocked.x ? 0 : Math.min(x * GLOBAL_ENV.EASING_MULTIPLIER, 1000);
        y = movementLocked.y ? 0 : Math.min(y * GLOBAL_ENV.EASING_MULTIPLIER, 1000);

        this.__addMovement(
            Math.abs(x) > MIN_VELOCITY ? (x * speed) : 0,
            Math.abs(y) > MIN_VELOCITY ? (y * speed) : 0
        );

        this.__unlockMovement();
        __touchRecord.release(evt);
        activeScrollbar = null;
    });
};

Object.defineProperty(SmoothScrollbar.prototype, '__touchHandler', {
    value: __touchHandler,
    writable: true,
    configurable: true,
});
<|endoftext|>


<commit_before>'use strict';

const { assignArray } = require('./reduce');
const { result } = require('./result');

// Similar to Lodash get(), but do not mutate, and faster
const get = function (obj, keys) {
  if (keys.length === 0) { return obj; }

  const [childKey, ...keysA] = keys;
  const child = obj[childKey];
  return get(child, keysA);
};

// Similar to Lodash set(), but do not mutate, and faster
const set = function (objArr, keys, val) {
  if (keys.length === 0) {
    return result(val, objArr, keys);
  }

  if (typeof keys[0] === 'number') {
    return setArray(objArr, keys, val);
  }

  return setObject(objArr, keys, val);
};

const setObject = function (obj = {}, keys, val) {
  const { child, childKey } = setVal({ objArr: obj, keys, val });

  return { ...obj, [childKey]: child };
};

const setArray = function (arr = [], keys, val) {
  const { child, childKey } = setVal({ objArr: arr, keys, val });

  return [
    ...arr.slice(0, childKey),
    child,
    ...arr.slice(childKey + 1),
  ];
};

const setVal = function ({ objArr, keys, val }) {
  const [childKey, ...keysA] = keys;
  const child = objArr[childKey];
  const childA = set(child, keysA, val);

  return { child: childA, childKey };
};

// Apply several set() at once, using an array of `paths`
const setAll = function (obj, paths, val) {
  return paths.reduce(
    (objA, inlineFuncPath) => set(objA, inlineFuncPath, val),
    obj,
  );
};

// Retrieves all recursive values (i.e. leaves) of an object,
// as a single array of [value, key] elements
const getAll = function (value, key = []) {
  if (value && value.constructor === Object) {
    return Object.entries(value)
      .map(([childKey, child]) => getAll(child, [...key, childKey]))
      .reduce(assignArray, []);
  }

  if (Array.isArray(value)) {
    return value
      .map((child, childKey) => getAll(child, [...key, childKey]))
      .reduce(assignArray, []);
  }

  return [[value, key]];
};

module.exports = {
  get,
  set,
  getAll,
  setAll,
};
<commit_msg>Add has() utility<commit_after>'use strict';

const { assignArray } = require('./reduce');
const { result } = require('./result');

// Similar to Lodash get(), but do not mutate, and faster
const get = function (obj, keys) {
  if (keys.length === 0) { return obj; }

  const [childKey, ...keysA] = keys;
  const child = obj[childKey];
  return get(child, keysA);
};

// Similar to Lodash set(), but do not mutate, and faster
const set = function (objArr, keys, val) {
  if (keys.length === 0) {
    return result(val, objArr, keys);
  }

  if (typeof keys[0] === 'number') {
    return setArray(objArr, keys, val);
  }

  return setObject(objArr, keys, val);
};

const setObject = function (obj = {}, keys, val) {
  const { child, childKey } = setVal({ objArr: obj, keys, val });

  return { ...obj, [childKey]: child };
};

const setArray = function (arr = [], keys, val) {
  const { child, childKey } = setVal({ objArr: arr, keys, val });

  return [
    ...arr.slice(0, childKey),
    child,
    ...arr.slice(childKey + 1),
  ];
};

const setVal = function ({ objArr, keys, val }) {
  const [childKey, ...keysA] = keys;
  const child = objArr[childKey];
  const childA = set(child, keysA, val);

  return { child: childA, childKey };
};

// Apply several set() at once, using an array of `paths`
const setAll = function (obj, paths, val) {
  return paths.reduce(
    (objA, inlineFuncPath) => set(objA, inlineFuncPath, val),
    obj,
  );
};

// Retrieves all recursive values (i.e. leaves) of an object,
// as a single array of [value, key] elements
const getAll = function (value, key = []) {
  if (value && value.constructor === Object) {
    return Object.entries(value)
      .map(([childKey, child]) => getAll(child, [...key, childKey]))
      .reduce(assignArray, []);
  }

  if (Array.isArray(value)) {
    return value
      .map((child, childKey) => getAll(child, [...key, childKey]))
      .reduce(assignArray, []);
  }

  return [[value, key]];
};

// Similar to Lodash has(), but faster
const has = function (obj, keys) {
  try {
    get(obj, keys);
  } catch (error) {
    return false;
  }

  return true;
};

module.exports = {
  get,
  set,
  getAll,
  setAll,
  has,
};
<|endoftext|>


<commit_before>/**
 * Create references
 */
var gulp = require('gulp');
var glob = require('glob');
var pkg = require('./package.json');
var common = require('./gulp/common.js');

/**
 * Auto load all gulp plugins
 */
var gulpLoadPlugins = require('gulp-load-plugins');
var plug = gulpLoadPlugins();

/**
 * Load common utilities for gulp
 */
var gutil = plug.loadUtils(['colors', 'env', 'log', 'date']);

/**
 * Could use a staging/development switch.
 * Run `gulp --staging`
 */
var type = gutil.env.staging ? 'staging' : 'development';
gutil.log('Building for', gutil.colors.magenta(type));
gutil.beep();

/**
 * Lint the code
 */
gulp.task('jshint', function () {
    var sources = [].concat(pkg.paths.js, pkg.paths.nodejs);
    return gulp.src(sources)
        .pipe(plug.jshint('./.jshintrc'))
//        .pipe(plug.jshint.reporter('default'));
        .pipe(plug.jshint.reporter('jshint-stylish'));
});

/**
 * Create $templateCache from the html templates
 */
gulp.task('templatecache', function () {
    gulp.src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.dev));
});

/**
 * Minify and bundle the JavaScript
 */
gulp.task('js', ['jshint', 'templatecache'], function () {
    var source = [].concat(pkg.paths.js, pkg.paths.dev + 'templates.js');
    return gulp.src(source)
//        .pipe(plug.size({showFiles: true}))
        .pipe(plug.sourcemaps.init())
        .pipe(plug.concat('all.min.js', {newLine: ';'}))
        // Annotate before uglify so the code get's min'd properly.
        .pipe(plug.ngAnnotate({
            // true helps add where @ngInject is not used. It infers.
            // Doesn't work with resolve, so we must be explicit there
            add: true
        }))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify({mangle: true}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(plug.sourcemaps.write('./'))
        .pipe(gulp.dest(pkg.paths.dev));
//        .pipe(plug.size({showFiles: true}));
});

/**
 * Copy the Vendor JavaScript
 */
gulp.task('vendorjs', function () {
    var source = [].concat(pkg.paths.vendorjs,
        pkg.paths.vendorjs.map(function (path) {
            return path + '.map';
        }));
    source.push('./bower_components/jquery/dist/jquery.min.map');
    return gulp.src(source)
        .pipe(gulp.dest(pkg.paths.dev + 'vendor'));
});

/**
 * Minify and bundle the CSS
 */
gulp.task('css', function () {
    return gulp.src(pkg.paths.css)
//        .pipe(plug.size({showFiles: true}))
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
//        .pipe(plug.size({showFiles: true}));
});

/**
 * Minify and bundle the Vendor CSS
 */
gulp.task('vendorcss', function () {
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
});

/**
 * Copy fonts
 */
gulp.task('fonts', function () {
    return gulp.src(pkg.paths.fonts)
        .pipe(gulp.dest(pkg.paths.dev + 'fonts'));
});

/**
 * Compress images
 */
gulp.task('images', function () {
    return gulp.src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(pkg.paths.dev + 'content/images'));
});

/**
 * Inject all the files into the new index.html
 */
gulp.task('htmlinject', ['js', 'vendorjs', 'css', 'vendorcss', 'images', 'fonts'], function () {
    var target = gulp.src('./client/index.html');
    var vjs = pkg.paths.vendorjs.map(function (path) {
        var file = path.split('/').pop();
        return pkg.paths.dev + 'vendor/' + file;
    });
    console.log(vjs);
    var sources = {
        css: gulp.src([pkg.paths.dev + 'content/all.min.css'], {read: false}),
        vendorcss: gulp.src([pkg.paths.dev + 'content/vendor.min.css'], {read: false}),
        js: gulp.src([pkg.paths.dev + 'all.min.js']),
        vendorjs: gulp.src(vjs)
    };
    var ignorePath = pkg.paths.dev.substring(1);

    target
        /** Can also use the starttag instead of name */
        /**
        .pipe(plug.inject(sources.vendorcss, {starttag: '<!-- inject:vendor:{{ext}} -->', ignorePath: ignorePath}))
        .pipe(plug.inject(sources.css, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.js, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.vendorjs, {starttag: '<!-- inject:vendor:{{ext}} -->', ignorePath: ignorePath}))
        */
        .pipe(plug.inject(sources.vendorcss, {name: 'inject-vendor', ignorePath: ignorePath}))
        .pipe(plug.inject(sources.css, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.js, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.vendorjs, {name: 'inject-vendor', ignorePath: ignorePath}))

        .pipe(gulp.dest(pkg.paths.dev));
});

/**
 * Bundle the JS, CSS, and compress images.
 * Then copy files to dev and show a toast.
 */
gulp.task('build', ['htmlinject'], function () {
    // Prepare files for dev
    return gulp.src(pkg.paths.dev)
        .pipe(plug.notify({
            onLast: true,
            message: 'linted, bundled, and images compressed!'
        }));
});

/**
 * Remove all files from the output folder
 */
gulp.task('clean', function () {
    return gulp.src([
            pkg.paths.dev
        ]).pipe(plug.clean({force: true}));
});

/**
 * Watch js files
 */
gulp.task('watchjs', function () {
    var js = ['gulpfile.js'].concat(pkg.paths.js);
    var watcher = gulp.watch(js, ['js', 'vendorjs']);

    watcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

/**
 * Watch css files
 */
gulp.task('watchcss', function () {
    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var watcher = gulp.watch(css, ['css', 'vendorcss']);

    watcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

/**
 * Watch all files
 */
gulp.task('watch', ['watchcss', 'watchjs'], function () {
});

/**
 * Run all tests
 */
gulp.task('test', function() {
    var testFiles = [
        'client/test/**.[Ss]pec.js'
    ];
    return gulp.src(testFiles)
        .pipe(plug.karma({
            configFile: pkg.paths.test + '/karma.conf.js',
            action: 'run'
        }))
        .on('error', function(err) {
            // Make sure failed tests cause gulp to exit non-zero
            throw err;
        });
});

/**
 * serve the dev environment
 */
gulp.task('dev', function () {
    plug.nodemon({
        script: 'server/server.js',
        ext: 'html js',
        env: { 'NODE_ENV': 'dev' },
        ignore: ['ignored.js'],
        nodeArgs: ['--debug=9999']
    })
        .on('change', ['jshint', 'test'])
        .on('restart', function () {
            console.log('restarted!');
        });
});

/**
 * serve the staging environment
 */
gulp.task('stage', function () {
    plug.nodemon({
        script: 'server/server.js',
        ext: 'html js',
        env: { 'NODE_ENV': 'stage' },
        ignore: ['ignored.js'],
        nodeArgs: ['--debug=9999']
    })
        .on('change', ['jshint', 'test'])
        .on('restart', function () {
            console.log('restarted!');
        });
});
<commit_msg>modular: minor gulp tweaks<commit_after>/**
 * Create references
 */
var gulp = require('gulp');
var glob = require('glob');
var pkg = require('./package.json');
var common = require('./gulp/common.js');

/**
 * Auto load all gulp plugins
 * Load common utilities for gulp
 */
var gulpLoadPlugins = require('gulp-load-plugins');
var plug = gulpLoadPlugins();
var gutil = plug.loadUtils(['colors', 'env', 'log', 'date']);

/**
 * @desc Lint the code
 */
gulp.task('jshint', function () {
    var sources = [].concat(pkg.paths.js, pkg.paths.nodejs);
    return gulp.src(sources)
        .pipe(plug.jshint('./.jshintrc'))
//        .pipe(plug.jshint.reporter('default'));
        .pipe(plug.jshint.reporter('jshint-stylish'));
});

/**
 * @desc Create $templateCache from the html templates
 */
gulp.task('templatecache', function () {
    gulp.src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.dev));
});

/**
 * @desc Add injection code for @ngInject annotations
 */
gulp.task('ngAnnotate', function () {
    gulp.src(pkg.paths.htmltemplates)
        .pipe(plug.ngAnnotate({
            // true helps add where @ngInject is not used. It infers.
            // Doesn't work with resolve, so we must be explicit there
            add: true
        }))
        .pipe(gulp.dest(pkg.paths.dev));
});

/**
 * @desc Minify and bundle the JavaScript
 */
gulp.task('js', ['jshint', 'templatecache'], function () {
    var source = [].concat(pkg.paths.js, pkg.paths.dev + 'templates.js');
    return gulp.src(source)
//        .pipe(plug.size({showFiles: true}))
        .pipe(plug.sourcemaps.init())
        .pipe(plug.concat('all.min.js', {newLine: ';'}))
        // Annotate before uglify so the code get's min'd properly.
        .pipe(plug.ngAnnotate({
            // true helps add where @ngInject is not used. It infers.
            // Doesn't work with resolve, so we must be explicit there
            add: true
        }))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify({mangle: true}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(plug.sourcemaps.write('./'))
        .pipe(gulp.dest(pkg.paths.dev));
//        .pipe(plug.size({showFiles: true}));
});

/**
 * @desc Copy the Vendor JavaScript
 */
gulp.task('vendorjs', function () {
    var source = [].concat(pkg.paths.vendorjs,
        pkg.paths.vendorjs.map(function (path) {
            return path + '.map';
        }));
    source.push('./bower_components/jquery/dist/jquery.min.map');
    return gulp.src(source)
        .pipe(gulp.dest(pkg.paths.dev + 'vendor'));
});

/**
 * @desc Minify and bundle the CSS
 */
gulp.task('css', function () {
    return gulp.src(pkg.paths.css)
//        .pipe(plug.size({showFiles: true}))
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
//        .pipe(plug.size({showFiles: true}));
});

/**
 * @desc Minify and bundle the Vendor CSS
 */
gulp.task('vendorcss', function () {
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
});

/**
 * @desc Copy fonts
 */
gulp.task('fonts', function () {
    return gulp.src(pkg.paths.fonts)
        .pipe(gulp.dest(pkg.paths.dev + 'fonts'));
});

/**
 * @desc Compress images
 */
gulp.task('images', function () {
    return gulp.src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(pkg.paths.dev + 'content/images'));
});

/**
 * @desc Inject all the files into the new index.html
 */
gulp.task('build-stage', ['js', 'vendorjs', 'css', 'vendorcss', 'images', 'fonts'], function () {
    var target = gulp.src('./client/index.html');
    var vjs = pkg.paths.vendorjs.map(function (path) {
        var file = path.split('/').pop();
        return pkg.paths.dev + 'vendor/' + file;
    });
//    console.log(vjs);
    var sources = {
        css: gulp.src([pkg.paths.dev + 'content/all.min.css'], {read: false}),
        vendorcss: gulp.src([pkg.paths.dev + 'content/vendor.min.css'], {read: false}),
        js: gulp.src([pkg.paths.dev + 'all.min.js']),
        vendorjs: gulp.src(vjs)
    };
    var ignorePath = pkg.paths.dev.substring(1);

    target
        .pipe(plug.inject(sources.vendorcss, {name: 'inject-vendor', ignorePath: ignorePath}))
        .pipe(plug.inject(sources.css, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.vendorjs, {name: 'inject-vendor', ignorePath: ignorePath}))
        .pipe(plug.inject(sources.js, {ignorePath: ignorePath}))

        .pipe(gulp.dest(pkg.paths.dev))
        .pipe(plug.notify({
            onLast: true,
            message: 'linted, bundled, and images compressed!'
        }));
});

/**
 * @desc Remove all files from the output folder
 */
gulp.task('clean', function () {
    return gulp.src([
            pkg.paths.dev
        ]).pipe(plug.clean({force: true}));
});

/**
 * @desc Watch files and build
 */
gulp.task('watchjs', function () {
    var js = ['gulpfile.js'].concat(pkg.paths.js);
    var jswatcher = gulp.watch(js, ['js', 'vendorjs']);

    jswatcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });

    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var csswatcher = gulp.watch(css, ['css', 'vendorcss']);

    csswatcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

/**
 * @desc Run all tests
 */
gulp.task('test', function() {
    var testFiles = [
        'client/test/**.[Ss]pec.js'
    ];
    return gulp.src(testFiles)
        .pipe(plug.karma({
            configFile: pkg.paths.test + '/karma.conf.js',
            action: 'run'
        }))
        .on('error', function(err) {
            // Make sure failed tests cause gulp to exit non-zero
            throw err;
        });
});

/**
 * serve the dev environment
 */
gulp.task('dev', function () {
    plug.nodemon({
        script: 'server/server.js',
        delayTime: 1,
        ext: 'html js',
        env: { 'NODE_ENV': 'dev' },
        ignore: ['build/'],
        nodeArgs: ['--debug=9999']
    })
        .on('change', ['jshint', 'test'])
        .on('restart', function () {
            console.log('restarted!');
        });
});

/**
 * serve the staging environment
 */
gulp.task('stage', function () {
    plug.nodemon({
        script: 'server/server.js',
        delayTime: 1,
        ext: 'html js',
        env: { 'NODE_ENV': 'stage' },
        ignore: ['build/'],
        nodeArgs: ['--debug=9999']
    })
        .on('change', ['jshint', 'test'])
        .on('restart', function () {
            console.log('restarted!');
        });
});
<|endoftext|>


<commit_before>define([

  'Backbone',

  //Model
  'app/models/project',

  //Collection
  'app/collections/projects',

  //View
  'app/views/taskController',
  'app/views/projectsController',
  'app/views/filterController',
  'app/views/gameController',

  //Templates
  'text!templates/project-page/gamePageTemplate.html',
  'text!templates/project-page/errorTemplate.html'

], function(

  Backbone,

  //Model
  Project,

  //Collection
  Projects,

  //Views
  taskController,
  projectsController,
  filterController,
  gameController,

  //Templates
  gamePageTemplate,
  errorTemplate
){

  var ProjectManager = Backbone.View.extend({

    template: _.template(gamePageTemplate),
    errorTemplate: _.template(errorTemplate),

    model: new Project(),

    initialize: function(){
      this.model.clear({silent: true}).off();
      this.model.bind('change:error', this.error, this);
      this.model.bind('change:name', this.render, this);

      this.model.fetch({data: {id: this.options.projectId}});

      this.projectsList = new projectsController({
        collection: new Projects(),
        router: this.options.router
      });

      this.games = new gameController({
        projectId: this.options.projectId
      });

      this.taskList = new taskController({
        projectId: this.options.projectId
      });

      this.filter = new filterController({
        collection: this.taskList.collection
      });
    },

    error: function(){
      var message = this.model.get('error');
      this.$el.html(this.errorTemplate({message: message}));
    },

    render: function(){
      this.$el.html(this.template({project: {name: this.model.get('name')}}));
      this.taskList.setElement('.js-taskList');
      this.taskList.collection.fetch();

      if(!$('.projects-list li')[0]){
        this.projectsList.setElement('.projects-list').start();
      }

      this.filter.setElement('.fn-filter-task');
      this.games.setElement('.js-game-list');
    }
  });

  return ProjectManager;

});
<commit_msg>Send project id on GET request for games<commit_after>define([

  'Backbone',

  //Model
  'app/models/project',

  //Collection
  'app/collections/projects',

  //View
  'app/views/taskController',
  'app/views/projectsController',
  'app/views/filterController',
  'app/views/gameController',

  //Templates
  'text!templates/project-page/gamePageTemplate.html',
  'text!templates/project-page/errorTemplate.html'

], function(

  Backbone,

  //Model
  Project,

  //Collection
  Projects,

  //Views
  taskController,
  projectsController,
  filterController,
  gameController,

  //Templates
  gamePageTemplate,
  errorTemplate
){

  var ProjectManager = Backbone.View.extend({

    template: _.template(gamePageTemplate),
    errorTemplate: _.template(errorTemplate),

    model: new Project(),

    initialize: function(){
      this.model.clear({silent: true}).off();
      this.model.bind('change:error', this.error, this);
      this.model.bind('change:name', this.render, this);

      this.model.fetch({data: {id: this.options.projectId}});

      this.projectsList = new projectsController({
        collection: new Projects(),
        router: this.options.router
      });

      this.games = new gameController({
        projectId: this.options.projectId
      });

      this.taskList = new taskController({
        projectId: this.options.projectId
      });

      this.filter = new filterController({
        collection: this.taskList.collection
      });
    },

    error: function(){
      var message = this.model.get('error');
      this.$el.html(this.errorTemplate({message: message}));
    },

    render: function(){
      this.$el.html(this.template({project: {name: this.model.get('name')}}));
      this.taskList.setElement('.js-taskList');
      this.filter.setElement('.fn-filter-task');
      this.games.setElement('.js-game-list');

      this.taskList.collection.fetch();
      this.games.collection.fetch({data: {project_id: this.options.projectId}});

      if(!$('.projects-list li')[0]){
        this.projectsList.setElement('.projects-list').start();
      }

    }
  });

  return ProjectManager;

});
<|endoftext|>


<commit_before>'use strict';

var fs                          = require('fs');
var path                        = require('path');
var mkdirp                      = require('mkdirp')
const uuidv1                    = require('uuid/v1');
var crypto                      = require('crypto');
var sqlite3                     = require('sqlite3');
var os                          = require('os')
var perf                        = require('./perf')
var db_helper                   = require("./db_helper")
var isBinaryFile                = require("isbinaryfile");
var userData
var childProcessName
var nextCallId = 0

var inProcessFilesFn                    = false;
var isWin                               = /^win/.test(process.platform);
var numberOfSecondsIndexFilesInterval   = 5;
var inScan                              = false;
var stmt2                               = null;
var stmt3                               = null;
var setIn                               = null;
var updateProcessTable                  = null;
var lockData                            = null;
var unlockData                          = null;
var inGetRelatedDocumentHashes          = false;
var inIndexFileRelationshipsFn          = false;
var finishedFindingFolders              = false;
var username                            = "Unknown user";
var dbsearch;
var xdiff;
var lhs;
var rhs;
var stmtInsertIntoRelationships;
var stmtUpdateRelationships2;

var stmtUpdateFolder;
var stmtResetFolders;
var stmtInsertDriver;
var stmtUpdateDriver;
var stmtInsertIntoQueries;

var stmtResetFiles;
var stmtFileChanged;
var stmtInsertIntoMessages;
var stmtInsertIntoFiles;
var stmtInsertIntoFiles2;
var stmtUpdateFileStatus;
var stmtUpdateFileSizeAndShaAndConnectionId;
var stmtUpdateFileProperties;

var stmtInsertIntoContents;
var stmtInsertIntoFolders;
var stmtInsertIntoConnections;
var stmtInsertIntoConnections2;

var stmtInsertIntoIntranetClientConnects;

var stmtInsertInsertIntoQueries;
var stmtUpdateRelatedDocumentCount;
var stmtUpdateRelationships;

var incrJobCount;

var decrJobCount;

var in_when_queries_changes             = false;
var in_when_connections_change          = false;

username = os.userInfo().username.toLowerCase();
//console.log(username);

//dbsearch.run("PRAGMA synchronous=OFF;")
//dbsearch.run("PRAGMA count_changes=OFF;")
//dbsearch.run("PRAGMA journal_mode=MEMORY;")
//dbsearch.run("PRAGMA temp_store=MEMORY;")

processMessagesFromMainProcess();

function processMessagesFromMainProcess() {
    process.on('message', (msg) => {

    if  (msg.message_type == 'init') {

        //console.log('-- Init v3');
        userData            = msg.user_data_path
        childProcessName    = msg.child_process_name

        //console.log("  Child recieved user data path: " + userData)
        var dbPath = path.join(userData, username + '.visi')

        //console.log("  DB path: " + dbPath)
        dbsearch = new sqlite3.Database(dbPath);
        dbsearch.run("PRAGMA journal_mode=WAL;")
        process.send({  message_type:       "database_setup_in_child" ,
                        child_process_name:  childProcessName
                        });

        setUpSql()

        } else if (msg.message_type == 'setUpSql') {

             //console.log(" --- setUpSql --- ")
             setUpSql();

     } else if (msg.message_type == "function_call_response") {

         //console.log("*) Response received at Scheduler ")
         //console.log("*) result generated by call ID: " + msg.called_call_id)
         var callDetails = callList[msg.called_call_id]
         //console.log("*) call details: " + JSON.stringify(msg,null,2))

         if (callDetails == null) {
            console.log("In Scheduler:function_call_response   callList    is not set for : " + JSON.stringify(msg,null,2))
            return
         }
         var parentCallId = callDetails.parent_call_id
         //console.log("*) parent call ID: " + JSON.stringify(parentCallId,null,2))

         var processName
         if (parentCallId == -1) {
             processName = "forked"
         } else {
             var parentCallDetails = callList[parentCallId]
             //console.log("*) parent call details: " + JSON.stringify(parentCallDetails,null,2))
             //console.log("*) Response: " + JSON.stringify(msg.result,null,2))
             processName = parentCallDetails.process_name
         }

         //console.log("msg.callback_index returned: " + msg.callback_index)
         process.send({     message_type:       "return_response_to_function_caller" ,
                            child_process_name:  processName,
                            callback_index:      msg.callback_index,
                            result:              msg.result
                        });

     } else if (msg.message_type == "processor_free") {

        processesInUse[msg.child_process_name] = false

        dbsearch.serialize(
            function() {
                dbsearch.run("begin exclusive transaction");
                decrJobCount.run(msg.child_process_name)
                dbsearch.run("commit");
            })

     } else if (msg.message_type == "function_call_request") {

        if (msg.find_component.driver_name && msg.find_component.method_name) {
            dbsearch.serialize(
                function() {
                    var stmt = dbsearch.all(
                      "SELECT * FROM system_code where base_component_id = ? and on_condition like '%" +
                        msg.find_component.method_name + "%' and code_tag = 'LATEST'; ",

                       msg.find_component.driver_name,

                        function(err, results)
                        {
                            if (results) {
                               scheduleJobWithCodeId(  results[0].id,
                                                       msg.args,
                                                       msg.caller_call_id,
                                                       msg.callback_index)
                                //callbackFn(results[0].id);
                            } else {
                                //callbackFn(null)
                            }

                        })
            }, sqlite3.OPEN_READONLY)

        } else if (msg.find_component.code_id) {
                       scheduleJobWithCodeId(  msg.find_component.code_id,
                                               msg.args,
                                               msg.caller_call_id,
                                               msg.callback_index)

        } else if (msg.find_component.base_component_id) {
                    dbsearch.serialize(
                        function() {
                            var stmt = dbsearch.all(
                              "SELECT * FROM system_code where base_component_id = ? and code_tag = 'LATEST'; ",

                               msg.find_component.base_component_id,

                                function(err, results)
                                {
                                    if (results && (results.length > 0)) {
                                        console.log("msg.find_component.base_component_id: " + msg.find_component.base_component_id  + " = " + results[0].id)
                                       scheduleJobWithCodeId(  results[0].id,
                                                               msg.args,
                                                               msg.caller_call_id,
                                                               msg.callback_index)
                                        //callbackFn(results[0].id);
                                    } else {
                                        //callbackFn(null)
                                    }

                                })
                    }, sqlite3.OPEN_READONLY)
                    }

        } else if (msg.message_type == 'startNode') {

             //console.log(" --- Started Node --- ")
             //console.log("     Node ID: " + msg.node_id)
             //console.log("     Process ID: " + msg.child_process_id)
             //console.log("     Started: " + msg.started)
             processesInUse[msg.node_id] = false
             dbsearch.serialize(
                 function() {
                     dbsearch.run("begin exclusive transaction");
                     updateProcessTable.run(
                         msg.node_id,
                         msg.child_process_id,
                         msg.started,
                         "IDLE",
                         null
                         )
                     dbsearch.run("commit");
                 })

        }

    });
}

//-----------------------------------------------------------------------------------------//
//                                                                                //
//                                        setUpSql                                         //
//                                                                                //
//   This sets up the SqlLite prepared statements                                          //
//                                                                                //
//                                                                                //
//                                                                                //
//                                                                                //
//                                                                                //
//                                                                                //
//-----------------------------------------------------------------------------------------//
function setUpSql() {

    incrJobCount = dbsearch.prepare("UPDATE system_process_info SET status = 'RUNNING', last_driver = ?, last_event = ?, system_code_id = ? WHERE process = ?");

    decrJobCount = dbsearch.prepare("UPDATE system_process_info SET status = 'IDLE' WHERE process = ?");

    updateProcessTable = dbsearch.prepare(
        " insert or replace into "+
        "     system_process_info (process, process_id, running_since, status, job_priority) " +
        " values " +
        "     (?,?,?,?,?)"
    )

    lockData = dbsearch.prepare("UPDATE all_data SET status = 'LOCKED' WHERE id = ?");

    unlockData = dbsearch.prepare("UPDATE all_data SET status = NULL WHERE id = ?");

}

function driversFn(callbackFn) {
    dbsearch.serialize(
        function() {
            var stmt = dbsearch.all(
                "SELECT * FROM drivers",

                function(err, results) {
                    callbackFn( results );
                })
    }, sqlite3.OPEN_READONLY)
}

var functions = new Object()

function init() {
    parseEvents()

    setInterval( findNextJobToRun, 1000)
}

function parseEvents() {

    //console.log("function(executeCode) {")
    parseAllEvents()

}

var inScheduleCode2 = false;
function findNextJobToRun() {
    if (inScheduleCode2) {
        return
    }
    inScheduleCode2 = true

    var code_id = null

    for (var ff = 0; ff < eventList.length; ff++) {
        var cond = eventList[ff]
        code_id = cond.id
        if (cond.condType == "query") {
            testQueryToExecute(cond, code_id)

        }
    }
    inScheduleCode2 = false

}

function testQueryToExecute(cond, code_id) {
    if (cond.condition.where) {
        dbsearch.serialize(
            function() {
                var stmt = dbsearch.all(
                    `select
                         count( process ) as cnt_max
                     from
                         system_process_info
                     where
                         system_code_id = ?
                     and
                         status = 'RUNNING'
                    `
                    ,
                    code_id
                    ,
                    function(err, results)
                    {
                        if (err) {
                            console.log("err: " + err)
                        } else {
                            //console.log("")
                            //console.log(JSON.stringify(cond,null,2))
                            //console.log("Process count    :" + JSON.stringify(results[0].cnt_max,null,2))
                            //console.log("Process count max:" + JSON.stringify(cond.max_processes,null,2))
                            //console.log("")
                            if (cond.max_processes && (results[0].cnt_max >= cond.max_processes)) {
                            } else {
                                //console.log("*) Executing SQlite: " + cond.condition.where)
                                dbsearch.serialize(
                                    function() {
                                        var stmt = dbsearch.all(
                                            "SELECT * FROM all_data where " +  cond.condition.where + " and status is NULL LIMIT 1",

                                            function(err, results)
                                            {
                                                if (results) {
                                                    if (results.length > 0) {

                                                        dbsearch.serialize(
                                                            function() {
                                                                dbsearch.run("begin exclusive transaction");
                                                                lockData.run(results[0].id)
                                                                dbsearch.run("commit",
                                                                    function() {

                                                                        //console.log("*) INIT -  starting the first job")
                                                                        scheduleJobWithCodeId(  code_id,  results,  null, null )
                                                                        inScheduleCode2 = false
                                                                    });
                                                                })

                                                    }
                                                } else {
                                                    inScheduleCode2 = false
                                                }
                                            })
                                }, sqlite3.OPEN_READONLY)
                            }
                        }
                    })
        }, sqlite3.OPEN_READONLY)
        //console.log("testQueryToExecute: " + JSON.stringify(cond,null,2))

    }
}

var processesInUse = new Object()

var tryAgain = true
function scheduleJobWithCodeId(codeId, args,  parentCallId, callbackIndex) {

    var processToUse = null
    var processNames = Object.keys(processesInUse)

    for( var processNameIndex = 0 ; processNameIndex < processNames.length; processNameIndex ++) {

        var actualProcessName   = processNames[ processNameIndex ]
        var isInUse             = processesInUse[ actualProcessName ]

        //console.log(" select * from system_process_info    ")
        //console.log("    " + JSON.stringify(results,null,2))

        if ( !isInUse ) {
            processToUse = actualProcessName
            processesInUse[actualProcessName] = true
            //console.log("    " + JSON.stringify(processToUse,null,2))
            sendJobToProcessName(codeId, args, actualProcessName, parentCallId, callbackIndex)
            break
        }
    }
    if (!processToUse) {
        console.log("Could not find a process to use for " + codeId)
        if (tryAgain) {
            console.log("Retry in 2 seconds ..." )
            setTimeout(function() {
                scheduleJobWithCodeId(codeId, args,  parentCallId, callbackIndex)
            },2000)
        }
    }
}

function sendToProcess(  id  ,  parentCallId  ,  callbackIndex, processName  ,  base_component_id ,  on_condition  ,  args) {

    var newCallId = nextCallId ++

    callList[  newCallId  ] = {     process_name:       processName,
                                    parent_call_id:     parentCallId        }
    dbsearch.serialize(
        function() {
            dbsearch.run("begin exclusive transaction");
            incrJobCount.run( base_component_id, on_condition, id, processName )
            dbsearch.run("commit");

           process.send({  message_type:       "execute_code_in_exe_child_process" ,
                           child_process_name:  processName,
                           code_id:             id,
                           args:                args,
                           call_id:             newCallId,
                           callback_index:      callbackIndex,
                           on_condition:        on_condition,
                           base_component_id:   base_component_id
                           });

        })
}

var callList = new Object
function sendJobToProcessName(id, args, processName, parentCallId, callbackIndex) {

    dbsearch.serialize(
        function() {
            var stmt = dbsearch.all(
                "SELECT base_component_id, on_condition FROM system_code where id = ? LIMIT 1",
                id,

                function(err, results)
                {
                    if (results) {
                        if (results.length > 0) {

                            sendToProcess(  id,
                                            parentCallId,
                                            callbackIndex,
                                            processName,
                                            results[0].base_component_id,
                                            results[0].on_condition,
                                            args)

                        }
                    }
                })
    }, sqlite3.OPEN_READONLY)

    }

function parseAllEvents( ) {

    dbsearch.serialize(
        function() {
            var stmt = dbsearch.all(
                "SELECT id, on_condition, max_processes FROM system_code; ",

                function(err, results)
                {
                    if (results) {
                        for (var tt = 0; tt < results.length; tt ++) {

                            var cond = results[tt].on_condition
                            try {
                                var evaledCond = eval("(" +  cond + ")")
                                saveEvent(evaledCond, results[tt].id, results[tt].max_processes)
                                //console.log("")
                            } catch (err) {
                                console.log("Error in: "+ cond)
                                console.log(err)
                            }

                        }

                    }

                })
    }, sqlite3.OPEN_READONLY)
}

var eventList = []

function saveEvent(cond, id, maxP) {
    var typeCond =  (typeof cond)
    var saveType = null

    if (typeCond == "string") {
        saveType = "method"

    } else if (typeCond == "object") {
        saveType = "query"

    }
    //console.log("*) type: " + saveType)

    eventList.push({condType:       saveType,
                    condition:      cond,
                    max_processes:  maxP,
                    id:             id})

}

process.on('exit', function(err) {
    shutdownExeProcess(err);
  });
process.on('quit', function(err) {
  shutdownExeProcess(err);
});

function shutdownExeProcess(err) {
    console.log("** Scheduler process was killed: " )
    if (err) {
        console.log("    : " + err)
    }

    if (dbsearch) {
        dbsearch.run("PRAGMA wal_checkpoint;")
    }
}
<commit_msg>Added debug checks<commit_after>'use strict';

var fs                          = require('fs');
var path                        = require('path');
var mkdirp                      = require('mkdirp')
const uuidv1                    = require('uuid/v1');
var crypto                      = require('crypto');
var sqlite3                     = require('sqlite3');
var os                          = require('os')
var perf                        = require('./perf')
var db_helper                   = require("./db_helper")
var isBinaryFile                = require("isbinaryfile");
var userData
var childProcessName
var nextCallId = 0

var inProcessFilesFn                    = false;
var isWin                               = /^win/.test(process.platform);
var numberOfSecondsIndexFilesInterval   = 5;
var inScan                              = false;
var stmt2                               = null;
var stmt3                               = null;
var setIn                               = null;
var updateProcessTable                  = null;
var lockData                            = null;
var unlockData                          = null;
var inGetRelatedDocumentHashes          = false;
var inIndexFileRelationshipsFn          = false;
var finishedFindingFolders              = false;
var username                            = "Unknown user";
var dbsearch;
var xdiff;
var lhs;
var rhs;
var stmtInsertIntoRelationships;
var stmtUpdateRelationships2;

var stmtUpdateFolder;
var stmtResetFolders;
var stmtInsertDriver;
var stmtUpdateDriver;
var stmtInsertIntoQueries;

var stmtResetFiles;
var stmtFileChanged;
var stmtInsertIntoMessages;
var stmtInsertIntoFiles;
var stmtInsertIntoFiles2;
var stmtUpdateFileStatus;
var stmtUpdateFileSizeAndShaAndConnectionId;
var stmtUpdateFileProperties;

var stmtInsertIntoContents;
var stmtInsertIntoFolders;
var stmtInsertIntoConnections;
var stmtInsertIntoConnections2;

var stmtInsertIntoIntranetClientConnects;

var stmtInsertInsertIntoQueries;
var stmtUpdateRelatedDocumentCount;
var stmtUpdateRelationships;

var incrJobCount;

var decrJobCount;

var in_when_queries_changes             = false;
var in_when_connections_change          = false;

username = os.userInfo().username.toLowerCase();
//console.log(username);

//dbsearch.run("PRAGMA synchronous=OFF;")
//dbsearch.run("PRAGMA count_changes=OFF;")
//dbsearch.run("PRAGMA journal_mode=MEMORY;")
//dbsearch.run("PRAGMA temp_store=MEMORY;")

processMessagesFromMainProcess();

function processMessagesFromMainProcess() {
    process.on('message', (msg) => {

    if  (msg.message_type == 'init') {

        //console.log('-- Init v3');
        userData            = msg.user_data_path
        childProcessName    = msg.child_process_name

        //console.log("  Child recieved user data path: " + userData)
        var dbPath = path.join(userData, username + '.visi')

        //console.log("  DB path: " + dbPath)
        dbsearch = new sqlite3.Database(dbPath);
        dbsearch.run("PRAGMA journal_mode=WAL;")
        process.send({  message_type:       "database_setup_in_child" ,
                        child_process_name:  childProcessName
                        });

        setUpSql()

        } else if (msg.message_type == 'setUpSql') {

             //console.log(" --- setUpSql --- ")
             setUpSql();

     } else if (msg.message_type == "function_call_response") {

         //console.log("*) Response received at Scheduler ")
         //console.log("*) result generated by call ID: " + msg.called_call_id)
         var callDetails = callList[msg.called_call_id]
         //console.log("*) call details: " + JSON.stringify(msg,null,2))

         if (callDetails == null) {
            console.log("In Scheduler:function_call_response   callList    is not set for : " + JSON.stringify(msg,null,2))
            return
         }
         var parentCallId = callDetails.parent_call_id
         //console.log("*) parent call ID: " + JSON.stringify(parentCallId,null,2))

         var processName
         if (parentCallId == -1) {
             processName = "forked"
         } else {
             var parentCallDetails = callList[parentCallId]
             //console.log("*) parent call details: " + JSON.stringify(parentCallDetails,null,2))
             //console.log("*) Response: " + JSON.stringify(msg.result,null,2))
             processName = parentCallDetails.process_name
         }

         //console.log("msg.callback_index returned: " + msg.callback_index)
         process.send({     message_type:       "return_response_to_function_caller" ,
                            child_process_name:  processName,
                            callback_index:      msg.callback_index,
                            result:              msg.result
                        });

     } else if (msg.message_type == "processor_free") {

        processesInUse[msg.child_process_name] = false

        dbsearch.serialize(
            function() {
                dbsearch.run("begin exclusive transaction");
                decrJobCount.run(msg.child_process_name)
                dbsearch.run("commit");
            })

     } else if (msg.message_type == "function_call_request") {

        if (msg.find_component.driver_name && msg.find_component.method_name) {
            dbsearch.serialize(
                function() {
                    var stmt = dbsearch.all(
                      "SELECT * FROM system_code where base_component_id = ? and on_condition like '%" +
                        msg.find_component.method_name + "%' and code_tag = 'LATEST'; ",

                       msg.find_component.driver_name,

                        function(err, results)
                        {
                            if (results && (results.length > 0)) {
                               scheduleJobWithCodeId(  results[0].id,
                                                       msg.args,
                                                       msg.caller_call_id,
                                                       msg.callback_index)
                                //callbackFn(results[0].id);
                            } else {
                                //callbackFn(null)
                            }

                        })
            }, sqlite3.OPEN_READONLY)

        } else if (msg.find_component.code_id) {
                       scheduleJobWithCodeId(  msg.find_component.code_id,
                                               msg.args,
                                               msg.caller_call_id,
                                               msg.callback_index)

        } else if (msg.find_component.base_component_id) {
            console.log("In msg.find_component.base_component_id")
                    dbsearch.serialize(
                        function() {
                            var stmt = dbsearch.all(
                              "SELECT * FROM system_code where base_component_id = ? and code_tag = 'LATEST'; ",

                               msg.find_component.base_component_id,

                                function(err, results)
                                {
                                    if (results && (results.length > 0)) {
                                        console.log("    msg.find_component.base_component_id: " + msg.find_component.base_component_id  + " = " + results[0].id)
                                       scheduleJobWithCodeId(  results[0].id,
                                                               msg.args,
                                                               msg.caller_call_id,
                                                               msg.callback_index)
                                        //callbackFn(results[0].id);
                                    } else {
                                        console.log("    msg.find_component.base_component_id: Could not find " +   msg.find_component.base_component_id)
                                    }

                                })
                    }, sqlite3.OPEN_READONLY)
                    }

        } else if (msg.message_type == 'startNode') {

             //console.log(" --- Started Node --- ")
             //console.log("     Node ID: " + msg.node_id)
             //console.log("     Process ID: " + msg.child_process_id)
             //console.log("     Started: " + msg.started)
             processesInUse[msg.node_id] = false
             dbsearch.serialize(
                 function() {
                     dbsearch.run("begin exclusive transaction");
                     updateProcessTable.run(
                         msg.node_id,
                         msg.child_process_id,
                         msg.started,
                         "IDLE",
                         null
                         )
                     dbsearch.run("commit");
                 })

        }

    });
}

//-----------------------------------------------------------------------------------------//
//                                                                                //
//                                        setUpSql                                         //
//                                                                                //
//   This sets up the SqlLite prepared statements                                          //
//                                                                                //
//                                                                                //
//                                                                                //
//                                                                                //
//                                                                                //
//                                                                                //
//-----------------------------------------------------------------------------------------//
function setUpSql() {

    incrJobCount = dbsearch.prepare("UPDATE system_process_info SET status = 'RUNNING', last_driver = ?, last_event = ?, system_code_id = ? WHERE process = ?");

    decrJobCount = dbsearch.prepare("UPDATE system_process_info SET status = 'IDLE' WHERE process = ?");

    updateProcessTable = dbsearch.prepare(
        " insert or replace into "+
        "     system_process_info (process, process_id, running_since, status, job_priority) " +
        " values " +
        "     (?,?,?,?,?)"
    )

    lockData = dbsearch.prepare("UPDATE all_data SET status = 'LOCKED' WHERE id = ?");

    unlockData = dbsearch.prepare("UPDATE all_data SET status = NULL WHERE id = ?");

}

function driversFn(callbackFn) {
    dbsearch.serialize(
        function() {
            var stmt = dbsearch.all(
                "SELECT * FROM drivers",

                function(err, results) {
                    callbackFn( results );
                })
    }, sqlite3.OPEN_READONLY)
}

var functions = new Object()

function init() {
    parseEvents()

    setInterval( findNextJobToRun, 1000)
}

function parseEvents() {

    //console.log("function(executeCode) {")
    parseAllEvents()

}

var inScheduleCode2 = false;
function findNextJobToRun() {
    if (inScheduleCode2) {
        return
    }
    inScheduleCode2 = true

    var code_id = null

    for (var ff = 0; ff < eventList.length; ff++) {
        var cond = eventList[ff]
        code_id = cond.id
        if (cond.condType == "query") {
            testQueryToExecute(cond, code_id)

        }
    }
    inScheduleCode2 = false

}

function testQueryToExecute(cond, code_id) {
    if (cond.condition.where) {
        dbsearch.serialize(
            function() {
                var stmt = dbsearch.all(
                    `select
                         count( process ) as cnt_max
                     from
                         system_process_info
                     where
                         system_code_id = ?
                     and
                         status = 'RUNNING'
                    `
                    ,
                    code_id
                    ,
                    function(err, results)
                    {
                        if (err) {
                            console.log("err: " + err)
                        } else {
                            //console.log("")
                            //console.log(JSON.stringify(cond,null,2))
                            //console.log("Process count    :" + JSON.stringify(results[0].cnt_max,null,2))
                            //console.log("Process count max:" + JSON.stringify(cond.max_processes,null,2))
                            //console.log("")
                            if (cond.max_processes && (results[0].cnt_max >= cond.max_processes)) {
                            } else {
                                //console.log("*) Executing SQlite: " + cond.condition.where)
                                dbsearch.serialize(
                                    function() {
                                        var stmt = dbsearch.all(
                                            "SELECT * FROM all_data where " +  cond.condition.where + " and status is NULL LIMIT 1",

                                            function(err, results)
                                            {
                                                if (results) {
                                                    if (results.length > 0) {

                                                        dbsearch.serialize(
                                                            function() {
                                                                dbsearch.run("begin exclusive transaction");
                                                                lockData.run(results[0].id)
                                                                dbsearch.run("commit",
                                                                    function() {

                                                                        //console.log("*) INIT -  starting the first job")
                                                                        scheduleJobWithCodeId(  code_id,  results,  null, null )
                                                                        inScheduleCode2 = false
                                                                    });
                                                                })

                                                    }
                                                } else {
                                                    inScheduleCode2 = false
                                                }
                                            })
                                }, sqlite3.OPEN_READONLY)
                            }
                        }
                    })
        }, sqlite3.OPEN_READONLY)
        //console.log("testQueryToExecute: " + JSON.stringify(cond,null,2))

    }
}

var processesInUse = new Object()

var tryAgain = true
function scheduleJobWithCodeId(codeId, args,  parentCallId, callbackIndex) {

    var processToUse = null
    var processNames = Object.keys(processesInUse)

    for( var processNameIndex = 0 ; processNameIndex < processNames.length; processNameIndex ++) {

        var actualProcessName   = processNames[ processNameIndex ]
        var isInUse             = processesInUse[ actualProcessName ]

        //console.log(" select * from system_process_info    ")
        //console.log("    " + JSON.stringify(results,null,2))

        if ( !isInUse ) {
            processToUse = actualProcessName
            processesInUse[actualProcessName] = true
            //console.log("    " + JSON.stringify(processToUse,null,2))
            sendJobToProcessName(codeId, args, actualProcessName, parentCallId, callbackIndex)
            break
        }
    }
    if (!processToUse) {
        console.log("Could not find a process to use for " + codeId)
        if (tryAgain) {
            console.log("Retry in 2 seconds ..." )
            setTimeout(function() {
                scheduleJobWithCodeId(codeId, args,  parentCallId, callbackIndex)
            },2000)
        }
    }
}

function sendToProcess(  id  ,  parentCallId  ,  callbackIndex, processName  ,  base_component_id ,  on_condition  ,  args) {

    var newCallId = nextCallId ++

    callList[  newCallId  ] = {     process_name:       processName,
                                    parent_call_id:     parentCallId        }
    dbsearch.serialize(
        function() {
            dbsearch.run("begin exclusive transaction");
            incrJobCount.run( base_component_id, on_condition, id, processName )
            dbsearch.run("commit");

           process.send({  message_type:       "execute_code_in_exe_child_process" ,
                           child_process_name:  processName,
                           code_id:             id,
                           args:                args,
                           call_id:             newCallId,
                           callback_index:      callbackIndex,
                           on_condition:        on_condition,
                           base_component_id:   base_component_id
                           });

        })
}

var callList = new Object
function sendJobToProcessName(id, args, processName, parentCallId, callbackIndex) {

    dbsearch.serialize(
        function() {
            var stmt = dbsearch.all(
                "SELECT base_component_id, on_condition FROM system_code where id = ? LIMIT 1",
                id,

                function(err, results)
                {
                    if (results) {
                        if (results.length > 0) {

                            sendToProcess(  id,
                                            parentCallId,
                                            callbackIndex,
                                            processName,
                                            results[0].base_component_id,
                                            results[0].on_condition,
                                            args)

                        }
                    }
                })
    }, sqlite3.OPEN_READONLY)

    }

function parseAllEvents( ) {

    dbsearch.serialize(
        function() {
            var stmt = dbsearch.all(
                "SELECT id, on_condition, max_processes FROM system_code; ",

                function(err, results)
                {
                    if (results) {
                        for (var tt = 0; tt < results.length; tt ++) {

                            var cond = results[tt].on_condition
                            try {
                                var evaledCond = eval("(" +  cond + ")")
                                saveEvent(evaledCond, results[tt].id, results[tt].max_processes)
                                //console.log("")
                            } catch (err) {
                                console.log("Error in: "+ cond)
                                console.log(err)
                            }

                        }

                    }

                })
    }, sqlite3.OPEN_READONLY)
}

var eventList = []

function saveEvent(cond, id, maxP) {
    var typeCond =  (typeof cond)
    var saveType = null

    if (typeCond == "string") {
        saveType = "method"

    } else if (typeCond == "object") {
        saveType = "query"

    }
    //console.log("*) type: " + saveType)

    eventList.push({condType:       saveType,
                    condition:      cond,
                    max_processes:  maxP,
                    id:             id})

}

process.on('exit', function(err) {
    shutdownExeProcess(err);
  });
process.on('quit', function(err) {
  shutdownExeProcess(err);
});

function shutdownExeProcess(err) {
    console.log("** Scheduler process was killed: " )
    if (err) {
        console.log("    : " + err)
    }

    if (dbsearch) {
        dbsearch.run("PRAGMA wal_checkpoint;")
    }
}
<|endoftext|>


<commit_before>//Constants for the different creeps' Bodies that auto spawn
//Tier 1
var hBody = [WORK, CARRY, CARRY, MOVE, MOVE];
var uBody = [WORK, CARRY, CARRY, CARRY, MOVE];
var bBody = [WORK, CARRY, WORK, MOVE];
var rBody = [WORK, WORK, CARRY, MOVE];

//Tier 2
var h2Body = [WORK, WORK, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE];
var u2Body = [WORK, WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE];
var b2Body = [WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE];
var r2Body = [WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE];

//Tier 3
var h3Body = [WORK, WORK, CARRY, CARRY, CARRY, CARRY,CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE];
var u3Body = [WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE];
var b3Body = [WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE];
var r3Body = [WORK, WORK, WORK, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE];

//Tier4
var haulerBody = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,ATTACK];
var feederBody = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,WORK];
var minerBody = [WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,CARRY,CARRY,MOVE];
var u4Body = [WORK, WORK, WORK, WORK, WORK, WORK, WORK, CARRY, MOVE];

//Object that holds a getter for these body types
var bodyObj = {
  //getter that useses a lot of switch statement to return the appropriate body array for the given role and tier
  getBody:function(role,tier){
      if(role==='harvester'){
        switch(tier){
          default:
            return hBody;
          case 2:
            return h2Body;
          case 3:
          case 4:
            return h3Body;
        }
      }else if(role === 'upgrader'){
        switch(tier){
          default:
            return uBody;
          case 2:
            return u2Body;
          case 3:
            return u3Body;
          case 4:
            return u4Body;
        }
      }else if(role === 'builder'){
        switch(tier){
          default:
            return bBody;
          case 2:
            return b2Body;
          case 3:
          case 4:
            return b3Body;
        }
      }else if(role === 'repair'){
        switch(tier){
          default:
            return rBody;
          case 2:
            return r2Body;
          case 3:
          case 4:
            return r3Body;
        }
      }else if(role === 'hauler'){
        return haulerBody;
      }else if(role === 'miner'){
        return minerBody;
      }else if(role === 'architect'){
        return bBody;
      }else if(role === 'feeder'){
        return feederBody;
      }
  }

};

module.exports = bodyObj;
<commit_msg>Updated the upgrader v4 to use more WORK parts<commit_after>//Constants for the different creeps' Bodies that auto spawn
//Tier 1
var hBody = [WORK, CARRY, CARRY, MOVE, MOVE];
var uBody = [WORK, CARRY, CARRY, CARRY, MOVE];
var bBody = [WORK, CARRY, WORK, MOVE];
var rBody = [WORK, WORK, CARRY, MOVE];

//Tier 2
var h2Body = [WORK, WORK, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE];
var u2Body = [WORK, WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE];
var b2Body = [WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE];
var r2Body = [WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE];

//Tier 3
var h3Body = [WORK, WORK, CARRY, CARRY, CARRY, CARRY,CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE];
var u3Body = [WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE];
var b3Body = [WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE];
var r3Body = [WORK, WORK, WORK, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE];

//Tier4
var haulerBody = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,ATTACK];
var feederBody = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,WORK];
var minerBody = [WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,CARRY,CARRY,MOVE];
var u4Body = [WORK, WORK, WORK, WORK, WORK, WORK, WORK, WORK, WORK, CARRY, MOVE];

//Object that holds a getter for these body types
var bodyObj = {
  //getter that useses a lot of switch statement to return the appropriate body array for the given role and tier
  getBody:function(role,tier){
      if(role==='harvester'){
        switch(tier){
          default:
            return hBody;
          case 2:
            return h2Body;
          case 3:
          case 4:
            return h3Body;
        }
      }else if(role === 'upgrader'){
        switch(tier){
          default:
            return uBody;
          case 2:
            return u2Body;
          case 3:
            return u3Body;
          case 4:
            return u4Body;
        }
      }else if(role === 'builder'){
        switch(tier){
          default:
            return bBody;
          case 2:
            return b2Body;
          case 3:
          case 4:
            return b3Body;
        }
      }else if(role === 'repair'){
        switch(tier){
          default:
            return rBody;
          case 2:
            return r2Body;
          case 3:
          case 4:
            return r3Body;
        }
      }else if(role === 'hauler'){
        return haulerBody;
      }else if(role === 'miner'){
        return minerBody;
      }else if(role === 'architect'){
        return bBody;
      }else if(role === 'feeder'){
        return feederBody;
      }
  }

};

module.exports = bodyObj;
<|endoftext|>