<commit_before>$(function () {
    $('.content').insertBefore('.hfooter');
    $('.content p:gt(0)').hide();
    $('.content .readmore').click(function () {
        if ($(this).hasClass('active')) {
            $('.content p:gt(0)').slideUp('fast');
            $(this).removeClass('active').text('Читать полностью');
        } else {
            $('.content p:gt(0)').slideDown('fast');
            $(this).addClass('active').text('Свернуть');
        }
        return false;
    });
    $(document).click(function (event) {
        if ($(event.target).closest(".text.active").length) return;
        $('.text .readmore.active').click();
        event.stopPropagation();
    });
    $('.text .readmore').click(function () {
        var text = $(this).closest('.text');
        if ($(this).hasClass('active')) {
            text.find('.fulltext').slideUp('fast', function () {
                text.removeClass('active');
            });
            $(this).removeClass('active').text('Читать полностью');
        } else {
            $('.text .readmore.active').click();
            text.addClass('active');
            text.find('.fulltext').slideDown('fast');
            $(this).addClass('active').text('Свернуть');
        }
        return false;
    });
    $('.topblock form input[type="text"],.advantages.inner form input[type="text"]').mask("+7 (999) 999-99-99");
    $('.products-line .category').hover(function () {
        var category = $(this);
        if (category.hasClass('top-left'))
            $('.products .categories .top-left').show();
        else if (category.hasClass('top-right'))
            $('.products .categories .top-right').show();
        else if (category.hasClass('bottom-left'))
            $('.products .categories .bottom-left').show();
        else if (category.hasClass('bottom-center'))
            $('.products .categories .bottom-center').show();
        else if (category.hasClass('bottom-right'))
            $('.products .categories .bottom-right').show();
        $('.products .bg').show();
    });
    $('.products .categories .category-content').mouseleave(function () {
        $('.products .categories .category-content,.products .bg').hide();
    });
    var overflowtimeout;

    function setOverflow(block, status) {
        $(block).css('overflow', status);
    }

    $('.catalog .catalog_blocks .category').hover(function () {
        var block = $(this);
        overflowtimeout = setTimeout(function () {
            setOverflow(block, 'visible');
        }, 300);
    }, function () {
        $(this).css('overflow', 'hidden');

        var wrapper = $(this).find('.list_wrapper');
        var button = $(this).find('.showall');
        var height = 193;
        var top = 0;
        wrapper.css('top', '');
        wrapper.find('.product:gt(3)').slideUp('fast');
        button.html('показать все').css('margin-right', '');
        wrapper.removeClass('active');

        clearTimeout(overflowtimeout);
    });
    $('.page .title .hidepage').click(function () {
        $('.text .readmore.active').click();
        var title = $(this).closest('.title');
        var span = title.find('span');
        var spantext = span.text();
        var page = $(this).closest('.page').find('.item');
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
            span.html(spantext.replace('(скрыта)', ''));
            $(this).text('Скрыть');
            page.slideDown('fast');
        } else {
            $(this).addClass('active');
            span.html(spantext + ' (скрыта)');
            $(this).text('Показать');
            page.slideUp('fast');
        }
        return false;
    });
    $('.tooltip').tooltipster({
        delay: 0,
        speed: 0,
        interactive: true,
        minWidth: 300,
        maxWidth: 300
    });
    $('.clients .carousel').jcarousel();
    $('.clients .next').click(function () {
        $('.clients .carousel').jcarousel('scroll', '+=1');
        return false;
    });
    $('.clients .prev').click(function () {
        $('.clients .carousel').jcarousel('scroll', '-=1');
        return false;
    });
    $('.category_page .page .item .right .select').click(function () {
        //$('.text .readmore.active').click();
        $('.popup').css('top', $(window).scrollTop());
        $('.popup,.background').fadeIn('fast');

        return false;
    });

    /*$('.selectMy').on('click', function () {
     $('.text .readmore.active').click();
     $('.popup').css('top', $(window).scrollTop());
     $('.popup,.background').fadeIn('fast');
     return false;
     });*/

    $('.background').click(function () {
        $('.popup,.background').fadeOut('fast');
        return false;
    });

    $('.list_wrapper').each(function () {
        $(this).find('.product:gt(3)').hide();
    });
    $('.list_wrapper .showall').click(function () {
        var wrapper = $(this).closest('.list_wrapper');
        if (wrapper.hasClass('active')) {
            var height = 193;
            var top = 0;
            wrapper.css('top', '');
            wrapper.find('.product:gt(3)').slideUp('fast');
            $(this).html('показать все').css('margin-right', '');
            wrapper.removeClass('active');
        } else {
            var height = wrapper.find('.product').length * 36 + 49;
            var top = 193 - height;
            wrapper.css('top', top);
            wrapper.find('.product:gt(3)').slideDown('fast');
            $(this).html('свернуть').css('margin-right', 25);
            wrapper.addClass('active');
        }
        return false;
    });
});

$(document).ready(function () {
    $('.selectMy').on('click', function () {
        //$('.text .readmore.active').click();
        var id = $(this).attr('data-target');
        $.ajax({
            type: "get",
            url: 'get_sup',
            data: "id=" + id,
            success: function (msg) {
                $('.popup').html(msg);
            }
        });
        $('.popup').css('top', $(window).scrollTop());
        $('.popup,.background').fadeIn('fast');
        return false;
    });

    $(document).on('click', '.close', function () {
        $('.popup,.background').fadeOut('fast');
        return false;
    });

    $(document).on('click','.order',function () {
        var blId = $(this).attr('blind-id');
        var mtId = $(this).attr('suuples-id');
        $('#productInfo').attr('blind-id', blId);
        $('#productInfo').attr('mat-id', mtId);
        $('#myModal3').modal('show');
       /* $.ajax({
            type: "get",
            url: 'get_order',
            data: "blId=" + blId +"mtId" + mtId,
            success: function (msg) {
                $('.popup').html(msg);
            }
        });*/
        return false;
    });

    $(document).on('click','#сheck',function () {
        var blId = $('#productInfo').attr('blind-id');
        var mtId = $('#productInfo').attr('mat-id');
        var tel = $('.tel').val();
        $.ajax({
            type: "get",
            url: 'get_order',
            data: "&blId=" + blId + "&mtId=" + mtId + "&tel=" + tel,
            success: function (msg) {
                console.log(msg);
            }
        });
    });

    $(document).on('click','.small', function(){

        var smallImg = $(this).children("img").attr('src');
        var imgBlock = $(this).parent().parent();

        imgBlock.children('.large').children().attr('src',smallImg);

        return false;

    });
});

<commit_msg>mail orders<commit_after>$(function () {
    $('.content').insertBefore('.hfooter');
    $('.content p:gt(0)').hide();
    $('.content .readmore').click(function () {
        if ($(this).hasClass('active')) {
            $('.content p:gt(0)').slideUp('fast');
            $(this).removeClass('active').text('Читать полностью');
        } else {
            $('.content p:gt(0)').slideDown('fast');
            $(this).addClass('active').text('Свернуть');
        }
        return false;
    });
    $(document).click(function (event) {
        if ($(event.target).closest(".text.active").length) return;
        $('.text .readmore.active').click();
        event.stopPropagation();
    });
    $('.text .readmore').click(function () {
        var text = $(this).closest('.text');
        if ($(this).hasClass('active')) {
            text.find('.fulltext').slideUp('fast', function () {
                text.removeClass('active');
            });
            $(this).removeClass('active').text('Читать полностью');
        } else {
            $('.text .readmore.active').click();
            text.addClass('active');
            text.find('.fulltext').slideDown('fast');
            $(this).addClass('active').text('Свернуть');
        }
        return false;
    });
    $('.topblock form input[type="text"],.advantages.inner form input[type="text"]').mask("+7 (999) 999-99-99");
    $('.products-line .category').hover(function () {
        var category = $(this);
        if (category.hasClass('top-left'))
            $('.products .categories .top-left').show();
        else if (category.hasClass('top-right'))
            $('.products .categories .top-right').show();
        else if (category.hasClass('bottom-left'))
            $('.products .categories .bottom-left').show();
        else if (category.hasClass('bottom-center'))
            $('.products .categories .bottom-center').show();
        else if (category.hasClass('bottom-right'))
            $('.products .categories .bottom-right').show();
        $('.products .bg').show();
    });
    $('.products .categories .category-content').mouseleave(function () {
        $('.products .categories .category-content,.products .bg').hide();
    });
    var overflowtimeout;

    function setOverflow(block, status) {
        $(block).css('overflow', status);
    }

    $('.catalog .catalog_blocks .category').hover(function () {
        var block = $(this);
        overflowtimeout = setTimeout(function () {
            setOverflow(block, 'visible');
        }, 300);
    }, function () {
        $(this).css('overflow', 'hidden');

        var wrapper = $(this).find('.list_wrapper');
        var button = $(this).find('.showall');
        var height = 193;
        var top = 0;
        wrapper.css('top', '');
        wrapper.find('.product:gt(3)').slideUp('fast');
        button.html('показать все').css('margin-right', '');
        wrapper.removeClass('active');

        clearTimeout(overflowtimeout);
    });
    $('.page .title .hidepage').click(function () {
        $('.text .readmore.active').click();
        var title = $(this).closest('.title');
        var span = title.find('span');
        var spantext = span.text();
        var page = $(this).closest('.page').find('.item');
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
            span.html(spantext.replace('(скрыта)', ''));
            $(this).text('Скрыть');
            page.slideDown('fast');
        } else {
            $(this).addClass('active');
            span.html(spantext + ' (скрыта)');
            $(this).text('Показать');
            page.slideUp('fast');
        }
        return false;
    });
    $('.tooltip').tooltipster({
        delay: 0,
        speed: 0,
        interactive: true,
        minWidth: 300,
        maxWidth: 300
    });
    $('.clients .carousel').jcarousel();
    $('.clients .next').click(function () {
        $('.clients .carousel').jcarousel('scroll', '+=1');
        return false;
    });
    $('.clients .prev').click(function () {
        $('.clients .carousel').jcarousel('scroll', '-=1');
        return false;
    });
    $('.category_page .page .item .right .select').click(function () {
        //$('.text .readmore.active').click();
        $('.popup').css('top', $(window).scrollTop());
        $('.popup,.background').fadeIn('fast');

        return false;
    });

    /*$('.selectMy').on('click', function () {
     $('.text .readmore.active').click();
     $('.popup').css('top', $(window).scrollTop());
     $('.popup,.background').fadeIn('fast');
     return false;
     });*/

    $('.background').click(function () {
        $('.popup,.background').fadeOut('fast');
        return false;
    });

    $('.list_wrapper').each(function () {
        $(this).find('.product:gt(3)').hide();
    });
    $('.list_wrapper .showall').click(function () {
        var wrapper = $(this).closest('.list_wrapper');
        if (wrapper.hasClass('active')) {
            var height = 193;
            var top = 0;
            wrapper.css('top', '');
            wrapper.find('.product:gt(3)').slideUp('fast');
            $(this).html('показать все').css('margin-right', '');
            wrapper.removeClass('active');
        } else {
            var height = wrapper.find('.product').length * 36 + 49;
            var top = 193 - height;
            wrapper.css('top', top);
            wrapper.find('.product:gt(3)').slideDown('fast');
            $(this).html('свернуть').css('margin-right', 25);
            wrapper.addClass('active');
        }
        return false;
    });
});

