<commit_before>//======================================
// Pak/DNT related extractor/compiler
//======================================
// This file requires the following ENV vars to be set in order for it to work:
// - DN_LEVEL_CAP - The level cap
// - DN_OUT_DIR - The directory where the JSON files will be written to
// - DN_UISTRING_PATH - The location of the uistring.xml file
//======================================

var JSystem = Java.type("java.lang.System")
var JString = Java.type("java.lang.String")
var JInteger = Java.type("java.lang.Integer")
var JFile = Java.type("java.io.File")
var JFileOutputStream = Java.type("java.io.FileOutputStream")
var JDocumentBuilderFactory = Java.type("javax.xml.parsers.DocumentBuilderFactory")

//======================================
// Pak object filter
//======================================
var regExps = {
    dnt: /\\(skilltable_character.*|skillleveltable_character.*|skilltreetable|jobtable|playerleveltable|itemtable|weapontable)\.dnt$/i,
    jobicon: /^\\resource\\ui\\mainbar\\jobicon.*/i,
    skillicon: /^\\resource\\ui\\mainbar\\skillicon.*/i,
    uistring: /^\\resource\\uistring\\uistring.xml$/i,
    version: /version.cfg$/i,
    skilltree: /^\\resource\\ui\\skill\\.*\.dds/i,
}

var filter = function(node) {
    for (i in regExps) {
        if (regExps[i].test(node.path) && node.size != 0) {
            return true
        }
    }

    return false
}

//======================================
// DNT compiling
//======================================
var LEVEL_CAP
var JSON_OUTPUT_DIR
var UISTRING_PATH
var skills = []
var skillLevels = []
var jobs = []
var playerLevels = []
var skillTree = []
var items = []
var weapons = []
var accumulate = function(entries, cols, file) {
    var name = file.getName()
    if (name.startsWith("skilltable")) {
        skills = skills.concat(entries)
    } else if (name.startsWith("skilltreetable")) {
        skillTree = skillTree.concat(entries)
    } else if (name.startsWith("skillleveltable")) {
        skillLevels = skillLevels.concat(entries);
    } else if (name.startsWith("jobtable")) {
        jobs = jobs.concat(entries)
    } else if (name.startsWith("playerleveltable")) {
        playerLevels = playerLevels.concat(entries)
    } else if (name.startsWith("itemtable")) {
        items = items.concat(entries)
    } else if (name.startsWith("weapontable")) {
        weapons = weapons.concat(entries)
    }
}

var compile = function() {
    LEVEL_CAP = parseInt(JSystem.getenv("DN_LEVEL_CAP"))
    JSON_OUTPUT_DIR = JSystem.getenv("DN_OUT_DIR")
    UISTRING_PATH = JSystem.getenv("DN_UISTRING_PATH")

    //================================================
    // Setup the UI String
    //================================================
    var uistring = []
    var uistringFile = new JFile(UISTRING_PATH)
    var document = JDocumentBuilderFactory.newInstance().newDocumentBuilder().parse(uistringFile)
    document.getDocumentElement().normalize()
    var nodes = document.getElementsByTagName("message")
    for (var i = 0; i < nodes.getLength(); i++) {
        var e = nodes.item(i)
        uistring[parseInt(e.getAttribute("mid"))] = e.getFirstChild().getData()
    }

    // the backend db
    var db = {Jobs: {}, Lookup: {}}

    //================================================
    // generate the job info, skill tree, and skills
    //================================================
    jobs.filter(function(job) job.Service).forEach(function(job) {
        // fix a few things
        job.MaxSPJob1 = Number(job.MaxSPJob1.toFixed(3))
        job.EnglishName = job.EnglishName.toLowerCase()

        // init the db skilltree for this job
        db.Jobs[job.EnglishName] = {SkillTree: [], LookupSet: []}

        var json = { EnglishName: job.EnglishName }

        // primary class
        if (job.JobNumber == 2) {
            var job1 = jobs.filter(function(j) j.PrimaryID == job.ParentJob)[0]
            var job0 = jobs.filter(function(j) j.PrimaryID == job1.ParentJob)[0]
            db.Jobs[job.EnglishName].Line = [
                job0.EnglishName.toLowerCase(),
                job1.EnglishName.toLowerCase(),
                job.EnglishName,
            ]

        }

        // setup skill table
        jobSkills = skills.filter(function(s) s.NeedJob == job.PrimaryID)
        jobSkillsID = jobSkills.map(function(s) s.PrimaryID)
        jobSkillTree = skillTree.filter(function(t) jobSkillsID.indexOf(t.SkillTableID) > -1)
        jobSkillTreeIDs = jobSkillTree.map(function(t) t.SkillTableID)
        jobSkillTree.filter(function(t) jobSkillsID.indexOf(t.SkillTableID) > -1).forEach(function(t) {
            db.Jobs[job.EnglishName].SkillTree[t.TreeSlotIndex] = t.SkillTableID

            // setup initial Skills with job sp req
            json[t.SkillTableID] = {
                NeedSP: [t.NeedBasicSP1, t.NeedFirstSP1, t.NeedSecondSP1]
            }

            var skill = json[t.SkillTableID]

            // setup the parent job hash
            if (t.ParentSkillID1 > 0) {
                skill.ParentSkills = {}
                skill.ParentSkills[t.ParentSkillID1] = t.NeedParentSkillLevel1
            }

            if (t.ParentSkillID2 > 0) {
                skill.ParentSkills[t.ParentSkillID2] = t.NeedParentSkillLevel2
            }

            if (t.ParentSkillID3 > 0) {
                skill.ParentSkills[t.ParentSkillID3] = t.NeedParentSkillLevel3
            }
        })

        // setup skill levels
        jobSkills.filter(function(s) jobSkillTreeIDs.indexOf(s.PrimaryID) > -1).forEach(function(s) {
            var levels = skillLevels.filter(function(l) l.SkillIndex == s.PrimaryID)
            var skill = json[s.PrimaryID]
            skill.NameID = s.NameID
            skill.MaxLevel = s.MaxLevel
            skill.SPMaxLevel = s.SPMaxLevel
            skill.SkillType = s.SkillType
            skill.Levels = {}

            // sprite stuff
            skill.Sprite = JString.format("%1$02d", new JInteger(parseInt(s.IconImageIndex / 200) + 1))
            skill.IconRow = parseInt((s.IconImageIndex % 200) / 10)
            skill.IconCol = s.IconImageIndex % 10

            db.Lookup[s.NameID] = uistring[s.NameID]
            db.Jobs[job.EnglishName].LookupSet.push(s.NameID)

            // BaseSkillID is when two skills can't be set at same time
            if (s.BaseSkillID > 0) {
                skill.BaseSkillID = s.BaseSkillID
            }

            // weapons can be uncommon + order doesn't matter
            if (s.NeedWeaponType1 > -1 || s.NeedWeaponType2 > -1) {
                skill.NeedWeaponType = []
                if (s.NeedWeaponType1 > -1) {
                    skill.NeedWeaponType.push(s.NeedWeaponType1)
                }

                if (s.NeedWeaponType2 > -1) {
                    skill.NeedWeaponType.push(s.NeedWeaponType2)
                }
            }

            // PvE
            levels.filter(function(l) l.SkillLevel > 0 && l.SkillLevel <= s.MaxLevel).forEach(function(l) {
                if (! skill.Levels[l.SkillLevel]) {
                    skill.Levels[l.SkillLevel] = {}
                }

                level = skill.Levels[l.SkillLevel]
                var applyType = {
                    DelayTime: l.DelayTime, // cooldown
                    DecreaseSP: l.DecreaseSP, // really is MP...
                    SkillExplanationID: l.SkillExplanationID,
                    SkillExplanationIDParam: l.SkillExplanationIDParam,
                }

                if (! level.ApplyType)  {
                    level.ApplyType = []
                }

                if (l.ApplyType == 0) { // PvE
                    level.LevelLimit = l.LevelLimit // required level
                    level.SkillPoint = l.NeedSkillPoint
                    level.ApplyType[0] = applyType
                } else { // PvP
                    level.ApplyType[1] = applyType
                }

                // add uistring
                db.Lookup[l.SkillExplanationID] = uistring[l.SkillExplanationID]
                if (db.Jobs[job.EnglishName].LookupSet.indexOf(l.SkillExplanationID) == -1) {
                    db.Jobs[job.EnglishName].LookupSet.push(l.SkillExplanationID)
                }
                if (l.SkillExplanationIDParam) {
                    l.SkillExplanationIDParam.split(",").forEach(function(param) {
                        if (param.startsWith("{") && param.endsWith("}")) {
                            var uistringID = parseInt(param.substring(1, param.length - 1))
                            if (db.Jobs[job.EnglishName].LookupSet.indexOf(uistringID) == -1) {
                                db.Jobs[job.EnglishName].LookupSet.push(uistringID)
                            }
                            db.Lookup[uistringID] = uistring[uistringID]
                        }
                    })
                }
            })
        })

        write(job.EnglishName, json)
        write("uistring_" + job.EnglishName, uistringSubset)
    })

    //================================================
    // get the map of all jobs
    //================================================
    jobs.filter(function(job) job.Service).forEach(function(job) {
        db.Jobs[job.EnglishName].JobNumber = job.JobNumber
        db.Jobs[job.EnglishName].JobName = uistring[job.JobName]
        db.Jobs[job.EnglishName].IconRow = parseInt(job.JobIcon / 9)
        db.Jobs[job.EnglishName].IconCol = job.JobIcon % 9

        if (job.JobNumber == 2) { // can reassign multiple times, not a big deal
            db.SP = [job.MaxSPJob0, job.MaxSPJob1, job.MaxSPJob2]
        }
    })

    //================================================
    // get the player levels
    //================================================
    db.Levels = playerLevels.filter(function(p) p.PrimaryID <= LEVEL_CAP).map(function(p) p.SkillPoint)

    //================================================
    // get the weapons
    //================================================
    var weaponTypeNameIDs = {}
    items.filter(function(i) i.NameID == 1000006853 && i.LevelLimit == 1)
        .reduce(function(p,c) {
            var find = p.filter(function(_p) _p.NameIDParam == c.NameIDParam)
            if (find.length == 0) {
                p.push(c)
            }
            return p
        }, [])
        .forEach(function(i) {
            var weapon = weapons.filter(function(w) w.PrimaryID == i.PrimaryID)[0]
            weaponTypeNameIDs[weapon.EquipType] = uistring[i.NameIDParam.substring(1, i.NameIDParam.length - 1)]
        })

    db.Weapons = weaponTypeNameIDs
    write("db", db)
}

var write = function(path, json) {
    var out = new JFileOutputStream(new JFile(JSON_OUTPUT_DIR, path + ".json"))
    out.write(JSON.stringify(json).getBytes("UTF-8"))
    out.close()
}<commit_msg>Needed to remove the creation uistring files<commit_after>//======================================
// Pak/DNT related extractor/compiler
//======================================
// This file requires the following ENV vars to be set in order for it to work:
// - DN_LEVEL_CAP - The level cap
// - DN_OUT_DIR - The directory where the JSON files will be written to
// - DN_UISTRING_PATH - The location of the uistring.xml file
//======================================

var JSystem = Java.type("java.lang.System")
var JString = Java.type("java.lang.String")
var JInteger = Java.type("java.lang.Integer")
var JFile = Java.type("java.io.File")
var JFileOutputStream = Java.type("java.io.FileOutputStream")
var JDocumentBuilderFactory = Java.type("javax.xml.parsers.DocumentBuilderFactory")

//======================================
// Pak object filter
//======================================
var regExps = {
    dnt: /\\(skilltable_character.*|skillleveltable_character.*|skilltreetable|jobtable|playerleveltable|itemtable|weapontable)\.dnt$/i,
    jobicon: /^\\resource\\ui\\mainbar\\jobicon.*/i,
    skillicon: /^\\resource\\ui\\mainbar\\skillicon.*/i,
    uistring: /^\\resource\\uistring\\uistring.xml$/i,
    version: /version.cfg$/i,
    skilltree: /^\\resource\\ui\\skill\\.*\.dds/i,
}

