<commit_before>/*
  Copyright (C) 2013 Alexander (Sasha) Mazurov <alexander.mazurov@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*global escope: true, define:true, require:true, exports:true */
(function(root, factory) {
    'use strict';

    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // Rhino, and plain browser loading.
    if (typeof exports === 'object') {
        module.exports = factory(require('escope'));
    } else if (typeof define === 'function' && define.amd) {
        define(['escope'], factory);
    } else {
        root.eslevels = factory(escope);
    }
}(this, function(escope) {
    'use strict';
    var exports = {};

    escope.Scope.prototype._cache = null;
    escope.Scope.prototype._level = null;

    escope.Scope.prototype.level = function() {
        if (this.functionExpressionScope) {
            return this.upper.level();
        }
        if (this._level === null) {
            this._level = 0;
            if (this.upper !== null) {
                this._level = 1 + this.upper.level();
            }
        }
        return this._level;
    };
    escope.Scope.prototype.find = function(name) {
        var vars;
        if (this._cache === null) {
            this._cache = {};
        }
        if (this._cache[name] === undefined) {
            vars = this.variables;
            for (var i = 0; i < vars.length; ++i) {
                if (vars[i].name === name) {
                    this._cache[name] = this.level();
                }
            }

            if (this._cache[name] === undefined) {
                if (this.upper === null) {
                    this._cache[name] = 0;
                } else {
                    this._cache[name] = this.upper.find(name);
                }
            }
        }
        return this._cache[name];
    };

    var Region = function(level, first, last) {
        this.level = level;
        this.first = first;
        this.last = last;
    };

    Region.prototype.list = function() {
        return [this.level, this.first, this.last];
    };

    var RegionNode = function(region) {
        this.region = region;
        this.next = null;
    };

    var RegionList = function() {
        this.root = null;
    };

    RegionList.prototype.addRegion = function(region) {
        var curr, prev, firstRegion, midRegion, lastRegion;
        if (this.root === null) {
            this.root = new RegionNode(region);
            return this.root;
        }
        curr = this.root;
        prev = null;
        while (true) {
            if (region.first === curr.region.first) {
                firstRegion = new RegionNode(region);
                lastRegion = new RegionNode(
                    new Region(
                        curr.region.level,
                        region.last + 1,
                        curr.region.last
                    )
                );
                break;
            }
            if (region.last === curr.region.last) {
                firstRegion = new RegionNode(
                    new Region(
                        curr.region.level,
                        curr.region.first,
                        region.first - 1
                    )
                );
                lastRegion = new RegionNode(region);
                break;
            }
            if ((region.first > curr.region.first) &&
                (region.last < curr.region.last)) {
                firstRegion = new RegionNode(
                    new Region(
                        curr.region.level,
                        curr.region.first,
                        region.first - 1
                    )
                );
                midRegion = new RegionNode(region);
                lastRegion = new RegionNode(
                    new Region(
                        curr.region.level,
                        region.last + 1,
                        curr.region.last
                    )
                );
                break;
            }
            prev = curr;
            curr = curr.next;
        }

        if (midRegion !== undefined) {
            firstRegion.next = midRegion;
            midRegion.next = lastRegion;
        } else {
            firstRegion.next = lastRegion;
        }
        lastRegion.next = curr.next;
        if (prev !== null) {
            prev.next = firstRegion;
        } else {
            this.root = firstRegion;
        }
        //console.log(this.root);
    };

    RegionList.prototype.list = function() {
        var result = [];
        var curr = this.root;
        while (curr !== null) {
            result.push(curr.region.list());
            curr = curr.next;
        }
        // console.log(result);
        return result;
    };

    function addMainScopes(result, scopes) {
        for (var i = 0; i < scopes.length; i++) {
            if (!scopes[i].functionExpressionScope) {
                result.addRegion(
                    new Region(
                        scopes[i].level(),
                        scopes[i].block.range[0],
                        scopes[i].block.range[1]
                    )
                );
            }
        }
    }

    function addScopeVariables(result, scope) {
        var refs = scope.references,
            vars = scope.variables;
        var level, identifier;
        for (var i = 0; i < vars.length; i++) {
            if ((vars[i].defs.length > 0) &&
                (vars[i].defs[0].type === 'FunctionName')) {
                result.addRegion(
                    new Region(
                        scope.level(),
                        vars[i].identifiers[0].range[0],
                        vars[i].identifiers[0].range[1] - 1
                    )
                );
            }
        }

        for (i = 0; i < refs.length; i++) {
            identifier = refs[i].identifier;
            level = scope.find(identifier.name);
            if (level !== scope.level()) {
                // console.log(identifier.range);
                result.addRegion(
                    new Region(
                        level,
                        identifier.range[0],
                        identifier.range[1] - 1
                    )
                );
            }
        }
    }

    var getScopes = function(ast) {
        if (typeof ast === 'object' && ast.type === 'Program') {
            if (typeof ast.range !== 'object' || ast.range.length !== 2) {
                throw new Error('eslevels: Context only accepts a syntax tree'+
                    'with range information');
            }
        }
        return escope.analyze(ast).scopes;
    };

    exports.levels = function(ast) {
        var result = new RegionList();
        var scopes = getScopes(ast);
        addMainScopes(result, scopes);
        for (var i = 0; i < scopes.length; i++) {
            addScopeVariables(result, scopes[i]);
        }
        return result.list();
    };

    return exports;
}));
<commit_msg>Begin commenting<commit_after>/*
  Copyright (C) 2013 Alexander (Sasha) Mazurov <alexander.mazurov@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*global escope: true, define:true, require:true, exports:true */
(function(root, factory) {
    'use strict';

    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // Rhino, and plain browser loading.
    if (typeof exports === 'object') {
        module.exports = factory(require('escope'));
    } else if (typeof define === 'function' && define.amd) {
        define(['escope'], factory);
    } else {
        root.eslevels = factory(escope);
    }
}(this, function(escope) {
    'use strict';
    var exports = {};

    // Cache names levels
    escope.Scope.prototype._cache = null;

    // Store scope level
    escope.Scope.prototype._level = null;

    // **Get scope level**
    //
    // Returns the Integer
    escope.Scope.prototype.level = function() {
        // Don't count functionExpressionScope
        if (this.functionExpressionScope) {
            return this.upper.level();
        }
        if (this._level === null) { // level not caclulated yer
            this._level = 0;
            if (this.upper !== null) {
                // ```upper``` points to parent scope
                this._level = 1 + this.upper.level();
            }
        }
        return this._level;
    };

    // **Find variable of function by name**
    //
    // Search in current or upper scopes
    //
    // Returns a level - the Integer
    escope.Scope.prototype.find = function(name) {
        //
        var vars;
        if (this._cache === null) {
            this._cache = {};
        }
        if (this._cache[name] === undefined) {
            vars = this.variables;
            for (var i = 0; i < vars.length; ++i) {
                if (vars[i].name === name) {
                    this._cache[name] = this.level();
                }
            }

            if (this._cache[name] === undefined) {
                if (this.upper === null) {
                    this._cache[name] = 0;
                } else {
                    this._cache[name] = this.upper.find(name);
                }
            }
        }
        return this._cache[name];
    };

    var Region = function(level, first, last) {
        this.level = level;
        this.first = first;
        this.last = last;
    };

    Region.prototype.list = function() {
        return [this.level, this.first, this.last];
    };

    var RegionNode = function(region) {
        this.region = region;
        this.next = null;
    };

    var RegionList = function() {
        this.root = null;
    };

    RegionList.prototype.addRegion = function(region) {
        var curr, prev, firstRegion, midRegion, lastRegion;
        if (this.root === null) {
            this.root = new RegionNode(region);
            return this.root;
        }
        curr = this.root;
        prev = null;
        while (true) {
            if (region.first === curr.region.first) {
                firstRegion = new RegionNode(region);
                lastRegion = new RegionNode(
                    new Region(
                        curr.region.level,
                        region.last + 1,
                        curr.region.last
                    )
                );
                break;
            }
            if (region.last === curr.region.last) {
                firstRegion = new RegionNode(
                    new Region(
                        curr.region.level,
                        curr.region.first,
                        region.first - 1
                    )
                );
                lastRegion = new RegionNode(region);
                break;
            }
            if ((region.first > curr.region.first) &&
                (region.last < curr.region.last)) {
                firstRegion = new RegionNode(
                    new Region(
                        curr.region.level,
                        curr.region.first,
                        region.first - 1
                    )
                );
                midRegion = new RegionNode(region);
                lastRegion = new RegionNode(
                    new Region(
                        curr.region.level,
                        region.last + 1,
                        curr.region.last
                    )
                );
                break;
            }
            prev = curr;
            curr = curr.next;
        }

        if (midRegion !== undefined) {
            firstRegion.next = midRegion;
            midRegion.next = lastRegion;
        } else {
            firstRegion.next = lastRegion;
        }
        lastRegion.next = curr.next;
        if (prev !== null) {
            prev.next = firstRegion;
        } else {
            this.root = firstRegion;
        }
        //console.log(this.root);
    };

    RegionList.prototype.list = function() {
        var result = [];
        var curr = this.root;
        while (curr !== null) {
            result.push(curr.region.list());
            curr = curr.next;
        }
        // console.log(result);
        return result;
    };

    function addMainScopes(result, scopes) {
        for (var i = 0; i < scopes.length; i++) {
            if (!scopes[i].functionExpressionScope) {
                result.addRegion(
                    new Region(
                        scopes[i].level(),
                        scopes[i].block.range[0],
                        scopes[i].block.range[1]
                    )
                );
            }
        }
    }

    function addScopeVariables(result, scope) {
        var refs = scope.references,
            vars = scope.variables;
        var level, identifier;
        for (var i = 0; i < vars.length; i++) {
            if ((vars[i].defs.length > 0) &&
                (vars[i].defs[0].type === 'FunctionName')) {
                result.addRegion(
                    new Region(
                        scope.level(),
                        vars[i].identifiers[0].range[0],
                        vars[i].identifiers[0].range[1] - 1
                    )
                );
            }
        }

        for (i = 0; i < refs.length; i++) {
            identifier = refs[i].identifier;
            level = scope.find(identifier.name);
            if (level !== scope.level()) {
                // console.log(identifier.range);
                result.addRegion(
                    new Region(
                        level,
                        identifier.range[0],
                        identifier.range[1] - 1
                    )
                );
            }
        }
    }

    var getScopes = function(ast) {
        if (typeof ast === 'object' && ast.type === 'Program') {
            if (typeof ast.range !== 'object' || ast.range.length !== 2) {
                throw new Error('eslevels: Context only accepts a syntax tree'+
                    'with range information');
            }
        }
        return escope.analyze(ast).scopes;
    };

    exports.levels = function(ast) {
        var result = new RegionList();
        var scopes = getScopes(ast);
        addMainScopes(result, scopes);
        for (var i = 0; i < scopes.length; i++) {
            addScopeVariables(result, scopes[i]);
        }
        return result.list();
    };

    return exports;
}));
<|endoftext|>