$(document).ready(function () {
    $('.selectMy').on('click', function () {
        //$('.text .readmore.active').click();
        var id = $(this).attr('data-target');
        $.ajax({
            type: "get",
            url: 'get_sup',
            data: "id=" + id,
            success: function (msg) {
                $('.popup').html(msg);
            }
        });
        $('.popup').css('top', $(window).scrollTop());
        $('.popup,.background').fadeIn('fast');
        return false;
    });

    $(document).on('click', '.close', function () {
        $('.popup,.background').fadeOut('fast');
        return false;
    });

    $(document).on('click','.order',function () {

        var blId = $(this).attr('blind-id');
        var mtId = $(this).attr('suuples-id');
        $('#productInfo').attr('blind-id', blId);
        $('#productInfo').attr('mat-id', mtId);
        document.getElementById('mod').style.display='block';
        $('#mod').css('top', $(window).scrollTop() + 50);
        return false;
    });

    $(document).on('click','#closePhone',function(){
        $('#mod').css('display','none');
    });

    $(document).on('click','#сheck',function () {
        var blId = $('#productInfo').attr('blind-id');
        var mtId = $('#productInfo').attr('mat-id');
        var tel = $('.tel').val();
        $.ajax({
            type: "get",
            url: 'get_order',
            data: "&blId=" + blId + "&mtId=" + mtId + "&tel=" + tel,
            success: function (msg) {
                alert('Ваш заказ сделан. В ближайшее время с вами свяжуться');
            }
        });
        $('#mod').css('display','none');
    });

    $(document).on('click','.small', function(){

        var smallImg = $(this).children("img").attr('src');
        var imgBlock = $(this).parent().parent();

        imgBlock.children('.large').children().attr('src',smallImg);

        return false;

    });
});

<|endoftext|>


<commit_before>const ARG_WATER_VOLUME = 'water_volume';
const Str = require('./strings');
const util = require('util');

class Conversation {
    constructor(dialogflowApp, userManager, waterLog, timeManager) {
        this.dialogflowApp = dialogflowApp;
        this.userManager = userManager;
        this.waterLog = waterLog;
        this.timeManager = timeManager;
    }

    //Intent input.welcome
    actionWelcomeUser() {
        return this.userManager.isFirstUsage(this._getCurrentUserId())
            .then(isFirstUsage => {
                if (isFirstUsage) {
                    this.userManager.saveAssistantUser(this._getCurrentUserId());
                    this._greetNewUser();
                } else {
                    return this._greetExistingUser();
                }

                return isFirstUsage;
            });
    }

    _greetNewUser() {
        this.dialogflowApp.ask(Str.GREETING_NEW_USER, Str.GREETING_NEW_USER_NO_INPUT_PROMPT);
    }

    _greetExistingUser() {
        const loggedWaterPromise = this.waterLog.getLoggedWaterForUser(this._getCurrentUserId());
        const userNamePromise = this.userManager.loadAssistantUser(this._getCurrentUserId());

        return Promise.all([loggedWaterPromise, userNamePromise])
            .then(values => {
                const loggedWater = values[0];
                const userGivenName = values[1].givenName;
                let formattedName = '';
                if (userGivenName) {
                    formattedName = ' ' + userGivenName;
                }
                this.dialogflowApp.ask(
                    util.format(Str.GREETING_EXISTING_USER, formattedName, loggedWater),
                    Str.GREETING_EXISTING_USER_NO_INPUT_PROMPT
                );
            });
    }

    //Intent log_water
    actionLogWater() {
        //Get argument extracted by Dialogflow
        let waterToLog = this.dialogflowApp.getArgument(ARG_WATER_VOLUME);
        //Save logged water into Firebase Realtime Database
        this.waterLog.saveLoggedWater(this._getCurrentUserId(), waterToLog);
        //Load sum of logged water for current user and reply user
        //with how much water he or she logged so far.
        //End the conversation.
        return this.waterLog.getLoggedWaterForUser(this._getCurrentUserId())
            .then(loggedWater => {
                this.dialogflowApp.tell(
                    util.format(Str.WATER_LOGGED_NOW,
                        waterToLog.amount,
                        waterToLog.unit,
                        loggedWater
                    )
                );
            });
    }

    //Intent get_logged_water
    actionGetLoggedWater() {
        return this.waterLog.getLoggedWaterForUser(this._getCurrentUserId())
            .then(loggedWater => this.dialogflowApp.tell(util.format(Str.WATER_LOGGED_OVERALL, loggedWater)));
    }

    //Intent update_settings
    actionUpdateSettings() {
        this._askForUserName();
    }

    _askForUserName() {
        const permission = this.dialogflowApp.SupportedPermissions.NAME;
        this.dialogflowApp.askForPermission(Str.PERMISSIONS_ASK_FOR_NAME, permission);
    }

    _askForUserPreciseLocation(userName) {
        const permission = this.dialogflowApp.SupportedPermissions.DEVICE_PRECISE_LOCATION;
        return this.timeManager.getPlatformTime().then(platformTime => {
            this.dialogflowApp.askForPermission(
                util.format(Str.PERMISSIONS_ASK_FOR_LOCATION, userName, platformTime),
                permission
            );
        })
    }

    //Intent user_data
    actionUserData() {
        if (this.dialogflowApp.isPermissionGranted()) {
            const userName = this.dialogflowApp.getUserName();
            if (userName) {
                this.userManager.saveAssistantUserName(this._getCurrentUserId(), userName);
                const deviceLocation = this.dialogflowApp.getDeviceLocation();
                if (deviceLocation) {
                    return this._setupUserTimezoneAndFinish(deviceLocation);
                } else {
                    return this._askForUserPreciseLocation(userName.givenName)
                }
            } else {
                this._finishWithUnexpectedProblems();
            }
        } else {
            this._finishWithPermissionsDenied();
        }

        return Promise.resolve(true);
    }

    _setupUserTimezoneAndFinish(deviceLocation) {
        const timezone = this.timeManager.getTimeZoneFromCoordinates(deviceLocation.coordinates);
        return this.timeManager.saveAssistantUserTimezone(this._getCurrentUserId(), timezone).then(() => {
            this.dialogflowApp.tell(Str.SETTINGS_UPDATE);
        });
    }

    _finishWithUnexpectedProblems() {
        this.dialogflowApp.tell(Str.PERMISSIONS_UNEXPECTED_ISSUES);
    }

    _finishWithPermissionsDenied() {
        this.dialogflowApp.tell(Str.PERMISSIONS_DENIED);
    }

    _getCurrentUserId() {
        return this.dialogflowApp.getUser().userId;
    }
}

module.exports = Conversation;
<commit_msg>code refactor<commit_after>const ARG_WATER_VOLUME = 'water_volume';
const Str = require('./strings');
const util = require('util');

class Conversation {
    constructor(dialogflowApp, userManager, waterLog, timeManager) {
        this.dialogflowApp = dialogflowApp;
        this.userManager = userManager;
        this.waterLog = waterLog;
        this.timeManager = timeManager;
    }

    //Intent input.welcome
    actionWelcomeUser() {
        return this.userManager.isFirstUsage(this._getCurrentUserId())
            .then(isFirstUsage => {
                if (isFirstUsage) {
                    this.userManager.saveAssistantUser(this._getCurrentUserId());
                    this._greetNewUser();
                } else {
                    return this._greetExistingUser();
                }

                return isFirstUsage;
            });
    }

    _greetNewUser() {
        this.dialogflowApp.ask(Str.GREETING_NEW_USER, Str.GREETING_NEW_USER_NO_INPUT_PROMPT);
    }