var filter = function(node) {
    for (i in regExps) {
        if (regExps[i].test(node.path) && node.size != 0) {
            return true
        }
    }

    return false
}

//======================================
// DNT compiling
//======================================
var LEVEL_CAP
var JSON_OUTPUT_DIR
var UISTRING_PATH
var skills = []
var skillLevels = []
var jobs = []
var playerLevels = []
var skillTree = []
var items = []
var weapons = []
var accumulate = function(entries, cols, file) {
    var name = file.getName()
    if (name.startsWith("skilltable")) {
        skills = skills.concat(entries)
    } else if (name.startsWith("skilltreetable")) {
        skillTree = skillTree.concat(entries)
    } else if (name.startsWith("skillleveltable")) {
        skillLevels = skillLevels.concat(entries);
    } else if (name.startsWith("jobtable")) {
        jobs = jobs.concat(entries)
    } else if (name.startsWith("playerleveltable")) {
        playerLevels = playerLevels.concat(entries)
    } else if (name.startsWith("itemtable")) {
        items = items.concat(entries)
    } else if (name.startsWith("weapontable")) {
        weapons = weapons.concat(entries)
    }
}

var compile = function() {
    LEVEL_CAP = parseInt(JSystem.getenv("DN_LEVEL_CAP"))
    JSON_OUTPUT_DIR = JSystem.getenv("DN_OUT_DIR")
    UISTRING_PATH = JSystem.getenv("DN_UISTRING_PATH")

    //================================================
    // Setup the UI String
    //================================================
    var uistring = []
    var uistringFile = new JFile(UISTRING_PATH)
    var document = JDocumentBuilderFactory.newInstance().newDocumentBuilder().parse(uistringFile)
    document.getDocumentElement().normalize()
    var nodes = document.getElementsByTagName("message")
    for (var i = 0; i < nodes.getLength(); i++) {
        var e = nodes.item(i)
        uistring[parseInt(e.getAttribute("mid"))] = e.getFirstChild().getData()
    }

    // the backend db
    var db = {Jobs: {}, Lookup: {}}

    //================================================
    // generate the job info, skill tree, and skills
    //================================================
    jobs.filter(function(job) job.Service).forEach(function(job) {
        // fix a few things
        job.MaxSPJob1 = Number(job.MaxSPJob1.toFixed(3))
        job.EnglishName = job.EnglishName.toLowerCase()

        // init the db skilltree for this job
        db.Jobs[job.EnglishName] = {SkillTree: [], LookupSet: []}

        var json = { EnglishName: job.EnglishName }

        // primary class
        if (job.JobNumber == 2) {
            var job1 = jobs.filter(function(j) j.PrimaryID == job.ParentJob)[0]
            var job0 = jobs.filter(function(j) j.PrimaryID == job1.ParentJob)[0]
            db.Jobs[job.EnglishName].Line = [
                job0.EnglishName.toLowerCase(),
                job1.EnglishName.toLowerCase(),
                job.EnglishName,
            ]

        }

        // setup skill table
        jobSkills = skills.filter(function(s) s.NeedJob == job.PrimaryID)
        jobSkillsID = jobSkills.map(function(s) s.PrimaryID)
        jobSkillTree = skillTree.filter(function(t) jobSkillsID.indexOf(t.SkillTableID) > -1)
        jobSkillTreeIDs = jobSkillTree.map(function(t) t.SkillTableID)
        jobSkillTree.filter(function(t) jobSkillsID.indexOf(t.SkillTableID) > -1).forEach(function(t) {
            db.Jobs[job.EnglishName].SkillTree[t.TreeSlotIndex] = t.SkillTableID

            // setup initial Skills with job sp req
            json[t.SkillTableID] = {
                NeedSP: [t.NeedBasicSP1, t.NeedFirstSP1, t.NeedSecondSP1]
            }

            var skill = json[t.SkillTableID]

            // setup the parent job hash
            if (t.ParentSkillID1 > 0) {
                skill.ParentSkills = {}
                skill.ParentSkills[t.ParentSkillID1] = t.NeedParentSkillLevel1
            }

            if (t.ParentSkillID2 > 0) {
                skill.ParentSkills[t.ParentSkillID2] = t.NeedParentSkillLevel2
            }

            if (t.ParentSkillID3 > 0) {
                skill.ParentSkills[t.ParentSkillID3] = t.NeedParentSkillLevel3
            }
        })

        // setup skill levels
        jobSkills.filter(function(s) jobSkillTreeIDs.indexOf(s.PrimaryID) > -1).forEach(function(s) {
            var levels = skillLevels.filter(function(l) l.SkillIndex == s.PrimaryID)
            var skill = json[s.PrimaryID]
            skill.NameID = s.NameID
            skill.MaxLevel = s.MaxLevel
            skill.SPMaxLevel = s.SPMaxLevel
            skill.SkillType = s.SkillType
            skill.Levels = {}

            // sprite stuff
            skill.Sprite = JString.format("%1$02d", new JInteger(parseInt(s.IconImageIndex / 200) + 1))
            skill.IconRow = parseInt((s.IconImageIndex % 200) / 10)
            skill.IconCol = s.IconImageIndex % 10

            db.Lookup[s.NameID] = uistring[s.NameID]
            db.Jobs[job.EnglishName].LookupSet.push(s.NameID)

            // BaseSkillID is when two skills can't be set at same time
            if (s.BaseSkillID > 0) {
                skill.BaseSkillID = s.BaseSkillID
            }

            // weapons can be uncommon + order doesn't matter
            if (s.NeedWeaponType1 > -1 || s.NeedWeaponType2 > -1) {
                skill.NeedWeaponType = []
                if (s.NeedWeaponType1 > -1) {
                    skill.NeedWeaponType.push(s.NeedWeaponType1)
                }

                if (s.NeedWeaponType2 > -1) {
                    skill.NeedWeaponType.push(s.NeedWeaponType2)
                }
            }

            // PvE
            levels.filter(function(l) l.SkillLevel > 0 && l.SkillLevel <= s.MaxLevel).forEach(function(l) {
                if (! skill.Levels[l.SkillLevel]) {
                    skill.Levels[l.SkillLevel] = {}
                }

                level = skill.Levels[l.SkillLevel]
                var applyType = {
                    DelayTime: l.DelayTime, // cooldown
                    DecreaseSP: l.DecreaseSP, // really is MP...
                    SkillExplanationID: l.SkillExplanationID,
                    SkillExplanationIDParam: l.SkillExplanationIDParam,
                }

                if (! level.ApplyType)  {
                    level.ApplyType = []
                }

                if (l.ApplyType == 0) { // PvE
                    level.LevelLimit = l.LevelLimit // required level
                    level.SkillPoint = l.NeedSkillPoint
                    level.ApplyType[0] = applyType
                } else { // PvP
                    level.ApplyType[1] = applyType
                }

                // add uistring
                db.Lookup[l.SkillExplanationID] = uistring[l.SkillExplanationID]
                if (db.Jobs[job.EnglishName].LookupSet.indexOf(l.SkillExplanationID) == -1) {
                    db.Jobs[job.EnglishName].LookupSet.push(l.SkillExplanationID)
                }
                if (l.SkillExplanationIDParam) {
                    l.SkillExplanationIDParam.split(",").forEach(function(param) {
                        if (param.startsWith("{") && param.endsWith("}")) {
                            var uistringID = parseInt(param.substring(1, param.length - 1))
                            if (db.Jobs[job.EnglishName].LookupSet.indexOf(uistringID) == -1) {
                                db.Jobs[job.EnglishName].LookupSet.push(uistringID)
                            }
                            db.Lookup[uistringID] = uistring[uistringID]
                        }
                    })
                }
            })
        })

        write(job.EnglishName, json)
    })

    //================================================
    // get the map of all jobs
    //================================================
    jobs.filter(function(job) job.Service).forEach(function(job) {
        db.Jobs[job.EnglishName].JobNumber = job.JobNumber
        db.Jobs[job.EnglishName].JobName = uistring[job.JobName]
        db.Jobs[job.EnglishName].IconRow = parseInt(job.JobIcon / 9)
        db.Jobs[job.EnglishName].IconCol = job.JobIcon % 9

        if (job.JobNumber == 2) { // can reassign multiple times, not a big deal
            db.SP = [job.MaxSPJob0, job.MaxSPJob1, job.MaxSPJob2]
        }
    })

    //================================================
    // get the player levels
    //================================================
    db.Levels = playerLevels.filter(function(p) p.PrimaryID <= LEVEL_CAP).map(function(p) p.SkillPoint)

    //================================================
    // get the weapons
    //================================================
    var weaponTypeNameIDs = {}
    items.filter(function(i) i.NameID == 1000006853 && i.LevelLimit == 1)
        .reduce(function(p,c) {
            var find = p.filter(function(_p) _p.NameIDParam == c.NameIDParam)
            if (find.length == 0) {
                p.push(c)
            }
            return p
        }, [])
        .forEach(function(i) {
            var weapon = weapons.filter(function(w) w.PrimaryID == i.PrimaryID)[0]
            weaponTypeNameIDs[weapon.EquipType] = uistring[i.NameIDParam.substring(1, i.NameIDParam.length - 1)]
        })

    db.Weapons = weaponTypeNameIDs
    write("db", db)
}

var write = function(path, json) {
    var out = new JFileOutputStream(new JFile(JSON_OUTPUT_DIR, path + ".json"))
    out.write(JSON.stringify(json).getBytes("UTF-8"))
    out.close()
}<|endoftext|>


<commit_before>var $ = {}
  , concat = Array.prototype.concat;

// multi-parameter versions for the associative operators
$.plus2 = (x, y) => x + y;
$.plus3 = (x, y, z) => x + y + z;
$.plus4 = (x, y, z, w) => x + y + z + w;
$.times2 = (x, y) => x * y;
$.times3 = (x, y, z) => x * y * z;
$.times4 = (x, y, z, w) => x * y * z * w;
$.and2 = (x, y) => x && y;
$.and3 = (x, y, z) => x && y && z;
$.and4 = (x, y, z, w) => x && y && z && w;
$.or2 = (x, y) => x || y;
$.or3 = (x, y, z) => x || y || z;
$.or4 = (x, y, z, w) => x || y || z || w;

// same, but on arrays
$.append2 = (xs, ys) => xs.concat(ys);
$.append3 = (xs, ys, zs) => xs.concat(ys, zs);
$.append4 = (xs, ys, zs, ws) => xs.concat(ys, zs, ws);
$.prepend2 = (xs, ys) => ys.concat(xs);

$.sum = (xs) => xs.reduce((acc, el) => acc + el, 0);
$.product = (xs) => xs.reduce((acc, el) => acc * el, 1);
$.and = (xs) => xs.reduce((acc, el) => acc && el, true);
$.or = (xs) => xs.reduce((acc, el) => acc || el, false);

$.flatten = (xs) => concat.apply([], xs);

// non-associative operators only get the 2 argument version
$.minus2 = (x, y) => x - y;
$.divide2 = (x, y) => x / y;
$.div2 = (x, y) => Math.floor(x / y);
$.mod2 = (x, y) => x % y;
$.pow2 = Math.pow;

$.log2 = (x, y) => Math.log(x) / Math.log(y);
$.eq2 = (x, y) => x === y;
$.neq2 = (x, y) => x !== y;
$.gt2 = (x, y) => x > y;
$.lt2 = (x, y) => x < y;
$.gte2 = (x, y) => x >= y;
$.lte2 = (x, y) => x <= y;

// curried versions
$.plus = (y) => (x) => x + y;
$.minus = (y) => (x) => x - y;
$.times = (y) => (x) => x * y;
$.divide = (y) => (x) => x / y;
$.div = (y) => (x) => Math.floor(x / y);
$.mod = (y) => (x) => x % y;
$.pow = (y) => (x) => Math.pow(x, y);
$.log = (y) => (x) => Math.log(x) / Math.log(y);
$.append = (ys) => (xs) => xs.concat(ys);
$.prepend = (ys) => (xs) => ys.concat(xs);
$.gt = (y) => (x) => x > y;
$.lt = (y) => (x) => x < y;
$.eq = (y) => (x) => x === y;
$.neq = (y) => (x) => x !== y;
$.gte = (y) => (x) => x >= y;
$.lte = (y) => (x) => x <= y;

