<commit_before>import projectModel from '../models/project.js'
import yapi from '../yapi.js'
import baseController from './base.js'
import interfaceModel from '../models/interface.js'
import groupModel from '../models/group'
import commons from '../utils/commons.js'

class projectController extends baseController {

    constructor(ctx){
        super(ctx)
        this.Model = yapi.getInst(projectModel);
        this.groupModel = yapi.getInst(groupModel);
    }

    /**
     * 添加项目分组
     * @interface /project/add
     * @method POST
     * @category project
     * @foldnumber 10
     * @param {String} name 项目名称，不能为空
     * @param {String} basepath 项目基本路径，不能为空
     * @param {String} prd_host 项目线上域名，不能为空。可通过配置的域名访问到mock数据
     * @param {Number} group_id 项目分组id，不能为空
     * @param  {String} [desc] 项目描述
     * @returns {Object}
     * @example ./api/project/add.json
     */
    async add(ctx) {
        let params = ctx.request.body;

        if(!params.group_id){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目分组id不能为空');
        }

        if(!params.name){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目名不能为空');
        }

        let checkRepeat = await this.Model.checkNameRepeat(params.name);
        if(checkRepeat > 0){
            return ctx.body =  yapi.commons.resReturn(null, 401, '已存在的项目名');
        }

        if(!params.basepath){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目basepath不能为空');
        }
        if(!params.prd_host){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目domain不能为空');
        }

        let checkRepeatDomain = await this.Model.checkDomainRepeat(params.prd_host, params.basepath);
        if(checkRepeatDomain > 0){
            return ctx.body =  yapi.commons.resReturn(null, 401, '已存在domain和basepath');
        }

        let data = {
            name: params.name,
            desc: params.desc,
            prd_host: params.prd_host,
            basepath: params.basepath,
            members: [this.getUid()],
            uid: this.getUid(),
            group_id: params.group_id,
            add_time: yapi.commons.time(),
            up_time: yapi.commons.time()
        }

        try{
            let result = await this.Model.save(data);
            ctx.body = yapi.commons.resReturn(result);
        }catch(e){
            ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }

    }
     /**
     * 添加项目
     * @interface /project/add_member
     * @method POST
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @param {String} member_uid 项目成员uid,不能为空
     * @returns {Object}
     * @example ./api/project/add_member.json
     */
    async addMember(ctx){
        let params = ctx.request.body;
        if(!params.member_uid){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目成员uid不能为空');
        }
        if(!params.id){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空');
        }

        var check = await this.Model.checkMemberRepeat(params.id, params.member_uid);
        if(check > 0){
             return ctx.body = yapi.commons.resReturn(null, 400, '项目成员已存在');
        }
        try{
            let result = await this.Model.addMember(params.id, params.member_uid);
            ctx.body = yapi.commons.resReturn(result);
        }catch(e){
            ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }

    }
     /**
     * 添加项目
     * @interface /project/del_member
     * @method POST
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @param {member_uid} uid 项目成员uid,不能为空
     * @returns {Object}
     * @example ./api/project/del_member.json
     */

    async delMember(ctx){
        let params = ctx.request.body;
        if(!params.member_uid){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目成员uid不能为空');
        }
        if(!params.id){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空');
        }
        var check = await this.Model.checkMemberRepeat(params.id, params.member_uid);
        if(check === 0){
             return ctx.body = yapi.commons.resReturn(null, 400, '项目成员不存在');
        }

         try{
            let result = await this.Model.delMember(params.id, params.member_uid);
            ctx.body = yapi.commons.resReturn(result);
        }catch(e){
            ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }
    }
<<<<<<< HEAD
=======

    /**
     * 获取项目成员列表
     * @interface /project/get_member_list
     * @method GET
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @return {Object}
     * @example ./api/project/get_member_list.json
     */

    async getMemberList(ctx) {
        let params = ctx.request.query;
        if(!params.id) {
            return ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空');
        }

        try {
            let project = await this.Model.get(params.id);
            let userInst = yapi.getInst(userModel);
            let result = [];

            for(let i of project.members) {
                let user = await userInst.findById(i);
                result.push({
                    _id: user._id,
                    email: user.email,
                    role: user.role,
                    add_time: user.add_time,
                    up_time: user.up_time
                });
            }

            ctx.body = yapi.commons.resReturn(result);
        } catch(e) {
            ctx.body = yapi.commons.resReturn(null, 402, e.message);
        }
    }

>>>>>>> 2467556d35eca929c40a1ffd1e5d64d047a9fc77
     /**
     * 添加项目
     * @interface /project/get
     * @method GET
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @returns {Object}
     * @example ./api/project/get.json
     */

    async get(ctx){
        let params = ctx.request.query;
        if(!params.id){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空');
        }
        try{
            let result = await this.Model.get(params.id);
            ctx.body = yapi.commons.resReturn(result);
        }catch(e){
            ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }
    }

    /**
     * 获取项目列表
     * @interface /project/list
     * @method GET
     * @category project
     * @foldnumber 10
     * @param {Number} group_id 项目group_id，不能为空
     * @param {Number} [pageNo] 分页页码
     * @param {Number} [pageSize] 分页大小
     * @returns {Object}
     * @example ./api/project/list.json
     */

    async list(ctx) {
        let group_id = ctx.request.query.group_id,
            pageNo = ctx.request.query.pageNo || 1,
            pageSize = ctx.request.query.pageSize || 10;

        if(!group_id){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目分组id不能为空');
        }

        try{
            let result = await this.Model.list(group_id);
            let resResult = [];
            for(let i = (pageNo - 1) * pageSize; i < pageNo * pageSize; i++) {
                if(!result[i]) break;
                resResult.push(result[i]);
            }
            ctx.body = yapi.commons.resReturn({
                total: result.length,
                list: resResult
            })
        }catch(err){
             ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }
    }

    /**
     * 删除项目
     * @interface /project/del
     * @method POST
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @returns {Object}
     * @example ./api/project/del.json
     */

    async del(ctx){
        try{
            let id = ctx.request.body.id;
            if(!id){
                return ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空');
            }
            let interfaceInst = yapi.getInst(interfaceModel);
            let count = await interfaceInst.countByProjectId(id);
            if(count > 0){
                return ctx.body = yapi.commons.resReturn(null, 400, '请先删除该项目下所有接口');
            }

            if(await this.jungeProjectAuth(id) !== true){
                return ctx.body = yapi.commons.resReturn(null, 405, '没有权限');
            }
            let result = await this.Model.del(id);
            ctx.body = yapi.commons.resReturn(result);
        }catch(err){
             ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }
    }

    /**
     * 编辑项目
     * @interface /project/up
     * @method GET
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @param {String} name 项目名称，不能为空
     * @param {String} basepath 项目基本路径，不能为空
     * @param {String} prd_host 项目线上域名，不能为空。可通过配置的域名访问到mock数据
     * @param {String} [desc] 项目描述
     * @param {Array} [env] 项目环境配置
     * @param {String} [env[].name] 环境名称
     * @param {String} [env[].host] 环境域名
     * @returns {Object}
     * @example ./api/project/up.json
     */

    async up(ctx){
        try{
            let id = ctx.request.body.id;
            let params = ctx.request.body;

            if(await this.jungeMemberAuth(id, this.getUid()) !== true){
                return ctx.body = yapi.commons.resReturn(null, 405, '没有权限');
            }

            if(params.name){
                let checkRepeat = await this.Model.checkNameRepeat(params.name);
                if(checkRepeat > 0){
                    return ctx.body =  yapi.commons.resReturn(null, 401, '已存在的项目名');
                }
            }

            if(params.basepath && params.prd_host){
                let checkRepeatDomain = await this.Model.checkDomainRepeat(params.prd_host, params.basepath);
                if(checkRepeatDomain > 0){
                    return ctx.body =  yapi.commons.resReturn(null, 401, '已存在domain和basepath');
                }
            }

            let data= {
                uid: this.getUid(),
                up_time: yapi.commons.time()
            }

            if(params.name) data.name = params.name;
            if(params.desc) data.desc = params.desc;
            if(params.prd_host && params.basepath){
                data.prd_host = params.prd_host;
                data.basepath = params.basepath;
            }
            if(params.env) data.env = params.env;

            let result = await this.Model.up(id, data);
            ctx.body = yapi.commons.resReturn(result)
        }catch(e){
             ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }
    }

    /**
     * 模糊搜索项目名称或者组名称
     * @interface /project/search
     * @method GET
     * @category project
     * @foldnumber 10
     * @param {String} q
     * @return {Object}
     * @example ./api/project/search.json
    */
    async search(ctx) {
        const { q } = ctx.request.query;

        if (!q) {
            return ctx.body = yapi.commons.resReturn(void 0, 400, 'No keyword.')
        }

        if (!yapi.commons.validateSearchKeyword(q)) {
            return ctx.body = yapi.commons.resReturn(void 0, 400, 'Bad query.')
        }

        let projectList = await this.Model.search(q);
        let groupList = await this.groupModel.search(q);
        let projectRules = [
            '_id',
            'name',
            'basepath',
            'uid',
            'env',
            'members',
            { key: 'group_id', alias: 'groupId' },
            { key: 'up_time', alias: 'upTime' },
            { key: 'prd_host', alias: 'prdHost' },
            { key: 'add_time', alias: 'addTime' }
        ];
        let groupRules = [
            '_id',
            'uid',
            { key: 'group_name', alias: 'groupName'},
            { key: 'group_desc', alias: 'groupDesc' },
            { key: 'add_time', alias: 'addTime' },
            { key: 'up_time', alias: 'upTime' }
        ];

        projectList = commons.filterRes(projectList, projectRules);
        groupList = commons.filterRes(groupList, groupRules);

        let queryList = {
            project: projectList,
            group: groupList
        };

        return ctx.body = yapi.commons.resReturn(queryList, 200, 'ok')
    }
}