<commit_before>'use strict';

pbc.moduleFunctionD.get('servo')['servo_write_angle'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length !== 2) {
        throw new Error("Incorrect number of arguments");
    }
    var pwmAstName = args[0]._astname;
    pbc.pinType="pins_pwm_pin";
    var pinblock;

    if (pwmAstName === "Num") {
        pinblock=py2block.convert(args[0])
    }
    pbc.pinType=null;
    var angleblock=py2block.convert(args[1]);

    return [block("servo_move", func.lineno, {}, {
        "PIN":pinblock,
        "DEGREE": angleblock,

    }, {
        "inline": "true"
    })];
}

pbc.moduleFunctionD.get('mixgo.led')['setonoff'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length !== 2) {
        throw new Error("Incorrect number of arguments");
    }
    pbc.pinType="number";
    var argblock = py2block.convert(args[0]);
    pbc.pinType=null;
    pbc.inScope="ledswitch";
    var mode = py2block.convert(args[1]);
     pbc.inScope=null;
    return [block("actuator_led_bright", func.lineno, {

    }, {
        'led': argblock,
        'bright':mode,
    }, {
        "inline": "true"
    }),
    ];
}

pbc.moduleFunctionD.get('mixgo.led')['getonoff'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length !== 1) {
        throw new Error("Incorrect number of arguments");
    }
    pbc.pinType="number";
    var argblock = py2block.convert(args[0]);
    pbc.pinType=null;
    return block("actuator_get_led_bright", func.lineno, {
    }, {
        'led': argblock,
    }, {
        "inline": "true"
    });
}

pbc.moduleFunctionD.get('mixgo.led')['setbrightness'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length !== 2) {
        throw new Error("Incorrect number of arguments");
    }
    pbc.pinType="number";
    var argblock = py2block.convert(args[0]);
    pbc.pinType=null;
    var brightblock = py2block.convert(args[1]);

    return [block("actuator_led_brightness", func.lineno, {}, {
        'led': argblock,
        'bright':brightblock,
    }, {
        "inline": "true"
    }),
    ];
}

pbc.moduleFunctionD.get('music')['pitch'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
	if(args.length!==2){
		throw new Error("Incorrect number of arguments");
	}

	 if (args.length === 2) {
        var roundAstName = args[0]._astname;
        var pwmAstName= args[1]._astname;
        pbc.pinType = "pins_pwm_pin";
        var pinblock = py2block.convert(args[1]);
        pbc.pinType=null;
        pbc.pinType = "pins_tone_notes";
        var pitchblock;

        if (roundAstName === "Call"&& pwmAstName=="Num"
            && args[0].func._astname == "Name" && py2block.Name_str(args[0].func) === "round") {

            pitchblock = py2block.convert(args[0].args[0])
        } else {
            pitchblock = py2block.convert(args[0])
        }

        return [block("esp32_music_pitch", func.lineno, {}, {
            'pitch': pitchblock,
            'PIN': pinblock,
        }, {
            "inline": "true"
        })];
    }
}

pbc.moduleFunctionD.get('music')['stop'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length !== 1) {
        throw new Error("Incorrect number of arguments");
    }
    pbc.pinType = "pins_pwm_pin";
    var argblock = py2block.convert(args[0]);
    pbc.pinType = null;
    return [block("esp32_music_stop", func.lineno, {}, {
        'PIN': argblock
    }, {
        "inline": "true"
    })];
}

pbc.assignD.get('Rgb')['check_assign'] = function(py2block, node, targets, value) {
    var funcName = py2block.identifier(value.func.attr);
    var moduleName=py2block.identifier(value.func.value.id);
    if(value._astname === "Call" && moduleName === "neopixel"
        && funcName === "NeoPixel" && value.args.length === 2&&value.keywords.length===1)
        return true;

    return false;
}

pbc.assignD.get('Rgb')['create_block'] = function(py2block, node, targets, value){

    var rgbblock=py2block.convert(targets[0]);
    pbc.inScope = "rgb_create_block";
    pbc.pinType = "pins_digital_pin";
    // value.args[0].args[0].n.v='pin'+value.args[0].args[0].n.v
    var pinblock = py2block.convert(value.args[0].args[0]);
    pbc.inScope = null;
    pbc.pinType = null;
    var countblock = py2block.convert(value.args[1]);

    return block("actuator_neopixel_init", node.lineno, {}, {
        "SUB":rgbblock,
        "PIN":pinblock,
        "LEDCOUNT":countblock
    });
}

pbc.moduleFunctionD.get('rgb')['write'] = function(py2block, func, args, keywords, starargs, kwargs, node){
    if(args.length!=0){
        throw new Error("Incorrect number of arguments");
    }

    var rgbblock=py2block.convert(func.value);

    return [block("actuator_neopixel_write", func.lineno, {}, { 'SUB':rgbblock,
    }, {
        "inline": "true"
    })];
}

<commit_msg>change actuaroe without damdamdam<commit_after>'use strict';

pbc.moduleFunctionD.get('servo')['servo_write_angle'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length !== 2) {
        throw new Error("Incorrect number of arguments");
    }
    var pwmAstName = args[0]._astname;
    pbc.pinType="pins_pwm_pin";
    var pinblock;

    if (pwmAstName === "Num") {
        pinblock=py2block.convert(args[0])
    }
    pbc.pinType=null;
    var angleblock=py2block.convert(args[1]);

    return [block("servo_move", func.lineno, {}, {
        "PIN":pinblock,
        "DEGREE": angleblock,

    }, {
        "inline": "true"
    })];
}

pbc.moduleFunctionD.get('mixgo.led')['setonoff'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length !== 2) {
        throw new Error("Incorrect number of arguments");
    }
    pbc.pinType="number";
    var argblock = py2block.convert(args[0]);
    pbc.pinType=null;
    pbc.inScope="ledswitch";
    var mode = py2block.convert(args[1]);
     pbc.inScope=null;
    return [block("actuator_led_bright", func.lineno, {

    }, {
        'led': argblock,
        'bright':mode,
    }, {
        "inline": "true"
    }),
    ];
}

pbc.moduleFunctionD.get('mixgo.led')['getonoff'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length !== 1) {
        throw new Error("Incorrect number of arguments");
    }
    pbc.pinType="number";
    var argblock = py2block.convert(args[0]);
    pbc.pinType=null;
    return block("actuator_get_led_bright", func.lineno, {
    }, {
        'led': argblock,
    }, {
        "inline": "true"
    });
}

pbc.moduleFunctionD.get('mixgo.led')['setbrightness'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length !== 2) {
        throw new Error("Incorrect number of arguments");
    }
    pbc.pinType="number";
    var argblock = py2block.convert(args[0]);
    pbc.pinType=null;
    var brightblock = py2block.convert(args[1]);

    return [block("actuator_led_brightness", func.lineno, {}, {
        'led': argblock,
        'bright':brightblock,
    }, {
        "inline": "true"
    }),
    ];
}

pbc.moduleFunctionD.get('music')['pitch'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
	/*if(args.length!==2){
		throw new Error("Incorrect number of arguments");
	}*/

	 if (args.length === 2) {
        pbc.pinType = "pins_pwm_pin";
        var pinblock = py2block.convert(args[0]);
        pbc.pinType=null;
        pbc.pinType = "pins_tone_notes";
        var pitchblock = py2block.convert(args[1]);
        pbc.pinType=null;

        return [block("esp32_music_pitch", func.lineno, {}, {
            'pitch': pitchblock,
            'PIN': pinblock,
        }, {
            "inline": "true"
        })];
    }
    else if (args.length=== 3){
        pbc.pinType = "pins_pwm_pin";
        var pinblock = py2block.convert(args[0]);
        pbc.pinType=null;
        pbc.pinType = "pins_tone_notes";
        var pitchblock = py2block.convert(args[1]);
        pbc.pinType=null;
        var timeblock=py2block.convert(args[2]);
     return [block("esp32_music_pitch_with_time", func.lineno, {}, {
                'pitch': pitchblock,
                'PIN': pinblock,
                "time":timeblock
            }, {
                "inline": "true"
            })];

    }

}

pbc.moduleFunctionD.get('music')['stop'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length !== 1) {
        throw new Error("Incorrect number of arguments");
    }
    pbc.pinType = "pins_pwm_pin";
    var argblock = py2block.convert(args[0]);
    pbc.pinType = null;
    return [block("esp32_music_stop", func.lineno, {}, {
        'PIN': argblock
    }, {
        "inline": "true"
    })];
}

pbc.moduleFunctionD.get('music')['play'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length !== 2) {
        throw new Error("Incorrect number of arguments");
    }

    var nameblock= py2block.convert(args[0].attr);

    pbc.pinType = "pins_pwm_pin";
    var argblock = py2block.convert(args[1]);
    pbc.pinType = null;
    return [block("esp32_music_play_list", func.lineno, {}, {
        "LIST":nameblock,
        'PIN': argblock
    }, {
        "inline": "true"
    })];
}

pbc.assignD.get('Rgb')['check_assign'] = function(py2block, node, targets, value) {
    var funcName = py2block.identifier(value.func.attr);
    var moduleName=py2block.identifier(value.func.value.id);
    if(value._astname === "Call" && moduleName === "neopixel"
        && funcName === "NeoPixel" && value.args.length === 2&&value.keywords.length===1)
        return true;

    return false;
}

pbc.assignD.get('Rgb')['create_block'] = function(py2block, node, targets, value){

    var rgbblock=py2block.convert(targets[0]);
    pbc.inScope = "rgb_create_block";
    pbc.pinType = "pins_digital_pin";
    // value.args[0].args[0].n.v='pin'+value.args[0].args[0].n.v
    var pinblock = py2block.convert(value.args[0].args[0]);
    pbc.inScope = null;
    pbc.pinType = null;
    var countblock = py2block.convert(value.args[1]);

    return block("actuator_neopixel_init", node.lineno, {}, {
        "SUB":rgbblock,
        "PIN":pinblock,
        "LEDCOUNT":countblock
    });
}

pbc.moduleFunctionD.get('rgb')['write'] = function(py2block, func, args, keywords, starargs, kwargs, node){
    if(args.length!=0){
        throw new Error("Incorrect number of arguments");
    }

    var rgbblock=py2block.convert(func.value);

    return [block("actuator_neopixel_write", func.lineno, {}, { 'SUB':rgbblock,
    }, {
        "inline": "true"
    })];
}