module.exports = $;
<commit_msg>can kill concat to make this module super sleek<commit_after>var $ = {};

// multi-parameter versions for the associative operators
$.plus2 = (x, y) => x + y;
$.plus3 = (x, y, z) => x + y + z;
$.plus4 = (x, y, z, w) => x + y + z + w;
$.times2 = (x, y) => x * y;
$.times3 = (x, y, z) => x * y * z;
$.times4 = (x, y, z, w) => x * y * z * w;
$.and2 = (x, y) => x && y;
$.and3 = (x, y, z) => x && y && z;
$.and4 = (x, y, z, w) => x && y && z && w;
$.or2 = (x, y) => x || y;
$.or3 = (x, y, z) => x || y || z;
$.or4 = (x, y, z, w) => x || y || z || w;

// same, but on arrays
$.append2 = (xs, ys) => xs.concat(ys);
$.append3 = (xs, ys, zs) => xs.concat(ys, zs);
$.append4 = (xs, ys, zs, ws) => xs.concat(ys, zs, ws);
$.prepend2 = (xs, ys) => ys.concat(xs);

$.sum = (xs) => xs.reduce((acc, el) => acc + el, 0);
$.product = (xs) => xs.reduce((acc, el) => acc * el, 1);
$.and = (xs) => xs.reduce((acc, el) => acc && el, true);
$.or = (xs) => xs.reduce((acc, el) => acc || el, false);
$.flatten = (xs) => Array.prototype.concat.apply([], xs);

// non-associative operators only get the 2 argument version
$.minus2 = (x, y) => x - y;
$.divide2 = (x, y) => x / y;
$.div2 = (x, y) => Math.floor(x / y);
$.mod2 = (x, y) => x % y;
$.pow2 = Math.pow;
$.log2 = (x, y) => Math.log(x) / Math.log(y);
$.eq2 = (x, y) => x === y;
$.neq2 = (x, y) => x !== y;
$.gt2 = (x, y) => x > y;
$.lt2 = (x, y) => x < y;
$.gte2 = (x, y) => x >= y;
$.lte2 = (x, y) => x <= y;

// curried versions
$.plus = (y) => (x) => x + y;
$.minus = (y) => (x) => x - y;
$.times = (y) => (x) => x * y;
$.divide = (y) => (x) => x / y;
$.div = (y) => (x) => Math.floor(x / y);
$.mod = (y) => (x) => x % y;
$.pow = (y) => (x) => Math.pow(x, y);
$.log = (y) => (x) => Math.log(x) / Math.log(y);
$.append = (ys) => (xs) => xs.concat(ys);
$.prepend = (ys) => (xs) => ys.concat(xs);
$.gt = (y) => (x) => x > y;
$.lt = (y) => (x) => x < y;
$.eq = (y) => (x) => x === y;
$.neq = (y) => (x) => x !== y;
$.gte = (y) => (x) => x >= y;
$.lte = (y) => (x) => x <= y;

module.exports = $;
<|endoftext|>


<commit_before>//Setup module to run Behave tests
require('behave').andSetup(this);
var Alloy = require("alloy");

describe('\n \nThe index screen', function() {
	var index = Alloy.createController('index');
	it('should create a controller', function() {
		expect(index).notToBe(null);
	});
	it('should create a table', function() {
		expect(index.getView("tbl")).notToBe(undefined);
	});
	describe('\nThe TableView \'tbl\' of the index screen', function() {
		it('should have a header with a button called \'Add\'', function() {
			expect(index.getView("headerView")).notToBe(undefined);
			expect(index.addSite.title).toBe("Add");
		});
	});
});

describe('\n \nThe modal with siteID 1', function () {
	var indexModal = Alloy.createController('siteSurveyModal', {siteID:1});
	it('should exist when created', function() {
		expect(indexModal).notToBe(undefined);
	});
	/*
	it('should be visible', function() {
		expect(indexModal.visible).toBe(true);
	});
	*/
	it('should have a park name of \'Kakwa Park\'', function() {
		expect(indexModal.parkName.text).toBe('Kakwa Park');
	});
	it('should have a year of 2014', function() {
		expect(indexModal.siteYear.text).toBe('2014');
	});
	/*
	it('should not be visible after \'Back\' is pressed', function() {
		indexModal.__views.backBtn.fireEvent('click');
		expect(indexModal.visible).toBe(false);
	});
	*/
});
describe('\n \nThe addSiteSurvey screen', function() {
	var addSiteSurvey = Alloy.createController('addSiteSurvey');
	it('should exist when created ', function() {
		expect(addSiteSurvey).notToBe(undefined);
	});
	it('should have no park name selected', function() {
		expect(addSiteSurvey.parkSrch.value).toBe(undefined);
	});
	/*
	it('should not allow empty forms to be submitted', function() {
		addSiteSurvey.__views.doneAddSite.fireEvent('click');
		expect(addSiteSurvey.parkSrchError.visible).toBe(true);
	});
	*/
	describe('\n The biome TabbedBar of addSiteSurvey', function () {
		it('should be unset when created', function() {
			expect(addSiteSurvey.pickBiome.index).toBe(undefined);
		});
		it('should be selectable', function() {
			addSiteSurvey.pickBiome.index=1;
			expect(addSiteSurvey.pickBiome.index == 1).toBe(true);
		});
	});
});
describe('\n \nThe export modal controller', function() {
	it('should be created when Export is selected', function() {
		exportModal = Alloy.createController('exportModal');
		expect(exportModal).notToBe(undefined);
	});
});
describe('\n\nThe addTransect screen of siteID 1', function() {
	var $ = Alloy.createController('addTransect', {siteID:1});
	it('should exist when created ', function() {
		expect($).notToBe(undefined);
	});
	it('should have all empty input field', function() {
		expect($.tsctName.value).toBe("");
		expect($.srvyName.value).toBe("");
		expect($.otherSrvyName.value).toBe("");
		expect($.pickStake.index).toBe(undefined);
		expect($.plotDist.value).toBe("");
		expect($.comments.value).toBe("");
	});
	describe('\naddTransect form input', function() {
		it('should set transect name to \'Strawberry\'', function() {
			$.tsctName.setValue("Strawberry");
			expect($.tsctName.value).toBe("Strawberry");
		});
		it('should set transect name to \'S\'', function() {
			$.tsctName.setValue("S");
			expect($.tsctName.value).toBe("S");
		});
		it('should set head surveyor to \'Cherry Tree\'', function() {
			$.srvyName.setValue("Cherry Tree");
			expect($.srvyName.value).toBe("Cherry Tree");
		});
		it('should set head surveyor to \'C\'', function() {
			$.srvyName.setValue("C");
			expect($.srvyName.value).toBe("C");
		});
		it('should set stake orientation', function() {
			$.pickStake.setIndex(1);
			expect($.pickStake.index == 1).toBe(true);
		});
		it('should set plot distance to 20', function() {
			$.plotDist.setValue(20);
			expect($.plotDist.value).toBe(20);
		});
		it('should set plot distance to 200', function() {
			$.plotDist.setValue(200);
			expect($.plotDist.value).toBe(200);
		});
	});
});
<commit_msg>grab database results and test against them<commit_after>//Setup module to run Behave tests
require('behave').andSetup(this);
var Alloy = require("alloy");

describe('\n \nThe index screen', function() {
	var index = Alloy.createController('index');
	it('should create a controller', function() {
		expect(index).notToBe(null);
	});
	it('should create a table', function() {
		expect(index.getView("tbl")).notToBe(undefined);
	});
	describe('\nThe TableView \'tbl\' of the index screen', function() {
		it('should have a header with a button called \'Add\'', function() {
			expect(index.getView("headerView")).notToBe(undefined);
			expect(index.addSite.title).toBe("Add");
		});
	});
});

describe('\n \nThe site survey modal with siteID 1', function () {
	var indexModal = Alloy.createController('siteSurveyModal', {siteID:1});
	it('should exist when created', function() {
		expect(indexModal).notToBe(undefined);
	});
	/*
	it('should be visible', function() {
		expect(indexModal.visible).toBe(true);
	});
	*/
	it('should have a park name of \'Kakwa Park\'', function() {
		expect(indexModal.parkName.text).toBe('Kakwa Park');
	});
	it('should have a year of 2014', function() {
		expect(indexModal.siteYear.text).toBe('2014');
	});
	/*
	it('should not be visible after \'Back\' is pressed', function() {
		indexModal.__views.backBtn.fireEvent('click');
		expect(indexModal.visible).toBe(false);
	});
	*/
});
describe('\n\nThe transect modal', function() {
	//generate some test data using transect_id 1
	var db = Ti.Database.open('ltemaDB');
	resultRow = db.execute(	'SELECT transect_id, transect_name, surveyor, plot_distance, stake_orientation, comments \
							FROM transect t \
							WHERE transect_id = 1');
	var transectName = resultRow.fieldByName('transect_name');
	var surveyor = resultRow.fieldByName('surveyor');
	var plotDistance = resultRow.fieldByName('plot_distance');
	var stakeOrientation = resultRow.fieldByName('stake_orientation');
	var comments = resultRow.fieldByName('comments');
	resultRow.close();
	db.close();

	var $ = Alloy.createController('transectsModal', {transectID:1});
	it('should exist when created', function() {
		expect($).notToBe(undefined);
	});
	it('should have a transect name of '+ transectName, function() {
		expect($.transectName.value).toBe(transectName);
	});

});

describe('\n \nThe addSiteSurvey screen', function() {
	var addSiteSurvey = Alloy.createController('addSiteSurvey');
	it('should exist when created ', function() {
		expect(addSiteSurvey).notToBe(undefined);
	});
	it('should have no park name selected', function() {
		expect(addSiteSurvey.parkSrch.value).toBe(undefined);
	});
	/*
	it('should not allow empty forms to be submitted', function() {
		addSiteSurvey.__views.doneAddSite.fireEvent('click');
		expect(addSiteSurvey.parkSrchError.visible).toBe(true);
	});
	*/
	describe('\n The biome TabbedBar of addSiteSurvey', function () {
		it('should be unset when created', function() {
			expect(addSiteSurvey.pickBiome.index).toBe(undefined);
		});
		it('should be selectable', function() {
			addSiteSurvey.pickBiome.index=1;
			expect(addSiteSurvey.pickBiome.index == 1).toBe(true);
		});
	});
});
describe('\n \nThe export modal controller', function() {
	it('should be created when Export is selected', function() {
		exportModal = Alloy.createController('exportModal');
		expect(exportModal).notToBe(undefined);
	});
});
describe('\n\nThe addTransect screen of siteID 1', function() {
	var $ = Alloy.createController('addTransect', {siteID:1});
	it('should exist when created ', function() {
		expect($).notToBe(undefined);
	});
	it('should have all empty input field', function() {
		expect($.tsctName.value).toBe("");
		expect($.srvyName.value).toBe("");
		expect($.otherSrvyName.value).toBe("");
		expect($.pickStake.index).toBe(undefined);
		expect($.plotDist.value).toBe("");
		expect($.comments.value).toBe("");
	});
	describe('\naddTransect form input', function() {
		it('should set transect name to \'Strawberry\'', function() {
			$.tsctName.setValue("Strawberry");
			expect($.tsctName.value).toBe("Strawberry");
		});
		it('should set transect name to \'S\'', function() {
			$.tsctName.setValue("S");
			expect($.tsctName.value).toBe("S");
		});
		it('should set head surveyor to \'Cherry Tree\'', function() {
			$.srvyName.setValue("Cherry Tree");
			expect($.srvyName.value).toBe("Cherry Tree");
		});
		it('should set head surveyor to \'C\'', function() {
			$.srvyName.setValue("C");
			expect($.srvyName.value).toBe("C");
		});
		it('should set stake orientation', function() {
			$.pickStake.setIndex(1);
			expect($.pickStake.index == 1).toBe(true);
		});
		it('should set plot distance to 20', function() {
			$.plotDist.setValue(20);
			expect($.plotDist.value).toBe(20);
		});
		it('should set plot distance to 200', function() {
			$.plotDist.setValue(200);
			expect($.plotDist.value).toBe(200);
		});
	});
});
<|endoftext|>