module.exports = projectController;<commit_msg>fix: 解决merge留下的问题<commit_after>import projectModel from '../models/project.js'
import yapi from '../yapi.js'
import baseController from './base.js'
import interfaceModel from '../models/interface.js'
import groupModel from '../models/group'
import commons from '../utils/commons.js'

class projectController extends baseController {

    constructor(ctx){
        super(ctx)
        this.Model = yapi.getInst(projectModel);
        this.groupModel = yapi.getInst(groupModel);
    }

    /**
     * 添加项目分组
     * @interface /project/add
     * @method POST
     * @category project
     * @foldnumber 10
     * @param {String} name 项目名称，不能为空
     * @param {String} basepath 项目基本路径，不能为空
     * @param {String} prd_host 项目线上域名，不能为空。可通过配置的域名访问到mock数据
     * @param {Number} group_id 项目分组id，不能为空
     * @param  {String} [desc] 项目描述
     * @returns {Object}
     * @example ./api/project/add.json
     */
    async add(ctx) {
        let params = ctx.request.body;

        if(!params.group_id){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目分组id不能为空');
        }

        if(!params.name){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目名不能为空');
        }

        let checkRepeat = await this.Model.checkNameRepeat(params.name);
        if(checkRepeat > 0){
            return ctx.body =  yapi.commons.resReturn(null, 401, '已存在的项目名');
        }

        if(!params.basepath){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目basepath不能为空');
        }
        if(!params.prd_host){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目domain不能为空');
        }

        let checkRepeatDomain = await this.Model.checkDomainRepeat(params.prd_host, params.basepath);
        if(checkRepeatDomain > 0){
            return ctx.body =  yapi.commons.resReturn(null, 401, '已存在domain和basepath');
        }

        let data = {
            name: params.name,
            desc: params.desc,
            prd_host: params.prd_host,
            basepath: params.basepath,
            members: [this.getUid()],
            uid: this.getUid(),
            group_id: params.group_id,
            add_time: yapi.commons.time(),
            up_time: yapi.commons.time()
        }

        try{
            let result = await this.Model.save(data);
            ctx.body = yapi.commons.resReturn(result);
        }catch(e){
            ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }

    }
     /**
     * 添加项目
     * @interface /project/add_member
     * @method POST
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @param {String} member_uid 项目成员uid,不能为空
     * @returns {Object}
     * @example ./api/project/add_member.json
     */
    async addMember(ctx){
        let params = ctx.request.body;
        if(!params.member_uid){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目成员uid不能为空');
        }
        if(!params.id){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空');
        }

        var check = await this.Model.checkMemberRepeat(params.id, params.member_uid);
        if(check > 0){
             return ctx.body = yapi.commons.resReturn(null, 400, '项目成员已存在');
        }
        try{
            let result = await this.Model.addMember(params.id, params.member_uid);
            ctx.body = yapi.commons.resReturn(result);
        }catch(e){
            ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }

    }
     /**
     * 添加项目
     * @interface /project/del_member
     * @method POST
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @param {member_uid} uid 项目成员uid,不能为空
     * @returns {Object}
     * @example ./api/project/del_member.json
     */

    async delMember(ctx){
        let params = ctx.request.body;
        if(!params.member_uid){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目成员uid不能为空');
        }
        if(!params.id){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空');
        }
        var check = await this.Model.checkMemberRepeat(params.id, params.member_uid);
        if(check === 0){
             return ctx.body = yapi.commons.resReturn(null, 400, '项目成员不存在');
        }

         try{
            let result = await this.Model.delMember(params.id, params.member_uid);
            ctx.body = yapi.commons.resReturn(result);
        }catch(e){
            ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }
    }

    /**
     * 获取项目成员列表
     * @interface /project/get_member_list
     * @method GET
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @return {Object}
     * @example ./api/project/get_member_list.json
     */

    async getMemberList(ctx) {
        let params = ctx.request.query;
        if(!params.id) {
            return ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空');
        }

        try {
            let project = await this.Model.get(params.id);
            let userInst = yapi.getInst(userModel);
            let result = [];

            for(let i of project.members) {
                let user = await userInst.findById(i);
                result.push({
                    _id: user._id,
                    email: user.email,
                    role: user.role,
                    add_time: user.add_time,
                    up_time: user.up_time
                });
            }

            ctx.body = yapi.commons.resReturn(result);
        } catch(e) {
            ctx.body = yapi.commons.resReturn(null, 402, e.message);
        }
    }

     /**
     * 添加项目
     * @interface /project/get
     * @method GET
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @returns {Object}
     * @example ./api/project/get.json
     */

    async get(ctx){
        let params = ctx.request.query;
        if(!params.id){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空');
        }
        try{
            let result = await this.Model.get(params.id);
            ctx.body = yapi.commons.resReturn(result);
        }catch(e){
            ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }
    }

    /**
     * 获取项目列表
     * @interface /project/list
     * @method GET
     * @category project
     * @foldnumber 10
     * @param {Number} group_id 项目group_id，不能为空
     * @param {Number} [pageNo] 分页页码
     * @param {Number} [pageSize] 分页大小
     * @returns {Object}
     * @example ./api/project/list.json
     */

    async list(ctx) {
        let group_id = ctx.request.query.group_id,
            pageNo = ctx.request.query.pageNo || 1,
            pageSize = ctx.request.query.pageSize || 10;

        if(!group_id){
            return ctx.body = yapi.commons.resReturn(null, 400, '项目分组id不能为空');
        }

        try{
            let result = await this.Model.list(group_id);
            let resResult = [];
            for(let i = (pageNo - 1) * pageSize; i < pageNo * pageSize; i++) {
                if(!result[i]) break;
                resResult.push(result[i]);
            }
            ctx.body = yapi.commons.resReturn({
                total: result.length,
                list: resResult
            })
        }catch(err){
             ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }
    }

    /**
     * 删除项目
     * @interface /project/del
     * @method POST
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @returns {Object}
     * @example ./api/project/del.json
     */

    async del(ctx){
        try{
            let id = ctx.request.body.id;
            if(!id){
                return ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空');
            }
            let interfaceInst = yapi.getInst(interfaceModel);
            let count = await interfaceInst.countByProjectId(id);
            if(count > 0){
                return ctx.body = yapi.commons.resReturn(null, 400, '请先删除该项目下所有接口');
            }

            if(await this.jungeProjectAuth(id) !== true){
                return ctx.body = yapi.commons.resReturn(null, 405, '没有权限');
            }
            let result = await this.Model.del(id);
            ctx.body = yapi.commons.resReturn(result);
        }catch(err){
             ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }
    }

    /**
     * 编辑项目
     * @interface /project/up
     * @method GET
     * @category project
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @param {String} name 项目名称，不能为空
     * @param {String} basepath 项目基本路径，不能为空
     * @param {String} prd_host 项目线上域名，不能为空。可通过配置的域名访问到mock数据
     * @param {String} [desc] 项目描述
     * @param {Array} [env] 项目环境配置
     * @param {String} [env[].name] 环境名称
     * @param {String} [env[].host] 环境域名
     * @returns {Object}
     * @example ./api/project/up.json
     */

    async up(ctx){
        try{
            let id = ctx.request.body.id;
            let params = ctx.request.body;

            if(await this.jungeMemberAuth(id, this.getUid()) !== true){
                return ctx.body = yapi.commons.resReturn(null, 405, '没有权限');
            }

            if(params.name){
                let checkRepeat = await this.Model.checkNameRepeat(params.name);
                if(checkRepeat > 0){
                    return ctx.body =  yapi.commons.resReturn(null, 401, '已存在的项目名');
                }
            }

            if(params.basepath && params.prd_host){
                let checkRepeatDomain = await this.Model.checkDomainRepeat(params.prd_host, params.basepath);
                if(checkRepeatDomain > 0){
                    return ctx.body =  yapi.commons.resReturn(null, 401, '已存在domain和basepath');
                }
            }

            let data= {
                uid: this.getUid(),
                up_time: yapi.commons.time()
            }

            if(params.name) data.name = params.name;
            if(params.desc) data.desc = params.desc;
            if(params.prd_host && params.basepath){
                data.prd_host = params.prd_host;
                data.basepath = params.basepath;
            }
            if(params.env) data.env = params.env;

            let result = await this.Model.up(id, data);
            ctx.body = yapi.commons.resReturn(result)
        }catch(e){
             ctx.body = yapi.commons.resReturn(null, 402, e.message)
        }
    }

    /**
     * 模糊搜索项目名称或者组名称
     * @interface /project/search
     * @method GET
     * @category project
     * @foldnumber 10
     * @param {String} q
     * @return {Object}
     * @example ./api/project/search.json
    */
    async search(ctx) {
        const { q } = ctx.request.query;

        if (!q) {
            return ctx.body = yapi.commons.resReturn(void 0, 400, 'No keyword.')
        }

        if (!yapi.commons.validateSearchKeyword(q)) {
            return ctx.body = yapi.commons.resReturn(void 0, 400, 'Bad query.')
        }

        let projectList = await this.Model.search(q);
        let groupList = await this.groupModel.search(q);
        let projectRules = [
            '_id',
            'name',
            'basepath',
            'uid',
            'env',
            'members',
            { key: 'group_id', alias: 'groupId' },
            { key: 'up_time', alias: 'upTime' },
            { key: 'prd_host', alias: 'prdHost' },
            { key: 'add_time', alias: 'addTime' }
        ];
        let groupRules = [
            '_id',
            'uid',
            { key: 'group_name', alias: 'groupName'},
            { key: 'group_desc', alias: 'groupDesc' },
            { key: 'add_time', alias: 'addTime' },
            { key: 'up_time', alias: 'upTime' }
        ];

        projectList = commons.filterRes(projectList, projectRules);
        groupList = commons.filterRes(groupList, groupRules);

        let queryList = {
            project: projectList,
            group: groupList
        };

        return ctx.body = yapi.commons.resReturn(queryList, 200, 'ok')
    }
}

module.exports = projectController;<|endoftext|>


<commit_before>var path = require('path');
var exceptions = require(path.resolve(__dirname,'../utils/exceptions'));
var generalUtils = require(path.resolve(__dirname,'../utils/general'));
var Leaderboard = require('agoragames-leaderboard');