pbc.moduleFunctionD.get('music')['get_tempo'] = function(py2block, func, args, keywords, starargs, kwargs, node){
    if(args.length!=0){
        throw new Error("Incorrect number of arguments");
    }

    return block("esp32_music_get_tempo", func.lineno, {}, {
    }, {
        "inline": "true"
    });
}

pbc.moduleFunctionD.get('music')['set_tempo'] = function(py2block, func, args, keywords, starargs, kwargs, node){
    if(args.length!=2){
        throw new Error("Incorrect number of arguments");
    }
    var resoblock=py2block.convert(args[0]);
    var speedblock=py2block.convert(args[1]);

    return [block("esp32_music_set_tempo", func.lineno, {}, {
        'TICKS':resoblock,
        "BPM":speedblock,
    }, {
        "inline": "true"
    })];
}
pbc.moduleFunctionD.get('music')['reset'] = function(py2block, func, args, keywords, starargs, kwargs, node){
    if(args.length!=0){
        throw new Error("Incorrect number of arguments");
    }

    return [block("esp32_music_reset", func.lineno, {}, {
    }, {
        "inline": "true"
    })];
}

<|endoftext|>


<commit_before>// @flow
/*
  https://api.lbry.tv/api/v1/proxy currently expects publish to consist
   of a multipart/form-data POST request with:
    - 'file' binary
    - 'json_payload' collection of publish params to be passed to the server's sdk.
 */
import { X_LBRY_AUTH_TOKEN } from '../../ui/constants/token';
import { doUpdateUploadProgress } from 'lbryinc';

// A modified version of Lbry.apiCall that allows
// to perform calling methods at arbitrary urls
// and pass form file fields
export default function apiPublishCallViaWeb(
  apiCall: (any, any, any, any) => any,
  connectionString: string,
  token: string,
  method: string,
  params: { file_path: string },
  resolve: Function,
  reject: Function
) {
  const { file_path: filePath } = params;

  if (!filePath) {
    return apiCall(method, params, resolve, reject);
  }

  const counter = new Date().getTime();
  const fileField = filePath;

  // Putting a dummy value here, the server is going to process the POSTed file
  // and set the file_path itself
  params.file_path = '__POST_FILE__';

  const jsonPayload = JSON.stringify({
    jsonrpc: '2.0',
    method,
    params,
    id: counter,
  });
  const body = new FormData();
  body.append('file', fileField);
  body.append('json_payload', jsonPayload);

  function makeRequest(connectionString, method, token, body, params) {
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();
      xhr.open(method, connectionString);
      xhr.setRequestHeader(X_LBRY_AUTH_TOKEN, token);
      xhr.responseType = 'json';
      xhr.upload.onprogress = e => {
        let percentComplete = Math.ceil((e.loaded / e.total) * 100);
        window.store.dispatch(doUpdateUploadProgress(percentComplete, params, xhr));
      };
      xhr.onload = () => {
        window.store.dispatch(doUpdateUploadProgress(undefined, params));
        resolve(xhr);
      };
      xhr.onerror = () => {
        window.store.dispatch(doUpdateUploadProgress(undefined, params));
        reject(new Error(__('There was a problem with your upload')));
      };

      xhr.onabort = () => {
        window.store.dispatch(doUpdateUploadProgress(undefined, params));
      };
      xhr.send(body);
    });
  }

  return makeRequest(connectionString, 'POST', token, body, params)
    .then(xhr => {
      let error;
      if (xhr && xhr.response) {
        if (xhr.status >= 200 && xhr.status < 300 && !xhr.response.error) {
          return resolve(xhr.response.result);
        } else if (xhr.response.error) {
          error = new Error(xhr.response.error.message);
        } else {
          error = new Error(__('Upload likely timed out. Try a smaller file while we work on this.'));
        }
      }

      if (error) {
        return Promise.reject(error);
      }
    })
    .catch(reject);
}
<commit_msg>Fix preview delay on Web by sending a dummy file.<commit_after>// @flow
/*
  https://api.lbry.tv/api/v1/proxy currently expects publish to consist
   of a multipart/form-data POST request with:
    - 'file' binary
    - 'json_payload' collection of publish params to be passed to the server's sdk.
 */
import { X_LBRY_AUTH_TOKEN } from '../../ui/constants/token';
import { doUpdateUploadProgress } from 'lbryinc';

// A modified version of Lbry.apiCall that allows
// to perform calling methods at arbitrary urls
// and pass form file fields
export default function apiPublishCallViaWeb(
  apiCall: (any, any, any, any) => any,
  connectionString: string,
  token: string,
  method: string,
  params: { file_path: string, preview: boolean },
  resolve: Function,
  reject: Function
) {
  const { file_path: filePath, preview } = params;

  if (!filePath) {
    return apiCall(method, params, resolve, reject);
  }

  const counter = new Date().getTime();
  let fileField = filePath;

  if (preview) {
    // Send dummy file for the preview. The tx-fee calculation does not depend on it.
    const dummyContent = 'x';
    fileField = new File([dummyContent], 'dummy.md', { type: 'text/markdown' });
  }

  // Putting a dummy value here, the server is going to process the POSTed file
  // and set the file_path itself
  params.file_path = '__POST_FILE__';

  const jsonPayload = JSON.stringify({
    jsonrpc: '2.0',
    method,
    params,
    id: counter,
  });
  const body = new FormData();
  body.append('file', fileField);
  body.append('json_payload', jsonPayload);

  function makeRequest(connectionString, method, token, body, params) {
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();
      xhr.open(method, connectionString);
      xhr.setRequestHeader(X_LBRY_AUTH_TOKEN, token);
      xhr.responseType = 'json';
      xhr.upload.onprogress = e => {
        let percentComplete = Math.ceil((e.loaded / e.total) * 100);
        window.store.dispatch(doUpdateUploadProgress(percentComplete, params, xhr));
      };
      xhr.onload = () => {
        window.store.dispatch(doUpdateUploadProgress(undefined, params));
        resolve(xhr);
      };
      xhr.onerror = () => {
        window.store.dispatch(doUpdateUploadProgress(undefined, params));
        reject(new Error(__('There was a problem with your upload')));
      };

      xhr.onabort = () => {
        window.store.dispatch(doUpdateUploadProgress(undefined, params));
      };
      xhr.send(body);
    });
  }

  return makeRequest(connectionString, 'POST', token, body, params)
    .then(xhr => {
      let error;
      if (xhr && xhr.response) {
        if (xhr.status >= 200 && xhr.status < 300 && !xhr.response.error) {
          return resolve(xhr.response.result);
        } else if (xhr.response.error) {
          error = new Error(xhr.response.error.message);
        } else {
          error = new Error(__('Upload likely timed out. Try a smaller file while we work on this.'));
        }
      }

      if (error) {
        return Promise.reject(error);
      }
    })
    .catch(reject);
}
<|endoftext|>


<commit_before><commit_msg>Get Programming<commit_after><|endoftext|>


<commit_before>'use strict';

describe('Controller: AdminAccountCtrl', function () {

  // load the controller's module
  beforeEach(module('fahrtenbuchApp'));
  var AdminAccountCtrl, $scope, $location, $httpBackend, fakeResponse;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope, _$location_, _$httpBackend_) {

    $scope = $rootScope.$new();
    $location = _$location_;
    $httpBackend = _$httpBackend_;
    fakeResponse = '';

    AdminAccountCtrl = $controller('AdminAccountCtrl', {
      $scope: $scope
    });

    $location.path('/admin/account');
  }));

	it('Ensure that the method was invoked', function () {
  	$httpBackend.expectGET('/api/accounts').respond([{test: "test"}]);
  	$httpBackend.when('GET', 'app/admin/admin.account.html').respond(fakeResponse);
    $httpBackend.flush();

	  expect($location.path()).toBe('/admin/account');
	  expect($scope.accounts).toBeDefined();
	  expect($scope.accounts).toEqual([{test: "test"}]);
	});

	// it('Ensure that the method was invoked', function () {
 //  	// $httpBackend.expectGET('/api/accounts').respond([{test: "test"}]);
 //  	// $httpBackend.when('GET', 'app/admin/admin.account.html').respond(fakeResponse);
 //   //  $httpBackend.flush();

	//   expect($location.path()).toBe('/admin/account');

 //   	// var valid = scope.addAccount();
 //    // expect(valid).toBeFalsy();

 //  	$httpBackend.expectGET('/api/accounts').respond([{_id: 1}, {_id: 2}, {_id: 3}]);
 //  	$httpBackend.when('GET', 'app/admin/admin.account.html').respond(fakeResponse);
 //  	$httpBackend.when('DELETE', '/api/accounts/1').respond(fakeResponse);
 //    $httpBackend.flush();

 //    console.log($scope.accounts);

 //    $scope.deleteAccount($scope.accounts[0]);

 //    $scope.$watch();
 //    $scope.$apply();
 //    console.log($scope.accounts);

    // var account = scope.accounts[0];
    // console.log(account);

    // angular.forEach(scope.accounts, function(a, i) {
    // 	console.log(a);
    //   if (a === account) {
    //   	console.log("hi");
    //     scope.accounts.splice(i, 1);
    //   }
    // });
    // console.log(scope.accounts);

//     expect($scope.accounts).toEqual([{_id: 2}, {_id: 3}]);
// 	});
});

// describe('Controller: AdminUserCtrl', function () {

//   // load the controller's module
//   beforeEach(module('fahrtenbuchApp'));
//   var AdminUserCtrl, scope, $httpBackend, testTrip;

//   // Initialize the controller and a mock scope
//   beforeEach(inject(function (_$httpBackend_, $controller, $rootScope, $routeParams) {

//     $httpBackend = _$httpBackend_;
//     scope = $rootScope.$new();
//     AdminUserCtrl = $controller('AdminUserCtrl', {
//       $scope: scope,
//       $routeParams: {id: 12345678}
//     });
//     testTrip = {_id: 12345678, stays: [{destination: "test"}]};
//   }));

//   it('should get trips', inject(function() {

//     $httpBackend.expectGET('/api/trips/' + testTrip._id).respond(testTrip);
//     $httpBackend.flush();

//     expect(scope.trip).toEqual({_id: 12345678, stays: [{destination: "test"}]});
//     expect(scope.destinations).toEqual("test");
//   }));
// });

// @todo AdminCarCtrl
// @todo AdminCarAddCtrl

<commit_msg>test webhook<commit_after>'use strict';