    _greetExistingUser() {
        const loggedWaterPromise = this.waterLog.getLoggedWaterForUser(this._getCurrentUserId());
        const userNamePromise = this.userManager.loadAssistantUser(this._getCurrentUserId());

        return Promise.all([loggedWaterPromise, userNamePromise])
            .then(values => {
                const loggedWater = values[0];
                const userGivenName = values[1].givenName;
                let formattedName = '';
                if (userGivenName) {
                    formattedName = ' ' + userGivenName;
                }
                this.dialogflowApp.ask(
                    util.format(Str.GREETING_EXISTING_USER, formattedName, loggedWater),
                    Str.GREETING_EXISTING_USER_NO_INPUT_PROMPT
                );
            });
    }

    //Intent log_water
    actionLogWater() {
        //Get argument extracted by Dialogflow
        let waterToLog = this.dialogflowApp.getArgument(ARG_WATER_VOLUME);
        //Save logged water into Firebase Realtime Database
        this.waterLog.saveLoggedWater(this._getCurrentUserId(), waterToLog);
        //Load sum of logged water for current user and reply user
        //with how much water he or she logged so far.
        //End the conversation.
        return this.waterLog.getLoggedWaterForUser(this._getCurrentUserId())
            .then(loggedWater => {
                this.dialogflowApp.tell(
                    util.format(Str.WATER_LOGGED_NOW,
                        waterToLog.amount,
                        waterToLog.unit,
                        loggedWater
                    )
                );
            });
    }

    //Intent get_logged_water
    actionGetLoggedWater() {
        return this.waterLog.getLoggedWaterForUser(this._getCurrentUserId())
            .then(loggedWater => this.dialogflowApp.tell(util.format(Str.WATER_LOGGED_OVERALL, loggedWater)));
    }

    //Intent update_settings
    actionUpdateSettings() {
        this._askForUserName();
    }

    _askForUserName() {
        const permission = this.dialogflowApp.SupportedPermissions.NAME;
        this.dialogflowApp.askForPermission(Str.PERMISSIONS_ASK_FOR_NAME, permission);
    }

    //Intent user_data
    actionUserData() {
        if (this.dialogflowApp.isPermissionGranted()) {
            const userName = this.dialogflowApp.getUserName();
            if (userName) {
                this.userManager.saveAssistantUserName(this._getCurrentUserId(), userName);
                const deviceLocation = this.dialogflowApp.getDeviceLocation();
                if (deviceLocation) {
                    return this._setupUserTimezoneAndFinish(deviceLocation);
                } else {
                    return this._askForUserPreciseLocation(userName.givenName)
                }
            } else {
                this._finishWithUnexpectedProblems();
            }
        } else {
            this._finishWithPermissionsDenied();
        }

        return Promise.resolve(true);
    }

    _setupUserTimezoneAndFinish(deviceLocation) {
        const timezone = this.timeManager.getTimeZoneFromCoordinates(deviceLocation.coordinates);
        return this.timeManager.saveAssistantUserTimezone(this._getCurrentUserId(), timezone).then(() => {
            this.dialogflowApp.tell(Str.SETTINGS_UPDATE);
        });
    }

    _askForUserPreciseLocation(userName) {
        const permission = this.dialogflowApp.SupportedPermissions.DEVICE_PRECISE_LOCATION;
        return this.timeManager.getPlatformTime().then(platformTime => {
            this.dialogflowApp.askForPermission(
                util.format(Str.PERMISSIONS_ASK_FOR_LOCATION, userName, platformTime),
                permission
            );
        })
    }

    _finishWithUnexpectedProblems() {
        this.dialogflowApp.tell(Str.PERMISSIONS_UNEXPECTED_ISSUES);
    }

    _finishWithPermissionsDenied() {
        this.dialogflowApp.tell(Str.PERMISSIONS_DENIED);
    }

    _getCurrentUserId() {
        return this.dialogflowApp.getUser().userId;
    }
}

module.exports = Conversation;
<|endoftext|>


<commit_before>
function BeamModel(a1, sensorRadius, map, width, height)
{
	//Gaussian noise on hit
	this.a1 = a1;

	this.map = map;

	this.width = width;
	this.height = height;

	//Sensor radius
	this.sensorRadius = sensorRadius;
}

/*
	Probability of getting measurement z
	if the robot pose is 'state'. (Given map m)
 */
BeamModel.prototype.probability = function(z, state)
{
    // if(state.x < 0 || state.y < 0 || state.x >= this.width || state.y >= this.height)
    //     return 0;

    const m = this.map;

    var z_true = new Array(z.length);

    var q = 1;

    //Obtain the true distances
    scan(state.x, state.y, this.sensorRadius, m, z_true);

    const nLasers = z.length;

    const dirOffset = Math.round(state.dir/(TWO_PI) * nLasers);

    //z will be an array of noised distances, obtained by robot's sensor
    var i = (dirOffset - nLasers/4);
    i += nLasers + nLasers;

    for(var index = 0; index <= nLasers/2; index ++, i++)
    {
        // if(z[i] > this.sensorRadius || z_true[i] > this.sensorRadius)
        //     continue;
        i %= nLasers;
        q *= (prob_gaussian(z[i] - z_true[i], this.a1*z_true[i]));
    }
    return q;
};

BeamModel.prototype.prob_log = function(z, state)
{
    // if(state.x < 0 || state.y < 0 || state.x >= this.width || state.y >= this.height)
    //     return Number.NEGATIVE_INFINITY;

    const m = this.map;

    var z_true = new Array(z.length);

    var q = 0;

    //Obtain the true distances
    scan(state.x, state.y, this.sensorRadius, m, z_true);

    const nLasers = z.length;

    const dirOffset = Math.round(state.dir/(TWO_PI) * nLasers);

    //z will be an array of noised distances, obtained by robot's sensor
    var i = (dirOffset - nLasers/4);
    i += nLasers + nLasers;

    for(var index = 0; index <= nLasers/2; index ++, i++)
    {
        // if(z[i] > this.senseRadius || z_true[i] > this.sensorRadius)
        //     continue;
        i %= nLasers;
        q += (prob_gaussian_log(z[i] - z_true[i], this.a1*z_true[i]));
    }
    return q;
};<commit_msg>added a few comments<commit_after>
function BeamModel(a1, sensorRadius, map, width, height)
{
	//Gaussian noise on hit
	this.a1 = a1;

	this.map = map;

	this.width = width;
	this.height = height;

	//Sensor radius
	this.sensorRadius = sensorRadius;
}

/*
	Probability of getting measurement z
	if the robot pose is 'state'. (Given map m)
 */
BeamModel.prototype.probability = function(z, state)
{
    // if(state.x < 0 || state.y < 0 || state.x >= this.width || state.y >= this.height)
    //     return 0;

    const m = this.map;

    var z_true = new Array(z.length);

    //Initialization of the probability
    var q = 1;

    //Obtain the true distances
    scan(state.x, state.y, this.sensorRadius, m, z_true);

    //Number of lasers that robot use to sense
    const nLasers = z.length;

    //Adjust the direction of all lasers base on the (estimated?) rotation of the robot
    const dirOffset = Math.round(state.dir/(TWO_PI) * nLasers);

    var i = (dirOffset - nLasers/4);
    i += nLasers + nLasers;

    for(var index = 0; index <= nLasers/2; index ++, i++)
    {
        // if(z[i] > this.sensorRadius || z_true[i] > this.sensorRadius)
        //     continue;
        i %= nLasers;
        q *= (prob_gaussian(z[i] - z_true[i], this.a1*z_true[i]));
    }
    return q;
};

BeamModel.prototype.prob_log = function(z, state)
{
    // if(state.x < 0 || state.y < 0 || state.x >= this.width || state.y >= this.height)
    //     return Number.NEGATIVE_INFINITY;

    const m = this.map;

    var z_true = new Array(z.length);

    var q = 0;

    //Obtain the true distances
    scan(state.x, state.y, this.sensorRadius, m, z_true);

    const nLasers = z.length;

    const dirOffset = Math.round(state.dir/(TWO_PI) * nLasers);

    //z will be an array of noised distances, obtained by robot's sensor
    var i = (dirOffset - nLasers/4);
    i += nLasers + nLasers;

    for(var index = 0; index <= nLasers/2; index ++, i++)
    {
        // if(z[i] > this.senseRadius || z_true[i] > this.sensorRadius)
        //     continue;
        i %= nLasers;
        q += (prob_gaussian_log(z[i] - z_true[i], this.a1*z_true[i]));
    }
    return q;
};<|endoftext|>