//Open connection to general leaderboards (not timebased)
var generalLeaderboard = new Leaderboard('topteamer:general');

//---------------------------------------------------------------------------------------------------------------------------
// private functions
//---------------------------------------------------------------------------------------------------------------------------

//---------------------------------------------------------------------------------------------------------------------------
// Get the general contest leaderboard
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getContestLeaderboard = getContestLeaderboard;
function getContestLeaderboard(contestId) {
    return new Leaderboard('topteamer:contest_' + contestId);
}

//---------------------------------------------------------------------------------------------------------------------------
// Get the contest leaderboard of a specific team
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getTeamLeaderboard = getTeamLeaderboard;
function getTeamLeaderboard(contestId, teamId) {
    return new Leaderboard('topteamer:contest_' + contestId + '_team' + teamId);
}

//---------------------------------------------------------------------------------------------------------------------------
// Get the weekly leaderboard
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getWeeklyLeaderboard = getWeeklyLeaderboard;
function getWeeklyLeaderboard() {
    return new Leaderboard('topteamer:weekly_' + generalUtils.getYearWeek());
}

//---------------------------------------------------------------------------------------------------------------------------
// prepareLeaderObject - parse member_data
//---------------------------------------------------------------------------------------------------------------------------
function prepareLeaderObject(id, leader, outsideLeaderboard) {
    var memberDataParts = leader.member_data.split('|');
    var leaderObject = {
        'id': id,
        'rank': leader.rank,
        'score': leader.score,
        'avatar': memberDataParts[0],
        'name': memberDataParts[1],
    };

    if (outsideLeaderboard) {
        leaderObject.outside = true;
    }

    return leaderObject;
}

//---------------------------------------------------------------------------------------------------------------------------
// addScore
//
// The following leaderboards are updated:
// =======================================
// 1. Contest general leaderboard - 'contest_<contestId>'
// 2. Contest team leaderboard - 'contest_<contestId>_team_<teamId>'
// 3. General Leaderboard (ever) - 'general' (will be used to display my friends' scores)
// 4. Weekly leaderboard - weekly_<YearWeek>
//
// @deltaScore - the score currently achieved which should be increased in all leaderboards
// @facebookUserId - used as the primary member key in all leaderboards (to be able to retrieve friends leaderboard)
//---------------------------------------------------------------------------------------------------------------------------
module.exports.addScore = addScore;
function addScore(contestId, teamId, deltaScore, facebookUserId, name, avatar) {

    var contestGeneralLeaderboard = getContestLeaderboard(contestId);
    var contestTeamLeaderboard = getTeamLeaderboard(contestId, teamId);
    var weeklyLeaderboard = getWeeklyLeaderboard();

    generalLeaderboard.changeScoreFor(facebookUserId, deltaScore, function (reply) {
        generalLeaderboard.updateMemberData(facebookUserId, avatar + '|' + name);
    });

    contestGeneralLeaderboard.changeScoreFor(facebookUserId, deltaScore, function (reply) {
        contestGeneralLeaderboard.updateMemberData(facebookUserId, avatar + '|' + name, function (reply) {
            contestGeneralLeaderboard.disconnect();
        });
    });

    contestTeamLeaderboard.changeScoreFor(facebookUserId, deltaScore, function (reply) {
        contestTeamLeaderboard.updateMemberData(facebookUserId, avatar + '|' + name, function (reply) {
            contestTeamLeaderboard.disconnect();
        });
    });

    weeklyLeaderboard.changeScoreFor(facebookUserId, deltaScore, function (reply) {
        weeklyLeaderboard.updateMemberData(facebookUserId, avatar + '|' + name, function (reply) {
            weeklyLeaderboard.disconnect();
        });
    });
};

//---------------------------------------------------------------------------------------------------------------------------
// getLeaders
//
// Retrieve the first page of the input leaderboard. If my user is not included in this page, add myself to the bottom
// with flagging outside=true.
//
// data: leaderboard
// output: data.clientResponse
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getLeaders = getLeaders;
function getLeaders(data, callback) {

    var options = {
        'withMemberData': true,
        'sortBy': 'rank',
        'pageSize': generalUtils.settings.server.leaderboard.pageSize
    };

    data.clientResponse = [];

    data.leaderboard.leaders(0, options, function (leaders) {
        for (var i = 0; i < leaders.length; i++) {

            if (leaders[i].member === data.session.facebookUserId) {
                data.inLeaderboard = true;
            }

            data.clientResponse.push(prepareLeaderObject(i, leaders[i]));

        }

        if (!data.inLeaderboard && data.clientResponse.length > 0) {

            //I am not in the first page of the leaderboard
            var options = {'withMemberData': true, 'sortBy': 'rank', 'pageSize': 1};
            data.leaderboard.aroundMe(data.session.facebookUserId, options, function (leaders) {
                if (leaders && leaders.length > 0) {
                    //I am in the leaderboard (not at the first page)
                    data.clientResponse.push(prepareLeaderObject(data.clientResponse.length, leaders[0], true));
                    callback(null, data);
                }
                else {
                    //I am not in the leaderboard at all (never played for that leaderboard)
                    callback(null, data);
                }
            });
        }
        else {
            //I am in the first page of the leaderboard
            callback(null, data);
        }
    });
}

//---------------------------------------------------------------------------------------------------------------------------
// getFriends
//
// Retrieve me and my friends from the general leaderboard
//
// data: session (including friends.list array of id,name objects)
// output: data.clientResponse
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getFriends = getFriends;
function getFriends(data, callback) {

    var options = {
        withMemberData: false,
        pageSize: generalUtils.settings.server.leaderboard.pageSize + 1 //Including myself
    };

    data.clientResponse = [];

    var members = [];
    for (var i = 0; i < data.session.friends.list.length; i++) {
        members.push(data.session.friends.list[i].id);
    }
    //Push myself as well
    members.push(data.session.facebookUserId);

    generalLeaderboard.rankedInList(members, options, function (leadersWithoutMemberData) {

      var trueLeaderboardMembers = [];
      for (var i = 0; i < leadersWithoutMemberData.length; i++) {

        //Check that rank exist - otherwise this friends did not play yet and he/she is not in the leaderboard
        if (leadersWithoutMemberData[i].rank) {
          trueLeaderboardMembers.push(leadersWithoutMemberData[i].member);
        }
      }

      options.withMemberData = true;
      options.sortBy = 'rank';
      options.reverse = true;

      generalLeaderboard.rankedInList(trueLeaderboardMembers, options, function (leaders) {

        for (var i = 0; i < leaders.length; i++) {
          data.clientResponse.push(prepareLeaderObject(i, leaders[i]));
        }

        callback(null, data);
      });

    })

}

//---------------------------------------------------------------------------------------------------------------------------
// getFriendsAboveMe
//
// getFriendsAboveMe - returns x (based on general settings) friends above me in the leaderboard
//
// data: session
// output: data.friendsAboveMe array
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getFriendsAboveMe = getFriendsAboveMe;
function getFriendsAboveMe(data, callback) {

    var options = {
        'withMemberData': true,
        'sortBy': 'rank',
        'pageSize': generalUtils.settings.server.leaderboard.friendsAboveMePageSize
    };

    data.friendsAboveMe = [];

    generalLeaderboard.aroundMe(data.session.facebookUserId, options, function (leaders) {
        if (leaders && leaders.length > 0) {

            //I will be in that list as the last one - all my friends that are above me - will be first in the array)
            //.id property for each item in the friendsAboveMe list is the facebookUserId - for later to compute the passedFriends
            for (var i = 0; i < leaders.length; i++) {
                data.friendsAboveMe.push(prepareLeaderObject(leaders[i].member, leaders[i]));
                if (leaders[i].member === data.session.facebookUserId) {
                    break;
                }
            }
        }

        callback(null, data);

    });
};

//---------------------------------------------------------------------------------------------------------------------------
// getPassedFriends
//
// getPassedFriends - returns all the friends that I passed (in relation to data.friendsAboveMe)
//
// data: session, friendsAboveMe (friends that previously were above me - I will be last in this array)
// output: data.passedFriends array
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getPassedFriends = getPassedFriends;
function getPassedFriends(data, callback) {

    var options = {
        'withMemberData': true,
        'sortBy': 'rank',
        'pageSize': data.friendsAboveMe.length
    };

    data.passedFriends = [];

    var members = [];
    for (var i = 0; i < data.friendsAboveMe.length; i++) {
        members.push(data.friendsAboveMe[i].id); //Id is the facebookUserId which is the key of the member in the leaderboard
    }

    generalLeaderboard.rankedInList(members, options, function (leaders) {
        var reachedMyself = false;
        var friendsAfterMe = 0;

        for (var i = 0; i < leaders.length; i++) {

            if (reachedMyself) {
                data.passedFriends.push(prepareLeaderObject(leaders[i].member, leaders[i]));
                friendsAfterMe++;
            }
            else if (leaders[i].member === data.session.facebookUserId) {
                reachedMyself = true;
            }
        }

        callback(null, data);
    });

};

<commit_msg>fix friends leaderboard<commit_after>var path = require('path');
var exceptions = require(path.resolve(__dirname,'../utils/exceptions'));
var generalUtils = require(path.resolve(__dirname,'../utils/general'));
var Leaderboard = require('agoragames-leaderboard');

//Open connection to general leaderboards (not timebased)
var generalLeaderboard = new Leaderboard('topteamer:general');

//---------------------------------------------------------------------------------------------------------------------------
// private functions
//---------------------------------------------------------------------------------------------------------------------------

//---------------------------------------------------------------------------------------------------------------------------
// Get the general contest leaderboard
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getContestLeaderboard = getContestLeaderboard;
function getContestLeaderboard(contestId) {
    return new Leaderboard('topteamer:contest_' + contestId);
}