describe('Controller: AdminAccountCtrl', function () {

  // load the controller's module
  beforeEach(module('fahrtenbuchApp'));
  var AdminAccountCtrl, $scope, $location, $httpBackend, fakeResponse;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope, _$location_, _$httpBackend_) {

    $scope = $rootScope.$new();
    $location = _$location_;
    $httpBackend = _$httpBackend_;
    fakeResponse = '';

    AdminAccountCtrl = $controller('AdminAccountCtrl', {
      $scope: $scope
    });

    $location.path('/admin/account');
  }));

	it('Ensure that the method was invoked', function () {
  	$httpBackend.expectGET('/api/accounts').respond([{test: "test"}]);
  	$httpBackend.when('GET', 'app/admin/admin.account.html').respond(fakeResponse);
    $httpBackend.flush();

	  expect($location.path()).toBe('/admin/account');
	  expect($scope.accounts).toBeDefined();
	  expect($scope.accounts).toEqual([{test: "test"}]);
	});

	// it('Ensure that the method was invoked', function () {
 //  	// $httpBackend.expectGET('/api/accounts').respond([{test: "test"}]);
 //  	// $httpBackend.when('GET', 'app/admin/admin.account.html').respond(fakeResponse);
 //   //  $httpBackend.flush();

	//   expect($location.path()).toBe('/admin/account');

 //   	// var valid = scope.addAccount();
 //    // expect(valid).toBeFalsy();

 //  	$httpBackend.expectGET('/api/accounts').respond([{_id: 1}, {_id: 2}, {_id: 3}]);
 //  	$httpBackend.when('GET', 'app/admin/admin.account.html').respond(fakeResponse);
 //  	$httpBackend.when('DELETE', '/api/accounts/1').respond(fakeResponse);
 //    $httpBackend.flush();

 //    console.log($scope.accounts);

 //    $scope.deleteAccount($scope.accounts[0]);

 //    $scope.$watch();
 //    $scope.$apply();
 //    console.log($scope.accounts);

    // var account = scope.accounts[0];
    // console.log(account);

    // angular.forEach(scope.accounts, function(a, i) {
    // 	console.log(a);
    //   if (a === account) {
    //   	console.log("hi");
    //     scope.accounts.splice(i, 1);
    //   }
    // });
    // console.log(scope.accounts);

//     expect($scope.accounts).toEqual([{_id: 2}, {_id: 3}]);
// 	});
});

// describe('Controller: AdminUserCtrl', function () {

//   // load the controller's module
//   beforeEach(module('fahrtenbuchApp'));
//   var AdminUserCtrl, scope, $httpBackend, testTrip;

//   // Initialize the controller and a mock scope
//   beforeEach(inject(function (_$httpBackend_, $controller, $rootScope, $routeParams) {

//     $httpBackend = _$httpBackend_;
//     scope = $rootScope.$new();
//     AdminUserCtrl = $controller('AdminUserCtrl', {
//       $scope: scope,
//       $routeParams: {id: 12345678}
//     });
//     testTrip = {_id: 12345678, stays: [{destination: "test"}]};
//   }));

//   it('should get trips', inject(function() {

//     $httpBackend.expectGET('/api/trips/' + testTrip._id).respond(testTrip);
//     $httpBackend.flush();

//     expect(scope.trip).toEqual({_id: 12345678, stays: [{destination: "test"}]});
//     expect(scope.destinations).toEqual("test");
//   }));
// });

// @todo AdminCarCtrl
// @todo AdminCarAddCtrl

<|endoftext|>