<commit_before>'use strict'

const {stdout, stderr} = require('process')
const testmsg = (stream, description, state) => stream.write(`  :: ${description} -> ${state}\n`)

module.exports = (...units) => units
  .map(
    ([description, action]) => {
      try {
        const passed = action()
        passed
          ? testmsg(stdout, description, 'passed')
          : testmsg(stderr, description, 'failed')
        return passed
      } catch (error) {
        testmsg(stderr, description, `errored\n${error}`)
        return false
      }
    }
  )
  .filter(x => !x)
  .length
<commit_msg>Print error.stack<commit_after>'use strict'

const {stdout, stderr} = require('process')
const testmsg = (stream, description, state) => stream.write(`  :: ${description} -> ${state}\n`)

module.exports = (...units) => units
  .map(
    ([description, action]) => {
      try {
        const passed = action()
        passed
          ? testmsg(stdout, description, 'passed')
          : testmsg(stderr, description, 'failed')
        return passed
      } catch (error) {
        testmsg(stderr, description, `errored\n${error.stack}`)
        return false
      }
    }
  )
  .filter(x => !x)
  .length
<|endoftext|>


<commit_before>/**
 * Definition of the operator class and several operators that can be used to implement
 * a lot of comparison semantics cleanly.
 *
 * (c) 2013, Greg Malysa <gmalysa@stanford.edu>
 * Permission to use governed by the terms of the MIT license. See LICENSE for details
 */

/******************************************************************************
 * Base class of all operators, a mostly abstract class
 *****************************************************************************/
function Operator() {}

/**
 * Access wrapper that will either return a value, or if it is a nested value,
 * will evaluate it and then return that
 * @param value The value to evaluate
 * @param key The column name of the value being retrieved
 * @param filter The filter context where we're retrieving values
 * @param options Options to be passed to the key escape function if necessary
 * @return String evaluated+escaped version of value
 */
Operator.prototype.eval = function(value, key, filter, options) {
	if (value instanceof Operator) {
		return '('+value.get(key, filter, options)+')';
	}
	else {
		return filter.handle_type(key, value);
	}
};

/**
 * Abstract implementation of get throws an exception, this should be overridden in
 * derived classes
 * @param key The column name being used in this comparison
 * @param filter The filter context where we're retrieving the value
 * @param options Options to be passed to the key escaping function if necessary
 * @return String complete conditional expression
 */
Operator.prototype.get = function(key, filter, options) {
	throw new Error('Call to abstract method db-filters.Operator.get()');
};

/******************************************************************************
 * Base class for all binary conditional operators that use the column name for an
 * lvalue
 *****************************************************************************/
function BinaryConditionFixed(op, value) {
	this.op = op;
	this.value = value;
}
BinaryConditionFixed.prototype = new Operator();
BinaryConditionFixed.prototype.constructor = BinaryConditionFixed;

/**
 * get() implementation, fixed to use the properly written column as the lval, and
 * the given user value as the rval
 * @see Operator.get for parameter information
 */
BinaryConditionFixed.prototype.get = function(key, filter, options) {
	return filter.escapeKey(key, options) + this.op + this.eval(this.value, key, filter, options);
};

/******************************************************************************
 * Base class for all binary condition operators that accept two proper values, which
 * effectively disregards the column name. However, it is passed to any evaluated
 * expressions, so it can be used to build complex expressions out of simple column-
 * derived ones
 *****************************************************************************/
function BinaryConditionFree(op, lval, rval) {
	this.op = op;
	this.lval = lval;
	this.rval = rval;
}
BinaryConditionFree.prototype = new Operator();
BinaryConditionFree.prototype.constructor = BinaryConditionFree;

/**
 * get() implementation, which performs the comparison on two arbitrary values
 * @see Operator.get for parameter information
 */
BinaryConditionFree.prototype.get = function(key, filter, options) {
	return this.eval(this.lval, key, filter, options) + this.op + this.eval(this.rval, key, filter, options);
};

/******************************************************************************
 * Because I am super lazy when it comes to writing out code, all of the actual operators
 * are generally generated programmatically, because that requires the least amount of typing.
 *****************************************************************************/
// List of all operator functions that will be passed back to db-filters
var operators = {};

// Binary fixed operator generation
var binary_fixed_templates = [
	['$eq', '='], ['$neq', '!='],
	['$gt', '>'], ['$ge', '>='],
	['$lt', '<'], ['$le', '<=']];
binary_fixed_templates.forEach(function(v) {
	operators[v[0]] = function(val) {
		return new BinaryConditionFixed(v[1], val);
	};
});

// Binary free operator generation
var binary_free_templates = [
	['$eq2', '='], ['$neq2', '!='],
	['$gt2', '>'], ['$ge2', '>='],
	['$lt2', '<'], ['%le2', '<=']];
binary_free_templates.forEach(function(v) {
	operators[v[0]] = function(lval, rval) {
		return new BinaryConditionFree(v[1], lval, rval);
	};
});

// Definition exports
module.exports.Operator = Operator;
module.exports.operators = operators;
<commit_msg>Added array operator definitions.<commit_after>/**
 * Definition of the operator class and several operators that can be used to implement
 * a lot of comparison semantics cleanly.
 *
 * (c) 2013, Greg Malysa <gmalysa@stanford.edu>
 * Permission to use governed by the terms of the MIT license. See LICENSE for details
 */

/******************************************************************************
 * Base class of all operators, a mostly abstract class
 *****************************************************************************/
function Operator() {}

/**
 * Access wrapper that will either return a value, or if it is a nested value,
 * will evaluate it and then return that
 * @param value The value to evaluate
 * @param key The column name of the value being retrieved
 * @param filter The filter context where we're retrieving values
 * @param options Options to be passed to the key escape function if necessary
 * @return String evaluated+escaped version of value
 */
Operator.prototype.eval = function(value, key, filter, options) {
	if (value instanceof Operator) {
		return '('+value.get(key, filter, options)+')';
	}
	else {
		return filter.handle_type(key, value);
	}
};

/**
 * Abstract implementation of get throws an exception, this should be overridden in
 * derived classes
 * @param key The column name being used in this comparison
 * @param filter The filter context where we're retrieving the value
 * @param options Options to be passed to the key escaping function if necessary
 * @return String complete conditional expression
 */
Operator.prototype.get = function(key, filter, options) {
	throw new Error('Call to abstract method db-filters.Operator.get()');
};

/******************************************************************************
 * Base class for all binary conditional operators that use the column name for an
 * lvalue
 *****************************************************************************/
function BinaryConditionFixed(op, value) {
	this.op = op;
	this.value = value;
}
BinaryConditionFixed.prototype = new Operator();
BinaryConditionFixed.prototype.constructor = BinaryConditionFixed;

/**
 * get() implementation, fixed to use the properly written column as the lval, and
 * the given user value as the rval
 * @see Operator.get for parameter information
 */
BinaryConditionFixed.prototype.get = function(key, filter, options) {
	return filter.escapeKey(key, options) + ' ' + this.op + ' ' + this.eval(this.value, key, filter, options);
};

/******************************************************************************
 * Base class for all binary condition operators that accept two proper values, which
 * effectively disregards the column name. However, it is passed to any evaluated
 * expressions, so it can be used to build complex expressions out of simple column-
 * derived ones
 *****************************************************************************/
function BinaryConditionFree(op, lval, rval) {
	this.op = op;
	this.lval = lval;
	this.rval = rval;
}
BinaryConditionFree.prototype = new Operator();
BinaryConditionFree.prototype.constructor = BinaryConditionFree;

/**
 * get() implementation, which performs the comparison on two arbitrary values
 * @see Operator.get for parameter information
 */
BinaryConditionFree.prototype.get = function(key, filter, options) {
	return this.eval(this.lval, key, filter, options) + ' ' + this.op + ' ' + this.eval(this.rval, key, filter, options);
};

/******************************************************************************
 * Checks if a value is in an array, comes in two forms, one that fixes the key and one that
 * allows a free lvalue
 *****************************************************************************/
function ArrayCondition(rval, lval) {
	this.rval = rval;
	this.lval = lval;
}
ArrayCondition.prototype = new Operator();
ArrayCondition.prototype.constructor = ArrayCondition;

/**
 * get() implementation, which sets up the list and does a check with IN()
 * @see Operator.get for parameter information
 */
ArrayCondition.prototype.get = function(key, filter, options) {
	var lval, rval;

	if (this.lval === undefined)
		lval = filter.escapeKey(key, options);
	else
		lval = this.eval(this.lval, key, filter, options);

	rval = this.rval.map(function(v) {
		return this.eval(v, key, filter, options);
	}, this);
	return lval + ' IN (' + rval.join(', ') + ')';
};

/******************************************************************************
 * Because I am super lazy when it comes to writing out code, all of the actual operators
 * are generally generated programmatically, because that requires the least amount of typing.
 *****************************************************************************/
// List of all operator functions that will be passed back to db-filters
var operators = {};

// Binary fixed operator generation
var binary_fixed_templates = [
	['$eq', '='], ['$neq', '!='],
	['$gt', '>'], ['$ge', '>='],
	['$lt', '<'], ['$le', '<=']];
binary_fixed_templates.forEach(function(v) {
	operators[v[0]] = function(val) {
		return new BinaryConditionFixed(v[1], val);
	};
});

// Binary free operator generation
var binary_free_templates = [
	['$eq2', '='], ['$neq2', '!='],
	['$gt2', '>'], ['$ge2', '>='],
	['$lt2', '<'], ['%le2', '<=']];
binary_free_templates.forEach(function(v) {
	operators[v[0]] = function(lval, rval) {
		return new BinaryConditionFree(v[1], lval, rval);
	};
});

// Array testing operators
operators.$in = function(v) { return new ArrayCondition(v, undefined); };
operators.$in2 = function(lval, arr) { return new ArrayCondition(arr, lval); };

// Definition exports
module.exports.Operator = Operator;
module.exports.operators = operators;
<|endoftext|>


<commit_before>/*
  blur.js
*/

var ip_blur = function(src, r){
  var dst = ip_create_img( src.width, src.height );

  _ip_gauss_blur( src,dst, src.width,src.height, r );

  return dst;
}

var _ip_gauss_boxes = function(sigma, n){
    var wIdeal = Math.sqrt((12*sigma*sigma/n)+1);  // Ideal averaging filter width
    var wl = Math.floor(wIdeal);  if(wl%2==0) wl--;
    var wu = wl+2;

    var mIdeal = (12*sigma*sigma - n*wl*wl - 4*n*wl - 3*n)/(-4*wl - 4);
    var m = Math.round(mIdeal);
    // var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)/12 );

    var sizes = [];  for(var i=0; i<n; i++) sizes.push(i<m?wl:wu);
    return sizes;
}

function _ip_gauss_blur(src,dst, w,h, r) {
    var bxs = _ip_gauss_boxes(r, 3);
    _ip_box_blur(src, dst, w, h, (bxs[0]-1)/2);
    //_ip_box_blur(dst, src, w, h, (bxs[1]-1)/2);
    //_ip_box_blur(src, dst, w, h, (bxs[2]-1)/2);
}
function _ip_box_blur(src,dst, w,h, r) {
    for(i=0;i<w;i++){
        for(j=0;j<h;j++) {
            var cr = 0,cg = 0,cb = 0;

            var st_x = Math.max( 0, i-r );
            var st_y = Math.max( 0, j-r );
            var to_x = Math.min( w-1, i+r+1 );
            var to_y = Math.min( h-1, j+r+1 );

            for(k=st_x;k<to_x;k++){
                for(l=st_y;l<to_y;l++) {
                    var p = ip_get_rgb_at( src, k,l );

                    cr += p[0];
                    cg += p[1];
                    cb += p[2];
                }
            }

            var div = ((r+r+1)*(r+r+1));
            ip_set_rgba_at(
            	dst, i,j,
            	cr/div,cg/div,cb/div,
            	255);
        }
    }
}
<commit_msg>Update ip_blur.js<commit_after>/*
  blur.js
*/