//---------------------------------------------------------------------------------------------------------------------------
// Get the contest leaderboard of a specific team
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getTeamLeaderboard = getTeamLeaderboard;
function getTeamLeaderboard(contestId, teamId) {
    return new Leaderboard('topteamer:contest_' + contestId + '_team' + teamId);
}

//---------------------------------------------------------------------------------------------------------------------------
// Get the weekly leaderboard
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getWeeklyLeaderboard = getWeeklyLeaderboard;
function getWeeklyLeaderboard() {
    return new Leaderboard('topteamer:weekly_' + generalUtils.getYearWeek());
}

//---------------------------------------------------------------------------------------------------------------------------
// prepareLeaderObject - parse member_data
//---------------------------------------------------------------------------------------------------------------------------
function prepareLeaderObject(id, leader, outsideLeaderboard) {
    var memberDataParts = leader.member_data.split('|');
    var leaderObject = {
        'id': id,
        'rank': leader.rank,
        'score': leader.score,
        'avatar': memberDataParts[0],
        'name': memberDataParts[1],
    };

    if (outsideLeaderboard) {
        leaderObject.outside = true;
    }

    return leaderObject;
}

//---------------------------------------------------------------------------------------------------------------------------
// addScore
//
// The following leaderboards are updated:
// =======================================
// 1. Contest general leaderboard - 'contest_<contestId>'
// 2. Contest team leaderboard - 'contest_<contestId>_team_<teamId>'
// 3. General Leaderboard (ever) - 'general' (will be used to display my friends' scores)
// 4. Weekly leaderboard - weekly_<YearWeek>
//
// @deltaScore - the score currently achieved which should be increased in all leaderboards
// @facebookUserId - used as the primary member key in all leaderboards (to be able to retrieve friends leaderboard)
//---------------------------------------------------------------------------------------------------------------------------
module.exports.addScore = addScore;
function addScore(contestId, teamId, deltaScore, facebookUserId, name, avatar) {

    var contestGeneralLeaderboard = getContestLeaderboard(contestId);
    var contestTeamLeaderboard = getTeamLeaderboard(contestId, teamId);
    var weeklyLeaderboard = getWeeklyLeaderboard();

    generalLeaderboard.changeScoreFor(facebookUserId, deltaScore, function (reply) {
        generalLeaderboard.updateMemberData(facebookUserId, avatar + '|' + name);
    });

    contestGeneralLeaderboard.changeScoreFor(facebookUserId, deltaScore, function (reply) {
        contestGeneralLeaderboard.updateMemberData(facebookUserId, avatar + '|' + name, function (reply) {
            contestGeneralLeaderboard.disconnect();
        });
    });

    contestTeamLeaderboard.changeScoreFor(facebookUserId, deltaScore, function (reply) {
        contestTeamLeaderboard.updateMemberData(facebookUserId, avatar + '|' + name, function (reply) {
            contestTeamLeaderboard.disconnect();
        });
    });

    weeklyLeaderboard.changeScoreFor(facebookUserId, deltaScore, function (reply) {
        weeklyLeaderboard.updateMemberData(facebookUserId, avatar + '|' + name, function (reply) {
            weeklyLeaderboard.disconnect();
        });
    });
};

//---------------------------------------------------------------------------------------------------------------------------
// getLeaders
//
// Retrieve the first page of the input leaderboard. If my user is not included in this page, add myself to the bottom
// with flagging outside=true.
//
// data: leaderboard
// output: data.clientResponse
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getLeaders = getLeaders;
function getLeaders(data, callback) {

    var options = {
        'withMemberData': true,
        'sortBy': 'rank',
        'pageSize': generalUtils.settings.server.leaderboard.pageSize
    };

    data.clientResponse = [];

    data.leaderboard.leaders(0, options, function (leaders) {
        for (var i = 0; i < leaders.length; i++) {

            if (leaders[i].member === data.session.facebookUserId) {
                data.inLeaderboard = true;
            }

            data.clientResponse.push(prepareLeaderObject(i, leaders[i]));

        }

        if (!data.inLeaderboard && data.clientResponse.length > 0) {

            //I am not in the first page of the leaderboard
            var options = {'withMemberData': true, 'sortBy': 'rank', 'pageSize': 1};
            data.leaderboard.aroundMe(data.session.facebookUserId, options, function (leaders) {
                if (leaders && leaders.length > 0) {
                    //I am in the leaderboard (not at the first page)
                    data.clientResponse.push(prepareLeaderObject(data.clientResponse.length, leaders[0], true));
                    callback(null, data);
                }
                else {
                    //I am not in the leaderboard at all (never played for that leaderboard)
                    callback(null, data);
                }
            });
        }
        else {
            //I am in the first page of the leaderboard
            callback(null, data);
        }
    });
}

//---------------------------------------------------------------------------------------------------------------------------
// getFriends
//
// Retrieve me and my friends from the general leaderboard
//
// data: session (including friends.list array of id,name objects)
// output: data.clientResponse
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getFriends = getFriends;
function getFriends(data, callback) {

    var options = {
        withMemberData: false,
        pageSize: generalUtils.settings.server.leaderboard.pageSize + 1 //Including myself
    };

    data.clientResponse = [];

    var members = [];
    for (var i = 0; i < data.session.friends.list.length; i++) {
        members.push(data.session.friends.list[i].id);
    }
    //Push myself as well
    members.push(data.session.facebookUserId);

    generalLeaderboard.rankedInList(members, options, function (leadersWithoutMemberData) {

      var trueLeaderboardMembers = [];
      for (var i = 0; i < leadersWithoutMemberData.length; i++) {

        //Check that rank exist - otherwise this friends did not play yet and he/she is not in the leaderboard
        if (leadersWithoutMemberData[i].rank) {
          trueLeaderboardMembers.push(leadersWithoutMemberData[i].member);
        }
      }

      options.withMemberData = true;
      options.sortBy = 'rank';
      options.reverse = true;

      generalLeaderboard.rankedInList(trueLeaderboardMembers, options, function (leaders) {
        console.log('final list: ' + JSON.stringify(leaders));
        for (var i = 0; i < leaders.length; i++) {
          data.clientResponse.push(prepareLeaderObject(i, leaders[i]));
        }

        callback(null, data);
      });

    })

}

//---------------------------------------------------------------------------------------------------------------------------
// getFriendsAboveMe
//
// getFriendsAboveMe - returns x (based on general settings) friends above me in the leaderboard
//
// data: session
// output: data.friendsAboveMe array
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getFriendsAboveMe = getFriendsAboveMe;
function getFriendsAboveMe(data, callback) {

    var options = {
        'withMemberData': true,
        'sortBy': 'rank',
        'pageSize': generalUtils.settings.server.leaderboard.friendsAboveMePageSize
    };

    data.friendsAboveMe = [];

    generalLeaderboard.aroundMe(data.session.facebookUserId, options, function (leaders) {
        if (leaders && leaders.length > 0) {

            //I will be in that list as the last one - all my friends that are above me - will be first in the array)
            //.id property for each item in the friendsAboveMe list is the facebookUserId - for later to compute the passedFriends
            for (var i = 0; i < leaders.length; i++) {
                data.friendsAboveMe.push(prepareLeaderObject(leaders[i].member, leaders[i]));
                if (leaders[i].member === data.session.facebookUserId) {
                    break;
                }
            }
        }

        callback(null, data);

    });
};

//---------------------------------------------------------------------------------------------------------------------------
// getPassedFriends
//
// getPassedFriends - returns all the friends that I passed (in relation to data.friendsAboveMe)
//
// data: session, friendsAboveMe (friends that previously were above me - I will be last in this array)
// output: data.passedFriends array
//---------------------------------------------------------------------------------------------------------------------------
module.exports.getPassedFriends = getPassedFriends;
function getPassedFriends(data, callback) {

    var options = {
        'withMemberData': true,
        'sortBy': 'rank',
        'pageSize': data.friendsAboveMe.length
    };

    data.passedFriends = [];

    var members = [];
    for (var i = 0; i < data.friendsAboveMe.length; i++) {
        members.push(data.friendsAboveMe[i].id); //Id is the facebookUserId which is the key of the member in the leaderboard
    }

    generalLeaderboard.rankedInList(members, options, function (leaders) {
        var reachedMyself = false;
        var friendsAfterMe = 0;

        for (var i = 0; i < leaders.length; i++) {

            if (reachedMyself) {
                data.passedFriends.push(prepareLeaderObject(leaders[i].member, leaders[i]));
                friendsAfterMe++;
            }
            else if (leaders[i].member === data.session.facebookUserId) {
                reachedMyself = true;
            }
        }

        callback(null, data);
    });

};

<|endoftext|>


<commit_before>const Sequelize = require('sequelize');
const db = require('../db.js');
const User = require('./User.js');

const SavedJobs = db.define('SavedJobs', {
  company: {
    type: Sequelize.STRING,
  },
  job_url: {
    type: Sequelize.STRING,
  },
  position: {
    type: Sequelize.STRING,
  },
  location: {
    type: Sequelize.STRING,
  },
  status: {
    type: Sequelize.INTEGER,
    defaultValue: -1,
  },
  post_date: {
    type: Sequelize.DATE,
  },
  created_at: {
    type: Sequelize.DATE,
  },
  updated_at: {
    type: Sequelize.DATE,
  },
  applied_date: {
    type: Sequelize.DATE,
  },
  closed_date: {
    type: Sequelize.DATE,
  },
  notes: {
    type: Sequelize.TEXT,
  },
});

SavedJobs.belongsTo(User, {
  as: 'user',
  foreignKey: 'user_id',
  constraints: false,
});

User.hasMany(SavedJobs, { foreignKey: 'user_id', constraints: false });

SavedJobs.sync();

module.exports = SavedJobs;
<commit_msg>fix(styled notes): styled notes<commit_after>const Sequelize = require('sequelize');
const db = require('../db.js');
const User = require('./User.js');