<commit_before>ENS.reportView = wgp.AbstractView
		.extend({
			tableColNames : [ "Id", "Start Time", "Finish Time", "Download",
					"", "Status" ],
			initialize : function(argument, treeSettings) {
				var appView = new ENS.AppView();
				this.treeSettings = treeSettings;
				var treeId = treeSettings.treeId;
				appView.addView(this, treeId + ENS.URL.PERFDOCTOR_POSTFIX_ID);

				this.tableMargin = 20;
				this.tableWidth = parseInt($("#" + this.id).width()
						- this.tableMargin * 4);

				// 空のテーブルを作成
				this.createTabelColModel();
				this.render();

				this.selectedRowId = 0;

				var reportName = treeSettings.parentTreeId + "/"
						+ treeSettings.data;

				this.getReportList(reportName);
			},
			render : function() {
				$("#" + this.id).append('

');
				$("#reportDiv").css({
					"margin-top" : 20,
					"margin-left" : 15
				});
				$("#reportDiv").append('

');
				$("#reportDiv").append('

');
				var height = "auto";

				$("#reportTable").jqGrid(
						{
							datatype : "local",
							data : "",
							colModel : this.tableColModel,
							colNames : this.tableColNames,
							caption : "Report List of "
									+ this.treeSettings.parentTreeId + "/"
									+ this.treeSettings.data,
							pager : "reportPager",
							rowList : [ 20, 50, 100 ],
							pgbuttons : true,
							pginput : true,
							height : height,
							width : this.tableWidth,
							sortname : "reportTermFrom",
							sortorder : "asc",
							viewrecords : true,
							rownumbers : true,
							shrinkToFit : false,
							cellEdit : true,
							cmTemplate : {
								title : false
							}
						});
				$("#reportTable").filterToolbar({
					defaultSearch : 'cn'
				});
				$("#reportDiv").css('font-size', '0.8em');
			},
			_parseModel : function(model) {
				var tableData = model.attributes;

				return tableData;
			},
			onAdd : function(element) {
				console.log('call onAdd');
			},
			onChange : function(element) {
				console.log('called changeModel');
			},
			onRemove : function(element) {
				console.log('called removeModel');
			},
			onComplete : function(element) {
				if (element == wgp.constants.syncType.SEARCH) {
					appView.syncData();
				}
				this.reloadTable();
			},
			createTabelColModel : function() {
				this.tableColModel = [ {
					name : "reportId",
					width : 0,
					hidden : true
				}, {
					name : "reportTermFrom",
					width : parseInt(this.tableWidth * 0.33)
				}, {
					name : "reportTermTo",
					width : parseInt(this.tableWidth * 0.33)
				}, {
					name : "download",
					width : parseInt(this.tableWidth * 0.098),
					formatter : ENS.Utility.makeAnchor,
					editoptions : {
						"onclick" : "ENS.report.download",
						"linkName" : "Download"
					}
				}, {
					name : "Delete",
					width : parseInt(this.tableWidth * 0.097),
					formatter : ENS.Utility.makeAnchor,
					editoptions : {
						"onclick" : "ENS.report.deleteNode",
						"linkName" : "Delete"
					}
				}, {
					name : "status",
					width : parseInt(this.tableWidth * 0.1)
				} ];
			},
			reloadTable : function() {
				var tableViewData = [];
				var instance = this;
				_.each(this.collection.models, function(model, index) {
					tableViewData.push(instance._parseModel(model));
				});

				$("#reportTable").clearGridData().setGridParam({
					data : tableViewData
				}).trigger("reloadGrid");
			},
			getReportList : function(reportName) {

				// レポート出力定義を取得する
				// Ajax通信用の設定
				var settings = {
					data : {
						reportName : reportName
					},
					url : ENS.tree.REPORT_SELECT_BY_REPORT_NAME_URL
				};

				// 非同期通信でデータを送信する
				var ajaxHandler = new wgp.AjaxHandler();
				settings[wgp.ConnectionConstants.SUCCESS_CALL_OBJECT_KEY] = this;
				settings[wgp.ConnectionConstants.SUCCESS_CALL_FUNCTION_KEY] = "callbackGetReportList";
				ajaxHandler.requestServerAsync(settings);
			},
			callbackGetReportList : function(reportList) {
				var tableViewData = [];
				var instance = this;
				_.each(reportList, function(report, index) {
					// レポート名についている余計なパスを除外する
					var reportPath = report.reportName;
					var reportPathSplitList = reportPath.split("/");
					var reportPathLength = reportPathSplitList.length;
					var reportName = reportPathSplitList[reportPathLength - 1];
					report.reportName = reportName;

					// 開始日と終了日のフォーマットを変更する
					var fmTimeDate = new Date(report.reportTermFrom);
					var toTimeDate = new Date(report.reportTermTo);

					var fmTimeStr = instance.getDateString(fmTimeDate);
					var toTimeStr = instance.getDateString(toTimeDate);

					report.reportTermFrom = fmTimeStr;
					report.reportTermTo = toTimeStr;

					tableViewData.push(report);
				});

				$("#reportTable").clearGridData().setGridParam({
					data : tableViewData
				}).trigger("reloadGrid");
			},
			getDateString : function(date) {
				// 年月日の取得
				var month = date.getMonth() + 1;
				var day = date.getDate();
				var hour = date.getHours();
				var minute = date.getMinutes();
				var second = date.getSeconds();

				// 1桁を2桁に変換する
				if (month < 10) {
					month = "0" + month;
				}
				if (day < 10) {
					day = "0" + day;
				}
				if (hour < 10) {
					hour = "0" + hour;
				}
				if (minute < 10) {
					minute = "0" + minute;
				}
				if (second < 10) {
					second = "0" + second;
				}

				// 整形して返却
				return date.getFullYear() + "/" + month + "/" + day + " "
						+ hour + ":" + minute + ":" + second;
			}
		});

ENS.report.download = function(id) {

	var event = {
		"file_name" : "20130512_133200-20130514_133200.zip"
	};

	var rowData = $("#reportTable").getRowData(id);
	var reportId = rowData.reportId;
	var status= rowData.status;
	if(status!="completed")
		{
		alert("Cannot Download yet because it does not finish to create!");
		return;
		}
	$("input#reportId").val(reportId);
	$('#btn').click();
};

ENS.report.callbackDownload = function(response) {
	alert(response);
};
ENS.report.deleteNode = function(id) {
	var rowData = $("#reportTable").getRowData(id);
	var ids = rowData.reportId;
	var url = ENS.tree.REPORT_DELETE_BY_ID_URL;
	this.selectedRowId = id;

	var settings = {
		data : {
			reportId : ids
		},
		url : url
	};
	settings[wgp.ConnectionConstants.SUCCESS_CALL_OBJECT_KEY] = this;
	settings[wgp.ConnectionConstants.SUCCESS_CALL_FUNCTION_KEY] = "_callbackDeleteNode";
	var ajaxHandler = new wgp.AjaxHandler();
	ajaxHandler.requestServerAsync(settings);
};

ENS.report._callbackDeleteNode = function(data) {
	if(data.result === "failure" ){
		alert("Delete the report is failed.");
		return;
	}
	var grid = $("#reportTable");
	var id = this.selectedRowId;
	grid.delRowData(id);
};<commit_msg>issues #663<commit_after>ENS.reportView = wgp.AbstractView
		.extend({
			tableColNames : [ "Id", "Start Time", "Finish Time", "Download",
					"", "Status" ],
			initialize : function(argument, treeSettings) {
				var appView = new ENS.AppView();
				this.treeSettings = treeSettings;
				var treeId = treeSettings.treeId;
				appView.addView(this, treeId + ENS.URL.PERFDOCTOR_POSTFIX_ID);

				this.tableMargin = 50;
				this.tableWidth = parseInt($("#" + this.id).width()
						- this.tableMargin);

				// 空のテーブルを作成
				this.createTabelColModel();
				this.render();

				this.selectedRowId = 0;

				var reportName = treeSettings.parentTreeId + "/"
						+ treeSettings.data;

				this.getReportList(reportName);
			},
			render : function() {
				$("#" + this.id).append('

');
				$("#reportDiv").css({
					"margin-top" : 20,
					"margin-left" : 15
				});
				$("#reportDiv").append('

');
				$("#reportDiv").append('

');
				var height = "auto";

				$("#reportTable").jqGrid(
						{
							datatype : "local",
							data : "",
							colModel : this.tableColModel,
							colNames : this.tableColNames,
							caption : "Report List of "
									+ this.treeSettings.parentTreeId + "/"
									+ this.treeSettings.data,
							pager : "reportPager",
							rowList : [ 20, 50, 100 ],
							pgbuttons : true,
							pginput : true,
							height : height,
							width : this.tableWidth,
							sortname : "reportTermFrom",
							sortorder : "asc",
							viewrecords : true,
							rownumbers : true,
							shrinkToFit : false,
							cellEdit : true,
							cmTemplate : {
								title : false
							}
						});
				$("#reportTable").filterToolbar({
					defaultSearch : 'cn'
				});
				$("#reportDiv").css('font-size', '0.8em');
			},
			_parseModel : function(model) {
				var tableData = model.attributes;

				return tableData;
			},
			onAdd : function(element) {
				console.log('call onAdd');
			},
			onChange : function(element) {
				console.log('called changeModel');
			},
			onRemove : function(element) {
				console.log('called removeModel');
			},
			onComplete : function(element) {
				if (element == wgp.constants.syncType.SEARCH) {
					appView.syncData();
				}
				this.reloadTable();
			},
			createTabelColModel : function() {
				this.tableColModel = [ {
					name : "reportId",
					width : 0,
					hidden : true
				}, {
					name : "reportTermFrom",
					width : parseInt(this.tableWidth * 0.33)
				}, {
					name : "reportTermTo",
					width : parseInt(this.tableWidth * 0.33)
				}, {
					name : "download",
					width : parseInt(this.tableWidth * 0.098),
					formatter : ENS.Utility.makeAnchor,
					editoptions : {
						"onclick" : "ENS.report.download",
						"linkName" : "Download"
					}
				}, {
					name : "Delete",
					width : parseInt(this.tableWidth * 0.087),
					formatter : ENS.Utility.makeAnchor,
					editoptions : {
						"onclick" : "ENS.report.deleteNode",
						"linkName" : "Delete"
					}
				}, {
					name : "status",
					width : parseInt(this.tableWidth * 0.1)
				} ];
			},
			reloadTable : function() {
				var tableViewData = [];
				var instance = this;
				_.each(this.collection.models, function(model, index) {
					tableViewData.push(instance._parseModel(model));
				});

				$("#reportTable").clearGridData().setGridParam({
					data : tableViewData
				}).trigger("reloadGrid");
			},
			getReportList : function(reportName) {

				// レポート出力定義を取得する
				// Ajax通信用の設定
				var settings = {
					data : {
						reportName : reportName
					},
					url : ENS.tree.REPORT_SELECT_BY_REPORT_NAME_URL
				};

				// 非同期通信でデータを送信する
				var ajaxHandler = new wgp.AjaxHandler();
				settings[wgp.ConnectionConstants.SUCCESS_CALL_OBJECT_KEY] = this;
				settings[wgp.ConnectionConstants.SUCCESS_CALL_FUNCTION_KEY] = "callbackGetReportList";
				ajaxHandler.requestServerAsync(settings);
			},
			callbackGetReportList : function(reportList) {
				var tableViewData = [];
				var instance = this;
				_.each(reportList, function(report, index) {
					// レポート名についている余計なパスを除外する
					var reportPath = report.reportName;
					var reportPathSplitList = reportPath.split("/");
					var reportPathLength = reportPathSplitList.length;
					var reportName = reportPathSplitList[reportPathLength - 1];
					report.reportName = reportName;

					// 開始日と終了日のフォーマットを変更する
					var fmTimeDate = new Date(report.reportTermFrom);
					var toTimeDate = new Date(report.reportTermTo);

					var fmTimeStr = instance.getDateString(fmTimeDate);
					var toTimeStr = instance.getDateString(toTimeDate);

					report.reportTermFrom = fmTimeStr;
					report.reportTermTo = toTimeStr;

					tableViewData.push(report);
				});

				$("#reportTable").clearGridData().setGridParam({
					data : tableViewData
				}).trigger("reloadGrid");
			},
			getDateString : function(date) {
				// 年月日の取得
				var month = date.getMonth() + 1;
				var day = date.getDate();
				var hour = date.getHours();
				var minute = date.getMinutes();
				var second = date.getSeconds();

				// 1桁を2桁に変換する
				if (month < 10) {
					month = "0" + month;
				}
				if (day < 10) {
					day = "0" + day;
				}
				if (hour < 10) {
					hour = "0" + hour;
				}
				if (minute < 10) {
					minute = "0" + minute;
				}
				if (second < 10) {
					second = "0" + second;
				}

				// 整形して返却
				return date.getFullYear() + "/" + month + "/" + day + " "
						+ hour + ":" + minute + ":" + second;
			}
		});

ENS.report.download = function(id) {

	var event = {
		"file_name" : "20130512_133200-20130514_133200.zip"
	};

	var rowData = $("#reportTable").getRowData(id);
	var reportId = rowData.reportId;
	var status= rowData.status;
	if(status!="completed")
		{
		alert("Cannot Download yet because it does not finish to create!");
		return;
		}
	$("input#reportId").val(reportId);
	$('#btn').click();
};

ENS.report.callbackDownload = function(response) {
	alert(response);
};
ENS.report.deleteNode = function(id) {
	var rowData = $("#reportTable").getRowData(id);
	var ids = rowData.reportId;
	var url = ENS.tree.REPORT_DELETE_BY_ID_URL;
	this.selectedRowId = id;

	var settings = {
		data : {
			reportId : ids
		},
		url : url
	};
	settings[wgp.ConnectionConstants.SUCCESS_CALL_OBJECT_KEY] = this;
	settings[wgp.ConnectionConstants.SUCCESS_CALL_FUNCTION_KEY] = "_callbackDeleteNode";
	var ajaxHandler = new wgp.AjaxHandler();
	ajaxHandler.requestServerAsync(settings);
};

ENS.report._callbackDeleteNode = function(data) {
	if(data.result === "failure" ){
		alert("Delete the report is failed.");
		return;
	}
	var grid = $("#reportTable");
	var id = this.selectedRowId;
	grid.delRowData(id);
};<|endoftext|>


<commit_before>FLOW.NotificationsView = Ember.View.extend({
  notificationOption: null,
  notificationType: null,
  expiryDate: null,
  notificationDestination: null,
  optionEmpty: false,
  typeEmpty: false,
  destinationEmpty: false,
  dateEmpty: false,

  addNotification: function() {
    if(this.get('notificationOption') === null) {
      this.set('optionEmpty', true);
    }
    if(this.get('notificationType') === null) {
      this.set('typeEmpty', true);
    }
    if(this.get('notificationDestination') === null) {
      this.set('destinationEmpty', true);
    }
    if(this.get('expiryDate') === null) {
      this.set('dateEmpty', true);
    }

    if(this.get('optionEmpty') || this.get('typeEmpty') || this.get('destinationEmpty') || this.get('dateEmpty')) {
      FLOW.store.createRecord(FLOW.NotificationSubscription, {
        "notificationOption": this.notificationOption.get('value'),
        "notificationType": this.notificationType.get('value'),
        "expiryDate": Date.parse(this.get('expiryDate')),
        "notificationDestination": this.get('notificationDestination'),
        "notificationMethod": "EMAIL",
        "entityId": FLOW.selectedControl.selectedSurvey.get('keyId')
      });
      FLOW.store.commit();
    }
  },

  cancelNotification: function() {
    this.set('notificationEvent', null);
    this.set('notificationType', null);
    this.set('notificationDestination', null);
    this.set('expiryDate', null);
  },

  closeNotifications: function(router, event) {
    FLOW.router.transitionTo('navSurveys.navSurveysEdit.editQuestions');
  },

  removeNotification: function(event) {
    var nDeleteId, notification;
    nDeleteId = event.context.get('keyId');

    notification = FLOW.store.find(FLOW.NotificationSubscription, nDeleteId);
    notification.deleteRecord();
    FLOW.store.commit();
  }
});<commit_msg>avoid NaN as date in notifications<commit_after>FLOW.NotificationsView = Ember.View.extend({
  notificationOption: null,
  notificationType: null,
  expiryDate: null,
  notificationDestination: null,
  optionEmpty: false,
  typeEmpty: false,
  destinationEmpty: false,
  dateEmpty: false,

  addNotification: function() {
    var date;
    if(this.get('notificationOption') === null) {
      this.set('optionEmpty', true);
    }
    if(this.get('notificationType') === null) {
      this.set('typeEmpty', true);
    }
    if(this.get('notificationDestination') === null) {
      this.set('destinationEmpty', true);
    }
    if(this.get('expiryDate') === null) {
      this.set('dateEmpty', true);
    }
    if (Ember.none(this.get('expiryDate'))){
      date = null;
    } else {
      date = Date.parse(this.get('expiryDate'));
    }
    if(this.get('optionEmpty') || this.get('typeEmpty') || this.get('destinationEmpty') || this.get('dateEmpty')) {
      FLOW.store.createRecord(FLOW.NotificationSubscription, {
        "notificationOption": this.notificationOption.get('value'),
        "notificationType": this.notificationType.get('value'),
        "expiryDate": date,
        "notificationDestination": this.get('notificationDestination'),
        "notificationMethod": "EMAIL",
        "entityId": FLOW.selectedControl.selectedSurvey.get('keyId')
      });
      FLOW.store.commit();
    }
  },

  cancelNotification: function() {
    this.set('notificationEvent', null);
    this.set('notificationType', null);
    this.set('notificationDestination', null);
    this.set('expiryDate', null);
  },

  closeNotifications: function(router, event) {
    FLOW.router.transitionTo('navSurveys.navSurveysEdit.editQuestions');
  },

  removeNotification: function(event) {
    var nDeleteId, notification;
    nDeleteId = event.context.get('keyId');

    notification = FLOW.store.find(FLOW.NotificationSubscription, nDeleteId);
    notification.deleteRecord();
    FLOW.store.commit();
  }
});<|endoftext|>


<commit_before>import {
    isEmpty, isNil, extend, map, bindAll, omit, inRange, find, range,
} from 'lodash';
import { reaction, observe } from 'mobx';

import Sync from '../sync';
import Result from './result';
import {
    belongsTo, computed, identifiedBy, observable, action,
} from '../base';

@identifiedBy('hippo/query/array-result')
export default class ArrayResult extends Result {

    @belongsTo query;
    @observable totalCount = 0;
    @observable rows;
    @observable rowUpdateCount = 0;
    @observable sortAscending;
    @observable sortField;
    @observable.shallow loadingRows = [];

    constructor(attrs) {
        super(attrs);
        bindAll(this, 'onQuerySortChange');
        this.rows = observable.shallowArray([]);
        this.sortField = this.query.sortField;
        this.sortAscending = this.query.sortAscending;

        reaction(
            () => [this.query.sortField, this.query.sortAscending],
            this.onQuerySortChange,
        );
    }

    @computed get updateKey() {
        return [
            this.rows.length,
            (this.sortField ? this.sortField.id : 'none'),
            this.sortAscending,
            this.rowUpdateCount,
        ].join('-');
    }

    insertRow() {
        this.rows.unshift(Array(this.query.info.loadableFields.length));
        this.totalCount += 1;
    }

    isIndexSaved(index) {
        const row = this.rows[index];
        return (row && row[this.query.info.identifierField.dataIndex]);
    }

    removeRow(index) {
        this.rows.splice(index, 1);
        this.totalCount -= 1;
    }

    rowAsObject(index) {
        const row = this.rows[index];
        const obj = {};
        this.query.info.loadableFields.forEach(
            f => (obj[f.id] = (row[f.dataIndex] || f.defaultValue)),
        );
        return obj;
    }

    modelForRow(index) {
        const model = new this.query.src(this.rowAsObject(index)); // eslint-disable-line new-cap
        observe(model, 'syncInProgress', ({ newValue, oldValue }) => {
            if (newValue && !oldValue && newValue.isUpdate) {
                newValue.whenComplete(() => {
                    const row = this.rows[index];
                    this.query.info.loadableFields.forEach((f) => {
                        if (model[f.id]) { row[f.dataIndex] = model[f.id]; }
                    });
                    this.rowUpdateCount += 1;
                }, 99);
            }
        });
        return model;
    }

    fetchModelForRow(index, syncOptions = {}) {
        const model = this.modelForRow(index);
        return model.isNew ? Promise.resolve(model) :
            model.fetch(extend({}, this.query.syncOptions, syncOptions));
    }

    onQuerySortChange() {
        if ((this.sortAscending === this.query.sortAscending) &&
            (this.sortField === this.query.sortField)) {
            return;
        }
        this.sortField = this.query.sortField;
        this.sortAscending = this.query.sortAscending;
        if (isNil(this.sortField)) { return; }
        if (this.fullyLoaded) {
            this.sort();
        } else {
            this.reset().fetch();
        }
    }

    @action
    sort() {
        const asc = this.sortAscending;
        const index = this.sortField.dataIndex;
        this.rows.replace(this.rows.sort((ar, br) => {
            const [a, b] = [ar[index], br[index]];
            if (a === b) { return 0; }
            if (asc) {
                return (a > b) ? 1 : -1;
            }
            return (a < b) ? 1 : -1;
        }));
        return this;
    }

    @computed get fullyLoaded() {
        return this.totalCount === this.rows.length;
    }

    @action reset() {
        this.totalCount = 0;
        this.rows.clear();
        return this;
    }

    searchFieldValues(field, value) {
        const index = field.dataIndex;
        for (let x = 0; x < this.rows.length; x += 1) {
            if (this.rows[x][index] === value) {
                return { row: this.rows[x], index: x };
            }
        }
        return {};
    }

    isRowLoading(index) {
        return !!find(this.loadingRows, ([start, end]) => inRange(index, start, end));
    }

    fetch({ start = this.rows.length, limit = this.query.pageSize } = {}) {
        const inProgress = [start, start + limit];
        this.loadingRows.push(inProgress);

        const query = {};
        this.query.clauses.forEach((clause) => {
            if (clause.isValid) {
                extend(query, clause.toParam());
            }
        });

        const options = extend({}, this.query.syncOptions, {
            start,
            limit,
            total_count: 't',
            format: 'array',
            fields: map(this.query.info.loadableFields, 'id'),
        });

        if (!isEmpty(query)) {
            options.query = query;
        }

        if (!isNil(this.sortField)) {
            options.order = {
                [`${this.sortField.id}`]: (this.sortAscending ? 'asc' : 'desc'),
            };
        }

        extend(options, omit(this.query.info.syncOptions, 'include'));

        this.syncInProgress = options;

        return Sync.perform(this.query.info.syncUrl, options).then((resp) => {
            const rows = resp.data || [];
            if (start + limit >= this.rows.length) {
                range(this.rows.length, start + limit).forEach(() => this.rows.push([]));
            }
            this.rows.splice(start, Math.max(limit, rows.length), ...rows);
            this.totalCount = resp.total;
            this.loadingRows.remove(inProgress);
            delete this.syncInProgress;
            return this;
        });
    }
}
<commit_msg>only insert needed rows<commit_after>import {
    isEmpty, isNil, extend, map, bindAll, omit, inRange, find, range,
} from 'lodash';
import { reaction, observe } from 'mobx';

import Sync from '../sync';
import Result from './result';
import {
    belongsTo, computed, identifiedBy, observable, action,
} from '../base';

@identifiedBy('hippo/query/array-result')
export default class ArrayResult extends Result {

    @belongsTo query;
    @observable totalCount = 0;
    @observable rows;
    @observable rowUpdateCount = 0;
    @observable sortAscending;
    @observable sortField;
    @observable.shallow loadingRows = [];

    constructor(attrs) {
        super(attrs);
        bindAll(this, 'onQuerySortChange');
        this.rows = observable.shallowArray([]);
        this.sortField = this.query.sortField;
        this.sortAscending = this.query.sortAscending;

        reaction(
            () => [this.query.sortField, this.query.sortAscending],
            this.onQuerySortChange,
        );
    }

    @computed get updateKey() {
        return [
            this.rows.length,
            (this.sortField ? this.sortField.id : 'none'),
            this.sortAscending,
            this.rowUpdateCount,
        ].join('-');
    }

    insertRow() {
        this.rows.unshift(Array(this.query.info.loadableFields.length));
        this.totalCount += 1;
    }

    isIndexSaved(index) {
        const row = this.rows[index];
        return (row && row[this.query.info.identifierField.dataIndex]);
    }

    removeRow(index) {
        this.rows.splice(index, 1);
        this.totalCount -= 1;
    }

    rowAsObject(index) {
        const row = this.rows[index];
        const obj = {};
        this.query.info.loadableFields.forEach(
            f => (obj[f.id] = (row[f.dataIndex] || f.defaultValue)),
        );
        return obj;
    }

    modelForRow(index) {
        const model = new this.query.src(this.rowAsObject(index)); // eslint-disable-line new-cap
        observe(model, 'syncInProgress', ({ newValue, oldValue }) => {
            if (newValue && !oldValue && newValue.isUpdate) {
                newValue.whenComplete(() => {
                    const row = this.rows[index];
                    this.query.info.loadableFields.forEach((f) => {
                        if (model[f.id]) { row[f.dataIndex] = model[f.id]; }
                    });
                    this.rowUpdateCount += 1;
                }, 99);
            }
        });
        return model;
    }

    fetchModelForRow(index, syncOptions = {}) {
        const model = this.modelForRow(index);
        return model.isNew ? Promise.resolve(model) :
            model.fetch(extend({}, this.query.syncOptions, syncOptions));
    }

    onQuerySortChange() {
        if ((this.sortAscending === this.query.sortAscending) &&
            (this.sortField === this.query.sortField)) {
            return;
        }
        this.sortField = this.query.sortField;
        this.sortAscending = this.query.sortAscending;
        if (isNil(this.sortField)) { return; }
        if (this.fullyLoaded) {
            this.sort();
        } else {
            this.reset().fetch();
        }
    }

    @action
    sort() {
        const asc = this.sortAscending;
        const index = this.sortField.dataIndex;
        this.rows.replace(this.rows.sort((ar, br) => {
            const [a, b] = [ar[index], br[index]];
            if (a === b) { return 0; }
            if (asc) {
                return (a > b) ? 1 : -1;
            }
            return (a < b) ? 1 : -1;
        }));
        return this;
    }

    @computed get fullyLoaded() {
        return this.totalCount === this.rows.length;
    }

    @action reset() {
        this.totalCount = 0;
        this.rows.clear();
        return this;
    }

    searchFieldValues(field, value) {
        const index = field.dataIndex;
        for (let x = 0; x < this.rows.length; x += 1) {
            if (this.rows[x][index] === value) {
                return { row: this.rows[x], index: x };
            }
        }
        return {};
    }

    isRowLoading(index) {
        return !!find(this.loadingRows, ([start, end]) => inRange(index, start, end));
    }

    fetch({ start = this.rows.length, limit = this.query.pageSize } = {}) {
        const inProgress = [start, start + limit];
        this.loadingRows.push(inProgress);

        const query = {};
        this.query.clauses.forEach((clause) => {
            if (clause.isValid) {
                extend(query, clause.toParam());
            }
        });

        const options = extend({}, this.query.syncOptions, {
            start,
            limit,
            total_count: 't',
            format: 'array',
            fields: map(this.query.info.loadableFields, 'id'),
        });

        if (!isEmpty(query)) {
            options.query = query;
        }

        if (!isNil(this.sortField)) {
            options.order = {
                [`${this.sortField.id}`]: (this.sortAscending ? 'asc' : 'desc'),
            };
        }

        extend(options, omit(this.query.info.syncOptions, 'include'));

        this.syncInProgress = options;

        return Sync.perform(this.query.info.syncUrl, options).then((resp) => {
            const rows = resp.data || [];
            if (start > this.rows.length) {
                range(this.rows.length, start).forEach(() => this.rows.push([]));
            }
            this.rows.splice(start, Math.max(limit, rows.length), ...rows);
            this.totalCount = resp.total;
            this.loadingRows.remove(inProgress);
            delete this.syncInProgress;
            return this;
        });
    }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
  withRouter,
  propTypes as routerPropTypes,
} from 'react-router-dom';

import Sidebar from 'react-sidebar';
import {
  List,
  ListItem,
  makeSelectable,
} from 'material-ui/List';
import ViewList from 'material-ui/svg-icons/action/view-list';
import ShoppingCart from 'material-ui/svg-icons/action/shopping-cart';
import Search from 'material-ui/svg-icons/action/search';
import Feedback from 'material-ui/svg-icons/action/feedback';

const SelectableList = makeSelectable(List);

class NavigationDrawer extends Component {
  static propTypes = {
    ...routerPropTypes,
    children: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.node),
      PropTypes.node,
    ]).isRequired,
    visible: PropTypes.bool.isRequired,
    style: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  };

  static defaultProps = {
    style: {},
  };

  static sidebarStyles = {
    root: {
      top: '4rem',
    },
    sidebar: {
      width: '20vw',
      backgroundColor: 'white',
    },
    content: {
      paddingTop: '2rem',
      paddingBottom: '2rem',
    },
  };

  static menuChildStyle = {
    paddingLeft: '16px',
  };

  handleMenuChange = (event, value) => {
    this.props.history.push(value);
  }

  openFeedback = () => {
    const win = window.open('https://goo.gl/forms/hsEbS3X2HVs4zzdE3', '_blank');
    win.focus();
  }

  render() {
    const currentMajorPath = this.props.location.pathname;

    const SidebarItems = (
      <SelectableList value={currentMajorPath} onChange={this.handleMenuChange}>
        <ListItem
          key="listings"
          primaryText="Listings"
          leftIcon={<ViewList />}
          initiallyOpen
          primaryTogglesNestedList
          nestedItems={[
            <ListItem
              key="recent"
              primaryText="Recent Listings"
              value="/listings"
              style={NavigationDrawer.menuChildStyle}
            />,
            <ListItem
              key="mine"
              primaryText="My Listings"
              value="/listings/mine"
              style={NavigationDrawer.menuChildStyle}
            />,
          ]}
        />
        <ListItem
          key="seeks"
          primaryText="Seeks"
          leftIcon={<ShoppingCart />}
          primaryTogglesNestedList
          nestedItems={[
            <ListItem
              key="recent"
              primaryText="Recent Seeks"
              value="/seeks"
              style={NavigationDrawer.menuChildStyle}
            />,
            <ListItem
              key="mine"
              primaryText="My Seeks"
              value="/seeks/mine"
              style={NavigationDrawer.menuChildStyle}
            />,
          ]}
        />
        <ListItem
          key="savedsearches"
          primaryText="Saved Searches"
          value="/savedsearches"
          leftIcon={<Search />}
        />
        <ListItem
          key="feedback"
          primaryText="Feedback"
          leftIcon={<Feedback />}
          onClick={this.openFeedback}
        />
      </SelectableList>
    );

    return (
      <Sidebar
        docked={this.props.visible}
        sidebar={SidebarItems}
        styles={NavigationDrawer.sidebarStyles}
      >
        {this.props.children}
      </Sidebar>
    );
  }
}

const mapStateToProps = state => ({
  visible: state.leftDrawerVisible,
});

export default withRouter(connect(mapStateToProps)(NavigationDrawer));
<commit_msg>seeks initially open<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
  withRouter,
  propTypes as routerPropTypes,
} from 'react-router-dom';

import Sidebar from 'react-sidebar';
import {
  List,
  ListItem,
  makeSelectable,
} from 'material-ui/List';
import ViewList from 'material-ui/svg-icons/action/view-list';
import ShoppingCart from 'material-ui/svg-icons/action/shopping-cart';
import Search from 'material-ui/svg-icons/action/search';
import Feedback from 'material-ui/svg-icons/action/feedback';

const SelectableList = makeSelectable(List);

class NavigationDrawer extends Component {
  static propTypes = {
    ...routerPropTypes,
    children: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.node),
      PropTypes.node,
    ]).isRequired,
    visible: PropTypes.bool.isRequired,
    style: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  };

  static defaultProps = {
    style: {},
  };

  static sidebarStyles = {
    root: {
      top: '4rem',
    },
    sidebar: {
      width: '20vw',
      backgroundColor: 'white',
    },
    content: {
      paddingTop: '2rem',
      paddingBottom: '2rem',
    },
  };

  static menuChildStyle = {
    paddingLeft: '16px',
  };

  handleMenuChange = (event, value) => {
    this.props.history.push(value);
  }

  openFeedback = () => {
    const win = window.open('https://goo.gl/forms/hsEbS3X2HVs4zzdE3', '_blank');
    win.focus();
  }

  render() {
    const currentMajorPath = this.props.location.pathname;

    const SidebarItems = (
      <SelectableList value={currentMajorPath} onChange={this.handleMenuChange}>
        <ListItem
          key="listings"
          primaryText="Listings"
          leftIcon={<ViewList />}
          initiallyOpen
          primaryTogglesNestedList
          nestedItems={[
            <ListItem
              key="recent"
              primaryText="Recent Listings"
              value="/listings"
              style={NavigationDrawer.menuChildStyle}
            />,
            <ListItem
              key="mine"
              primaryText="My Listings"
              value="/listings/mine"
              style={NavigationDrawer.menuChildStyle}
            />,
          ]}
        />
        <ListItem
          key="seeks"
          primaryText="Seeks"
          leftIcon={<ShoppingCart />}
          initiallyOpen
          primaryTogglesNestedList
          nestedItems={[
            <ListItem
              key="recent"
              primaryText="Recent Seeks"
              value="/seeks"
              style={NavigationDrawer.menuChildStyle}
            />,
            <ListItem
              key="mine"
              primaryText="My Seeks"
              value="/seeks/mine"
              style={NavigationDrawer.menuChildStyle}
            />,
          ]}
        />
        <ListItem
          key="savedsearches"
          primaryText="Saved Searches"
          value="/savedsearches"
          leftIcon={<Search />}
        />
        <ListItem
          key="feedback"
          primaryText="Feedback"
          leftIcon={<Feedback />}
          onClick={this.openFeedback}
        />
      </SelectableList>
    );

    return (
      <Sidebar
        docked={this.props.visible}
        sidebar={SidebarItems}
        styles={NavigationDrawer.sidebarStyles}
      >
        {this.props.children}
      </Sidebar>
    );
  }
}