var ip_blur = function(src, r){
  var dst = ip_create_img( src.width, src.height );

  _ip_gauss_blur( src,dst, src.width,src.height, r );

  return dst;
}

var _ip_gauss_boxes = function(sigma, n){
    var wIdeal = Math.sqrt((12*sigma*sigma/n)+1);  // Ideal averaging filter width
    var wl = Math.floor(wIdeal);  if(wl%2==0) wl--;
    var wu = wl+2;

    var mIdeal = (12*sigma*sigma - n*wl*wl - 4*n*wl - 3*n)/(-4*wl - 4);
    var m = Math.round(mIdeal);
    // var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)/12 );

    var sizes = [];  for(var i=0; i<n; i++) sizes.push(i<m?wl:wu);
    return sizes;
}

function _ip_gauss_blur(src,dst, w,h, r) {
    var bxs = _ip_gauss_boxes(r, 3);
    _ip_box_blur(src, dst, w, h, (bxs[0]-1)/2);
    _ip_box_blur(dst, src, w, h, (bxs[1]-1)/2);
    _ip_box_blur(src, dst, w, h, (bxs[2]-1)/2);
}
function _ip_box_blur(src,dst, w,h, r) {
    for(i=0;i<w;i++){
        for(j=0;j<h;j++) {
            var cr = 0,cg = 0,cb = 0;

            var st_x = Math.max( 0, i-r );
            var st_y = Math.max( 0, j-r );
            var to_x = Math.min( w-1, i+r+1 );
            var to_y = Math.min( h-1, j+r+1 );

            /*
            for(k=st_x;k<to_x;k++){
                for(l=st_y;l<to_y;l++) {
                    var p = ip_get_rgb_at( src, k,l );

                    cr += p[0];
                    cg += p[1];
                    cb += p[2];
                }
            }
            */

            for(var iy=i-r; iy<i+r+1; iy++){
                for(var ix=j-r; ix<j+r+1; ix++) {
                    var x = Math.min(w-1, Math.max(0, ix));
                    var y = Math.min(h-1, Math.max(0, iy));

                    var p = ip_get_rgb_at( src, x,y );

                    cr += p[0];
                    cg += p[1];
                    cb += p[2];
                }
            }

            var div = ((r+r+1)*(r+r+1));
            ip_set_rgba_at(
            	dst, i,j,
            	cr/div,cg/div,cb/div,
            	255);
        }
    }
}
<|endoftext|>