const SavedJobs = db.define('SavedJobs', {
  company: {
    type: Sequelize.STRING,
  },
  job_url: {
    type: Sequelize.STRING,
  },
  position: {
    type: Sequelize.STRING,
  },
  location: {
    type: Sequelize.STRING,
  },
  status: {
    type: Sequelize.INTEGER,
    defaultValue: -1,
  },
  post_date: {
    type: Sequelize.DATE,
  },
  created_at: {
    type: Sequelize.DATE,
  },
  updated_at: {
    type: Sequelize.DATE,
  },
  applied_date: {
    type: Sequelize.DATE,
  },
  closed_date: {
    type: Sequelize.DATE,
  },
  cover_letter_key: {
    type: Sequelize.TEXT,
  },
});

SavedJobs.belongsTo(User, {
  as: 'user',
  foreignKey: 'user_id',
  constraints: false,
});

User.hasMany(SavedJobs, { foreignKey: 'user_id', constraints: false });

SavedJobs.sync();

module.exports = SavedJobs;
<|endoftext|>


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

/**
 * @fileoverview Test for CSS-style selectors for JS objects.
 * @author cpcallen@google.com (Christopher Allen)
 */
'use strict';

const Selector = require('../selector');
const {T} = require('./testing');
const util = require('util');

/**
 * Unit tests for Selector
 * @param {!T} t The test runner object.
 */
exports.testSelector = function(t) {
  const cases = [
    ['foo', 1, 'foo', 'foo', 'foo'],
    [['foo'], 1, 'foo', 'foo', 'foo'],

    ['foo.bar', 2, 'foo', 'bar', 'foo.bar'],
    ['foo["bar"]', 2, 'foo', 'bar', 'foo.bar'],
    ["foo['bar']", 2, 'foo', 'bar', 'foo.bar'],
    [['foo', 'bar'], 2, 'foo', 'bar', 'foo.bar'],

    ['foo[42]', 2, 'foo', '42', 'foo[42]'],
    [['foo', '42'], 2, 'foo', '42', 'foo[42]'],

    ['foo["bar baz"]', 2, 'foo', 'bar baz', "foo['bar baz']"],
    ["foo['bar baz']", 2, 'foo', 'bar baz', "foo['bar baz']"],
    [['foo', 'bar baz'], 2, 'foo', 'bar baz', "foo['bar baz']"],

    ["foo['\"\\'\"']", 2, 'foo', '"\'"', "foo['\"\\'\"']"],
    [['foo', '"\'"'], 2, 'foo', '"\'"', "foo['\"\\'\"']"],

    ['foo["\'\\"\'"]', 2, 'foo', "'\"'", 'foo["\'\\"\'"]'],
    [['foo', "'\"'"], 2, 'foo', "'\"'", 'foo["\'\\"\'"]'],

    ['foo.bar.baz', 3, 'foo', 'baz', 'foo.bar.baz'],
    [['foo', 'bar', 'baz'], 3, 'foo', 'baz', 'foo.bar.baz'],

    ['$._.__.$$', 4, '$', '$$', '$._.__.$$'],
    [['$', '_', '__', '$$'], 4, '$', '$$', '$._.__.$$'],

    ['foo^', 2, 'foo', Selector.PROTOTYPE, 'foo^',
        'Object.getPrototypeOf(foo)', 'Object.setPrototypeOf(foo, NEW)'],
    [['foo', Selector.PROTOTYPE], 2, 'foo', Selector.PROTOTYPE, 'foo^',
        'Object.getPrototypeOf(foo)', 'Object.setPrototypeOf(foo, NEW)'],

    ['foo^.bar', 3, 'foo', 'bar', 'foo^.bar',
        'Object.getPrototypeOf(foo).bar',
        'Object.getPrototypeOf(foo).bar = NEW'],
    [['foo', Selector.PROTOTYPE, 'bar'], 3, 'foo', 'bar', 'foo^.bar',
        'Object.getPrototypeOf(foo).bar',
        'Object.getPrototypeOf(foo).bar = NEW'],
  ];
  for (const tc of cases) {
    const s = new Selector(tc[0]);
    const name = util.format('new Selector(%o)', tc[0]);
    t.expect(name + '.length', s.length, tc[1]);
    t.expect(name + '[0]', s[0], tc[2]);
    t.expect(name + '[/*last*/]', s[s.length - 1], tc[3]);
    t.expect(name + '.toString()', s.toString(), tc[4]);
    const expr = tc[5] || tc[4];
    t.expect(name + '.toExpr()', s.toExpr(), expr);
    const setExpr = tc[6] || tc[4] + ' = NEW';
    t.expect(name + '.toSetExpr()', s.toSetExpr('NEW'), setExpr);
  }
};

<commit_msg>Clean up Selector tests<commit_after>/**
 * @license
 * Code City: Selectors (tests)
 *
 * Copyright 2018 Google Inc.
 * https://github.com/NeilFraser/CodeCity
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Test for CSS-style selectors for JS objects.
 * @author cpcallen@google.com (Christopher Allen)
 */
'use strict';

const Selector = require('../selector');
const {T} = require('./testing');
const util = require('util');

/**
 * Unit tests for Selector
 * @param {!T} t The test runner object.
 */
exports.testSelector = function(t) {
  const cases = [
    // Test cases  of form [SS, [P1, P2, ...], tS, tE, tSE] where
    // SS: selector string, to use as argument to Selector constructor,
    // [Pn...]: expected parts array,
    // tS: expected toString output,
    // tE: expected toExpr output (can be omitted if same),
    // tSE: expected toSetExpr output (if different not same + ' = NEW').

    ['foo', ['foo'], 'foo'],

    ['foo.bar', ['foo', 'bar'], 'foo.bar'],
    ['foo["bar"]', ['foo', 'bar'], 'foo.bar'],
    ["foo['bar']", ['foo', 'bar'], 'foo.bar'],

    ['foo[42]', ['foo', '42'], 'foo[42]'],
    ["foo['42']", ['foo', '42'], 'foo[42]'],
    ['foo["42"]', ['foo', '42'], 'foo[42]'],

    ['foo["bar baz"]', ['foo', 'bar baz'], "foo['bar baz']"],
    ["foo['bar baz']", ['foo', 'bar baz'], "foo['bar baz']"],

    ["foo['\"\\'\"']", ['foo', '"\'"'], "foo['\"\\'\"']"],
    ['foo["\'\\"\'"]', ['foo', "'\"'"], 'foo["\'\\"\'"]'],
    ['foo.bar.baz', ['foo', 'bar', 'baz'], 'foo.bar.baz'],
    ['$._.__.$$', ['$', '_', '__', '$$'], '$._.__.$$'],
    ['foo^', ['foo', Selector.PROTOTYPE], 'foo^',
        'Object.getPrototypeOf(foo)', 'Object.setPrototypeOf(foo, NEW)'],
    ['foo^.bar', ['foo', Selector.PROTOTYPE, 'bar'], 'foo^.bar',
        'Object.getPrototypeOf(foo).bar',
        'Object.getPrototypeOf(foo).bar = NEW'],
  ];
  for (const [input, parts, str, expr, setExpr] of cases) {
    // Do test with selector string.
    let name = util.format('new Selector(%o)', input);
    let s = new Selector(input);
    t.expect(name + '.length', s.length, parts.length);
    for (let i = 0; i < s.length; i++) {
      t.expect(util.format('%s[%d]', name, i), s[i], parts[i]);
    }
    t.expect(name + '.toString()', s.toString(), str);
    let expectedExpr = expr || str;
    t.expect(name + '.toExpr()', s.toExpr(), expectedExpr);
    let expectedSetExpr = setExpr || expectedExpr + ' = NEW';
    t.expect(name + '.toSetExpr()', s.toSetExpr('NEW'), expectedSetExpr);

    // Repeat test using parts array.
    name = util.format('new Selector(%o)', parts);
    s = new Selector(parts);
    t.expect(name + '.toString()', s.toString(), str);
    t.expect(name + '.toExpr()', s.toExpr(), expectedExpr);
    t.expect(name + '.toSetExpr()', s.toSetExpr('NEW'), expectedSetExpr);
  }
};

<|endoftext|>


<commit_before>var express = require('express');
var app= express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

//connect to mongo db
var db = mongoose.connect('mongodb://localhost/images');