<commit_before>function OSocialContainer() {
    this.cross_uri = "http://tradeify.org/osocial/Cross.png";
    this.tick_uri = "http://tradeify.org/osocial/Tick.png";
    this.offers_uri = "http://tradeify.org/tradeify_json.aspx";
    this.tags_uri = "http://tradeify.org/tags_json.aspx";
    this.parse_uri = "http://tradeify.org/parse.aspx?jsoncallback=?";
    this.accept_post_url = "http://tradeify.org/accept_post.aspx";
    this.tags_ahead_uri = "http://tradeify.org/tags_ahead.aspx";

    this.adjustHeight = function(height) {
        gadgets.window.adjustHeight(height);
    }

    /* ------------------------------
         sending data from form
       ------------------------------*/
    this.get_user_location = function() {
        req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
        var location;
        req.send(function(response) {
            var viewer = response.get('viewer').getData();
            //var viewerJson = gadgets.json.stringify(viewer);
            location = viewer.getField(opensocial.Person.Field.UNSTRUCTURED_ADDRESS, null);
        });
        return location;
    };

    this.post_message = function(message) {

        callback = (arguments.length > 1) ? arguments[1] : function() { }

        var message = message;
        var url = this.accept_post_url;
        var req = opensocial.newDataRequest();
        req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
        req.send(function(response) {

            var viewer = response.get('viewer').getData();
            //var viewerJson = gadgets.json.stringify(viewer);
            var name = viewer.getDisplayName();
            var thumbnail = viewer.getField(opensocial.Person.Field.THUMBNAIL_URL, null);
            var profileUrl = viewer.getField(opensocial.Person.Field.PROFILE_URL, null);

            //not sure if we need/want this approach or not
            var dataPacket = {};
            dataPacket.Message = message;
            dataPacket.User = viewer;
            var dataPacketJSON = gadgets.json.stringify(dataPacket);

            var message_data = {
                message: message,
                username: name,
                thumbnail: thumbnail,
                namespace: "ooooby", //FIXME
                profileurl: profileUrl,
                DataPacket: dataPacketJSON
            };

            var params = {};
            var postdata = gadgets.io.encodeValues(message_data);
            params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
            params[gadgets.io.RequestParameters.POST_DATA] = postdata;
            gadgets.io.makeRequest(url, callback, params);

            var params = {};
            params[opensocial.Activity.Field.TITLE] = message;
            var activity = opensocial.newActivity(params);
            /*"If the activity is of high importance, it will be created even if this requires asking the user for permission.
            This may cause the container to open a user flow which may navigate away from your gagdet.
            If the activity is of low importance, it will not be created if the user has not given permission for the current app to create activities.
            With this priority, the requestCreateActivity call will never open a user flow"*/
            opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.LOW);
        });
    }
//    this.parse_message = function(message,callback) {
//        var message_data = {
//            message: message,
//        };
//        var params = {};
//        var postdata = gadgets.io.encodeValues(message_data);
//        params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
//        params[gadgets.io.RequestParameters.POST_DATA] = postdata;
//        gadgets.io.makeRequest(this.parse_uri+"?jsoncallback=?",callback, params);
//    }

}

var container = new OSocialContainer();<commit_msg>updated osocial widget, tryed to get location details through osocial 3<commit_after>function OSocialContainer() {
    this.cross_uri = "http://tradeify.org/osocial/Cross.png";
    this.tick_uri = "http://tradeify.org/osocial/Tick.png";
    this.offers_uri = "http://tradeify.org/tradeify_json.aspx";
    this.tags_uri = "http://tradeify.org/tags_json.aspx";
    this.parse_uri = "http://tradeify.org/parse.aspx?jsoncallback=?";
    this.accept_post_url = "http://tradeify.org/accept_post.aspx";
    this.tags_ahead_uri = "http://tradeify.org/tags_ahead.aspx";

    this.adjustHeight = function(height) {
        gadgets.window.adjustHeight(height);
    }

    /* ------------------------------
         sending data from form
       ------------------------------*/
    this.get_user_location = function() {
        var req = opensocial.newDataRequest();
        req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
        var location;
        req.send(function(response) {
            var viewer = response.get('viewer').getData();
            //var viewerJson = gadgets.json.stringify(viewer);
            location = viewer.getField(opensocial.Person.Field.UNSTRUCTURED_ADDRESS, null);
        });
        return location;
    };

    this.post_message = function(message) {

        callback = (arguments.length > 1) ? arguments[1] : function() { }

        var message = message;
        var url = this.accept_post_url;
        var req = opensocial.newDataRequest();
        req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
        req.send(function(response) {

            var viewer = response.get('viewer').getData();
            //var viewerJson = gadgets.json.stringify(viewer);
            var name = viewer.getDisplayName();
            var thumbnail = viewer.getField(opensocial.Person.Field.THUMBNAIL_URL, null);
            var profileUrl = viewer.getField(opensocial.Person.Field.PROFILE_URL, null);

            //not sure if we need/want this approach or not
            var dataPacket = {};
            dataPacket.Message = message;
            dataPacket.User = viewer;
            var dataPacketJSON = gadgets.json.stringify(dataPacket);

            var message_data = {
                message: message,
                username: name,
                thumbnail: thumbnail,
                namespace: "ooooby", //FIXME
                profileurl: profileUrl,
                DataPacket: dataPacketJSON
            };

            var params = {};
            var postdata = gadgets.io.encodeValues(message_data);
            params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
            params[gadgets.io.RequestParameters.POST_DATA] = postdata;
            gadgets.io.makeRequest(url, callback, params);

            var params = {};
            params[opensocial.Activity.Field.TITLE] = message;
            var activity = opensocial.newActivity(params);
            /*"If the activity is of high importance, it will be created even if this requires asking the user for permission.
            This may cause the container to open a user flow which may navigate away from your gagdet.
            If the activity is of low importance, it will not be created if the user has not given permission for the current app to create activities.
            With this priority, the requestCreateActivity call will never open a user flow"*/
            opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.LOW);
        });
    }
//    this.parse_message = function(message,callback) {
//        var message_data = {
//            message: message,
//        };
//        var params = {};
//        var postdata = gadgets.io.encodeValues(message_data);
//        params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
//        params[gadgets.io.RequestParameters.POST_DATA] = postdata;
//        gadgets.io.makeRequest(this.parse_uri+"?jsoncallback=?",callback, params);
//    }

}

var container = new OSocialContainer();<|endoftext|>