<commit_before>exports.webdriver = function() {
    return {
        phantomjs: require('webdriverjs').remote({
            desiredCapabilities: {
                browserName: "phantomjs",
            },
            logLevel: 'silent"'
    });

});
<commit_msg>no longer needed<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';
import RedmineClient from './redmine';
import GitHubClient from './github';
import Task from './task';
import { TaskWidget, ProjectWidget } from './widgets';
import classNames from 'classnames';
import Configstore from 'configstore';
import { LogChart } from './chart';
import Log from './log';
import TaskList from './tasklist';
// import pkg from '../../package.json';
const pkg = {name: 'task-list-app'};

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      workTime: 30*60,
      breakTime: 60,
      alertTime: 60,
      idleTime: 6,

      projects: [],
      tasks: [],

      view: 'projects',
      compactView: false,

      taskId: null,
      taskLabel: '-',
      startTime: null,
      lastWorkTime: null,
      timeElapsed: 0,
      timeRemaining: 0,
      timeIdle: 0,
      currently: 'stopped',
      timer: null,

      log: [],
      showLog: false,
      messages: [],
      showMessages: false,

      alertMessage: "",
      showAlert: false,
      afterWaiting: null
    };
    this.actions = {
      click: this.click.bind(this),
      start: this.start.bind(this),
      stop: this.stop.bind(this),
      pause: this.pause.bind(this),
      setTask: this.setTask.bind(this),
      refresh: this.refresh.bind(this),
      save: this.save.bind(this),
      uploadLogs: this.uploadLogs.bind(this),
      toggleView: this.toggleView.bind(this),
      toggleCompactView: this.toggleCompactView.bind(this),
      showLog: this.showLog.bind(this),
      showMessages: this.showMessages.bind(this),
      dismissPopups: this.dismissPopups.bind(this)
    };
    this.conf = new Configstore(pkg.name);
  }
  componentWillMount() {
    this.load().then(this.refresh.bind(this)).then(this.stop.bind(this));
  }
  componentWillUnmount() {
    this.stop();
    this.save();
  }
  addMessage(message) {
    this.setState({
      messages: this.state.messages.concat(['' + message])
    });
  }
  click() {
    this.setState({
      timeIdle: 0
    });
  }
  save() {
    console.log("Saving to conf");
    this.conf.set('log', this.state.log);
  }
  load() {
    const s = {};
    s.log = this.conf.get('log') || this.state.log;
    this.setState(s);
    return Promise.resolve();
  }
  loadRedmine() {
    const redmine = new RedmineClient();
    return redmine.load().then( (data) => {
      this.setState({projects: data.projects, tasks: data.tasks});
    }, (err) => {
      this.addMessage("Error loading Redmine: " + err);
    });
  }
  loadGitHub() {
    const github = new GitHubClient();
    return github.load().then( (data) => {
      this.setState({projects: data.projects, tasks: data.tasks});
    }, (err) => {
      this.addMessage("Error loading GitHub: " + err);
    });
  }
  uploadLogs() {
    const redmine = new RedmineClient();
    redmine.upload(this.state.log).then( (updatedLog) => {
      console.log("Redmine uploaded");
      this.setState({log: updatedLog});
      this.save();
    }, (err) => {
      console.log("Error! " + err);
    });
  }
  refresh() {
    this.addMessage("Loading Redmine");
    console.log("refresh");

    const redmine = new RedmineClient();
    const github = new GitHubClient();

    const projects = [];
    const tasks = [];
    return redmine.load().then( (data) => {
      Array.prototype.push.apply(projects, data.projects);
      Array.prototype.push.apply(tasks, data.tasks);
    }).then( () => {
      this.setState({projects: projects, tasks: tasks});
    });
    /*
    return Promise.all([
      redmine.load(),
      github.load()
    ]).then( (data) => {
      var projects = [].concat(data[0].projects, data[1].projects);
      var tasks = [].concat(data[0].tasks, data[1].tasks);
      this.setState({projects: projects, tasks: tasks});
    }, (err) => {
      this.addMessage(err);
    });
    */
  }
  handleRowClick(row) {
    console.log("Clicked on row: " + row);
  }
  formatTime(t) {
    var neg = (t < 0);
    t = Math.abs(t);
    var s = t%60;
    var m = (Math.trunc(t/60)%60);
    var h = Math.trunc(t/3600);

    function pad2(d) {
      return (d >= 10 ? '' : '0') + d;
    }

    var sign = neg ? '-' : '';
    if (h > 0) {
      return sign + h + ':' + pad2(m) + ':' + pad2(s);
    } else {
      return sign + m + ':' + pad2(s);
    }
  }
  getTask(taskId) {
    var foundTask = null;
    function findTask(task) {
      if (task && Task.getUID(task) == taskId) {
        foundTask = task;
        return true;
      }
    }
    this.state.projects.some( (project) => {
      return findTask(project) ||
        project.tasks.some( (task) => {
          return findTask(task);
        });
    });
    return foundTask;
  }
  render() {
    // All the available callbacks from the UI
    const actions = this.actions;
    // Context provided to children (eg. task widgets)
    const context = {
      selectedTaskId: this.state.taskId,
      currently: this.state.currently,
      actions: actions,
      view: this.state.view
    };

    const taskList = (
      <TaskList projects={this.state.project} tasks={this.state.tasks}
        context={context} />
    );
    /*
    const rows = [];
    if (this.state.view == 'projects') {
      this.state.projects.forEach( (project) => {
        rows.push(
          <ProjectWidget key={Task.getUID(project)} task={project} context={context} />
        );
      });
    } else {
      this.state.tasks.forEach( (task) => {
        rows.push(
          <TaskWidget key={Task.getUID(task)} task={task} context={context} />
        );
      });
    }
    */
    const logDisplay = (
      <Log log={this.state.log}/>
    );
    /*
    const logRows = []
    this.state.log.forEach( (logEntry, i) => {
      logRows.push(

{logEntry.task} ({this.formatTime(logEntry.timeElapsed)})

      );
    });
    */
    const messageRows = []
    this.state.messages.forEach( (message, i) => {
      messageRows.push(

{message}

      );
    });
    const timeElapsed = this.formatTime(this.state.timeElapsed);
    const timeRemaining = this.formatTime(this.state.timeRemaining);
    var idleLevel = '';
    if (this.state.timeIdle > 5) { idleLevel = 'idle-1'; }
    if (this.state.timeIdle > 10) { idleLevel = 'idle-2'; }

    const className = classNames(
      'main',
      this.state.currently,
      idleLevel,
      {
       'has-task': this.state.taskId,
       'compact': this.state.compactView,
       'show-popup': (this.state.showLog || this.state.showMessages || this.state.showAlert),
       'show-log': this.state.showLog,
       'show-messages': this.state.showMessages,
       'show-alert': this.state.showAlert
      });
    const currentTask = this.state.taskLabel;
    const compactButtonClassName = classNames(
      'fa',
      (this.state.compactView ? 'fa-toggle-up' : 'fa-toggle-down')
      );
    return(

               Reload

               Log

               Debug

               Group

               Compact

               Upload

          Stop

{timeRemaining}

Task{currentTask}

Elapsed{timeElapsed}

          {/*
Idle{this.formatTime(this.state.timeIdle)}
 */}

{taskList}

Messages
{messageRows}

Log
{logDisplay}

Alert

{this.state.alertMessage}

    );
  }
  setTask(task) {
    const taskId = Task.getUID(task);
    const taskLabel = Task.getLabel(task);
    if (taskId != this.state.taskId) {
      console.log("setTask: " + taskId);
      this.stop();
      this.setState({
        taskId: taskId,
        taskLabel: taskLabel,
        timeElapsed: 0,
        timeRemaining: 0
      });
    }
  }
  toggleView() {
    this.setState({
      view: (this.state.view == 'projects' ? 'tasks' : 'projects')
    });
  }
  toggleCompactView() {
    this.setState({
      compactView: !this.state.compactView
    });
  }
  showLog() {
    this.setState({
      showLog: true
    });
  }
  showMessages() {
    this.setState({
      showMessages: true
    });
  }
  dismissPopups() {
    this.setState({
      showLog: false,
      showMessages: false,
      showAlert: false
    });
    if (this.state.afterWaiting) {
      this.afterWaiting(this.state.afterWaiting);
    }
  }
  afterWaiting(next) {
    const timerPeriod = ({
      working: this.state.workTime,
      paused: this.state.breakTime,
      stopped: 0
    })[next];
    this.setState({
      currently: next,
      afterWaiting: null,
      timeRemaining: timerPeriod
    });
    this.stopTimer();
    if (timerPeriod) {
      this.startTimer();
    }
  }
  waitForUser(message, next) {
    this.setState({
      showAlert: true,
      alertMessage: message,
      afterWaiting: next
    });
  }
  /* Timer */
  start(task) {
    if (task && !task.source) { task = null; }
    const changedTask = (task && Task.getUID(task) != this.state.taskId);
    if (changedTask) {
      this.setTask(task);
    }
    else if (this.state.currently == "working") {
      console.log("extend");
      // Don't interfere with timer, just reset the remaining time
      this.setState({
        timeRemaining: this.state.workTime
      });
      return;
    }
    if (!task || !Task.getUID(task)) { return; }
    this.setState({
      currently: "working",
      startTime: this.state.startTime || new Date(),
      timeRemaining: this.state.workTime
    });
    this.startTimer();
  }
  tick() {
    const state = {};
    if (this.state.currently == "stopped" || this.state.showAlert) {
      state.timeIdle = this.state.timeIdle + 1;
    }
    else if (this.state.currently == "working") {
      state.timeElapsed = this.state.timeElapsed + 1;
      state.lastWorkTime = new Date();
    }
    if (this.state.timeRemaining > 0) {
      state.timeRemaining = this.state.timeRemaining - 1;
    }
    this.setState(state);
    if (state.timeRemaining === 0) {
      this.timeUp();
    }
  }
  timeUp() {
    switch (this.state.currently) {
      case "working":
        this.waitForUser("Time for a break!", "paused");
        break;
      case "paused":
        this.waitForUser("Ready to go!", "paused");
        break;
      case "stopped":
        this.waitForUser("Hello!", "stopped");
        break;
    }
  }
  startTimer() {
    this.stopTimer();
    var tick = this.tick.bind(this);
    this.setState({
      timer: window.setInterval(tick, 1000)
    });
  }
  stopTimer() {
    if (this.state.timer) {
      window.clearInterval(this.state.timer);
      this.setState({
        timer: null
      });
    }
  }
  pause() {
    if (! this.state.taskId) { return; }
    if (this.state.currently == "working") {
      this.setState({
        currently: "paused",
        timeRemaining: this.state.breakTime
      });
      this.startTimer();
    } else {
      this.start(this.getTask(this.state.taskId));
    }
  }
  stop() {
    if (this.state.startTime) {
      this.log();
    }
    this.setState({
      currently: "stopped",
      timeRemaining: 0,
      timeElapsed: 0,
      startTime: null,
    });
    this.startTimer();
  }
  log() {
    const logEntry = {
      task: this.state.taskId,
      startTime: this.state.startTime.toISOString(),
      endTime: this.state.lastWorkTime.toISOString(),
      timeElapsed: this.state.timeElapsed
    }
    this.setState({
      log: this.state.log.concat([logEntry])
    }, (err) => {
      if (!err) { this.save(); }
    });
    const logEntryStr = JSON.stringify(logEntry);
    console.log(`LOG: task: ${logEntryStr}`);
  }

}
<commit_msg>Refactor rendering of the top toolbar and popups<commit_after>import React, { Component } from 'react';
import RedmineClient from './redmine';
import GitHubClient from './github';
import Task from './task';
import { TaskWidget, ProjectWidget } from './widgets';
import classNames from 'classnames';
import Configstore from 'configstore';
import { LogChart } from './chart';
import Log from './log';
import TaskList from './tasklist';
// import pkg from '../../package.json';
const pkg = {name: 'task-list-app'};

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      workTime: 30*60,
      breakTime: 60,
      alertTime: 60,
      idleTime: 6,

      projects: [],
      tasks: [],

      view: 'projects',
      compactView: false,

      taskId: null,
      taskLabel: '-',
      startTime: null,
      lastWorkTime: null,
      timeElapsed: 0,
      timeRemaining: 0,
      timeIdle: 0,
      currently: 'stopped',
      timer: null,

      log: [],
      showLog: false,
      messages: [],
      showMessages: false,

      alertMessage: "",
      showAlert: false,
      afterWaiting: null
    };
    this.actions = {
      click: this.click.bind(this),
      start: this.start.bind(this),
      stop: this.stop.bind(this),
      pause: this.pause.bind(this),
      setTask: this.setTask.bind(this),
      refresh: this.refresh.bind(this),
      save: this.save.bind(this),
      uploadLogs: this.uploadLogs.bind(this),
      toggleView: this.toggleView.bind(this),
      toggleCompactView: this.toggleCompactView.bind(this),
      showLog: this.showLog.bind(this),
      showMessages: this.showMessages.bind(this),
      dismissPopups: this.dismissPopups.bind(this)
    };
    this.conf = new Configstore(pkg.name);
  }
  componentWillMount() {
    this.load().then(this.refresh.bind(this)).then(this.stop.bind(this));
  }
  componentWillUnmount() {
    this.stop();
    this.save();
  }
  addMessage(message) {
    this.setState({
      messages: this.state.messages.concat(['' + message])
    });
  }
  click() {
    this.setState({
      timeIdle: 0
    });
  }
  save() {
    console.log("Saving to conf");
    this.conf.set('log', this.state.log);
  }
  load() {
    const s = {};
    s.log = this.conf.get('log') || this.state.log;
    this.setState(s);
    return Promise.resolve();
  }
  loadRedmine() {
    const redmine = new RedmineClient();
    return redmine.load().then( (data) => {
      this.setState({projects: data.projects, tasks: data.tasks});
    }, (err) => {
      this.addMessage("Error loading Redmine: " + err);
    });
  }
  loadGitHub() {
    const github = new GitHubClient();
    return github.load().then( (data) => {
      this.setState({projects: data.projects, tasks: data.tasks});
    }, (err) => {
      this.addMessage("Error loading GitHub: " + err);
    });
  }
  uploadLogs() {
    const redmine = new RedmineClient();
    redmine.upload(this.state.log).then( (updatedLog) => {
      console.log("Redmine uploaded");
      this.setState({log: updatedLog});
      this.save();
    }, (err) => {
      console.log("Error! " + err);
    });
  }
  refresh() {
    this.addMessage("Loading Redmine");
    console.log("refresh");

    const redmine = new RedmineClient();
    const github = new GitHubClient();

    const projects = [];
    const tasks = [];
    return redmine.load().then( (data) => {
      Array.prototype.push.apply(projects, data.projects);
      Array.prototype.push.apply(tasks, data.tasks);
    }).then( () => {
      this.setState({projects: projects, tasks: tasks});
    });
    /*
    return Promise.all([
      redmine.load(),
      github.load()
    ]).then( (data) => {
      var projects = [].concat(data[0].projects, data[1].projects);
      var tasks = [].concat(data[0].tasks, data[1].tasks);
      this.setState({projects: projects, tasks: tasks});
    }, (err) => {
      this.addMessage(err);
    });
    */
  }
  handleRowClick(row) {
    console.log("Clicked on row: " + row);
  }
  formatTime(t) {
    var neg = (t < 0);
    t = Math.abs(t);
    var s = t%60;
    var m = (Math.trunc(t/60)%60);
    var h = Math.trunc(t/3600);

    function pad2(d) {
      return (d >= 10 ? '' : '0') + d;
    }

    var sign = neg ? '-' : '';
    if (h > 0) {
      return sign + h + ':' + pad2(m) + ':' + pad2(s);
    } else {
      return sign + m + ':' + pad2(s);
    }
  }
  getTask(taskId) {
    var foundTask = null;
    function findTask(task) {
      if (task && Task.getUID(task) == taskId) {
        foundTask = task;
        return true;
      }
    }
    this.state.projects.some( (project) => {
      return findTask(project) ||
        project.tasks.some( (task) => {
          return findTask(task);
        });
    });
    return foundTask;
  }
  render() {
    // All the available callbacks from the UI
    const actions = this.actions;
    // Context provided to children (eg. task widgets)
    const context = {
      selectedTaskId: this.state.taskId,
      currently: this.state.currently,
      actions: actions,
      view: this.state.view
    };

    const taskList = (
      <TaskList projects={this.state.project} tasks={this.state.tasks}
        context={context} />
    );
    /*
    const rows = [];
    if (this.state.view == 'projects') {
      this.state.projects.forEach( (project) => {
        rows.push(
          <ProjectWidget key={Task.getUID(project)} task={project} context={context} />
        );
      });
    } else {
      this.state.tasks.forEach( (task) => {
        rows.push(
          <TaskWidget key={Task.getUID(task)} task={task} context={context} />
        );
      });
    }
    */
    const logDisplay = (
      <Log log={this.state.log}/>
    );
    /*
    const logRows = []
    this.state.log.forEach( (logEntry, i) => {
      logRows.push(

{logEntry.task} ({this.formatTime(logEntry.timeElapsed)})

      );
    });
    */
    const messageRows = []
    this.state.messages.forEach( (message, i) => {
      messageRows.push(

{message}

      );
    });
    const timeElapsed = this.formatTime(this.state.timeElapsed);
    const timeRemaining = this.formatTime(this.state.timeRemaining);
    var idleLevel = '';
    if (this.state.timeIdle > 5) { idleLevel = 'idle-1'; }
    if (this.state.timeIdle > 10) { idleLevel = 'idle-2'; }

    const className = classNames(
      'main',
      this.state.currently,
      idleLevel,
      {
       'has-task': this.state.taskId,
       'compact': this.state.compactView,
       'show-popup': (this.state.showLog || this.state.showMessages || this.state.showAlert),
       'show-log': this.state.showLog,
       'show-messages': this.state.showMessages,
       'show-alert': this.state.showAlert
      });
    const currentTask = this.state.taskLabel;
    const compactButtonClassName = classNames(
      'fa',
      (this.state.compactView ? 'fa-toggle-up' : 'fa-toggle-down')
      );

    const toolbar = (

             Reload

             Log

             Upload

             Debug

             Group

             Compact

    );
    const popups = (

Messages
{messageRows}

Log
{logDisplay}

Alert

{this.state.alertMessage}

    );
    return(

        {toolbar}

          Stop

{timeRemaining}

Task{currentTask}

Elapsed{timeElapsed}

          {/*
Idle{this.formatTime(this.state.timeIdle)}
 */}

{taskList}

        {popups}

    );
  }
  setTask(task) {
    const taskId = Task.getUID(task);
    const taskLabel = Task.getLabel(task);
    if (taskId != this.state.taskId) {
      console.log("setTask: " + taskId);
      this.stop();
      this.setState({
        taskId: taskId,
        taskLabel: taskLabel,
        timeElapsed: 0,
        timeRemaining: 0
      });
    }
  }
  toggleView() {
    this.setState({
      view: (this.state.view == 'projects' ? 'tasks' : 'projects')
    });
  }
  toggleCompactView() {
    this.setState({
      compactView: !this.state.compactView
    });
  }
  showLog() {
    this.setState({
      showLog: true
    });
  }
  showMessages() {
    this.setState({
      showMessages: true
    });
  }
  dismissPopups() {
    this.setState({
      showLog: false,
      showMessages: false,
      showAlert: false
    });
    if (this.state.afterWaiting) {
      this.afterWaiting(this.state.afterWaiting);
    }
  }
  afterWaiting(next) {
    const timerPeriod = ({
      working: this.state.workTime,
      paused: this.state.breakTime,
      stopped: 0
    })[next];
    this.setState({
      currently: next,
      afterWaiting: null,
      timeRemaining: timerPeriod
    });
    this.stopTimer();
    if (timerPeriod) {
      this.startTimer();
    }
  }
  waitForUser(message, next) {
    this.setState({
      showAlert: true,
      alertMessage: message,
      afterWaiting: next
    });
  }
  /* Timer */
  start(task) {
    if (task && !task.source) { task = null; }
    const changedTask = (task && Task.getUID(task) != this.state.taskId);
    if (changedTask) {
      this.setTask(task);
    }
    else if (this.state.currently == "working") {
      console.log("extend");
      // Don't interfere with timer, just reset the remaining time
      this.setState({
        timeRemaining: this.state.workTime
      });
      return;
    }
    if (!task || !Task.getUID(task)) { return; }
    this.setState({
      currently: "working",
      startTime: this.state.startTime || new Date(),
      timeRemaining: this.state.workTime
    });
    this.startTimer();
  }
  tick() {
    const state = {};
    if (this.state.currently == "stopped" || this.state.showAlert) {
      state.timeIdle = this.state.timeIdle + 1;
    }
    else if (this.state.currently == "working") {
      state.timeElapsed = this.state.timeElapsed + 1;
      state.lastWorkTime = new Date();
    }
    if (this.state.timeRemaining > 0) {
      state.timeRemaining = this.state.timeRemaining - 1;
    }
    this.setState(state);
    if (state.timeRemaining === 0) {
      this.timeUp();
    }
  }
  timeUp() {
    switch (this.state.currently) {
      case "working":
        this.waitForUser("Time for a break!", "paused");
        break;
      case "paused":
        this.waitForUser("Ready to go!", "paused");
        break;
      case "stopped":
        this.waitForUser("Hello!", "stopped");
        break;
    }
  }
  startTimer() {
    this.stopTimer();
    var tick = this.tick.bind(this);
    this.setState({
      timer: window.setInterval(tick, 1000)
    });
  }
  stopTimer() {
    if (this.state.timer) {
      window.clearInterval(this.state.timer);
      this.setState({
        timer: null
      });
    }
  }
  pause() {
    if (! this.state.taskId) { return; }
    if (this.state.currently == "working") {
      this.setState({
        currently: "paused",
        timeRemaining: this.state.breakTime
      });
      this.startTimer();
    } else {
      this.start(this.getTask(this.state.taskId));
    }
  }
  stop() {
    if (this.state.startTime) {
      this.log();
    }
    this.setState({
      currently: "stopped",
      timeRemaining: 0,
      timeElapsed: 0,
      startTime: null,
    });
    this.startTimer();
  }
  log() {
    const logEntry = {
      task: this.state.taskId,
      startTime: this.state.startTime.toISOString(),
      endTime: this.state.lastWorkTime.toISOString(),
      timeElapsed: this.state.timeElapsed
    }
    this.setState({
      log: this.state.log.concat([logEntry])
    }, (err) => {
      if (!err) { this.save(); }
    });
    const logEntryStr = JSON.stringify(logEntry);
    console.log(`LOG: task: ${logEntryStr}`);
  }

}
<|endoftext|>