app.get('/', (req,res) =>
{
	res.send(" use the route /api/images
 reference <\p>  ");
});

app.listen(9999);
console.log('Starting on port 9999...');<commit_msg>removed app.js<commit_after><|endoftext|>


<commit_before>YUI.add('aui-tree-tests', function(Y) {

    var suite = new Y.Test.Suite('aui-tree');

    var createNewTreeView = function() {
        return new Y.TreeView({
            children: [
                {
                    children: [
                        {
                            id: 'one-one'
                        },
                        {
                            id: 'one-two'
                        },
                        {
                            id: 'one-three'
                        },
                        {
                            id: 'one-four'
                        }
                    ],
                    id: 'one'
                },
                {
                    id: 'two'
                },
                {
                    id: 'three'
                }
            ]
        });
    };

    suite.add(new Y.Test.Case({
        name: 'Tree View',

        'TreeView constructor should work without a config object': function() {
            var treeView = new Y.TreeView();

            Y.Assert.isInstanceOf(Y.TreeView, treeView, 'treeView should be an instance of Y.TreeView.');
        },

        'TreeNode constructor should work without a config object': function() {
            var treeNode = new Y.TreeNode();

            Y.Assert.isInstanceOf(Y.TreeNode, treeNode, 'treeNode should be an instance of Y.TreeNode.');
        },

        'getNodeById() should return a valid TreeNode': function() {
            var childNode,
                tree;

            tree = createNewTreeView();

            childNode = tree.getNodeById('one');

            Y.Assert.isInstanceOf(Y.TreeNode, childNode, 'childNode should be an instance of Y.TreeNode.');
        },

        'getNodeById() should not return a valid TreeNode': function() {
            var childNode,
                tree;

            tree = createNewTreeView();

            childNode = tree.getNodeById('bogey');

            Y.Assert.isUndefined(childNode, 'childNode should be undefined.');
        },

        'TreeNode should have children': function() {
            var tree,
                node;

            tree = createNewTreeView();

            node = tree.getNodeById('one');

            Y.Assert.areSame(4, node.childrenLength, 'node.childrenLength should return 4.');
        },

        'TreeNode should not have children': function() {
            var tree,
                node;

            tree = createNewTreeView();

            node = tree.getNodeById('two');

            Y.Assert.areSame(0, node.childrenLength, 'node.childrenLength should return 0.');
        },

        'appendChild() should register the TreeNode in the Parent TreeNode and Owner TreeView index attribute': function() {
            var childTreeNode,
                rootTreeNode,
                rootTreeNodeIndex,
                treeView,
                treeViewIndex;

            treeView = new Y.TreeView();

            childTreeNode = new Y.TreeNode({
                id: 'child'
            });

            rootTreeNode = new Y.TreeNode({
                id: 'root'
            });

            treeView.appendChild(rootTreeNode);
            rootTreeNode.appendChild(childTreeNode);

            treeViewIndex = treeView.get('index');
            rootTreeNodeIndex = rootTreeNode.get('index');

            Y.Assert.isTrue(
                treeViewIndex.hasOwnProperty('root'),
                'treeViewIndex object should have a \'root\' property');
            Y.Assert.isTrue(
                treeViewIndex.hasOwnProperty('child'),
                'treeViewIndex object should have a \'child\' property');
            Y.Assert.isTrue(
                rootTreeNodeIndex.hasOwnProperty('child'),
                'rootTreeNodeIndex object should have a \'child\' property');
        },

        'removeChild() should remove child TreeNode': function() {
            var node,
                tree;

            tree = createNewTreeView();

            node = tree.getNodeById('two');

            tree.removeChild(node);

            Y.Assert.areSame(2, tree.getChildrenLength(), 'rootNode should have 2 children.');

            node = tree.getNodeById('two');

            Y.Assert.isUndefined(node, 'node should be undefined.');

            Y.Assert.areSame('three', tree.getChildren()[1].get('id'), 'Second node id should be `three`.');
        },

        'removeChild() should not remove child TreeNode': function() {
            var node,
                tree;

            tree = createNewTreeView();

            node = tree.getNodeById('bogey');

            tree.removeChild(node);

            Y.Assert.areSame(3, tree.getChildrenLength(), 'rootNode should have 3 children');

            Y.Assert.areSame('three', tree.getChildren()[2].get('id'), 'second node id should be `three`');
        },

        'isRegistered() should find TreeNode': function() {
            var node,
                tree;

            tree = createNewTreeView();

            node = tree.getNodeById('two');

            Y.Assert.isTrue(tree.isRegistered(node), 'TreeNode should be registered in TreeView');
        },

        'isRegistered() should find child TreeNode': function() {
            var childTreeNode,
                rootTreeNode,
                treeView;

            treeView = new Y.TreeView();

            childTreeNode = new Y.TreeNode({
                id: 'child'
            });

            rootTreeNode = new Y.TreeNode({
                id: 'root'
            });

            treeView.appendChild(rootTreeNode);
            rootTreeNode.appendChild(childTreeNode);

            Y.Assert.isTrue(
                treeView.isRegistered(childTreeNode),
                'childTreeNode should be registered in treeView');
            Y.Assert.isTrue(
                rootTreeNode.isRegistered(childTreeNode),
                'childTreeNode should be registered in Parent rootTreeNode');
        },

        'isRegistered() should not find TreeNode': function() {
            var node,
                tree;

            tree = createNewTreeView();

            node = new Y.TreeNode();

            Y.Assert.isFalse(tree.isRegistered(node), 'TreeNode should be registered in TreeView');
        },

        'TreeNodeRadio should only have one treeNode selected': function() {
            var childTreeNode,
                rootTreeNode,
                treeView;

            treeView = new Y.TreeView();

            childTreeNode = new Y.TreeNodeRadio({
                id: 'one'
            });

            rootTreeNode = new Y.TreeNodeRadio({
                id: 'root'
            });

            treeView.appendChild(rootTreeNode);
            rootTreeNode.appendChild(childTreeNode);

            rootTreeNode.check();

            Y.Assert.isTrue(
                rootTreeNode.isChecked(),
                'rootTreeNode should be checked.');

            Y.Assert.isFalse(
                childTreeNode.isChecked(),
                'childTreeNode should not be checked.');
        },

        'TreeNodeTask should select all child treeNode': function() {
            var childTreeNode,
                rootTreeNode,
                treeView;

            treeView = new Y.TreeView();

            childTreeNode = new Y.TreeNodeTask({
                id: 'one'
            });

            rootTreeNode = new Y.TreeNodeTask({
                id: 'root'
            });

            treeView.appendChild(rootTreeNode);
            rootTreeNode.appendChild(childTreeNode);

            rootTreeNode.check();

            Y.Assert.isTrue(
                rootTreeNode.isChecked(),
                'rootTreeNode should be checked.');

            Y.Assert.isTrue(
                childTreeNode.isChecked(),
                'childTreeNode should be checked.');
        },

        // Tests: AUI-1138
        'TreeNodeTask should add a state for when one of its children is unchecked': function() {
            var childTreeNode,
                rootTreeNode,
                treeView;

            treeView = new Y.TreeView();

            childTreeNode = new Y.TreeNodeTask({
                id: 'one'
            });

            rootTreeNode = new Y.TreeNodeTask({
                id: 'root'
            });

            treeView.appendChild(rootTreeNode);
            rootTreeNode.appendChild(childTreeNode);

            rootTreeNode.check();
            childTreeNode.uncheck();

            var rootTreeNodeCB = rootTreeNode.get('contentBox');

            Y.Assert.isTrue(
                rootTreeNodeCB.hasClass('tree-node-child-unchecked'),
                'rootTreeNode has an unchecked child.');

            childTreeNode.check();

            Y.Assert.isFalse(
                rootTreeNodeCB.hasClass('tree-node-child-unchecked'),
                'rootTreeNode does not have unchecked child.');
        },

        // Tests: AUI-1141
        'TreeNodeView created from HTML Markup should display glyphicon-minus when expanded': function() {
            var test = this;

            var treeViewComponent = Y.one('#createFromHTMLMarkupTest');

            var treeView = new Y.TreeView({
                boundingBox: treeViewComponent,
                contentBox: Y.one('#createFromHTMLMarkupTest > ul'),
                type: 'normal'
            }).render();

            var allHitareas = treeViewComponent.all('.tree-container .tree-hitarea');

            setTimeout(function() {
                test.resume(function() {
                    Y.each(
                        allHitareas,
                        function(hitarea) {
                            Y.Assert.isTrue(
                                hitarea.hasClass('glyphicon-minus'),
                                hitarea + ' does not have class glyphicon-minus.');
                        }
                    );
                });
            }, 800);

            setTimeout(function() {
                treeViewComponent.one('.tree-root-container .tree-hitarea').simulate('click');

                Y.each(
                    allHitareas,
                    function(hitarea) {
                        hitarea.simulate('click');
                    }
                );
            });

            test.wait(1000);
        },

        'TreeNodeView created from HTML Markup should display glyphicon-plus when collapsed': function() {
            var test = this;
            var treeViewComponent = Y.one('#createFromHTMLMarkupTest');

            var allTreeHitareas = treeViewComponent.all('.tree-container .tree-hitarea');
            var treeHitareasArray = [];

            Y.each(
                allTreeHitareas,
                function(hitarea) {
                    treeHitareasArray.push(hitarea);
                }
            );

            setTimeout(function() {
                test.resume(function() {
                    for (var i = treeHitareasArray.length; i--;) {
                        Y.Assert.isTrue(treeHitareasArray[i].hasClass('glyphicon-plus'),
                            treeHitareasArray[i] + ' does not have class glyphicon-plus');
                    }
                });
            }, 800);

            setTimeout(function() {
                for (var i = treeHitareasArray.length; i--;) {
                    treeHitareasArray[i].simulate('click');
                }
            });

            test.wait(1000);
        },

        // Tests: AUI-1156
        'Display \'Load More Results\' link for TreeNodes': function() {
            var childTreeNode,
                hitAreaNodeList,
                paginatorLink,
                rootHitArea,
                rootTreeNode,
                rootTreeNodeBB,
                treeView;

            treeView = new Y.TreeView();

            childTreeNode = [
                {
                    id: 'child-one',
                    io: 'assets/pages.html',
                    label: 'child-one',
                    paginator: {
                        limit: 3,
                        offsetParam: 'start',
                        start: 0,
                        total: 6
                    },
                    type: 'io'
                },
                {
                    label: 'child-two'
                },
                {
                    label: 'child-three'
                },
                {
                    label: 'child-four'
                }
            ];

            rootTreeNode = new Y.TreeNode({
                children: childTreeNode,
                id: 'root-one',
                label: 'root-one'
            });

            treeView.appendChild(rootTreeNode);

            treeView.render();

            rootTreeNodeBB = rootTreeNode.get('boundingBox');

            rootHitArea = rootTreeNodeBB.one('.tree-hitarea');

            rootHitArea.simulate('click');

            hitAreaNodeList = rootTreeNodeBB.all('.tree-hitarea');

            Y.Assert.areEqual(2, hitAreaNodeList.size(), 'There must be two hit-area elements');

            /*
             * We can Mock the AJAX request here, but this is not what we want to test. We want to test
             * if paginator link will appear, so we will invoke the success handler directly here,
             * assumming that server returned correct response. Clicking on hit area was proved to work above.
             */
            rootTreeNode.get('children')[0].ioSuccessHandler(null, null, {
                responseText: '[ \
                    { \
                        "label": "subchild-one", \
                        "leaf": true, \
                        "type": "node" \
                    }, \
                    { \
                        "label": "subchild-two", \
                        "leaf": true, \
                        "type": "node" \
                    }, \
                    { \
                        "label": "subchild-three", \
                        "leaf": true, \
                        "type": "node" \
                    } \
                ]'
            });

            paginatorLink = rootTreeNodeBB.one('a');

            Y.Assert.isTrue(
                paginatorLink.hasClass('tree-node-paginator'),
                'childTreeNode has a paginator link');
        }
    }));

    Y.Test.Runner.add(suite);

}, '', {
    requires: ['aui-tree', 'node-event-simulate', 'test']
});
<commit_msg>AUI-1174 Validate source code with JSHint (source formatting)<commit_after>YUI.add('aui-tree-tests', function(Y) {

    var suite = new Y.Test.Suite('aui-tree');

    var createNewTreeView = function() {
        return new Y.TreeView({
            children: [
                {
                    children: [
                        {
                            id: 'one-one'
                        },
                        {
                            id: 'one-two'
                        },
                        {
                            id: 'one-three'
                        },
                        {
                            id: 'one-four'
                        }
                    ],
                    id: 'one'
                },
                {
                    id: 'two'
                },
                {
                    id: 'three'
                }
            ]
        });
    };

    suite.add(new Y.Test.Case({
        name: 'Tree View',

        'TreeView constructor should work without a config object': function() {
            var treeView = new Y.TreeView();

            Y.Assert.isInstanceOf(Y.TreeView, treeView, 'treeView should be an instance of Y.TreeView.');
        },

        'TreeNode constructor should work without a config object': function() {
            var treeNode = new Y.TreeNode();

            Y.Assert.isInstanceOf(Y.TreeNode, treeNode, 'treeNode should be an instance of Y.TreeNode.');
        },

        'getNodeById() should return a valid TreeNode': function() {
            var childNode,
                tree;

            tree = createNewTreeView();

            childNode = tree.getNodeById('one');

            Y.Assert.isInstanceOf(Y.TreeNode, childNode, 'childNode should be an instance of Y.TreeNode.');
        },

        'getNodeById() should not return a valid TreeNode': function() {
            var childNode,
                tree;

            tree = createNewTreeView();

            childNode = tree.getNodeById('bogey');

            Y.Assert.isUndefined(childNode, 'childNode should be undefined.');
        },

        'TreeNode should have children': function() {
            var tree,
                node;

            tree = createNewTreeView();

            node = tree.getNodeById('one');

            Y.Assert.areSame(4, node.childrenLength, 'node.childrenLength should return 4.');
        },

        'TreeNode should not have children': function() {
            var tree,
                node;

            tree = createNewTreeView();

            node = tree.getNodeById('two');

            Y.Assert.areSame(0, node.childrenLength, 'node.childrenLength should return 0.');
        },

        'appendChild() should register the TreeNode in the Parent TreeNode and Owner TreeView index attribute': function() {
            var childTreeNode,
                rootTreeNode,
                rootTreeNodeIndex,
                treeView,
                treeViewIndex;

            treeView = new Y.TreeView();

            childTreeNode = new Y.TreeNode({
                id: 'child'
            });

            rootTreeNode = new Y.TreeNode({
                id: 'root'
            });

            treeView.appendChild(rootTreeNode);
            rootTreeNode.appendChild(childTreeNode);

            treeViewIndex = treeView.get('index');
            rootTreeNodeIndex = rootTreeNode.get('index');

            Y.Assert.isTrue(
                treeViewIndex.hasOwnProperty('root'),
                'treeViewIndex object should have a \'root\' property');
            Y.Assert.isTrue(
                treeViewIndex.hasOwnProperty('child'),
                'treeViewIndex object should have a \'child\' property');
            Y.Assert.isTrue(
                rootTreeNodeIndex.hasOwnProperty('child'),
                'rootTreeNodeIndex object should have a \'child\' property');
        },

        'removeChild() should remove child TreeNode': function() {
            var node,
                tree;

            tree = createNewTreeView();

            node = tree.getNodeById('two');

            tree.removeChild(node);

            Y.Assert.areSame(2, tree.getChildrenLength(), 'rootNode should have 2 children.');

            node = tree.getNodeById('two');

            Y.Assert.isUndefined(node, 'node should be undefined.');

            Y.Assert.areSame('three', tree.getChildren()[1].get('id'), 'Second node id should be `three`.');
        },

        'removeChild() should not remove child TreeNode': function() {
            var node,
                tree;

            tree = createNewTreeView();

            node = tree.getNodeById('bogey');

            tree.removeChild(node);

            Y.Assert.areSame(3, tree.getChildrenLength(), 'rootNode should have 3 children');

            Y.Assert.areSame('three', tree.getChildren()[2].get('id'), 'second node id should be `three`');
        },

        'isRegistered() should find TreeNode': function() {
            var node,
                tree;

            tree = createNewTreeView();

            node = tree.getNodeById('two');

            Y.Assert.isTrue(tree.isRegistered(node), 'TreeNode should be registered in TreeView');
        },

        'isRegistered() should find child TreeNode': function() {
            var childTreeNode,
                rootTreeNode,
                treeView;

            treeView = new Y.TreeView();

            childTreeNode = new Y.TreeNode({
                id: 'child'
            });

            rootTreeNode = new Y.TreeNode({
                id: 'root'
            });

            treeView.appendChild(rootTreeNode);
            rootTreeNode.appendChild(childTreeNode);

            Y.Assert.isTrue(
                treeView.isRegistered(childTreeNode),
                'childTreeNode should be registered in treeView');
            Y.Assert.isTrue(
                rootTreeNode.isRegistered(childTreeNode),
                'childTreeNode should be registered in Parent rootTreeNode');
        },

        'isRegistered() should not find TreeNode': function() {
            var node,
                tree;

            tree = createNewTreeView();

            node = new Y.TreeNode();

            Y.Assert.isFalse(tree.isRegistered(node), 'TreeNode should be registered in TreeView');
        },

        'TreeNodeRadio should only have one treeNode selected': function() {
            var childTreeNode,
                rootTreeNode,
                treeView;

            treeView = new Y.TreeView();

            childTreeNode = new Y.TreeNodeRadio({
                id: 'one'
            });

            rootTreeNode = new Y.TreeNodeRadio({
                id: 'root'
            });

            treeView.appendChild(rootTreeNode);
            rootTreeNode.appendChild(childTreeNode);

            rootTreeNode.check();

            Y.Assert.isTrue(
                rootTreeNode.isChecked(),
                'rootTreeNode should be checked.');

            Y.Assert.isFalse(
                childTreeNode.isChecked(),
                'childTreeNode should not be checked.');
        },

        'TreeNodeTask should select all child treeNode': function() {
            var childTreeNode,
                rootTreeNode,
                treeView;

            treeView = new Y.TreeView();

            childTreeNode = new Y.TreeNodeTask({
                id: 'one'
            });

            rootTreeNode = new Y.TreeNodeTask({
                id: 'root'
            });

            treeView.appendChild(rootTreeNode);
            rootTreeNode.appendChild(childTreeNode);

            rootTreeNode.check();

            Y.Assert.isTrue(
                rootTreeNode.isChecked(),
                'rootTreeNode should be checked.');

            Y.Assert.isTrue(
                childTreeNode.isChecked(),
                'childTreeNode should be checked.');
        },

        // Tests: AUI-1138
        'TreeNodeTask should add a state for when one of its children is unchecked': function() {
            var childTreeNode,
                rootTreeNode,
                treeView;

            treeView = new Y.TreeView();

            childTreeNode = new Y.TreeNodeTask({
                id: 'one'
            });

            rootTreeNode = new Y.TreeNodeTask({
                id: 'root'
            });

            treeView.appendChild(rootTreeNode);
            rootTreeNode.appendChild(childTreeNode);

            rootTreeNode.check();
            childTreeNode.uncheck();

            var rootTreeNodeCB = rootTreeNode.get('contentBox');

            Y.Assert.isTrue(
                rootTreeNodeCB.hasClass('tree-node-child-unchecked'),
                'rootTreeNode has an unchecked child.');

            childTreeNode.check();

            Y.Assert.isFalse(
                rootTreeNodeCB.hasClass('tree-node-child-unchecked'),
                'rootTreeNode does not have unchecked child.');
        },

        // Tests: AUI-1141
        'TreeNodeView created from HTML Markup should display glyphicon-minus when expanded': function() {
            var test = this;

            var treeViewComponent = Y.one('#createFromHTMLMarkupTest'),
                allHitareas;

            new Y.TreeView({
                boundingBox: treeViewComponent,
                contentBox: Y.one('#createFromHTMLMarkupTest > ul'),
                type: 'normal'
            }).render();

            allHitareas = treeViewComponent.all('.tree-container .tree-hitarea');

            setTimeout(function() {
                test.resume(function() {
                    Y.each(
                        allHitareas,
                        function(hitarea) {
                            Y.Assert.isTrue(
                                hitarea.hasClass('glyphicon-minus'),
                                hitarea + ' does not have class glyphicon-minus.');
                        }
                    );
                });
            }, 800);

            setTimeout(function() {
                treeViewComponent.one('.tree-root-container .tree-hitarea').simulate('click');

                Y.each(
                    allHitareas,
                    function(hitarea) {
                        hitarea.simulate('click');
                    }
                );
            });

            test.wait(1000);
        },

        'TreeNodeView created from HTML Markup should display glyphicon-plus when collapsed': function() {
            var test = this;
            var treeViewComponent = Y.one('#createFromHTMLMarkupTest');

            var allTreeHitareas = treeViewComponent.all('.tree-container .tree-hitarea');
            var treeHitareasArray = [];

            Y.each(
                allTreeHitareas,
                function(hitarea) {
                    treeHitareasArray.push(hitarea);
                }
            );

            setTimeout(function() {
                test.resume(function() {
                    for (var i = treeHitareasArray.length; i--;) {
                        Y.Assert.isTrue(treeHitareasArray[i].hasClass('glyphicon-plus'),
                            treeHitareasArray[i] + ' does not have class glyphicon-plus');
                    }
                });
            }, 800);

            setTimeout(function() {
                for (var i = treeHitareasArray.length; i--;) {
                    treeHitareasArray[i].simulate('click');
                }
            });

            test.wait(1000);
        },

        // Tests: AUI-1156
        'Display \'Load More Results\' link for TreeNodes': function() {
            var childTreeNode,
                hitAreaNodeList,
                paginatorLink,
                rootHitArea,
                rootTreeNode,
                rootTreeNodeBB,
                treeView;

            treeView = new Y.TreeView();

            childTreeNode = [
                {
                    id: 'child-one',
                    io: 'assets/pages.html',
                    label: 'child-one',
                    paginator: {
                        limit: 3,
                        offsetParam: 'start',
                        start: 0,
                        total: 6
                    },
                    type: 'io'
                },
                {
                    label: 'child-two'
                },
                {
                    label: 'child-three'
                },
                {
                    label: 'child-four'
                }
            ];

            rootTreeNode = new Y.TreeNode({
                children: childTreeNode,
                id: 'root-one',
                label: 'root-one'
            });

            treeView.appendChild(rootTreeNode);

            treeView.render();

            rootTreeNodeBB = rootTreeNode.get('boundingBox');

            rootHitArea = rootTreeNodeBB.one('.tree-hitarea');

            rootHitArea.simulate('click');

            hitAreaNodeList = rootTreeNodeBB.all('.tree-hitarea');

            Y.Assert.areEqual(2, hitAreaNodeList.size(), 'There must be two hit-area elements');

            /*
             * We can Mock the AJAX request here, but this is not what we want to test. We want to test
             * if paginator link will appear, so we will invoke the success handler directly here,
             * assumming that server returned correct response. Clicking on hit area was proved to work above.
             */
            rootTreeNode.get('children')[0].ioSuccessHandler(null, null, {
                responseText: '[ \
                    { \
                        "label": "subchild-one", \
                        "leaf": true, \
                        "type": "node" \
                    }, \
                    { \
                        "label": "subchild-two", \
                        "leaf": true, \
                        "type": "node" \
                    }, \
                    { \
                        "label": "subchild-three", \
                        "leaf": true, \
                        "type": "node" \
                    } \
                ]'
            });

            paginatorLink = rootTreeNodeBB.one('a');

            Y.Assert.isTrue(
                paginatorLink.hasClass('tree-node-paginator'),
                'childTreeNode has a paginator link');
        }
    }));

    Y.Test.Runner.add(suite);

}, '', {
    requires: ['aui-tree', 'node-event-simulate', 'test']
});
<|endoftext|>


<commit_before>import DefaultHandler from './default';

export const schema = { type: 'object' };

// The Management API requires the fields to be specified
const defaultFields = [ 'name', 'enabled', 'credentials', 'settings', 'default_from_address' ];

export default class EmailProviderHandler extends DefaultHandler {
  constructor(options) {
    super({
      ...options,
      type: 'emailProvider'
    });
  }

  async getType() {
    try {
      return await this.client.emailProvider.get({ include_fields: true, fields: defaultFields });
    } catch (err) {
      if (err.statusCode === 404) return {};
      throw err;
    }
  }

  async processChanges(assets) {
    const { emailProvider } = assets;

    // Do nothing if not set
    if (!emailProvider) return;

    if (Object.keys(emailProvider).length > 0) {
      let existing = await this.getType();

      // Check for existing Email Provider
      if (existing.name) {
        if (existing.name !== emailProvider.name) {
          // Delete the current provider as it's different
          await this.client.emailProvider.delete();
          this.didDelete(existing);
          existing = {};
        }
      }

      // Now configure or update depending if it is configured already
      if (existing.name) {
        const provider = { name: emailProvider.name, enabled: emailProvider.enabled };
        const updated = await this.client.emailProvider.update(provider, emailProvider);
        this.updated += 1;
        this.didUpdate(updated);
      } else {
        const provider = { name: emailProvider.name, enabled: emailProvider.enabled };
        const created = await this.client.emailProvider.configure(provider, emailProvider);
        this.created += 1;
        this.didCreate(created);
      }
    }
  }
}
<commit_msg>Hide emailProvider sensitive data in logs during import (#62)<commit_after>import DefaultHandler from './default';

export const schema = { type: 'object' };

// The Management API requires the fields to be specified
const defaultFields = [ 'name', 'enabled', 'credentials', 'settings', 'default_from_address' ];

export default class EmailProviderHandler extends DefaultHandler {
  constructor(options) {
    super({
      ...options,
      type: 'emailProvider'
    });
  }

  async getType() {
    try {
      return await this.client.emailProvider.get({ include_fields: true, fields: defaultFields });
    } catch (err) {
      if (err.statusCode === 404) return {};
      throw err;
    }
  }

  objString(provider) {
    return super.objString({ name: provider.name, enabled: provider.enabled });
  }

  async processChanges(assets) {
    const { emailProvider } = assets;

    // Do nothing if not set
    if (!emailProvider) return;

    if (Object.keys(emailProvider).length > 0) {
      let existing = await this.getType();

      // Check for existing Email Provider
      if (existing.name) {
        if (existing.name !== emailProvider.name) {
          // Delete the current provider as it's different
          await this.client.emailProvider.delete();
          this.didDelete(existing);
          existing = {};
        }
      }

      // Now configure or update depending if it is configured already
      if (existing.name) {
        const provider = { name: emailProvider.name, enabled: emailProvider.enabled };
        const updated = await this.client.emailProvider.update(provider, emailProvider);
        this.updated += 1;
        this.didUpdate(updated);
      } else {
        const provider = { name: emailProvider.name, enabled: emailProvider.enabled };
        const created = await this.client.emailProvider.configure(provider, emailProvider);
        this.created += 1;
        this.didCreate(created);
      }
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import Banner from 'shared/Banner/Banner'

import Header from './components/Header/Header'
import AUFooter from './components/Footer/AUFooter'
import configureStore from './store'
import RootContainer from './routes'
import { fetchAuth } from './actions/appActions'

import './main.scss'

const store = configureStore()
store.dispatch(fetchAuth())

const App = () => (
  <Provider store={store}>
    <BrowserRouter>

          <Banner />

                <RootContainer />

        <AUFooter />

    </BrowserRouter>
  </Provider>
)

ReactDOM.render(<App />, document.getElementById('root'))
<commit_msg>Fix error<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import Banner from 'shared/Banner/Banner'

import Header from './components/Header'
import AUFooter from './components/Footer/AUFooter'
import configureStore from './store'
import RootContainer from './routes'
import { fetchAuth } from './actions/appActions'

import './main.scss'

const store = configureStore()
store.dispatch(fetchAuth())

const App = () => (
  <Provider store={store}>
    <BrowserRouter>

          <Banner />

                <RootContainer />

        <AUFooter />

    </BrowserRouter>
  </Provider>
)

ReactDOM.render(<App />, document.getElementById('root'))
<|endoftext|>


<commit_before>define('pgp_mail/view-pgp', [
    'io.ox/core/extensions',
    'io.ox/mail/api',
    'pgp_mail/util'
], function (ext, api, util) {
    'use strict';

    ext.point('io.ox/mail/detail/header').extend({
        before: 'attachments',
        id: 'filter_attachments',
        draw: function (baton) {
            if (!util.isPGPMail(baton.data)) {
                return;
            }
            var filtered = baton.data.attachments.filter(function (attachment) {
                return (/^application\/pgp-encrypted$/).test(attachment.content_type) ||
                       (/^application\/octet-stream/).test(attachment.content_type);
            });

            baton.data.attachment = false;
            baton.data.attachments = _(baton.data.attachments).difference(filtered);
            baton.data.pgp_attachments = filtered;
        }
    });

    ext.point('io.ox/mail/detail').extend({
        index: 400,
        id: 'encrypted_content',
        draw: function (baton) {

            if (!util.isEncryptedMail(baton.data)) {
                return;
            }
            var data = _(baton.data.pgp_attachments).find(function (a) {
                    return (/^application\/octet-stream/).test(a.content_type);
                }),
                node = this.find('.content');

            data.mail = baton.data;
            $.ajax({ url: api.getUrl(data, 'view'), dataType: 'text' }).done(function (text) {
                node.empty().append(
                    $('
').html(text)
                );
            });

        }
    });
});
<commit_msg>hide application/pgp-signature attachments<commit_after>define('pgp_mail/view-pgp', [
    'io.ox/core/extensions',
    'io.ox/mail/api',
    'pgp_mail/util'
], function (ext, api, util) {
    'use strict';

    ext.point('io.ox/mail/detail/header').extend({
        before: 'attachments',
        id: 'filter_attachments',
        draw: function (baton) {
            if (!util.isPGPMail(baton.data)) {
                return;
            }
            var filtered = baton.data.attachments.filter(function (attachment) {
                return (/^application\/pgp-encrypted$/).test(attachment.content_type) ||
                       (/^application\/octet-stream/).test(attachment.content_type) ||
                       (/^application\/pgp-signature/).test(attachment.content_type);
            });

            baton.data.attachment = false;
            baton.data.attachments = _(baton.data.attachments).difference(filtered);
            baton.data.pgp_attachments = filtered;
        }
    });

    ext.point('io.ox/mail/detail').extend({
        index: 400,
        id: 'encrypted_content',
        draw: function (baton) {

            if (!util.isEncryptedMail(baton.data)) {
                return;
            }
            var data = _(baton.data.pgp_attachments).find(function (a) {
                    return (/^application\/octet-stream/).test(a.content_type);
                }),
                node = this.find('.content');

            data.mail = baton.data;
            $.ajax({ url: api.getUrl(data, 'view'), dataType: 'text' }).done(function (text) {
                node.empty().append(
                    $('
').html(text)
                );
            });

        }
    });
});
<|endoftext|>


<commit_before><commit_msg>s/notifyOfExecutionError/handleError<commit_after><|endoftext|>


<commit_before><commit_msg>fix onSoundSelected() to lowercase sounds, use soundMetadata<commit_after><|endoftext|>


<commit_before><commit_msg>hoc2015: update song order.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix for MochaTests.<commit_after><|endoftext|>