const mapStateToProps = state => ({
  visible: state.leftDrawerVisible,
});

export default withRouter(connect(mapStateToProps)(NavigationDrawer));
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import {Button, Pagination} from 'react-bootstrap'
import autobind from 'autobind-decorator'

import LongActionModal from 'components/LongActionModal'
import ReportSummary from 'components/ReportSummary'
import ReportTable from 'components/ReportTable'
import ButtonToggleGroup from 'components/ButtonToggleGroup'
import Leaflet from 'components/Leaflet'
import _get from 'lodash.get'

import DOWNLOAD_ICON from 'resources/download.png'

const FORMAT_SUMMARY = 'summary'
const FORMAT_TABLE = 'table'
const FORMAT_MAP = 'map'

const GQL_REPORT_FIELDS =  /* GraphQL */`
	id, intent, engagementDate, keyOutcomes, nextSteps, cancelledReason
	atmosphere, atmosphereDetails, state
	author { id, name }
	primaryAdvisor { id, name, role, position { organization { id, shortName}}},
	primaryPrincipal { id, name, role, position { organization { id, shortName}}},
	advisorOrg { id, shortName},
	principalOrg { id, shortName},
	location { id, name, lat, lng},
	poams {id, shortName, longName},
	tags {id, name, description}
	approvalStatus {
		type, createdAt
		step { id , name
			approvers { id, name, person { id, name, rank } }
		},
		person { id, name, rank}
	}
`