<commit_before>steal('can/util/can.js', 'can/util/attr', 'can/util/array/each.js', 'can/util/array/makeArray.js', function (can, attr) {

	var core_trim = String.prototype.trim;
	var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

	function likeArray(obj) {
		return typeof obj.length === 'number';
	}

	function flatten(array) {
		return array.length > 0 ? Array.prototype.concat.apply([], array) : array;
	}

	can.isFunction = (function () {
		if (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') {
			return function (value) {
				return Object.prototype.toString.call(value) === '[object Function]';
			};
		} else {
			return function (value) {
				return typeof value === 'function';
			};
		}
	})();

	can.trim = core_trim && !core_trim.call('\uFEFF\xA0') ?
		function (text) {
			return text == null ? '' : core_trim.call(text);
		} :
		// Otherwise use our own trimming functionality
		function (text) {
			return text == null ? '' : (text + '')
				.replace(rtrim, '');
		};

	// This extend() function is ruthlessly and shamelessly stolen from
	// jQuery 1.8.2:, lines 291-353.
	can.extend = function () {
		/*jshint maxdepth:6 */
		var options, name, src, copy, copyIsArray, clone,
			target = arguments[0] || {},
			i = 1,
			length = arguments.length,
			deep = false;

		// Handle a deep copy situation
		if (typeof target === "boolean") {
			deep = target;
			target = arguments[1] || {};
			// skip the boolean and the target
			i = 2;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if (typeof target !== "object" && !can.isFunction(target)) {
			target = {};
		}

		// extend jQuery itself if only one argument is passed
		if (length === i) {
			target = this;
			--i;
		}

		for (; i < length; i++) {
			// Only deal with non-null/undefined values
			if ((options = arguments[i]) != null) {
				// Extend the base object
				for (name in options) {
					src = target[name];
					copy = options[name];

					// Prevent never-ending loop
					if (target === copy) {
						continue;
					}

					// Recurse if we're merging plain objects or arrays
					if (deep && copy && (can.isPlainObject(copy) || (copyIsArray = can.isArray(copy)))) {
						if (copyIsArray) {
							copyIsArray = false;
							clone = src && can.isArray(src) ? src : [];

						} else {
							clone = src && can.isPlainObject(src) ? src : {};
						}

						// Never move original objects, clone them
						target[name] = can.extend(deep, clone, copy);

						// Don't bring in undefined values
					} else if (copy !== undefined) {
						target[name] = copy;
					}
				}
			}
		}

		// Return the modified object
		return target;
	};

	can.map = function (elements, callback) {
		var values = [],
			putValue = function (val, index) {
				var value = callback(val, index);
				if (value != null) {
					values.push(value);
				}
			};
		if (likeArray(elements)) {
			for (var i = 0, l = elements.length; i < l; i++) {
				putValue(elements[i], i);
			}
		} else {
			for (var key in elements) {
				putValue(elements[key], key);
			}
		}
		return flatten(values);
	};
	can.proxy = function (cb, that) {
		return function () {
			return cb.apply(that, arguments);
		};
	};

	can.attr = attr;

	return can;

});
<commit_msg>adds isArray<commit_after>steal('can/util/can.js', 'can/util/attr', 'can/util/array/each.js', 'can/util/array/makeArray.js', function (can, attr) {

	var core_trim = String.prototype.trim;
	var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

	function likeArray(obj) {
		return typeof obj.length === 'number';
	}

	function flatten(array) {
		return array.length > 0 ? Array.prototype.concat.apply([], array) : array;
	}

	can.isArray = function(arr){
		return arr instanceof arr;
	};

	can.isFunction = (function () {
		if (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') {
			return function (value) {
				return Object.prototype.toString.call(value) === '[object Function]';
			};
		} else {
			return function (value) {
				return typeof value === 'function';
			};
		}
	})();

	can.trim = core_trim && !core_trim.call('\uFEFF\xA0') ?
		function (text) {
			return text == null ? '' : core_trim.call(text);
		} :
		// Otherwise use our own trimming functionality
		function (text) {
			return text == null ? '' : (text + '')
				.replace(rtrim, '');
		};

	// This extend() function is ruthlessly and shamelessly stolen from
	// jQuery 1.8.2:, lines 291-353.
	can.extend = function () {
		/*jshint maxdepth:6 */
		var options, name, src, copy, copyIsArray, clone,
			target = arguments[0] || {},
			i = 1,
			length = arguments.length,
			deep = false;

		// Handle a deep copy situation
		if (typeof target === "boolean") {
			deep = target;
			target = arguments[1] || {};
			// skip the boolean and the target
			i = 2;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if (typeof target !== "object" && !can.isFunction(target)) {
			target = {};
		}

		// extend jQuery itself if only one argument is passed
		if (length === i) {
			target = this;
			--i;
		}

		for (; i < length; i++) {
			// Only deal with non-null/undefined values
			if ((options = arguments[i]) != null) {
				// Extend the base object
				for (name in options) {
					src = target[name];
					copy = options[name];

					// Prevent never-ending loop
					if (target === copy) {
						continue;
					}

					// Recurse if we're merging plain objects or arrays
					if (deep && copy && (can.isPlainObject(copy) || (copyIsArray = can.isArray(copy)))) {
						if (copyIsArray) {
							copyIsArray = false;
							clone = src && can.isArray(src) ? src : [];

						} else {
							clone = src && can.isPlainObject(src) ? src : {};
						}

						// Never move original objects, clone them
						target[name] = can.extend(deep, clone, copy);

						// Don't bring in undefined values
					} else if (copy !== undefined) {
						target[name] = copy;
					}
				}
			}
		}

		// Return the modified object
		return target;
	};

	can.map = function (elements, callback) {
		var values = [],
			putValue = function (val, index) {
				var value = callback(val, index);
				if (value != null) {
					values.push(value);
				}
			};
		if (likeArray(elements)) {
			for (var i = 0, l = elements.length; i < l; i++) {
				putValue(elements[i], i);
			}
		} else {
			for (var key in elements) {
				putValue(elements[key], key);
			}
		}
		return flatten(values);
	};
	can.proxy = function (cb, that) {
		return function () {
			return cb.apply(that, arguments);
		};
	};

	can.attr = attr;

	return can;

});
<|endoftext|>


<commit_before>var fs     = require("fs"),
    path   = require("path"),
    Stream = require("stream");

require("./lazy_spec.js");
require("./map_spec.js");
require("./filter_spec.js");
require("./reverse_spec.js");
require("./shuffle_spec.js");
require("./concat_spec.js");
require("./flatten_spec.js");
require("./take_spec.js");
require("./drop_spec.js");
require("./sort_by_spec.js");
require("./group_by_spec.js");
require("./count_by_spec.js");
require("./without_spec.js");
require("./union_spec.js");
require("./intersection_spec.js");
require("./uniq_spec.js");
require("./zip_spec.js");
require("./find_spec.js");
require("./min_spec.js");
require("./max_spec.js");
require("./sum_spec.js");
require("./watch_spec.js");

// Sequence types
require("./string_like_sequence_spec.js");
require("./async_sequence_spec.js");

// Clean up temporary file (if it exists) after each run
var TEMP_FILE_PATH = path.join(__dirname, 'data/temp.txt');

afterEach(function() {
  if ((fs.existsSync || path.existsSync)(TEMP_FILE_PATH)) {
    fs.unlinkSync(TEMP_FILE_PATH);
  }
});

describe("working with streams", function() {

  // TODO: Figure out a smart way to test HTTP streams and other types of
  // streams as well.
  it("can split the contents of the stream, as if it were a string", function() {
    var stream = fs.createReadStream("./spec/data/haiku.txt"),
        words  = [];

    Lazy(stream).split(/\s+/).each(function(word) {
      words.push(word);
    });

    waitsFor(toBePopulated(words));

    runs(function() {
      expect(words).toEqual([
        'at', 'the', 'age', 'old', 'pond',
        'a', 'frog', 'leaps', 'into', 'water',
        'a', 'deep', 'resonance'
      ]);
    });
  });

  it("can also do string-style matching on streams", function() {
    var stream = fs.createReadStream("./spec/data/haiku.txt"),
        words  = [];

    Lazy(stream).match(/\ba\w*/).each(function(word) {
      words.push(word);
    });

    waitsFor(toBePopulated(words));

    runs(function() {
      expect(words).toEqual(['at', 'age', 'a', 'a']);
    });
  });

  it("does not insert extra breaks on newlines when splitting", function() {
    var stream = fs.createReadStream("./spec/data/commas.txt"),
        chunks = [];

    Lazy(stream).split(/,\s*/).each(function(chunk) {
      chunks.push(chunk);
    });

    waitsFor(toBePopulated(chunks));

    runs(function() {
      expect(chunks).toEqual([
        'first chunk',
        'second chunk',
        'third\nchunk',
        'fourth chunk',
        'fifth chunk'
      ]);
    });
  });

  describe("file streams", function() {
    describe("lines", function() {
      it("reads every line of a file", function() {
        var lines = [];

        runs(function() {
          Lazy.readFile("./spec/data/lines.txt")
            .lines()
            .each(function(line) {
              lines.push(line);
            });
        });

        waitsFor(toBePopulated(lines, 25));

        runs(function() {
          expect(lines).toEqual(Lazy.repeat("The quick brown fox jumped over the lazy dog.", 25).toArray());
        });
      });
    });

    describe("wrapping a stream directly", function() {
      it("works the same as calling a helper, e.g., readFile", function() {
        var lines = [];

        runs(function() {
          Lazy(fs.createReadStream("./spec/data/lines.txt"))
            .lines()
            .take(1)
            .each(function(line) {
              lines.push(line);
            });
        });

        waitsFor(function() {
          return lines.length > 0;
        });

        runs(function() {
          expect(lines[0]).toEqual("The quick brown fox jumped over the lazy dog.");
        });
      });
    });

    describe("wrapping non-text streams", function() {
      var JSONStream = require('JSONStream');

      it("works with whatever the stream produces, such as objects", function() {
        var objects = [];

        runs(function() {
          var stream = fs.createReadStream("./spec/data/objects.json")
            .pipe(JSONStream.parse("*"));

          Lazy(stream).each(function(object) {
            objects.push(object);
          });
        });

        waitsFor(toBePopulated(objects));

        runs(function() {
          var names = Lazy(objects).pluck("name");
          expect(names).toComprise(["foobar", "flintstones"]);
        });
      });
    });
  });

  if (typeof Stream.Readable !== "undefined") {
    describe("toStream", function() {
      it('creates a readable stream that you can use just like any other stream', function() {
        var stream = Lazy(fs.createReadStream('./spec/data/lines.txt'))
          .map(function(chunk) { return chunk.toUpperCase(); })
          .toStream();

        var finished = jasmine.createSpy();

        stream.pipe(fs.createWriteStream(TEMP_FILE_PATH));

        stream.on('end', finished);

        waitsFor(toBeCalled(finished));

        runs(function() {
          var contents = fs.readFileSync(TEMP_FILE_PATH, 'utf-8');
          var expected = Lazy.repeat('The quick brown fox jumped over the lazy dog.'.toUpperCase(), 25).join('\n');
          expect(contents).toEqual(expected);
        });
      });
    });
  }
});
<commit_msg>maybe this will make a difference? (probably not)<commit_after>var fs     = require("fs"),
    path   = require("path"),
    Stream = require("stream");

require("./lazy_spec.js");
require("./map_spec.js");
require("./filter_spec.js");
require("./reverse_spec.js");
require("./shuffle_spec.js");
require("./concat_spec.js");
require("./flatten_spec.js");
require("./take_spec.js");
require("./drop_spec.js");
require("./sort_by_spec.js");
require("./group_by_spec.js");
require("./count_by_spec.js");
require("./without_spec.js");
require("./union_spec.js");
require("./intersection_spec.js");
require("./uniq_spec.js");
require("./zip_spec.js");
require("./find_spec.js");
require("./min_spec.js");
require("./max_spec.js");
require("./sum_spec.js");
require("./watch_spec.js");

// Sequence types
require("./string_like_sequence_spec.js");
require("./async_sequence_spec.js");

// Clean up temporary file (if it exists) after each run
var TEMP_FILE_PATH = path.join(__dirname, 'data/temp.txt');

afterEach(function() {
  if ((fs.existsSync || path.existsSync)(TEMP_FILE_PATH)) {
    fs.unlinkSync(TEMP_FILE_PATH);
  }
});

describe("working with streams", function() {

  // TODO: Figure out a smart way to test HTTP streams and other types of
  // streams as well.
  it("can split the contents of the stream, as if it were a string", function() {
    var stream = fs.createReadStream("./spec/data/haiku.txt"),
        words  = [];

    Lazy(stream).split(/\s+/).each(function(word) {
      words.push(word);
    });

    waitsFor(toBePopulated(words));

    runs(function() {
      expect(words).toEqual([
        'at', 'the', 'age', 'old', 'pond',
        'a', 'frog', 'leaps', 'into', 'water',
        'a', 'deep', 'resonance'
      ]);
    });
  });

  it("can also do string-style matching on streams", function() {
    var stream = fs.createReadStream("./spec/data/haiku.txt"),
        words  = [];

    Lazy(stream).match(/\ba\w*/).each(function(word) {
      words.push(word);
    });

    waitsFor(toBePopulated(words));

    runs(function() {
      expect(words).toEqual(['at', 'age', 'a', 'a']);
    });
  });

  it("does not insert extra breaks on newlines when splitting", function() {
    var stream = fs.createReadStream("./spec/data/commas.txt"),
        chunks = [];

    Lazy(stream).split(/,\s*/).each(function(chunk) {
      chunks.push(chunk);
    });

    waitsFor(toBePopulated(chunks));

    runs(function() {
      expect(chunks).toEqual([
        'first chunk',
        'second chunk',
        'third\nchunk',
        'fourth chunk',
        'fifth chunk'
      ]);
    });
  });

  describe("file streams", function() {
    describe("lines", function() {
      it("reads every line of a file", function() {
        var lines = [];

        runs(function() {
          Lazy.readFile("./spec/data/lines.txt")
            .lines()
            .each(function(line) {
              lines.push(line);
            });
        });

        waitsFor(toBePopulated(lines, 25));

        runs(function() {
          expect(lines).toEqual(Lazy.repeat("The quick brown fox jumped over the lazy dog.", 25).toArray());
        });
      });
    });

    describe("wrapping a stream directly", function() {
      it("works the same as calling a helper, e.g., readFile", function() {
        var lines = [];

        runs(function() {
          Lazy(fs.createReadStream("./spec/data/lines.txt"))
            .lines()
            .take(1)
            .each(function(line) {
              lines.push(line);
            });
        });

        waitsFor(function() {
          return lines.length > 0;
        });

        runs(function() {
          expect(lines[0]).toEqual("The quick brown fox jumped over the lazy dog.");
        });
      });
    });

    describe("wrapping non-text streams", function() {
      var JSONStream = require('JSONStream');

      it("works with whatever the stream produces, such as objects", function() {
        var objects = [];

        runs(function() {
          var stream = fs.createReadStream("./spec/data/objects.json")
            .pipe(JSONStream.parse("*"));

          Lazy(stream).each(function(object) {
            objects.push(object);
          });
        });

        waitsFor(toBePopulated(objects));

        runs(function() {
          var names = Lazy(objects).pluck("name");
          expect(names).toComprise(["foobar", "flintstones"]);
        });
      });
    });
  });

  if (typeof Stream.Readable !== "undefined") {
    describe("toStream", function() {
      it('creates a readable stream that you can use just like any other stream', function() {
        var stream = Lazy(fs.createReadStream('./spec/data/lines.txt'))
          .map(function(chunk) { return chunk.toUpperCase(); })
          .toStream();

        var finished = jasmine.createSpy();

        var output = fs.createWriteStream(TEMP_FILE_PATH);

        output.on('open', function() {
          stream.pipe(output);
        });

        stream.on('end', finished);

        waitsFor(toBeCalled(finished));

        runs(function() {
          var contents = fs.readFileSync(TEMP_FILE_PATH, 'utf-8');
          var expected = Lazy.repeat('The quick brown fox jumped over the lazy dog.'.toUpperCase(), 25).join('\n');
          expect(contents).toEqual(expected);
        });
      });
    });
  }
});
<|endoftext|>


<commit_before>
/**
 * @constructor
 */
Melown.Core = function(element_, config_, interface_) {
    this.killed_ = false;
    this.initConfig();
    this.configStorage_ = {};
    this.setConfigParams(config_);
    this.element_ = element_;
    this.interface_ = interface_;
    //this.options_ = options_;
    this.ready_ = false;
    this.listeners_ = [];
    this.listenerCounter_ = 0;
    this.tokenCookieHost_ = null;
    this.tokenIFrame_ = null;
    this.xhrParams_ = {};
    this.inspector_ = (Melown.Inspector != null) ? (new Melown.Inspector(this)) : null;

    this.map_ = null;
    this.mapInterface_ = null;
    this.renderer_ = new Melown.Renderer(this, this.element_, null, this.onResize.bind(this), this.config_);
    this.rendererInterface_ = new Melown.RendererInterface(this.renderer_);
    this.proj4_ = window["_mproj4_"];

    //platform detection
    Melown.Platform.init();

    this.loadMap(this.config_.map_);

    window.requestAnimFrame(this.onUpdate.bind(this));
};

Melown.Core.prototype.onResize = function() {
    if (this.map_ != null) {
        this.map_.markDirty();
    }
};

Melown.Core.prototype.loadMap = function(path_) {
    if (this.map_ != null) {
        this.destroyMap();
    }

    if (path_ == null) {
        return;
    }

    path_ = Melown.Url.getProcessUrl(path_, window.location.href);

    this.tokenCookieLoaded_ = true;
    this.mapConfigData_ = null;
    this.tokenExpiration_ = null;
    this.tokenExpirationCallback_ = null;
    this.tokenExpirationLoop_ = false;
    this.tokenCanBeSkiped_ = true;
    this.mapRunnig_ = false;

    var onLoaded_ = (function() {
        if (!(this.tokenCookieLoaded_ || this.tokenCanBeSkiped_) || !this.mapConfigData_ || this.mapRunnig_) {
            return;
        }

        this.mapRunnig_ = true;
        var data_ = this.mapConfigData_;

        this.callListener("map-mapconfig-loaded", data_);

        this.map_ = new Melown.Map(this, data_, path_, this.config_);
        this.mapInterface_ = new Melown.MapInterface(this.map_);
        this.setConfigParams(this.map_.browserOptions_);
        this.setConfigParams(this.configStorage_);

        if (this.config_.position_) {
            this.map_.setPosition(this.config_.position_);
            this.config_.position_ = null;
        }

        if (this.config_.view_) {
            this.map_.setView(this.config_.view_);
            this.config_.view_ = null;
        }

        this.callListener("map-loaded", { "browserOptions":this.map_.browserOptions_});
    }).bind(this);

    var onMapConfigLoaded_ = (function(data_) {
        this.mapConfigData_ = data_;
        onLoaded_();
    }).bind(this);

    var onMapConfigError_ = (function() {
    }).bind(this);

    //this.tokenLoaded_ = true;

    var onAutorizationLoaded_ = (function(data_) {
        this.tokenLoaded_ = true;
        this.xhrParams_["token"] = data_["token"];
        this.xhrParams_["tokenHeader"] = data_["header"];
        this.tokenExpiration_ = data_["expires"] * 1000;
        this.tokenExpirationCallback_ = (function(){
            //this.tokenLoaded_ = false;
            //this.tokenCookieLoaded_ = false;
            this.tokenExpiration_ = null;
            this.tokenExpirationLoop_ = true;
            if (typeof this.config_.authorization_ === "string") {
                Melown.loadJSON(this.config_.authorization_, onAutorizationLoaded_, onAutorizationError_, null, Melown["useCredentials"], this.xhrParams_);
            } else {
                this.config_.authorization_(onAutorizationLoaded_);
            }
        }).bind(this);

        if (!this.tokenExpirationLoop_) {
            onLoadMapconfig(path_);
        }

        if (typeof this.config_.authorization_ === "string") {
            onLoadImageCookie(data_["cookieInjector"], this.config_.authorization_);
        } else {
            onLoadImageCookie(data_["cookieInjector"], path_);
        }

    }).bind(this);

    var onAutorizationError_ = (function() {
        console.log("auth token not loaded");

        if (this.tokenCanBeSkiped_) {
            onLoadMapconfig(path_);
        }
    }).bind(this);

    var onImageCookieLoaded_ = (function(data_) {
        document.body.removeChild(this.tokenIFrame_);
        this.tokenIFrame_ = null;
        this.tokenCookieLoaded_ = true;
        onLoaded_();
    }).bind(this);

    var onImageCookieError_ = (function() {
        console.log("auth cookie not loaded");
    }).bind(this);

    //var baseUrl_ = path_.split('?')[0].split('/').slice(0, -1).join('/')+'/';

    var onLoadMapconfig = (function(path_) {
        Melown.loadJSON(path_, onMapConfigLoaded_, onMapConfigError_, null, Melown["useCredentials"], this.xhrParams_);
    }).bind(this);

    var onLoadImageCookie = (function(url_, originUrl_) {
        url_ = Melown.Url.getProcessUrl(url_, originUrl_);
        this.tokenCookieHost_ = Melown.Url.getHost(url_);
        //Melown.Http.imageFactory(url_, onImageCookieLoaded_, onImageCookieError_);
        var iframe_ = document.createElement('iframe');
        this.tokenIFrame_ = iframe_;
        iframe_.onload = onImageCookieLoaded_;
        iframe_.src = url_;
        iframe_.style.display = "none";
        document.body.appendChild(iframe_);
    }).bind(this);

    //if (false && this.config_.authorization_) {
    if (this.config_.authorization_) {
        this.tokenCookieLoaded_ = false;

        if (typeof this.config_.authorization_ === "string") {
            Melown.loadJSON(this.config_.authorization_, onAutorizationLoaded_, onAutorizationError_, null, Melown["useCredentials"], this.xhrParams_);
        } else {
            this.config_.authorization_(onAutorizationLoaded_);
        }
    } else {
        onLoadMapconfig(path_);
    }

};

Melown.Core.prototype.destroy = function() {
    if (this.killed_) {
        return;
    }

    this.destroyMap();
    if (this.renderer_) {
        this.renderer_.kill();
    }
    this.element_ = null;
    this.killed_ = true;
};

Melown.Core.prototype.destroyMap = function() {
    if (this.map_) {
        this.map_.kill();
        this.map_ = null;
        this.mapInterface_ = null;
        this.callListener("map-unloaded", {});
    }
};

Melown.Core.prototype.getMap = function() {
    return this.map_;
};

Melown.Core.prototype.getMapInterface = function() {
    return this.mapInterface_;
};

Melown.Core.prototype.getRenderer = function() {
    return this.renderer_;
};

Melown.Core.prototype.getRendererInterface = function() {
    return this.rendererInterface_;
};

Melown.Core.prototype.getProj4 = function() {
    return this.proj4_;
};

Melown.Core.prototype.getOption = function(key_, value_) {
};

Melown.Core.prototype.setOption = function(key_, value_) {
};

Melown.Core.prototype.on = function(name_, listener_) {
    if (this.killed_ == true) { // || this.renderer_ == null) {
        return;
    }

    if (listener_ == null) {
        return;
    }

    this.listenerCounter_++;
    this.listeners_.push({ name_ : name_, listener_ : listener_, id_ : this.listenerCounter_ });

    return (function(id_){ this.removeListener(id_); }).bind(this, this.listenerCounter_);
};

// private
Melown.Core.prototype.callListener = function(name_, event_) {
    for (var i = 0; i < this.listeners_.length; i++) {
        if (this.listeners_[i].name_ == name_) {
            this.listeners_[i].listener_(event_);
        }
    }
};

// private
Melown.Core.prototype.removeListener = function(id_) {
    for (var i = 0; i < this.listeners_.length; i++) {
        if (this.listeners_[i].id_ == id_) {
            //this.listeners_[i].splice(i, 1);
            this.listeners_.splice(i, 1);
            return;
        }
    }
};

/*
string getCoreVersion()

    Returns string with Melown version
*/

Melown.getCoreVersion = function(full_) {
    return (full_ ? "Core: " : "") + "1.68";
};

/*
bool checkSupport()

    Returns true if the environment is capable of running the WebGL browser, false otherwise.
*/

Melown.checkSupport = function() {
    Melown.Platform.init();

    //is webgl supported
    var canvas_ = document.createElement("canvas");

    if (canvas_ == null) {
        return false;
    }

    canvas_.width = 1024;
    canvas_.height = 768;

    if (canvas_.getContext == null) {
        return false;
    }

    var gl_ = null;

    try {
        gl_ = canvas_.getContext("webgl") || canvas_.getContext("experimental-webgl");
    } catch(e) {
        return false;
    }

    if (!gl_) {
        return false;
    }

    return true;
};

<commit_msg>version update<commit_after>
/**
 * @constructor
 */
Melown.Core = function(element_, config_, interface_) {
    this.killed_ = false;
    this.initConfig();
    this.configStorage_ = {};
    this.setConfigParams(config_);
    this.element_ = element_;
    this.interface_ = interface_;
    //this.options_ = options_;
    this.ready_ = false;
    this.listeners_ = [];
    this.listenerCounter_ = 0;
    this.tokenCookieHost_ = null;
    this.tokenIFrame_ = null;
    this.xhrParams_ = {};
    this.inspector_ = (Melown.Inspector != null) ? (new Melown.Inspector(this)) : null;

    this.map_ = null;
    this.mapInterface_ = null;
    this.renderer_ = new Melown.Renderer(this, this.element_, null, this.onResize.bind(this), this.config_);
    this.rendererInterface_ = new Melown.RendererInterface(this.renderer_);
    this.proj4_ = window["_mproj4_"];

    //platform detection
    Melown.Platform.init();

    this.loadMap(this.config_.map_);

    window.requestAnimFrame(this.onUpdate.bind(this));
};

Melown.Core.prototype.onResize = function() {
    if (this.map_ != null) {
        this.map_.markDirty();
    }
};

Melown.Core.prototype.loadMap = function(path_) {
    if (this.map_ != null) {
        this.destroyMap();
    }

    if (path_ == null) {
        return;
    }

    path_ = Melown.Url.getProcessUrl(path_, window.location.href);

    this.tokenCookieLoaded_ = true;
    this.mapConfigData_ = null;
    this.tokenExpiration_ = null;
    this.tokenExpirationCallback_ = null;
    this.tokenExpirationLoop_ = false;
    this.tokenCanBeSkiped_ = true;
    this.mapRunnig_ = false;

    var onLoaded_ = (function() {
        if (!(this.tokenCookieLoaded_ || this.tokenCanBeSkiped_) || !this.mapConfigData_ || this.mapRunnig_) {
            return;
        }

        this.mapRunnig_ = true;
        var data_ = this.mapConfigData_;

        this.callListener("map-mapconfig-loaded", data_);

        this.map_ = new Melown.Map(this, data_, path_, this.config_);
        this.mapInterface_ = new Melown.MapInterface(this.map_);
        this.setConfigParams(this.map_.browserOptions_);
        this.setConfigParams(this.configStorage_);

        if (this.config_.position_) {
            this.map_.setPosition(this.config_.position_);
            this.config_.position_ = null;
        }

        if (this.config_.view_) {
            this.map_.setView(this.config_.view_);
            this.config_.view_ = null;
        }

        this.callListener("map-loaded", { "browserOptions":this.map_.browserOptions_});
    }).bind(this);

    var onMapConfigLoaded_ = (function(data_) {
        this.mapConfigData_ = data_;
        onLoaded_();
    }).bind(this);

    var onMapConfigError_ = (function() {
    }).bind(this);

    //this.tokenLoaded_ = true;

    var onAutorizationLoaded_ = (function(data_) {
        this.tokenLoaded_ = true;
        this.xhrParams_["token"] = data_["token"];
        this.xhrParams_["tokenHeader"] = data_["header"];
        this.tokenExpiration_ = data_["expires"] * 1000;
        this.tokenExpirationCallback_ = (function(){
            //this.tokenLoaded_ = false;
            //this.tokenCookieLoaded_ = false;
            this.tokenExpiration_ = null;
            this.tokenExpirationLoop_ = true;
            if (typeof this.config_.authorization_ === "string") {
                Melown.loadJSON(this.config_.authorization_, onAutorizationLoaded_, onAutorizationError_, null, Melown["useCredentials"], this.xhrParams_);
            } else {
                this.config_.authorization_(onAutorizationLoaded_);
            }
        }).bind(this);

        if (!this.tokenExpirationLoop_) {
            onLoadMapconfig(path_);
        }

        if (typeof this.config_.authorization_ === "string") {
            onLoadImageCookie(data_["cookieInjector"], this.config_.authorization_);
        } else {
            onLoadImageCookie(data_["cookieInjector"], path_);
        }

    }).bind(this);

    var onAutorizationError_ = (function() {
        console.log("auth token not loaded");

        if (this.tokenCanBeSkiped_) {
            onLoadMapconfig(path_);
        }
    }).bind(this);

    var onImageCookieLoaded_ = (function(data_) {
        document.body.removeChild(this.tokenIFrame_);
        this.tokenIFrame_ = null;
        this.tokenCookieLoaded_ = true;
        onLoaded_();
    }).bind(this);

    var onImageCookieError_ = (function() {
        console.log("auth cookie not loaded");
    }).bind(this);

    //var baseUrl_ = path_.split('?')[0].split('/').slice(0, -1).join('/')+'/';

    var onLoadMapconfig = (function(path_) {
        Melown.loadJSON(path_, onMapConfigLoaded_, onMapConfigError_, null, Melown["useCredentials"], this.xhrParams_);
    }).bind(this);

    var onLoadImageCookie = (function(url_, originUrl_) {
        url_ = Melown.Url.getProcessUrl(url_, originUrl_);
        this.tokenCookieHost_ = Melown.Url.getHost(url_);
        //Melown.Http.imageFactory(url_, onImageCookieLoaded_, onImageCookieError_);
        var iframe_ = document.createElement('iframe');
        this.tokenIFrame_ = iframe_;
        iframe_.onload = onImageCookieLoaded_;
        iframe_.src = url_;
        iframe_.style.display = "none";
        document.body.appendChild(iframe_);
    }).bind(this);

    //if (false && this.config_.authorization_) {
    if (this.config_.authorization_) {
        this.tokenCookieLoaded_ = false;

        if (typeof this.config_.authorization_ === "string") {
            Melown.loadJSON(this.config_.authorization_, onAutorizationLoaded_, onAutorizationError_, null, Melown["useCredentials"], this.xhrParams_);
        } else {
            this.config_.authorization_(onAutorizationLoaded_);
        }
    } else {
        onLoadMapconfig(path_);
    }

};

Melown.Core.prototype.destroy = function() {
    if (this.killed_) {
        return;
    }

    this.destroyMap();
    if (this.renderer_) {
        this.renderer_.kill();
    }
    this.element_ = null;
    this.killed_ = true;
};

Melown.Core.prototype.destroyMap = function() {
    if (this.map_) {
        this.map_.kill();
        this.map_ = null;
        this.mapInterface_ = null;
        this.callListener("map-unloaded", {});
    }
};

Melown.Core.prototype.getMap = function() {
    return this.map_;
};

Melown.Core.prototype.getMapInterface = function() {
    return this.mapInterface_;
};

Melown.Core.prototype.getRenderer = function() {
    return this.renderer_;
};

Melown.Core.prototype.getRendererInterface = function() {
    return this.rendererInterface_;
};

Melown.Core.prototype.getProj4 = function() {
    return this.proj4_;
};

Melown.Core.prototype.getOption = function(key_, value_) {
};

Melown.Core.prototype.setOption = function(key_, value_) {
};

Melown.Core.prototype.on = function(name_, listener_) {
    if (this.killed_ == true) { // || this.renderer_ == null) {
        return;
    }

    if (listener_ == null) {
        return;
    }

    this.listenerCounter_++;
    this.listeners_.push({ name_ : name_, listener_ : listener_, id_ : this.listenerCounter_ });

    return (function(id_){ this.removeListener(id_); }).bind(this, this.listenerCounter_);
};

// private
Melown.Core.prototype.callListener = function(name_, event_) {
    for (var i = 0; i < this.listeners_.length; i++) {
        if (this.listeners_[i].name_ == name_) {
            this.listeners_[i].listener_(event_);
        }
    }
};

// private
Melown.Core.prototype.removeListener = function(id_) {
    for (var i = 0; i < this.listeners_.length; i++) {
        if (this.listeners_[i].id_ == id_) {
            //this.listeners_[i].splice(i, 1);
            this.listeners_.splice(i, 1);
            return;
        }
    }
};

/*
string getCoreVersion()

    Returns string with Melown version
*/

Melown.getCoreVersion = function(full_) {
    return (full_ ? "Core: " : "") + "1.69";
};

/*
bool checkSupport()

    Returns true if the environment is capable of running the WebGL browser, false otherwise.
*/

Melown.checkSupport = function() {
    Melown.Platform.init();

    //is webgl supported
    var canvas_ = document.createElement("canvas");

    if (canvas_ == null) {
        return false;
    }

    canvas_.width = 1024;
    canvas_.height = 768;

    if (canvas_.getContext == null) {
        return false;
    }

    var gl_ = null;

    try {
        gl_ = canvas_.getContext("webgl") || canvas_.getContext("experimental-webgl");
    } catch(e) {
        return false;
    }

    if (!gl_) {
        return false;
    }

    return true;
};

<|endoftext|>


<commit_before>const Yodot = require('../yodot');
const _ = require('lodash');

module.exports = class extends Yodot {
	async ask() {
		let answers = await this.prompt([ {
			name: 'name',
			type: 'input',
			message: 'Scene name?',
			default: 'main'
		} ]);
		_.assign(this.ctx, answers);

		answers = await this.prompt([ {
			name: 'nodeName',
			type: 'input',
			message: 'Root node name?',
			default: answers.name
		}, {
			name: 'nodeType',
			type: 'input',
			message: 'Root node type?',
			default: 'Node2D'
		}, {
			name: 'main',
			type: 'confirm',
			message: 'Make main scene?',
			default: false
		} ]);
		_.assign(this.ctx, answers);
	}

	main() {
		const sceneName = `scenes/${this.ctx.name}.tscn`;

		super.main({
			mappings: { 'scenes/scene.tscn': sceneName }
		});

		// Register as main scene
		if (this.ctx.main) {
			const file = this.destinationPath('project.godot');
			const setting = `run/main_scene="res://${sceneName}"`;

			let lines = this.fs.read(file).split('\n');
			lines = lines.map((line, l) => {
				if (/^config\/name=/.test(line)) lines.splice(l + 1, 0, setting);
				return line;
			});
			lines.push('');

			this.fs.write(file, lines.join('\n'));
		}
	}
};
<commit_msg>Updated main scene setting when already present.<commit_after>const Yodot = require('../yodot');
const _ = require('lodash');

module.exports = class extends Yodot {
	async ask() {
		let answers = await this.prompt([ {
			name: 'name',
			type: 'input',
			message: 'Scene name?',
			default: 'main'
		} ]);
		_.assign(this.ctx, answers);

		answers = await this.prompt([ {
			name: 'nodeName',
			type: 'input',
			message: 'Root node name?',
			default: answers.name
		}, {
			name: 'nodeType',
			type: 'input',
			message: 'Root node type?',
			default: 'Node2D'
		}, {
			name: 'main',
			type: 'confirm',
			message: 'Make main scene?',
			default: false
		} ]);
		_.assign(this.ctx, answers);
	}

	main() {
		const sceneName = `scenes/${this.ctx.name}.tscn`;

		super.main({
			mappings: { 'scenes/scene.tscn': sceneName }
		});

		// Register as main scene
		if (this.ctx.main) {
			const file = this.destinationPath('project.godot');
			const setting = `run/main_scene="res://${sceneName}"`;

			let lines = this.fs.read(file).split('\n');
			for (let l = 0; l <= lines.length; l++) {
				let line = lines[l];
				// Update setting if already present
				if (/^run\/main_scene=/.test(line)) {
					lines[l] = setting;
					break;
				}
				// Add setting if not already present
				if (/^config\/icon=/.test(line)) {
					lines.splice(l, 0, setting);
					break;
				}
			}
			lines.push('');

			this.fs.write(file, lines.join('\n'));
		}
	}
};
<|endoftext|>


<commit_before>'use strict';

/* deps: jshint-stylish mocha */
var path = require('path');
var istanbul = require('gulp-istanbul');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
var gutil = require('gulp-util');
var verb = require('verb');

verb.helper('rename', function(str, a, b, c) {
  str = str.split(a + '.').join(b + '.');
  str = str.split('var ' + a).join('var ' + b);
  var upperB = b[0].toUpperCase() + b.slice(1);
  str = str.split(c).join(upperB);
  return str;
});

verb.helper('npm', function (name) {
  return 'node_modules/' + name + '/index.js';
});

verb.helper('home', function (name) {
  var dir = path.dirname(require.resolve(name));
  var pkg = path.resolve(dir, 'package.json');
  return require(pkg).homepage + '/blob/master/index.js';
});

verb.task('readme', function() {
  verb.src('.verb.md')
    .pipe(verb.dest('./'));
});

verb.task('docs', function() {
  verb.src('docs/_verb/*.md')
    .pipe(verb.dest('docs'));
});

verb.task('lint', function () {
  verb.src(['index.js', 'lib/**/*.js'])
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('jshint-stylish'));
});

verb.task('test', function (cb) {
  verb.src(['index.js', 'lib/**/*.js'])
    .pipe(istanbul({includeUntested: true}))
    .pipe(istanbul.hookRequire())
    .on('finish', function () {
      verb.src(['test/*.js'])
        .pipe(mocha())
        .pipe(istanbul.writeReports({
          reporters: [ 'text' ],
          reportOpts: {dir: 'coverage', file: 'summary.txt'}
        }))
        .on('end', function () {
          cb();
        });
    });
});

verb.task('default', ['readme', 'lint', 'test']);
<commit_msg>adds deps<commit_after>'use strict';

/* deps: jshint-stylish mocha */
var path = require('path');
var istanbul = require('gulp-istanbul');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
var gutil = require('gulp-util');
var verb = require('verb');

verb.helper('rename', function(str, a, b, c) {
  str = str.split(a + '.').join(b + '.');
  str = str.split('var ' + a).join('var ' + b);
  var upperB = b[0].toUpperCase() + b.slice(1);
  str = str.split(c).join(upperB);
  return str;
});

verb.helper('npm', function (name) {
  return 'node_modules/' + name + '/index.js';
});

verb.helper('home', function (name) {
  var dir = path.dirname(require.resolve(name));
  var pkg = path.resolve(dir, 'package.json');
  return require(pkg).homepage + '/blob/master/index.js';
});

verb.task('readme', function() {
  verb.src('.verb.md')
    .pipe(verb.dest('./'));
});

verb.task('docs', function() {
  verb.src('docs/_verb/*.md')
    .pipe(verb.dest('docs'));
});

verb.task('lint', function () {
  verb.src(['index.js', 'lib/**/*.js'])
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('jshint-stylish'));
});