<commit_before>/**
 * Created by Corey600 on 2016/6/18.
 */

var retrys = 1;

function MyZookeeper() {
}

MyZookeeper.prototype.connect = function () {
};

MyZookeeper.prototype.close = function () {
};

MyZookeeper.prototype.getChildren = function (path, watcher, callback) {
  var cb;
  var wt;
  if (!callback) {
    cb = watcher;
    wt = undefined;
  } else {
    cb = callback;
    wt = watcher;
  }
  setImmediate(function () {
    if (-1 < path.indexOf('providers')) {
      cb(false, [
        'dubbo%3A%2F%2F127.0.0.1%3A20880%2Fcom.demo.Service%3Fanyhost%3Dtrue%26application%3DDemo%26dubbo%3D2.5.3%26version%3D1.0.0%26interface%3Dcom.demo.Service%26methods%3Dpost%2Cget%26owner%3Dxxx%26pid%3D22792%26revision%3D1.0.0-SNAPSHOT%26side%3Dprovider%26timestamp%3D1467033838005%26weight%3D100%26warmup%3D9467033838005',
        'dubbo%3A%2F%2F127.0.0.1%3A20881%2Fcom.demo.Service%3Fanyhost%3Dtrue%26application%3DDemo%26dubbo%3D2.5.3%26version%3D1.0.0%26interface%3Dcom.demo.Service%26methods%3Dpost%2Cget%26owner%3Dxxx%26pid%3D22792%26revision%3D1.0.0-SNAPSHOT%26side%3Dprovider%26timestamp%3D1467033838006%26weight%3D100'
      ]);
    } else {
      cb(false, [
        'override%3A%2F%2F127.0.0.1%3A20880%2Fcom.demo.Service%3Fcategory%3Dconfigurators%26dynamic%3Dfalse%26enabled%3Dtrue%26weight%3D20',
        'override%3A%2F%2F127.0.0.1%3A20881%2Fcom.demo.Service%3Fcategory%3Dconfigurators%26dynamic%3Dfalse%26enabled%3Dtrue%26weight%3D200',
        'override%3A%2F%2F127.0.0.1%3A20881%2Fcom.demo.Service%3Fcategory%3Dconfigurators%26dynamic%3Dfalse%26enabled%3Dfalse%26weight%3D300',
      ]);
    }
  });
  if (0 < retrys && wt) {
    retrys -= 1;
    setImmediate(function () {
      wt();
    });
  }
};

module.exports = MyZookeeper;
<commit_msg>Modify test code.<commit_after>/**
 * Created by Corey600 on 2016/6/18.
 */

var retrys = 1;

function MyZookeeper() {
}

MyZookeeper.prototype.connect = function () {
};

MyZookeeper.prototype.close = function () {
};

MyZookeeper.prototype.getChildren = function (path, watcher, callback) {
  var cb;
  var wt;
  if (!callback) {
    cb = watcher;
    wt = undefined;
  } else {
    cb = callback;
    wt = watcher;
  }
  setImmediate(function () {
    if (-1 < path.indexOf('providers')) {
      cb(false, [
        'dubbo%3A%2F%2F127.0.0.1%3A20880%2Fcom.demo.Service%3Fanyhost%3Dtrue%26application%3DDemo%26dubbo%3D2.5.3%26version%3D1.0.0%26interface%3Dcom.demo.Service%26methods%3Dpost%2Cget%26owner%3Dxxx%26pid%3D22792%26revision%3D1.0.0-SNAPSHOT%26side%3Dprovider%26timestamp%3D1467033838005%26weight%3D100%26warmup%3D9467033838005',
        'dubbo%3A%2F%2F127.0.0.1%3A20881%2Fcom.demo.Service%3Fanyhost%3Dtrue%26application%3DDemo%26dubbo%3D2.5.3%26version%3D1.0.0%26interface%3Dcom.demo.Service%26methods%3Dpost%2Cget%26owner%3Dxxx%26pid%3D22792%26revision%3D1.0.0-SNAPSHOT%26side%3Dprovider%26timestamp%3D1467033838006%26weight%3D100'
      ]);
    } else {
      cb(false, [
        'override%3A%2F%2F127.0.0.1%3A20880%2Fcom.demo.Service%3Fcategory%3Dconfigurators%26dynamic%3Dfalse%26enabled%3Dtrue%26weight%3D20',
        'override%3A%2F%2F127.0.0.1%3A20881%2Fcom.demo.Service%3Fcategory%3Dconfigurators%26dynamic%3Dfalse%26enabled%3Dtrue%26weight%3D200',
        'override%3A%2F%2F127.0.0.1%3A20881%2Fcom.demo.Service%3Fcategory%3Dconfigurators%26dynamic%3Dfalse%26enabled%3Dfalse%26weight%3D300'
      ]);
    }
  });
  if (0 < retrys && wt) {
    retrys -= 1;
    setImmediate(function () {
      wt();
    });
  }
};

module.exports = MyZookeeper;
<|endoftext|>


<commit_before>import React, { h } from 'preact';

const styles = {
    mapCard: {
        margin: '10px 0'
    },
    map: {
        height: '200px'
    }
};

class Map extends React.Component {
    constructor(props) {
        super(props);
        console.log('map props:' + JSON.stringify(props));
        console.log('map props geometry:' + JSON.stringify(props.geometry));
        console.log('map props place:' + JSON.stringify(props.place));
    }
    componentDidMount() {
        const map = new google.maps.Map(document.getElementById('map-' + this.props.place._id), {
            zoom: 12,
            center: this.props.place.geometry.location
        });
        console.log('map-' + this.props.place._id);
        const marker = new google.maps.Marker({
            position: this.props.place.geometry.location,
            map: map,
            title: this.props.place.address
        });
    }
    render() {
        return (

                            {this.props.place.name || this.props.place.address.formatted_address}

                            <button
                                type="button"
                                className="btn btn-danger"
                                onClick={() => this.props.onDelete(this.props.place._id)}
                            >

                            </button>

        );
    }
}

export default Map;
<commit_msg>Map fix field names<commit_after>import React, { h } from 'preact';

const styles = {
	mapCard: {
		margin: '10px 0'
	},
	map: {
		height: '200px'
	}
};

class Map extends React.Component {
	constructor(props) {
		super(props);
		// console.log('map props:' + JSON.stringify(props));
		// console.log('map props place:' + JSON.stringify(props.place));
	}
	componentDidMount() {
		const map = new google.maps.Map(document.getElementById('map-' + this.props.place._id), {
			zoom: 12,
			center: this.props.place.geometry.location
		});
		// console.log('map-' + this.props.place._id + ' address: ' + JSON.stringify(this.props.place.address));
		const marker = new google.maps.Marker({
			position: this.props.place.geometry.location,
			map: map,
			title: this.props.place.address.formatted_address
		});
	}
	render() {
		return (

							{this.props.place.name || this.props.place.address.formatted_address}

							<button
								type="button"
								className="btn btn-danger"
								onClick={() => this.props.onDelete(this.props.place._id)}
							>

							</button>

		);
	}
}

export default Map;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { MODE_NAMES, MODES } from '../reducers/microcontrollerEnums';
import { intersection, propOr } from 'ramda';
import './Pin.sass';
import rd3 from 'rd3';

export default class Pin extends Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
    tags: PropTypes.array.isRequired,
    pin: PropTypes.object.isRequired,
    changeMode: PropTypes.func.isRequired,
    setEnabled: PropTypes.func.isRequired,
    listen: PropTypes.func.isRequired,
    digitalWrite: PropTypes.func.isRequired,
    analogWrite: PropTypes.func.isRequired,
  };

  render() {
    const {
      changeMode,
      setEnabled,
      listen,
      digitalWrite,
      analogWrite,
      pin,
      name,
      tags
    } = this.props;
    const { id, mode, values } = pin;

    const supportedModes = intersection(
      pin.supportedModes,
      Object.keys(MODE_NAMES).map(k => parseInt(k, 10))
    );
    const getModeDescriptionForModeNumber = (num) => propOr('Not Set', num, MODE_NAMES);

    const data = [
      {
        name: 'series1',
        values,
      },
    ];

    const AreaChart = rd3.AreaChart;
    const chart = values.length === 0 ?
No data
 : (
      <AreaChart
        data={data}
        width="100%"
        height={200}
        viewBoxObject={{
          x: 0,
          y: 0,
          width: 500,
          height: 200
        }}
        title="Line Chart"
        yAxisLabel="Value (%)"
        xAxisTickValues={[]}
        xAxisLabel="Elapsed Time"
        domain={{ y: [0, 100] }}
        gridHorizontal
      />
    );

    const modeSelector = (
      <select
        defaultValue="{defaultMode}"
        onChange={event => changeMode(id, event.target.value)}
        disabled={supportedModes.length === 0}
      >
        {supportedModes.map((supportedMode) => (
          <option key={supportedMode} value={supportedMode}>
            {getModeDescriptionForModeNumber(supportedMode)}
          </option>
          )
        )}
      </select>
    );

    const pinClass = pin.isAnalogPin ? 'pin pin--analog' : 'pin pin--digital';

    const pinControls = () => {
      switch (mode) {
        case MODES.INPUT:
        case MODES.ANALOG:
          return (

               listen(id, mode, name)}>
                Listen

              {chart}

          );
        case MODES.OUTPUT:
          return (

              <input
                type="checkbox"
                onChange={(e) => digitalWrite(id, e.target.checked ? 1 : 0)}
              />

          );
        case MODES.PWM:
          return (
            <input
              type="range"
              name="pwm"
              min="0" max="255"
              defaultValue="0"
              onChange={(e) => analogWrite(id, e.target.value)}
            />
          );
        default:
          return

;
      }
    };

    return (

{name}

          {tags.map((tag) =>

{tag}

          )}

          <input
            type="checkbox"
            name="Enabled"
            checked={pin.enabled}
            onChange={(e) => setEnabled(pin.id, e.target.checked)}
          />
          Enabled
          {modeSelector}

          {pinControls(mode)}

    );
  }
}
<commit_msg>Remove chart labels<commit_after>import React, { Component, PropTypes } from 'react';
import { MODE_NAMES, MODES } from '../reducers/microcontrollerEnums';
import { intersection, propOr } from 'ramda';
import './Pin.sass';
import rd3 from 'rd3';