export default class ReportCollection extends Component {
	static propTypes = {
		reports: PropTypes.array,
		paginatedReports: PropTypes.shape({
			totalCount: PropTypes.number,
			pageNum: PropTypes.number,
			pageSize: PropTypes.number,
			list: PropTypes.array.isRequired,
		}),
		goToPage: PropTypes.func,
		downloadAll: PropTypes.func
	}

	constructor(props) {
		super(props)

		this.state = {
			viewFormat: 'summary',
			showCSVExportModal: false,
			current: 0,
			total: 1
		}
	}

	render() {
		var reports

		if (this.props.paginatedReports) {
			var {pageSize, pageNum, totalCount} = this.props.paginatedReports
			var numPages = Math.ceil(totalCount / pageSize)
			reports = this.props.paginatedReports.list
			pageNum++
		} else {
			reports = this.props.reports
		}

		let reportsExist = _get(reports, 'length', 0) > 0

		return

			{reportsExist ?

						<ButtonToggleGroup value={this.state.viewFormat} onChange={this.changeViewFormat} className="hide-for-print">
							<Button value={FORMAT_SUMMARY}>Summary</Button>
							<Button value={FORMAT_TABLE}>Table</Button>
							<Button value={FORMAT_MAP}>Map</Button>
						</ButtonToggleGroup>

						{numPages > 1 &&
							<Pagination
								className="pull-right"
								prev
								next
								items={numPages}
								ellipsis
								maxButtons={6}
								activePage={pageNum}
								onSelect={(value) => {this.props.goToPage(value - 1)}}
							/>
						}

						{
							this.props.downloadAll &&

								<Button  onClick={this.startCSVExportModal}></Button>
								<LongActionModal showModal={this.state.showCSVExportModal && (this.state.current < this.state.total - 1)} onCancel={this.cancelCSVExportModal} current={this.state.current} total={this.state.total} ></LongActionModal>

						}
						{this.props.isSuperUser &&

								Filter: {this.renderToggleFilterButton(this.props)}

						}

						{this.state.viewFormat === FORMAT_TABLE && this.renderTable(reports)}
						{this.state.viewFormat === FORMAT_SUMMARY && this.renderSummary(reports)}
						{this.state.viewFormat === FORMAT_MAP && this.renderMap(reports)}

				:
				No reports found
			}

	}

	renderToggleFilterButton(props) {
		let showAll = 'Show all reports'
		let showPendingApproval = 'Show pending approval'
		let buttonText = (props.filterIsSet) ? showAll: showPendingApproval
		let button = <Button value="toggle-filter" className="btn btn-sm" onClick={props.setReportsFilter}>{buttonText}</Button>
		return button
	}

	renderTable(reports) {
		return <ReportTable showAuthors={true} reports={reports} />
	}

	renderSummary(reports) {
		return

			{reports.map(report =>
				<ReportSummary report={report} key={report.id} />
			)}

	}

	renderMap(reports) {
		let markers = []
		reports.forEach(report => {
			if (report.location && report.location.lat) {
				markers.push({id: report.id, lat: report.location.lat, lng: report.location.lng , name: report.intent })
			}
		})
		return <Leaflet markers={markers} />
	}

	@autobind
	changeViewFormat(value) {
		this.setState({viewFormat: value})
	}

	@autobind
	startCSVExportModal() {
		this.setState({showCSVExportModal: true})
		let that = this
		this.props.downloadAll(
			(current,total) => {
				that.setState({current: current,
					total : total})
			}
		 )
	}

	@autobind
	cancelCSVExportModal(success) {
		this.setState({showCSVExportModal: false})
	}

}