verb.task('test', function (cb) {
  // deps: coveralls istanbul jshint-stylish
  verb.src(['index.js', 'lib/**/*.js'])
    .pipe(istanbul({includeUntested: true}))
    .pipe(istanbul.hookRequire())
    .on('finish', function () {
      verb.src(['test/*.js'])
        .pipe(mocha())
        .pipe(istanbul.writeReports({
          reporters: [ 'text' ],
          reportOpts: {dir: 'coverage', file: 'summary.txt'}
        }))
        .on('end', function () {
          cb();
        });
    });
});

verb.task('default', ['readme', 'lint', 'test']);
<|endoftext|>


<commit_before>'use strict';

angular.module('SmithsonianApp')
  .service('Collection', function ($resource, route) {
    var Collection = $resource(route.api + '/collections/:id'),
      Tags = $resource(route.api + '/collections/:id/tags', {}, {
        update: {method: 'PUT'}
      });

    return {
      get: function (id, params) {
        var defaultParams;

        defaultParams = {
          start: 0
        };

        params = _.extend(defaultParams, params);

        if (_.isUndefined(id)) {
          params = _.extend(params, {id: id});
        }

        return Collection.get(params);
      },
      getTags: function (id, params) {
        params = _.extend(params, {id: id});
        return Tags.get(params);
      },
      createTag: function (id, data) {
        return Tags.save({id: id}, data);
      },
      modifyTag: function (id, data) {
        return Tags.update({id: id}, data);
      },
      deleteTag: function (id, data) {
        return Tags.delete({id: id}, data);
      }
    };

    function resolve (deferred) {
      return function (data) {
        deferred.resolve(data);
      };
    }

    function reject (deferred) {
      return function (error) {
        deferred.reject(error);
      };
    }
  });
<commit_msg>Added url for update method for tags in collection service<commit_after>'use strict';

angular.module('SmithsonianApp')
  .service('Collection', function ($resource, route) {
    var Collection = $resource(route.api + '/collections/:id'),
      Tags = $resource(route.api + '/collections/:id/tags', {}, {
        update: {method: 'PUT', '/:tagId'}
      });

    return {
      get: function (id, params) {
        var defaultParams;

        defaultParams = {
          start: 0
        };

        params = _.extend(defaultParams, params);

        if (_.isUndefined(id)) {
          params = _.extend(params, {id: id});
        }

        return Collection.get(params);
      },
      getTags: function (id, params) {
        params = _.extend(params, {id: id});
        return Tags.get(params);
      },
      createTag: function (id, data) {
        return Tags.save({id: id}, data);
      },
      modifyTag: function (id, data) {
        return Tags.update({id: id}, data);
      },
      deleteTag: function (id, data) {
        return Tags.delete({id: id}, data);
      }
    };

    function resolve (deferred) {
      return function (data) {
        deferred.resolve(data);
      };
    }

    function reject (deferred) {
      return function (error) {
        deferred.reject(error);
      };
    }
  });
<|endoftext|>