export default class Pin extends Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
    tags: PropTypes.array.isRequired,
    pin: PropTypes.object.isRequired,
    changeMode: PropTypes.func.isRequired,
    setEnabled: PropTypes.func.isRequired,
    listen: PropTypes.func.isRequired,
    digitalWrite: PropTypes.func.isRequired,
    analogWrite: PropTypes.func.isRequired,
  };

  render() {
    const {
      changeMode,
      setEnabled,
      listen,
      digitalWrite,
      analogWrite,
      pin,
      name,
      tags
    } = this.props;
    const { id, mode, values } = pin;

    const supportedModes = intersection(
      pin.supportedModes,
      Object.keys(MODE_NAMES).map(k => parseInt(k, 10))
    );
    const getModeDescriptionForModeNumber = (num) => propOr('Not Set', num, MODE_NAMES);

    const data = [
      {
        name: 'series1',
        values,
      },
    ];

    const AreaChart = rd3.AreaChart;
    const chart = values.length === 0 ?
No data
 : (
      <AreaChart
        data={data}
        width="100%"
        height={200}
        viewBoxObject={{
          x: 0,
          y: 0,
          width: 500,
          height: 200
        }}
        title="Line Chart"
        xAxisTickValues={[]}
        yAxisTicks="2"
        domain={{ y: [0, 100] }}
        gridHorizontal
      />
    );

    const modeSelector = (
      <select
        defaultValue="{defaultMode}"
        onChange={event => changeMode(id, event.target.value)}
        disabled={supportedModes.length === 0}
      >
        {supportedModes.map((supportedMode) => (
          <option key={supportedMode} value={supportedMode}>
            {getModeDescriptionForModeNumber(supportedMode)}
          </option>
          )
        )}
      </select>
    );

    const pinClass = pin.isAnalogPin ? 'pin pin--analog' : 'pin pin--digital';

    const pinControls = () => {
      switch (mode) {
        case MODES.INPUT:
        case MODES.ANALOG:
          return (

               listen(id, mode, name)}>
                Listen

              {chart}

          );
        case MODES.OUTPUT:
          return (

              <input
                type="checkbox"
                onChange={(e) => digitalWrite(id, e.target.checked ? 1 : 0)}
              />

          );
        case MODES.PWM:
          return (
            <input
              type="range"
              name="pwm"
              min="0" max="255"
              defaultValue="0"
              onChange={(e) => analogWrite(id, e.target.value)}
            />
          );
        default:
          return

;
      }
    };

    return (

{name}

          {tags.map((tag) =>

{tag}

          )}

          <input
            type="checkbox"
            name="Enabled"
            checked={pin.enabled}
            onChange={(e) => setEnabled(pin.id, e.target.checked)}
          />
          Enabled
          {modeSelector}

          {pinControls(mode)}

    );
  }
}
<|endoftext|>


<commit_before>//给按钮绑定事件
function handleButton() {
	var buttonGroup = document.querySelector('.button-group');
	buttonGroup.addEventListener('click',()=>{
		//获得点击的按钮并取得id和数字
		var target = event.target;
		var type = target.id;
		var number = document.getElementById('numberIn').value;
		//根据选取到的id对数队列进行操作；
		if(number){
			handleQueue(type,number);
		}
	});
}

//处理数组队列，主要是增加队列和减少队列
function handleQueue(type,number){
	var queue = document.querySelector('.number-queue');
	type.substr(-2,2) === 'in' ? addItem(type,number,queue) : deleteItem(type,queue);
}

function addItem(type,number,node){
	var item = document.createElement('span');
	item.setAttribute('class','queue-item');
	item.innerHTML = number;
	type === 'leftin' ? node.insertBefore(item,node.firstElementChild) : node.appendChild(item);
}

function deleteItem(type,node){
	var number;
	if (node.firstElementChild) {
		type === 'leftout'? number=node.removeChild(node.firstElementChild) : number=node.removeChild(node.lastElementChild);
		alert("您删除的是："+number.innerText);
	}

}

function deleteSelf(){
	var queue = document.querySelector('.number-queue');
	queue.addEventListener('click',(event)=>{
		if (event.target.nodeName === 'SPAN' && event.target.nodeType === 1) {
			queue.removeChild(event.target);
		}
	});
}

handleButton();
deleteSelf();

<commit_msg>update task5<commit_after>//给按钮绑定事件
function handleButton() {
	var buttonGroup = document.querySelector('.button-group');
	buttonGroup.addEventListener('click',()=>{
		//获得点击的按钮并取得id和数字
		var target = event.target;
		var type = target.id;
		var number = document.getElementById('numberIn').value;
		//根据选取到的id对数队列进行操作；
		if(Number(number)){
			handleQueue(type,number);
		}else {
			alert('请输入正确值');
		}
	});
}

//处理数组队列，主要是增加队列和减少队列
function handleQueue(type,number){
	var queue = document.querySelector('.number-queue');
	type.substr(-2,2) === 'in' ? addItem(type,number,queue) : deleteItem(type,queue);
}

function addItem(type,number,node){
	var item = document.createElement('span');
	item.setAttribute('class','queue-item');
	item.innerHTML = number;
	type === 'leftin' ? node.insertBefore(item,node.firstElementChild) : node.appendChild(item);
}

function deleteItem(type,node){
	var number;
	if (node.firstElementChild) {
		type === 'leftout'? number=node.removeChild(node.firstElementChild) : number=node.removeChild(node.lastElementChild);
		alert("您删除的是："+number.innerText);
	}

}

function deleteSelf(){
	var queue = document.querySelector('.number-queue');
	queue.addEventListener('click',(event)=>{
		if (event.target.nodeName === 'SPAN' && event.target.nodeType === 1) {
			queue.removeChild(event.target);
		}
	});
}

handleButton();
deleteSelf();

<|endoftext|>


<commit_before>var assert = require('assert');

describe('methods', function (){

  var f_ = require('./../../index.js');

  describe('#abort', function (){
    it('emits an abort event with an err_object.message prefixed with "abort, "', function (done){
      var test = new (f_.getConstructor({
        function_flow: []
      }));

      test.on('abort', function (err_object) {
        assert.equal(err_object.message, 'abort, test1');
        done();
      });

      test.f_abort('test1');
    });

    it('results in not calling any more functions from function_flow', function (done) {
      var next_called = false;

      var test = new (f_.getConstructor({
        function_flow: [
          { name: 'one', function: function () { this.f_abort(); } },
          { name: 'two', function: function () { this.f_next(); } }
        ]
      }));

      setTimeout(function () {
        assert.equal(next_called, false);
        done();
      }, 50);

      test.f_go();

      test.on('next', function () {
        next_called = true;
      });
    });
  });

  describe('#next', function () {
    it('calls all methods in the function_flow and emits the finish event', function (done) {
      var method1_called = false,
          method2_called = false;

          // @TODO FIX
      var instance = (new (f_.getConstructor({
        function_flow: [
          { name: 'one', function: function () { method1_called = true; this.f_next(); } },
          { name: 'two', function: function () { method2_called = true; this.f_next(); } }
        ]
      }))).f_go();

      setTimeout(function () {
        assert.equal(method1_called, true);
        assert.equal(method2_called, true);
        done();
      }, 50);
    });
    it('emits the finish event when all methods in function_flow are completed', function (done) {
      var method1_called = false,
          method2_called = false;

      var instance = new (f_.getConstructor({
        function_flow: [
          { name: 'one', function: function () { method1_called = true; this.f_next(); } },
          { name: 'two', function: function () { method2_called = true; this.f_next(); } }
        ]
      }));

      instance.on('finish', function () {
        done();
      });

      instance.f_go();
    });

  });

  describe('#go', function (){
    it('calls f_next with the passed arguments', function (done){
      var test = new (f_.getConstructor({
        function_flow: [
          { name: 'one',
            function: function (test1, test2) {
              assert.equal(test1, 'test1');
              assert.equal(test2, 'test2');
              done();
            }
          },
        ]
      }));

      test.f_go('test1', 'test2');
    });
  });

  describe('#retryAll', function (){
    var f_ = require('./../../index.js');

    it('resets f_flow_i to 0 and starts the flow from the first method specified in the function_flow', function (done){
      var methods_called = 0;

      var Constructor = f_.getConstructor({
        function_flow: [
          {
            name: 'm1',
            function: function () {
              methods_called++;
              this.f_next();
            },
            max_tries: 5
          },
          {
            name: 'm2',
            function: function () {
              methods_called++;
              this.f_retryAll();
            },
            max_tries: 5
          }
        ]
      });

      var instance = new Constructor();

      instance.f_go();

      assert.equal(methods_called, 10);
      done();
    });

    it('emits an retryAll event', function (done) {
      var Constructor = f_.getConstructor({
        function_flow: [
          {
            name: 'm1',
            function: function () {
              this.f_next();
            },
            max_tries: 1
          },
          {
            name: 'm2',
            function: function () {
              this.f_retryAll();
            },
            max_tries: 1
          }
        ]
      });

      var instance = new Constructor();

      instance.on('retryAll', function () {
        done();
      });

      instance.f_go();

    });
  });

});<commit_msg>Newlines<commit_after>var assert = require('assert');

describe('methods', function (){

  var f_ = require('./../../index.js');

  describe('#abort', function (){
    it('emits an abort event with an err_object.message prefixed with "abort, "', function (done){
      var test = new (f_.getConstructor({
        function_flow: []
      }));

      test.on('abort', function (err_object) {
        assert.equal(err_object.message, 'abort, test1');
        done();
      });

      test.f_abort('test1');
    });

    it('results in not calling any more functions from function_flow', function (done) {
      var next_called = false;

      var test = new (f_.getConstructor({
        function_flow: [
          { name: 'one', function: function () { this.f_abort(); } },
          { name: 'two', function: function () { this.f_next(); } }
        ]
      }));

      setTimeout(function () {
        assert.equal(next_called, false);
        done();
      }, 50);

      test.f_go();

      test.on('next', function () {
        next_called = true;
      });
    });
  });

  describe('#next', function () {
    it('calls all methods in the function_flow and emits the finish event', function (done) {
      var method1_called = false,
          method2_called = false;

          // @TODO FIX
      var instance = (new (f_.getConstructor({
        function_flow: [
          { name: 'one', function: function () { method1_called = true; this.f_next(); } },
          { name: 'two', function: function () { method2_called = true; this.f_next(); } }
        ]
      }))).f_go();

      setTimeout(function () {
        assert.equal(method1_called, true);
        assert.equal(method2_called, true);
        done();
      }, 50);
    });
    it('emits the finish event when all methods in function_flow are completed', function (done) {
      var method1_called = false,
          method2_called = false;

      var instance = new (f_.getConstructor({
        function_flow: [
          { name: 'one', function: function () { method1_called = true; this.f_next(); } },
          { name: 'two', function: function () { method2_called = true; this.f_next(); } }
        ]
      }));

      instance.on('finish', function () {
        done();
      });

      instance.f_go();
    });
    it('throws an error object when there is no function in function_flow (deletion?)', function (done) {
      var instance = new (f_.getConstructor({
        function_flow: [
          { name: 'one', function: function () { this.f_function_flow[1] = 'not a function'; this.f_next(); } },
          { name: 'two', function: function () { this.f_next(); } }
        ]
      }));

      instance.on('abort', function (err) {
        assert.equal(typeof err, 'object');
        done();
      });
    });

  });

  describe('#go', function (){
    it('calls f_next with the passed arguments', function (done){
      var test = new (f_.getConstructor({
        function_flow: [
          { name: 'one',
            function: function (test1, test2) {
              assert.equal(test1, 'test1');
              assert.equal(test2, 'test2');
              done();
            }
          },
        ]
      }));

      test.f_go('test1', 'test2');
    });
  });

  describe('#retryAll', function (){
    var f_ = require('./../../index.js');

    it('resets f_flow_i to 0 and starts the flow from the first method specified in the function_flow', function (done){
      var methods_called = 0;

      var Constructor = f_.getConstructor({
        function_flow: [
          {
            name: 'm1',
            function: function () {
              methods_called++;
              this.f_next();
            },
            max_tries: 5
          },
          {
            name: 'm2',
            function: function () {
              methods_called++;
              this.f_retryAll();
            },
            max_tries: 5
          }
        ]
      });

      var instance = new Constructor();

      instance.f_go();

      assert.equal(methods_called, 10);
      done();
    });

    it('emits an retryAll event', function (done) {
      var Constructor = f_.getConstructor({
        function_flow: [
          {
            name: 'm1',
            function: function () {
              this.f_next();
            },
            max_tries: 1
          },
          {
            name: 'm2',
            function: function () {
              this.f_retryAll();
            },
            max_tries: 1
          }
        ]
      });

      var instance = new Constructor();

      instance.on('retryAll', function () {
        done();
      });

      instance.f_go();

    });
  });

});<|endoftext|>