ReportCollection.GQL_REPORT_FIELDS = GQL_REPORT_FIELDS
<commit_msg>Correcly compute numPages when pageSize <= 0<commit_after>import React, {Component, PropTypes} from 'react'
import {Button, Pagination} from 'react-bootstrap'
import autobind from 'autobind-decorator'

import LongActionModal from 'components/LongActionModal'
import ReportSummary from 'components/ReportSummary'
import ReportTable from 'components/ReportTable'
import ButtonToggleGroup from 'components/ButtonToggleGroup'
import Leaflet from 'components/Leaflet'
import _get from 'lodash.get'

import DOWNLOAD_ICON from 'resources/download.png'

const FORMAT_SUMMARY = 'summary'
const FORMAT_TABLE = 'table'
const FORMAT_MAP = 'map'

const GQL_REPORT_FIELDS =  /* GraphQL */`
	id, intent, engagementDate, keyOutcomes, nextSteps, cancelledReason
	atmosphere, atmosphereDetails, state
	author { id, name }
	primaryAdvisor { id, name, role, position { organization { id, shortName}}},
	primaryPrincipal { id, name, role, position { organization { id, shortName}}},
	advisorOrg { id, shortName},
	principalOrg { id, shortName},
	location { id, name, lat, lng},
	poams {id, shortName, longName},
	tags {id, name, description}
	approvalStatus {
		type, createdAt
		step { id , name
			approvers { id, name, person { id, name, rank } }
		},
		person { id, name, rank}
	}
`

export default class ReportCollection extends Component {
	static propTypes = {
		reports: PropTypes.array,
		paginatedReports: PropTypes.shape({
			totalCount: PropTypes.number,
			pageNum: PropTypes.number,
			pageSize: PropTypes.number,
			list: PropTypes.array.isRequired,
		}),
		goToPage: PropTypes.func,
		downloadAll: PropTypes.func
	}

	constructor(props) {
		super(props)

		this.state = {
			viewFormat: 'summary',
			showCSVExportModal: false,
			current: 0,
			total: 1
		}
	}

	render() {
		var reports

		if (this.props.paginatedReports) {
			var {pageSize, pageNum, totalCount} = this.props.paginatedReports
			var numPages = (pageSize <= 0) ? 1 : Math.ceil(totalCount / pageSize)
			reports = this.props.paginatedReports.list
			pageNum++
		} else {
			reports = this.props.reports
		}

		let reportsExist = _get(reports, 'length', 0) > 0

		return

			{reportsExist ?

						<ButtonToggleGroup value={this.state.viewFormat} onChange={this.changeViewFormat} className="hide-for-print">
							<Button value={FORMAT_SUMMARY}>Summary</Button>
							<Button value={FORMAT_TABLE}>Table</Button>
							<Button value={FORMAT_MAP}>Map</Button>
						</ButtonToggleGroup>

						{numPages > 1 &&
							<Pagination
								className="pull-right"
								prev
								next
								items={numPages}
								ellipsis
								maxButtons={6}
								activePage={pageNum}
								onSelect={(value) => {this.props.goToPage(value - 1)}}
							/>
						}

						{
							this.props.downloadAll &&

								<Button  onClick={this.startCSVExportModal}></Button>
								<LongActionModal showModal={this.state.showCSVExportModal && (this.state.current < this.state.total - 1)} onCancel={this.cancelCSVExportModal} current={this.state.current} total={this.state.total} ></LongActionModal>

						}
						{this.props.isSuperUser &&

								Filter: {this.renderToggleFilterButton(this.props)}

						}

						{this.state.viewFormat === FORMAT_TABLE && this.renderTable(reports)}
						{this.state.viewFormat === FORMAT_SUMMARY && this.renderSummary(reports)}
						{this.state.viewFormat === FORMAT_MAP && this.renderMap(reports)}

				:
				No reports found
			}

	}

	renderToggleFilterButton(props) {
		let showAll = 'Show all reports'
		let showPendingApproval = 'Show pending approval'
		let buttonText = (props.filterIsSet) ? showAll: showPendingApproval
		let button = <Button value="toggle-filter" className="btn btn-sm" onClick={props.setReportsFilter}>{buttonText}</Button>
		return button
	}

	renderTable(reports) {
		return <ReportTable showAuthors={true} reports={reports} />
	}

	renderSummary(reports) {
		return

			{reports.map(report =>
				<ReportSummary report={report} key={report.id} />
			)}

	}

	renderMap(reports) {
		let markers = []
		reports.forEach(report => {
			if (report.location && report.location.lat) {
				markers.push({id: report.id, lat: report.location.lat, lng: report.location.lng , name: report.intent })
			}
		})
		return <Leaflet markers={markers} />
	}

	@autobind
	changeViewFormat(value) {
		this.setState({viewFormat: value})
	}

	@autobind
	startCSVExportModal() {
		this.setState({showCSVExportModal: true})
		let that = this
		this.props.downloadAll(
			(current,total) => {
				that.setState({current: current,
					total : total})
			}
		 )
	}

	@autobind
	cancelCSVExportModal(success) {
		this.setState({showCSVExportModal: false})
	}

}

ReportCollection.GQL_REPORT_FIELDS = GQL_REPORT_FIELDS
<|endoftext|>


<commit_before>import React from 'react';

import '../../styles/routes/route.css';

const RoutePage = ({
  id, log_number, status, delivery_count,
  updated_at, driver, truck, deliveries
}) => {
  const last_updated = new Date(updated_at).toDateString();
  const delivery_list = deliveries.map(delivery =>
{delivery.invoice_number}
)
  return (
    <div id={`route-${id}`}>

Route -> Log number {log_number}

Status: {status}

Driver: {driver.username}

Truck: {truck.name}

Last Updated: {last_updated}

Deliveries:

        {delivery_list}

  );
}

export default RoutePage;<commit_msg>add modal and move to inherit from component<commit_after>import React, {Component} from 'react';

import { Modal } from 'react-bootstrap';

import DeliveryContainer from '../../containers/DeliveryContainer';

import '../../styles/routes/route.css';

class RoutePage extends Component{

  render () {
    const last_updated = new Date(this.props.updated_at).toDateString();
    const delivery_list = this.props.deliveries.map((delivery, index) =>
      <DeliveryContainer key={index} route_id={this.props.id} delivery={delivery}/>
    )

    return (
      <div id={`route-${this.props.id}`}>

Route -> Log number {this.props.log_number}

Status: {this.props.status}

Driver: {this.props.driver.username}

Truck: {this.props.truck.name}

Last Updated: {last_updated}

          Deliveries:
          <button className="btn btn-primary" onClick={this.props.createDelivery}>Add Delivery</button>

          {delivery_list}

    );
  }
}

export default RoutePage;<|endoftext|>


<commit_before>import React from "react";
import CX from "classnames";
import { get } from "lodash-es";
import { connect } from "react-redux";
import { LinkContainer } from "react-router-bootstrap";
import { Row, Col, Label } from "react-bootstrap";

import { getTaskDisplayName } from "../../utils/utils";
import { Icon, Loader, RelativeTime } from "../../base";
import { removeAnalysis } from "../actions";
import { getCanModify } from "../../samples/selectors";

export const AnalysisItem = props => {
    const itemClass = CX("list-group-item spaced", { hoverable: props.ready });
    const loaderIcon = <Loader size="14px" color="#3c8786" style={{ display: "inline" }} />;
    const canRemove = props.ready && props.canModify;

    const endIcon = canRemove ? (
        <Icon name="trash" bsStyle="danger" onClick={props.onRemove} style={{ fontSize: "17px" }} pullRight />
    ) : (
        {loaderIcon}
    );

    const reference = props.placeholder ? null : (

            {props.reference.name}
            {props.index.version}

    );

    const content = (

            <Row>
                <Col xs={4} sm={4} md={4}>
                    {getTaskDisplayName(props.algorithm)}
                </Col>
                <Col xs={5} sm={4} md={4}>
                    Started <RelativeTime time={props.created_at} />
                    {props.placeholder ? null : ` by ${props.user.id}`}
                </Col>
                <Col xs={2} sm={2} md={2}>
                    {reference}
                </Col>
                <Col xs={1} smHidden mdHidden lgHidden>
                    {endIcon}
                </Col>
                <Col xsHidden sm={2} md={2}>
                    {canRemove ? endIcon : {loaderIcon} In Progress}
                </Col>
            </Row>

    );

    if (props.placeholder) {
        return content;
    }

    return <LinkContainer to={`/samples/${props.sampleId}/analyses/${props.id}`}>{content}</LinkContainer>;
};

const mapStateToProps = state => ({
    sampleId: get(state.samples.detail, "id"),
    canModify: getCanModify(state)
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    onRemove: () => {
        dispatch(removeAnalysis(ownProps.id));
    }
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(AnalysisItem);
<commit_msg>Fix incorrect loading state for some analysis items<commit_after>import React from "react";
import CX from "classnames";
import { get } from "lodash-es";
import { connect } from "react-redux";
import { LinkContainer } from "react-router-bootstrap";
import { Row, Col, Label } from "react-bootstrap";

import { getTaskDisplayName } from "../../utils/utils";
import { Icon, Loader, RelativeTime } from "../../base";
import { removeAnalysis } from "../actions";
import { getCanModify } from "../../samples/selectors";

export const RightIcon = ({ canModify, onRemove, ready }) => {
    if (ready) {
        if (canModify) {
            return <Icon name="trash" bsStyle="danger" onClick={onRemove} style={{ fontSize: "17px" }} pullRight />;
        }

        return null;
    }

    return (

            <Loader size="14px" color="#3c8786" />

    );
};

export const AnalysisItem = props => {
    const itemClass = CX("list-group-item spaced", { hoverable: props.ready });

    const reference = props.placeholder ? null : (

            {props.reference.name}
            {props.index.version}

    );

    const content = (

            <Row>
                <Col xs={4} sm={4} md={4}>
                    {getTaskDisplayName(props.algorithm)}
                </Col>
                <Col xs={5} sm={4} md={4}>
                    Started <RelativeTime time={props.created_at} />
                    {props.placeholder ? null : ` by ${props.user.id}`}
                </Col>
                <Col xs={2}>{reference}</Col>
                <Col xsHidden sm={2} md={2}>
                    <RightIcon {...props} />
                </Col>
            </Row>

    );

    if (props.placeholder) {
        return content;
    }

    return <LinkContainer to={`/samples/${props.sampleId}/analyses/${props.id}`}>{content}</LinkContainer>;
};

const mapStateToProps = state => ({
    sampleId: get(state.samples.detail, "id"),
    canModify: getCanModify(state)
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    onRemove: () => {
        dispatch(removeAnalysis(ownProps.id));
    }
});

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