entities
listlengths
1
8.61k
max_stars_repo_path
stringlengths
7
172
max_stars_repo_name
stringlengths
5
89
max_stars_count
int64
0
82k
content
stringlengths
14
1.05M
id
stringlengths
2
6
new_content
stringlengths
15
1.05M
modified
bool
1 class
references
stringlengths
29
1.05M
[ { "context": "l 200\n\t\t\t\tlayer.states.current.name.should.equal \"testA\"\n\t\t\t\tlayer.stateCycle [\"testA\", \"testB\"], onEnd: ", "end": 16306, "score": 0.9354599714279175, "start": 16301, "tag": "NAME", "value": "testA" }, { "context": " 400\n\t\t\t\t\tlayer.states.current.name.should.equal \"testB\"\n\t\t\t\t\tlayer.stateCycle [\"testA\", \"testB\"], onEnd:", "end": 16439, "score": 0.8878051042556763, "start": 16434, "tag": "NAME", "value": "testB" }, { "context": "200\n\t\t\t\t\t\tlayer.states.current.name.should.equal \"testA\"\n\t\t\t\t\t\tdone()\n\n\t\tit \"should cycle list without op", "end": 16575, "score": 0.9291504621505737, "start": 16570, "tag": "NAME", "value": "testA" }, { "context": "d, ->\n\t\t\t\tlayer.states.current.name.should.equal \"testB\"\n\t\t\t\tlayer.once Events.StateSwitchEnd, ->\n\t\t\t\t\tla", "end": 16866, "score": 0.9385035037994385, "start": 16861, "tag": "NAME", "value": "testB" }, { "context": ", ->\n\t\t\t\t\tlayer.states.current.name.should.equal \"testA\"\n\t\t\t\t\tdone()\n\t\t\t\tlayer.stateCycle [\"testB\", \"test", "end": 16959, "score": 0.9395171403884888, "start": 16954, "tag": "NAME", "value": "testA" }, { "context": "d, ->\n\t\t\t\tlayer.states.current.name.should.equal \"testB\"\n\t\t\t\tlayer.once Events.StateSwitchEnd, ->\n\t\t\t\t\tla", "end": 17342, "score": 0.9051928520202637, "start": 17337, "tag": "NAME", "value": "testB" }, { "context": ", ->\n\t\t\t\t\tlayer.states.current.name.should.equal \"testA\"\n\t\t\t\t\tdone()\n\t\t\t\tlayer.stateCycle \"testB\", \"testA", "end": 17435, "score": 0.7591820359230042, "start": 17430, "tag": "NAME", "value": "testA" } ]
test/tests/LayerStatesTest.coffee
ig-la/Framer
3,817
assert = require "assert" {expect} = require "chai" initialStateName = "default" AnimationTime = 0.001 stateWithoutName = (state) -> return _.pickBy(state, (value, key) -> key isnt "name") describe "LayerStates", -> describe "Events", -> beforeEach -> @layer = new Layer() @layer.states.a = {x: 100, y: 100} @layer.states.b = {x: 200, y: 200} it "should emit StateSwitchStart when switching", (done) -> test = (previous, current, states) => previous.should.equal initialStateName current.should.equal "a" @layer.states.current.name.should.equal initialStateName @layer.states.machine._previousNames.should.eql [] stateWithoutName(@layer.states.current).should.eql @layer.states[initialStateName] done() @layer.on Events.StateSwitchStart, test @layer.animate "a", instant: true it "should emit StateSwitchStop when switching", (done) -> test = (previous, current, states) => previous.should.equal initialStateName current.should.equal "a" @layer.states.current.name.should.equal "a" @layer.states.machine._previousNames.should.eql ["default"] stateWithoutName(@layer.states.current).should.eql @layer.states.a done() @layer.on Events.StateSwitchStop, test @layer.animate "a", time: AnimationTime it "should emit StateSwitchStop when switching instant", (done) -> test = (previous, current, states) => previous.should.equal initialStateName current.should.equal "a" @layer.states.current.name.should.equal "a" @layer.states.machine._previousNames.should.eql ["default"] stateWithoutName(@layer.states.current).should.eql @layer.states.a done() @layer.on Events.StateSwitchStop, test @layer.animate "a", instant: true describe "Special states", -> it "should work for current", -> layer = new Layer layer.states.current.name.should.equal "default" it "should work for previous", -> layer = new Layer layer.states.testA = {x: 100} layer.stateSwitch("testA") layer.x.should.equal 100 layer.states.current.name.should.equal "testA" layer.states.current.x.should.equal 100 layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 it "should always have previous", -> layer = new Layer layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 describe "Defaults", -> it "should set defaults", -> layer = new Layer layer.states.test = {x: 123} animation = layer.animate "test" animation.options.curve.should.equal Framer.Curves.fromString(Framer.Defaults.Animation.curve) Framer.Defaults.Animation = curve: "spring(1, 2, 3)" layer = new Layer layer.states.test = {x: 456} animation = layer.animate "test" animator = animation.options.curve() animator.options.tension.should.equal 1 animator.options.friction.should.equal 2 animator.options.velocity.should.equal 3 Framer.resetDefaults() describe "Adding", -> describe "when setting multiple states", -> it "should override existing states", -> layer = new Layer layer.states.test = x: 100 layer.stateNames.sort().should.eql [initialStateName, "test"].sort() layer.states = stateA: x: 200 stateB: scale: 0.5 layer.stateNames.sort().should.eql [initialStateName, "stateA", "stateB"].sort() it "should reset the previous and current states", -> layer = new Layer layer.states.test = x: 100 layer.stateSwitch "test" layer.states = stateA: x: 200 stateB: scale: 0.5 layer.states.previous.name.should.equal initialStateName layer.states.current.name.should.equal initialStateName describe "Initial", -> testStates = (layer, states) -> layer.stateNames.sort().should.eql(states) Object.keys(layer.states).sort().should.eql(states) (k for k, v of layer.states).sort().should.eql(states) it "should have an initial state", -> layer = new Layer testStates(layer, [initialStateName]) it "should have an extra state", -> layer = new Layer layer.states.test = {x: 100} testStates(layer, [initialStateName, "test"]) describe "Switch", -> it "should switch instant", -> layer = new Layer layer.states = stateA: x: 123 stateB: y: 123 options: instant: true layer.stateSwitch "stateA" layer.states.current.name.should.equal "stateA" layer.x.should.equal 123 layer.stateSwitch "stateB" layer.states.current.name.should.equal "stateB" layer.y.should.equal 123 it "should not change html when using switch instant", -> layer = new Layer html: "fff" layer.states.stateA = {x: 100} layer.animate "stateA", instant: true layer.html.should.equal "fff" it "should switch non animatable properties", -> layer = new Layer layer.states.stateA = {x: 100, image: "static/test2.png"} layer.animate "stateA", instant: true layer.x.should.equal 100 layer.image.should.equal "static/test2.png" it "should not convert html to a color value if used in a state", -> layer = new Layer layer.states.stateA = {x: 100, html: "aaa"} layer.animate "stateA", instant: true layer.html.should.equal "aaa" it "should not change style when going back to initial", -> layer = new Layer layer.style.fontFamily = "Arial" layer.style.fontFamily.should.equal "Arial" layer.states = test: {x: 500} layer.animate "test", instant: true layer.x.should.equal 500 layer.style.fontFamily = "Helvetica" layer.style.fontFamily.should.equal "Helvetica" layer.animate initialStateName, instant: true layer.x.should.equal 0 layer.style.fontFamily.should.equal "Helvetica" # it "should be a no-op to change to the current state", -> # layer = new Layer # layer.states.stateA = {x: 100} # layer.stateSwitch "stateA" # animation = layer.animate "stateA", time: AnimationTime # assert.equal(animation, null) it "should change to a state when the properties defined are not the current", (done) -> layer = new Layer layer.states.stateA = {x: 100} layer.stateSwitch "stateA" layer.x = 150 layer.onStateDidSwitch -> layer.states.current.name.should.equal "stateA" layer.x.should.equal 100 done() animation = layer.animate "stateA", time: AnimationTime it "should change the state name when using 'previous' as stateName", (done) -> layer = new Layer layer.states = stateA: x: 200 stateB: scale: 0.5 layer.stateSwitch "stateB" layer.stateSwitch "stateA" layer.stateSwitch "stateB" layer.onStateDidSwitch -> assert.equal layer.states.current.name, "stateA" done() layer.animate "previous" describe "Properties", -> it "should bring back the 'initial' state values when using 'stateCycle'", (done) -> layer = new Layer layer.states = stateA: {x: 100, rotation: 90, options: time: AnimationTime} stateB: {x: 200, rotation: 180, options: time: AnimationTime} layer.x.should.equal 0 ready = (animation, layer) -> switch layer.states.current.name when "stateA" layer.x.should.equal 100 layer.rotation.should.equal 90 layer.stateCycle() when "stateB" layer.x.should.equal 200 layer.rotation.should.equal 180 layer.stateCycle(time: AnimationTime) when initialStateName layer.x.should.equal 0 layer.rotation.should.equal 0 done() layer.on Events.AnimationEnd, ready layer.stateCycle() it "should bring cycle when using 'stateCycle'", (done) -> layer = new Layer layer.states.stateA = x: 302 y: 445 layer.x.should.equal 0 layer.animationOptions.time = AnimationTime count = 0 ready = (animation, layer) -> if count is 4 done() return count++ switch layer.states.current.name when "stateA" layer.x.should.equal 302 layer.y.should.equal 445 layer.stateCycle(time: AnimationTime) when initialStateName layer.x.should.equal 0 layer.rotation.should.equal 0 layer.stateCycle(time: AnimationTime) layer.on Events.AnimationEnd, ready layer.stateCycle(time: AnimationTime) it "ignoreEvents should not be part of the initial state", -> layer = new Layer layer.states.stateA = backgroundColor: "rgba(255, 0, 255, 1)" layer.onClick -> layer.stateCycle() layer.x.should.equal 0 layer.stateCycle(instant: true) layer.stateCycle(instant: true) layer.stateCycle(instant: true) layer.ignoreEvents.should.equal false it "should set scroll property", -> layer = new Layer layer.states = stateA: {scroll: true} stateB: {scroll: false} layer.animate "stateA", instant: true layer.scroll.should.equal true layer.animate "stateB", instant: true layer.scroll.should.equal false layer.animate "stateA", instant: true layer.scroll.should.equal true it "should set non numeric properties with animation", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states = stateA: {scroll: true, backgroundColor: "red"} layer.scroll.should.equal false layer.on Events.StateDidSwitch, -> layer.scroll.should.equal true layer.style.backgroundColor.should.equal new Color("red").toString() done() layer.animate "stateA" it "should set non and numeric properties with animation", (done) -> layer = new Layer layer.states = stateA: {x: 200, backgroundColor: "red"} # layer.scroll.should.equal false layer.x.should.equal 0 layer.on Events.StateDidSwitch, -> # layer.scroll.should.equal true layer.x.should.equal 200 layer.style.backgroundColor.should.equal new Color("red").toString() done() layer.animate "stateA", {curve: "linear", time: AnimationTime} it "should restore the initial state when using non exportable properties", -> layer = new Layer layer.states = stateA: {midX: 200} layer.x.should.equal 0 layer.animate "stateA", instant: true layer.x.should.equal 200 - (layer.width // 2) layer.animate initialStateName, instant: true layer.x.should.equal 0 it "should set the parent", -> layerA = new Layer layerB = new Layer parent: layerA layerC = new Layer layerB.states = noParent: parent: null parentC: parent: layerC assert.equal(layerB.parent, layerA) layerB.animate "parentC", instant: true assert.equal(layerB.parent, layerC) layerB.animate "noParent", instant: true assert.equal(layerB.parent, null) layerB.animate initialStateName, instant: true # assert.equal(layerB.parent, layerA) it "should set the current and previous states when switching", -> layer = new Layer layer.states = stateA: {x: 100, options: instant: true} stateB: {y: 200, options: instant: true} layer.states.default.hasOwnProperty("name").should.equal false layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 layer.states.previous.y.should.equal 0 stateWithoutName(layer.states.previous).should.eql layer.states.default layer.states.default.hasOwnProperty("name").should.equal false layer.stateSwitch("stateA") layer.states.current.name.should.equal "stateA" layer.states.current.x.should.equal 100 layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 layer.states.previous.y.should.equal 0 stateWithoutName(layer.states.current).should.eql layer.states.stateA stateWithoutName(layer.states.previous).should.eql layer.states.default it "should set the default state when creating a", -> layer = new Layer layer.states.current.name.should.equal initialStateName layer.states.default.x.should.equal 0 it "should set the default state when creating b", -> layer = new Layer x: 100 layer.states.current.name.should.equal initialStateName layer.states.default.x.should.equal 100 it "should set the default state when creating c", -> layer = new Layer layer.states.default.x = 100 layer.states.current.name.should.equal initialStateName layer.states.default.x.should.equal 100 it "should capture shadowType as part of the default state", -> l = new Layer size: 60 borderRadius: 30 backgroundColor: "red" shadowColor: "blue" shadowSpread: 10 l.states.a = shadowColor: "red" shadowSpread: 3 l.stateSwitch "a" l.stateSwitch "default" l.style.boxShadow.should.equal "rgb(0, 0, 255) 0px 0px 0px 10px" it "should listen to options provided to stateCycle", -> layer = new Layer layer.states = stateA: x: 300 stateB: y: 300 animation = layer.stateCycle ["stateA", "stateB"], curve: Bezier.linear animation.options.curve.should.equal Bezier.linear it "should correctly switch to next state without using an array stateCycle", -> layer = new Layer layer.states = stateA: x: 300 stateB: y: 300 layer.stateCycle "stateA", "stateB", {instant: true} layer.states.current.name.should.equal "stateA" layer.stateCycle "stateA", "stateB", {instant: true} layer.states.current.name.should.equal "stateB" layer.stateCycle "stateA", "stateB", {instant: true} layer.states.current.name.should.equal "stateA" it "should listen to options provided to stateCycle when no states are provided", -> layer = new Layer layer.states.test = x: 300 animation = layer.stateCycle curve: "ease-in-out" animation.options.curve.should.equal Bezier.easeInOut # it "should throw an error when you try to override a special state", -> # layer = new Layer # throwing = -> # layer.states.initial = x: 300 # expect(throwing).to.throw('The state \'initial\' is a reserved name.') it "should throw an error when one fo the states is a special state", -> layer = new Layer throwing = -> layer.states = something: y: 10 previous: x: 300 expect(throwing).to.throw('The state \'previous\' is a reserved name.') describe "Cycling", -> it "should do nothing without states", -> layer = new Layer layer.stateCycle() layer.states.current.name.should.equal "default" it "should cycle two", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.test = {x: 200} layer.on Events.StateSwitchEnd, -> layer.states.current.name.should.equal "test" done() layer.stateCycle() it "should cycle two with options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.test = {x: 200} layer.stateCycle onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "test" layer.stateCycle onEnd: -> layer.x.should.equal 0 layer.states.current.name.should.equal "default" layer.stateCycle onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "test" done() it "should not touch the options object", (done) -> layer = new Layer layer.states.test = {x: 200} options = {time: AnimationTime} layer.stateCycle(options) layer.once Events.StateDidSwitch, -> layer.x.should.equal 200 layer.states.current.name.should.equal "test" layer.stateCycle(options) layer.once Events.StateDidSwitch, -> layer.x.should.equal 0 layer.states.current.name.should.equal "default" done() it "should cycle three with options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "testA" layer.stateCycle onEnd: -> layer.x.should.equal 400 layer.states.current.name.should.equal "testB" layer.stateCycle onEnd: -> layer.x.should.equal 0 layer.states.current.name.should.equal "default" done() it "should cycle two out of three in a list", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle ["testA", "testB"], onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "testA" layer.stateCycle ["testA", "testB"], onEnd: -> layer.x.should.equal 400 layer.states.current.name.should.equal "testB" layer.stateCycle ["testA", "testB"], onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "testA" done() it "should cycle list without options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "testB" layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "testA" done() layer.stateCycle ["testB", "testA"] layer.stateCycle ["testB", "testA"] it "should cycle multiple arguments without options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "testB" layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "testA" done() layer.stateCycle "testB", "testA" layer.stateCycle "testB", "testA" it "should cycle two out of three in arguments", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle "testA", "testB", onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "testA" layer.stateCycle "testA", "testB", onEnd: -> layer.x.should.equal 400 layer.states.current.name.should.equal "testB" layer.stateCycle "testA", "testB", onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "testA" done() it "should cycle all without state list", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testA" layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testB" layer.stateCycle onEnd: -> layer.states.current.name.should.equal "default" done() it "should listen to animationOptions defined in a state", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200, animationOptions: curve: Bezier.easeOut} cycle = layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testA" cycle2 = layer.stateCycle onEnd: -> layer.states.current.name.should.equal "default" cycle3 = layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testA" done() cycle3.options.curve.should.equal Bezier.easeOut layer.animationOptions.should.eql {time: AnimationTime} cycle2.options.curve.should.equal Bezier.ease layer.animationOptions.should.eql {time: AnimationTime} cycle.options.curve.should.equal Bezier.easeOut layer.animationOptions.should.eql {time: AnimationTime} describe "Switch", -> it "should switch", -> layer = new Layer layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.states.current.name.should.equal "default" layer.stateSwitch("testA") layer.states.current.name.should.equal "testA" layer.x.should.equal 200 layer.stateSwitch("testB") layer.x.should.equal 400 layer.states.current.name.should.equal "testB" it "should throw an error when called without a stateName", -> layer = new Layer layer.states.testA = {x: 200} expect(-> layer.stateSwitch()).to.throw("Missing required argument 'stateName' in stateSwitch()") describe "Options", -> it "should listen to layer.options", -> layer = new Layer layer.animationOptions = time: 4 animation = layer.animate x: 100 animation.options.time.should.equal 4 it "should listen to layer.animate options", -> layer = new Layer layer.states.test = {x: 100} animation = layer.animate "test", time: 4 animation.options.time.should.equal 4 it "should listen to layer.animate options.start", -> layer = new Layer layer.states.test = {x: 100} animation = layer.animate "test", start: false animation.isAnimating.should.equal false animation.start() animation.isAnimating.should.equal true describe "Callbacks", -> it "should call start", (done) -> layer = new Layer layer.states.test = x: 300 onStart = -> layer.x.should.eql 0 done() animation = layer.animate "test", onStart: onStart animation.options.onStart.should.equal onStart it "should call stop", (done) -> layer = new Layer layer.states.test = x: 300 onStop = -> layer.x.should.eql 300 done() animation = layer.animate "test", onStop: onStop time: AnimationTime animation.options.onStop.should.equal onStop it "should call end", (done) -> layer = new Layer layer.states.test = x: 300 onEnd = -> layer.x.should.eql 300 done() animation = layer.animate "test", onEnd: onEnd time: AnimationTime animation.options.onEnd.should.equal onEnd
102970
assert = require "assert" {expect} = require "chai" initialStateName = "default" AnimationTime = 0.001 stateWithoutName = (state) -> return _.pickBy(state, (value, key) -> key isnt "name") describe "LayerStates", -> describe "Events", -> beforeEach -> @layer = new Layer() @layer.states.a = {x: 100, y: 100} @layer.states.b = {x: 200, y: 200} it "should emit StateSwitchStart when switching", (done) -> test = (previous, current, states) => previous.should.equal initialStateName current.should.equal "a" @layer.states.current.name.should.equal initialStateName @layer.states.machine._previousNames.should.eql [] stateWithoutName(@layer.states.current).should.eql @layer.states[initialStateName] done() @layer.on Events.StateSwitchStart, test @layer.animate "a", instant: true it "should emit StateSwitchStop when switching", (done) -> test = (previous, current, states) => previous.should.equal initialStateName current.should.equal "a" @layer.states.current.name.should.equal "a" @layer.states.machine._previousNames.should.eql ["default"] stateWithoutName(@layer.states.current).should.eql @layer.states.a done() @layer.on Events.StateSwitchStop, test @layer.animate "a", time: AnimationTime it "should emit StateSwitchStop when switching instant", (done) -> test = (previous, current, states) => previous.should.equal initialStateName current.should.equal "a" @layer.states.current.name.should.equal "a" @layer.states.machine._previousNames.should.eql ["default"] stateWithoutName(@layer.states.current).should.eql @layer.states.a done() @layer.on Events.StateSwitchStop, test @layer.animate "a", instant: true describe "Special states", -> it "should work for current", -> layer = new Layer layer.states.current.name.should.equal "default" it "should work for previous", -> layer = new Layer layer.states.testA = {x: 100} layer.stateSwitch("testA") layer.x.should.equal 100 layer.states.current.name.should.equal "testA" layer.states.current.x.should.equal 100 layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 it "should always have previous", -> layer = new Layer layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 describe "Defaults", -> it "should set defaults", -> layer = new Layer layer.states.test = {x: 123} animation = layer.animate "test" animation.options.curve.should.equal Framer.Curves.fromString(Framer.Defaults.Animation.curve) Framer.Defaults.Animation = curve: "spring(1, 2, 3)" layer = new Layer layer.states.test = {x: 456} animation = layer.animate "test" animator = animation.options.curve() animator.options.tension.should.equal 1 animator.options.friction.should.equal 2 animator.options.velocity.should.equal 3 Framer.resetDefaults() describe "Adding", -> describe "when setting multiple states", -> it "should override existing states", -> layer = new Layer layer.states.test = x: 100 layer.stateNames.sort().should.eql [initialStateName, "test"].sort() layer.states = stateA: x: 200 stateB: scale: 0.5 layer.stateNames.sort().should.eql [initialStateName, "stateA", "stateB"].sort() it "should reset the previous and current states", -> layer = new Layer layer.states.test = x: 100 layer.stateSwitch "test" layer.states = stateA: x: 200 stateB: scale: 0.5 layer.states.previous.name.should.equal initialStateName layer.states.current.name.should.equal initialStateName describe "Initial", -> testStates = (layer, states) -> layer.stateNames.sort().should.eql(states) Object.keys(layer.states).sort().should.eql(states) (k for k, v of layer.states).sort().should.eql(states) it "should have an initial state", -> layer = new Layer testStates(layer, [initialStateName]) it "should have an extra state", -> layer = new Layer layer.states.test = {x: 100} testStates(layer, [initialStateName, "test"]) describe "Switch", -> it "should switch instant", -> layer = new Layer layer.states = stateA: x: 123 stateB: y: 123 options: instant: true layer.stateSwitch "stateA" layer.states.current.name.should.equal "stateA" layer.x.should.equal 123 layer.stateSwitch "stateB" layer.states.current.name.should.equal "stateB" layer.y.should.equal 123 it "should not change html when using switch instant", -> layer = new Layer html: "fff" layer.states.stateA = {x: 100} layer.animate "stateA", instant: true layer.html.should.equal "fff" it "should switch non animatable properties", -> layer = new Layer layer.states.stateA = {x: 100, image: "static/test2.png"} layer.animate "stateA", instant: true layer.x.should.equal 100 layer.image.should.equal "static/test2.png" it "should not convert html to a color value if used in a state", -> layer = new Layer layer.states.stateA = {x: 100, html: "aaa"} layer.animate "stateA", instant: true layer.html.should.equal "aaa" it "should not change style when going back to initial", -> layer = new Layer layer.style.fontFamily = "Arial" layer.style.fontFamily.should.equal "Arial" layer.states = test: {x: 500} layer.animate "test", instant: true layer.x.should.equal 500 layer.style.fontFamily = "Helvetica" layer.style.fontFamily.should.equal "Helvetica" layer.animate initialStateName, instant: true layer.x.should.equal 0 layer.style.fontFamily.should.equal "Helvetica" # it "should be a no-op to change to the current state", -> # layer = new Layer # layer.states.stateA = {x: 100} # layer.stateSwitch "stateA" # animation = layer.animate "stateA", time: AnimationTime # assert.equal(animation, null) it "should change to a state when the properties defined are not the current", (done) -> layer = new Layer layer.states.stateA = {x: 100} layer.stateSwitch "stateA" layer.x = 150 layer.onStateDidSwitch -> layer.states.current.name.should.equal "stateA" layer.x.should.equal 100 done() animation = layer.animate "stateA", time: AnimationTime it "should change the state name when using 'previous' as stateName", (done) -> layer = new Layer layer.states = stateA: x: 200 stateB: scale: 0.5 layer.stateSwitch "stateB" layer.stateSwitch "stateA" layer.stateSwitch "stateB" layer.onStateDidSwitch -> assert.equal layer.states.current.name, "stateA" done() layer.animate "previous" describe "Properties", -> it "should bring back the 'initial' state values when using 'stateCycle'", (done) -> layer = new Layer layer.states = stateA: {x: 100, rotation: 90, options: time: AnimationTime} stateB: {x: 200, rotation: 180, options: time: AnimationTime} layer.x.should.equal 0 ready = (animation, layer) -> switch layer.states.current.name when "stateA" layer.x.should.equal 100 layer.rotation.should.equal 90 layer.stateCycle() when "stateB" layer.x.should.equal 200 layer.rotation.should.equal 180 layer.stateCycle(time: AnimationTime) when initialStateName layer.x.should.equal 0 layer.rotation.should.equal 0 done() layer.on Events.AnimationEnd, ready layer.stateCycle() it "should bring cycle when using 'stateCycle'", (done) -> layer = new Layer layer.states.stateA = x: 302 y: 445 layer.x.should.equal 0 layer.animationOptions.time = AnimationTime count = 0 ready = (animation, layer) -> if count is 4 done() return count++ switch layer.states.current.name when "stateA" layer.x.should.equal 302 layer.y.should.equal 445 layer.stateCycle(time: AnimationTime) when initialStateName layer.x.should.equal 0 layer.rotation.should.equal 0 layer.stateCycle(time: AnimationTime) layer.on Events.AnimationEnd, ready layer.stateCycle(time: AnimationTime) it "ignoreEvents should not be part of the initial state", -> layer = new Layer layer.states.stateA = backgroundColor: "rgba(255, 0, 255, 1)" layer.onClick -> layer.stateCycle() layer.x.should.equal 0 layer.stateCycle(instant: true) layer.stateCycle(instant: true) layer.stateCycle(instant: true) layer.ignoreEvents.should.equal false it "should set scroll property", -> layer = new Layer layer.states = stateA: {scroll: true} stateB: {scroll: false} layer.animate "stateA", instant: true layer.scroll.should.equal true layer.animate "stateB", instant: true layer.scroll.should.equal false layer.animate "stateA", instant: true layer.scroll.should.equal true it "should set non numeric properties with animation", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states = stateA: {scroll: true, backgroundColor: "red"} layer.scroll.should.equal false layer.on Events.StateDidSwitch, -> layer.scroll.should.equal true layer.style.backgroundColor.should.equal new Color("red").toString() done() layer.animate "stateA" it "should set non and numeric properties with animation", (done) -> layer = new Layer layer.states = stateA: {x: 200, backgroundColor: "red"} # layer.scroll.should.equal false layer.x.should.equal 0 layer.on Events.StateDidSwitch, -> # layer.scroll.should.equal true layer.x.should.equal 200 layer.style.backgroundColor.should.equal new Color("red").toString() done() layer.animate "stateA", {curve: "linear", time: AnimationTime} it "should restore the initial state when using non exportable properties", -> layer = new Layer layer.states = stateA: {midX: 200} layer.x.should.equal 0 layer.animate "stateA", instant: true layer.x.should.equal 200 - (layer.width // 2) layer.animate initialStateName, instant: true layer.x.should.equal 0 it "should set the parent", -> layerA = new Layer layerB = new Layer parent: layerA layerC = new Layer layerB.states = noParent: parent: null parentC: parent: layerC assert.equal(layerB.parent, layerA) layerB.animate "parentC", instant: true assert.equal(layerB.parent, layerC) layerB.animate "noParent", instant: true assert.equal(layerB.parent, null) layerB.animate initialStateName, instant: true # assert.equal(layerB.parent, layerA) it "should set the current and previous states when switching", -> layer = new Layer layer.states = stateA: {x: 100, options: instant: true} stateB: {y: 200, options: instant: true} layer.states.default.hasOwnProperty("name").should.equal false layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 layer.states.previous.y.should.equal 0 stateWithoutName(layer.states.previous).should.eql layer.states.default layer.states.default.hasOwnProperty("name").should.equal false layer.stateSwitch("stateA") layer.states.current.name.should.equal "stateA" layer.states.current.x.should.equal 100 layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 layer.states.previous.y.should.equal 0 stateWithoutName(layer.states.current).should.eql layer.states.stateA stateWithoutName(layer.states.previous).should.eql layer.states.default it "should set the default state when creating a", -> layer = new Layer layer.states.current.name.should.equal initialStateName layer.states.default.x.should.equal 0 it "should set the default state when creating b", -> layer = new Layer x: 100 layer.states.current.name.should.equal initialStateName layer.states.default.x.should.equal 100 it "should set the default state when creating c", -> layer = new Layer layer.states.default.x = 100 layer.states.current.name.should.equal initialStateName layer.states.default.x.should.equal 100 it "should capture shadowType as part of the default state", -> l = new Layer size: 60 borderRadius: 30 backgroundColor: "red" shadowColor: "blue" shadowSpread: 10 l.states.a = shadowColor: "red" shadowSpread: 3 l.stateSwitch "a" l.stateSwitch "default" l.style.boxShadow.should.equal "rgb(0, 0, 255) 0px 0px 0px 10px" it "should listen to options provided to stateCycle", -> layer = new Layer layer.states = stateA: x: 300 stateB: y: 300 animation = layer.stateCycle ["stateA", "stateB"], curve: Bezier.linear animation.options.curve.should.equal Bezier.linear it "should correctly switch to next state without using an array stateCycle", -> layer = new Layer layer.states = stateA: x: 300 stateB: y: 300 layer.stateCycle "stateA", "stateB", {instant: true} layer.states.current.name.should.equal "stateA" layer.stateCycle "stateA", "stateB", {instant: true} layer.states.current.name.should.equal "stateB" layer.stateCycle "stateA", "stateB", {instant: true} layer.states.current.name.should.equal "stateA" it "should listen to options provided to stateCycle when no states are provided", -> layer = new Layer layer.states.test = x: 300 animation = layer.stateCycle curve: "ease-in-out" animation.options.curve.should.equal Bezier.easeInOut # it "should throw an error when you try to override a special state", -> # layer = new Layer # throwing = -> # layer.states.initial = x: 300 # expect(throwing).to.throw('The state \'initial\' is a reserved name.') it "should throw an error when one fo the states is a special state", -> layer = new Layer throwing = -> layer.states = something: y: 10 previous: x: 300 expect(throwing).to.throw('The state \'previous\' is a reserved name.') describe "Cycling", -> it "should do nothing without states", -> layer = new Layer layer.stateCycle() layer.states.current.name.should.equal "default" it "should cycle two", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.test = {x: 200} layer.on Events.StateSwitchEnd, -> layer.states.current.name.should.equal "test" done() layer.stateCycle() it "should cycle two with options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.test = {x: 200} layer.stateCycle onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "test" layer.stateCycle onEnd: -> layer.x.should.equal 0 layer.states.current.name.should.equal "default" layer.stateCycle onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "test" done() it "should not touch the options object", (done) -> layer = new Layer layer.states.test = {x: 200} options = {time: AnimationTime} layer.stateCycle(options) layer.once Events.StateDidSwitch, -> layer.x.should.equal 200 layer.states.current.name.should.equal "test" layer.stateCycle(options) layer.once Events.StateDidSwitch, -> layer.x.should.equal 0 layer.states.current.name.should.equal "default" done() it "should cycle three with options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "testA" layer.stateCycle onEnd: -> layer.x.should.equal 400 layer.states.current.name.should.equal "testB" layer.stateCycle onEnd: -> layer.x.should.equal 0 layer.states.current.name.should.equal "default" done() it "should cycle two out of three in a list", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle ["testA", "testB"], onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "<NAME>" layer.stateCycle ["testA", "testB"], onEnd: -> layer.x.should.equal 400 layer.states.current.name.should.equal "<NAME>" layer.stateCycle ["testA", "testB"], onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "<NAME>" done() it "should cycle list without options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "<NAME>" layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "<NAME>" done() layer.stateCycle ["testB", "testA"] layer.stateCycle ["testB", "testA"] it "should cycle multiple arguments without options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "<NAME>" layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "<NAME>" done() layer.stateCycle "testB", "testA" layer.stateCycle "testB", "testA" it "should cycle two out of three in arguments", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle "testA", "testB", onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "testA" layer.stateCycle "testA", "testB", onEnd: -> layer.x.should.equal 400 layer.states.current.name.should.equal "testB" layer.stateCycle "testA", "testB", onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "testA" done() it "should cycle all without state list", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testA" layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testB" layer.stateCycle onEnd: -> layer.states.current.name.should.equal "default" done() it "should listen to animationOptions defined in a state", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200, animationOptions: curve: Bezier.easeOut} cycle = layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testA" cycle2 = layer.stateCycle onEnd: -> layer.states.current.name.should.equal "default" cycle3 = layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testA" done() cycle3.options.curve.should.equal Bezier.easeOut layer.animationOptions.should.eql {time: AnimationTime} cycle2.options.curve.should.equal Bezier.ease layer.animationOptions.should.eql {time: AnimationTime} cycle.options.curve.should.equal Bezier.easeOut layer.animationOptions.should.eql {time: AnimationTime} describe "Switch", -> it "should switch", -> layer = new Layer layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.states.current.name.should.equal "default" layer.stateSwitch("testA") layer.states.current.name.should.equal "testA" layer.x.should.equal 200 layer.stateSwitch("testB") layer.x.should.equal 400 layer.states.current.name.should.equal "testB" it "should throw an error when called without a stateName", -> layer = new Layer layer.states.testA = {x: 200} expect(-> layer.stateSwitch()).to.throw("Missing required argument 'stateName' in stateSwitch()") describe "Options", -> it "should listen to layer.options", -> layer = new Layer layer.animationOptions = time: 4 animation = layer.animate x: 100 animation.options.time.should.equal 4 it "should listen to layer.animate options", -> layer = new Layer layer.states.test = {x: 100} animation = layer.animate "test", time: 4 animation.options.time.should.equal 4 it "should listen to layer.animate options.start", -> layer = new Layer layer.states.test = {x: 100} animation = layer.animate "test", start: false animation.isAnimating.should.equal false animation.start() animation.isAnimating.should.equal true describe "Callbacks", -> it "should call start", (done) -> layer = new Layer layer.states.test = x: 300 onStart = -> layer.x.should.eql 0 done() animation = layer.animate "test", onStart: onStart animation.options.onStart.should.equal onStart it "should call stop", (done) -> layer = new Layer layer.states.test = x: 300 onStop = -> layer.x.should.eql 300 done() animation = layer.animate "test", onStop: onStop time: AnimationTime animation.options.onStop.should.equal onStop it "should call end", (done) -> layer = new Layer layer.states.test = x: 300 onEnd = -> layer.x.should.eql 300 done() animation = layer.animate "test", onEnd: onEnd time: AnimationTime animation.options.onEnd.should.equal onEnd
true
assert = require "assert" {expect} = require "chai" initialStateName = "default" AnimationTime = 0.001 stateWithoutName = (state) -> return _.pickBy(state, (value, key) -> key isnt "name") describe "LayerStates", -> describe "Events", -> beforeEach -> @layer = new Layer() @layer.states.a = {x: 100, y: 100} @layer.states.b = {x: 200, y: 200} it "should emit StateSwitchStart when switching", (done) -> test = (previous, current, states) => previous.should.equal initialStateName current.should.equal "a" @layer.states.current.name.should.equal initialStateName @layer.states.machine._previousNames.should.eql [] stateWithoutName(@layer.states.current).should.eql @layer.states[initialStateName] done() @layer.on Events.StateSwitchStart, test @layer.animate "a", instant: true it "should emit StateSwitchStop when switching", (done) -> test = (previous, current, states) => previous.should.equal initialStateName current.should.equal "a" @layer.states.current.name.should.equal "a" @layer.states.machine._previousNames.should.eql ["default"] stateWithoutName(@layer.states.current).should.eql @layer.states.a done() @layer.on Events.StateSwitchStop, test @layer.animate "a", time: AnimationTime it "should emit StateSwitchStop when switching instant", (done) -> test = (previous, current, states) => previous.should.equal initialStateName current.should.equal "a" @layer.states.current.name.should.equal "a" @layer.states.machine._previousNames.should.eql ["default"] stateWithoutName(@layer.states.current).should.eql @layer.states.a done() @layer.on Events.StateSwitchStop, test @layer.animate "a", instant: true describe "Special states", -> it "should work for current", -> layer = new Layer layer.states.current.name.should.equal "default" it "should work for previous", -> layer = new Layer layer.states.testA = {x: 100} layer.stateSwitch("testA") layer.x.should.equal 100 layer.states.current.name.should.equal "testA" layer.states.current.x.should.equal 100 layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 it "should always have previous", -> layer = new Layer layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 describe "Defaults", -> it "should set defaults", -> layer = new Layer layer.states.test = {x: 123} animation = layer.animate "test" animation.options.curve.should.equal Framer.Curves.fromString(Framer.Defaults.Animation.curve) Framer.Defaults.Animation = curve: "spring(1, 2, 3)" layer = new Layer layer.states.test = {x: 456} animation = layer.animate "test" animator = animation.options.curve() animator.options.tension.should.equal 1 animator.options.friction.should.equal 2 animator.options.velocity.should.equal 3 Framer.resetDefaults() describe "Adding", -> describe "when setting multiple states", -> it "should override existing states", -> layer = new Layer layer.states.test = x: 100 layer.stateNames.sort().should.eql [initialStateName, "test"].sort() layer.states = stateA: x: 200 stateB: scale: 0.5 layer.stateNames.sort().should.eql [initialStateName, "stateA", "stateB"].sort() it "should reset the previous and current states", -> layer = new Layer layer.states.test = x: 100 layer.stateSwitch "test" layer.states = stateA: x: 200 stateB: scale: 0.5 layer.states.previous.name.should.equal initialStateName layer.states.current.name.should.equal initialStateName describe "Initial", -> testStates = (layer, states) -> layer.stateNames.sort().should.eql(states) Object.keys(layer.states).sort().should.eql(states) (k for k, v of layer.states).sort().should.eql(states) it "should have an initial state", -> layer = new Layer testStates(layer, [initialStateName]) it "should have an extra state", -> layer = new Layer layer.states.test = {x: 100} testStates(layer, [initialStateName, "test"]) describe "Switch", -> it "should switch instant", -> layer = new Layer layer.states = stateA: x: 123 stateB: y: 123 options: instant: true layer.stateSwitch "stateA" layer.states.current.name.should.equal "stateA" layer.x.should.equal 123 layer.stateSwitch "stateB" layer.states.current.name.should.equal "stateB" layer.y.should.equal 123 it "should not change html when using switch instant", -> layer = new Layer html: "fff" layer.states.stateA = {x: 100} layer.animate "stateA", instant: true layer.html.should.equal "fff" it "should switch non animatable properties", -> layer = new Layer layer.states.stateA = {x: 100, image: "static/test2.png"} layer.animate "stateA", instant: true layer.x.should.equal 100 layer.image.should.equal "static/test2.png" it "should not convert html to a color value if used in a state", -> layer = new Layer layer.states.stateA = {x: 100, html: "aaa"} layer.animate "stateA", instant: true layer.html.should.equal "aaa" it "should not change style when going back to initial", -> layer = new Layer layer.style.fontFamily = "Arial" layer.style.fontFamily.should.equal "Arial" layer.states = test: {x: 500} layer.animate "test", instant: true layer.x.should.equal 500 layer.style.fontFamily = "Helvetica" layer.style.fontFamily.should.equal "Helvetica" layer.animate initialStateName, instant: true layer.x.should.equal 0 layer.style.fontFamily.should.equal "Helvetica" # it "should be a no-op to change to the current state", -> # layer = new Layer # layer.states.stateA = {x: 100} # layer.stateSwitch "stateA" # animation = layer.animate "stateA", time: AnimationTime # assert.equal(animation, null) it "should change to a state when the properties defined are not the current", (done) -> layer = new Layer layer.states.stateA = {x: 100} layer.stateSwitch "stateA" layer.x = 150 layer.onStateDidSwitch -> layer.states.current.name.should.equal "stateA" layer.x.should.equal 100 done() animation = layer.animate "stateA", time: AnimationTime it "should change the state name when using 'previous' as stateName", (done) -> layer = new Layer layer.states = stateA: x: 200 stateB: scale: 0.5 layer.stateSwitch "stateB" layer.stateSwitch "stateA" layer.stateSwitch "stateB" layer.onStateDidSwitch -> assert.equal layer.states.current.name, "stateA" done() layer.animate "previous" describe "Properties", -> it "should bring back the 'initial' state values when using 'stateCycle'", (done) -> layer = new Layer layer.states = stateA: {x: 100, rotation: 90, options: time: AnimationTime} stateB: {x: 200, rotation: 180, options: time: AnimationTime} layer.x.should.equal 0 ready = (animation, layer) -> switch layer.states.current.name when "stateA" layer.x.should.equal 100 layer.rotation.should.equal 90 layer.stateCycle() when "stateB" layer.x.should.equal 200 layer.rotation.should.equal 180 layer.stateCycle(time: AnimationTime) when initialStateName layer.x.should.equal 0 layer.rotation.should.equal 0 done() layer.on Events.AnimationEnd, ready layer.stateCycle() it "should bring cycle when using 'stateCycle'", (done) -> layer = new Layer layer.states.stateA = x: 302 y: 445 layer.x.should.equal 0 layer.animationOptions.time = AnimationTime count = 0 ready = (animation, layer) -> if count is 4 done() return count++ switch layer.states.current.name when "stateA" layer.x.should.equal 302 layer.y.should.equal 445 layer.stateCycle(time: AnimationTime) when initialStateName layer.x.should.equal 0 layer.rotation.should.equal 0 layer.stateCycle(time: AnimationTime) layer.on Events.AnimationEnd, ready layer.stateCycle(time: AnimationTime) it "ignoreEvents should not be part of the initial state", -> layer = new Layer layer.states.stateA = backgroundColor: "rgba(255, 0, 255, 1)" layer.onClick -> layer.stateCycle() layer.x.should.equal 0 layer.stateCycle(instant: true) layer.stateCycle(instant: true) layer.stateCycle(instant: true) layer.ignoreEvents.should.equal false it "should set scroll property", -> layer = new Layer layer.states = stateA: {scroll: true} stateB: {scroll: false} layer.animate "stateA", instant: true layer.scroll.should.equal true layer.animate "stateB", instant: true layer.scroll.should.equal false layer.animate "stateA", instant: true layer.scroll.should.equal true it "should set non numeric properties with animation", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states = stateA: {scroll: true, backgroundColor: "red"} layer.scroll.should.equal false layer.on Events.StateDidSwitch, -> layer.scroll.should.equal true layer.style.backgroundColor.should.equal new Color("red").toString() done() layer.animate "stateA" it "should set non and numeric properties with animation", (done) -> layer = new Layer layer.states = stateA: {x: 200, backgroundColor: "red"} # layer.scroll.should.equal false layer.x.should.equal 0 layer.on Events.StateDidSwitch, -> # layer.scroll.should.equal true layer.x.should.equal 200 layer.style.backgroundColor.should.equal new Color("red").toString() done() layer.animate "stateA", {curve: "linear", time: AnimationTime} it "should restore the initial state when using non exportable properties", -> layer = new Layer layer.states = stateA: {midX: 200} layer.x.should.equal 0 layer.animate "stateA", instant: true layer.x.should.equal 200 - (layer.width // 2) layer.animate initialStateName, instant: true layer.x.should.equal 0 it "should set the parent", -> layerA = new Layer layerB = new Layer parent: layerA layerC = new Layer layerB.states = noParent: parent: null parentC: parent: layerC assert.equal(layerB.parent, layerA) layerB.animate "parentC", instant: true assert.equal(layerB.parent, layerC) layerB.animate "noParent", instant: true assert.equal(layerB.parent, null) layerB.animate initialStateName, instant: true # assert.equal(layerB.parent, layerA) it "should set the current and previous states when switching", -> layer = new Layer layer.states = stateA: {x: 100, options: instant: true} stateB: {y: 200, options: instant: true} layer.states.default.hasOwnProperty("name").should.equal false layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 layer.states.previous.y.should.equal 0 stateWithoutName(layer.states.previous).should.eql layer.states.default layer.states.default.hasOwnProperty("name").should.equal false layer.stateSwitch("stateA") layer.states.current.name.should.equal "stateA" layer.states.current.x.should.equal 100 layer.states.previous.name.should.equal "default" layer.states.previous.x.should.equal 0 layer.states.previous.y.should.equal 0 stateWithoutName(layer.states.current).should.eql layer.states.stateA stateWithoutName(layer.states.previous).should.eql layer.states.default it "should set the default state when creating a", -> layer = new Layer layer.states.current.name.should.equal initialStateName layer.states.default.x.should.equal 0 it "should set the default state when creating b", -> layer = new Layer x: 100 layer.states.current.name.should.equal initialStateName layer.states.default.x.should.equal 100 it "should set the default state when creating c", -> layer = new Layer layer.states.default.x = 100 layer.states.current.name.should.equal initialStateName layer.states.default.x.should.equal 100 it "should capture shadowType as part of the default state", -> l = new Layer size: 60 borderRadius: 30 backgroundColor: "red" shadowColor: "blue" shadowSpread: 10 l.states.a = shadowColor: "red" shadowSpread: 3 l.stateSwitch "a" l.stateSwitch "default" l.style.boxShadow.should.equal "rgb(0, 0, 255) 0px 0px 0px 10px" it "should listen to options provided to stateCycle", -> layer = new Layer layer.states = stateA: x: 300 stateB: y: 300 animation = layer.stateCycle ["stateA", "stateB"], curve: Bezier.linear animation.options.curve.should.equal Bezier.linear it "should correctly switch to next state without using an array stateCycle", -> layer = new Layer layer.states = stateA: x: 300 stateB: y: 300 layer.stateCycle "stateA", "stateB", {instant: true} layer.states.current.name.should.equal "stateA" layer.stateCycle "stateA", "stateB", {instant: true} layer.states.current.name.should.equal "stateB" layer.stateCycle "stateA", "stateB", {instant: true} layer.states.current.name.should.equal "stateA" it "should listen to options provided to stateCycle when no states are provided", -> layer = new Layer layer.states.test = x: 300 animation = layer.stateCycle curve: "ease-in-out" animation.options.curve.should.equal Bezier.easeInOut # it "should throw an error when you try to override a special state", -> # layer = new Layer # throwing = -> # layer.states.initial = x: 300 # expect(throwing).to.throw('The state \'initial\' is a reserved name.') it "should throw an error when one fo the states is a special state", -> layer = new Layer throwing = -> layer.states = something: y: 10 previous: x: 300 expect(throwing).to.throw('The state \'previous\' is a reserved name.') describe "Cycling", -> it "should do nothing without states", -> layer = new Layer layer.stateCycle() layer.states.current.name.should.equal "default" it "should cycle two", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.test = {x: 200} layer.on Events.StateSwitchEnd, -> layer.states.current.name.should.equal "test" done() layer.stateCycle() it "should cycle two with options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.test = {x: 200} layer.stateCycle onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "test" layer.stateCycle onEnd: -> layer.x.should.equal 0 layer.states.current.name.should.equal "default" layer.stateCycle onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "test" done() it "should not touch the options object", (done) -> layer = new Layer layer.states.test = {x: 200} options = {time: AnimationTime} layer.stateCycle(options) layer.once Events.StateDidSwitch, -> layer.x.should.equal 200 layer.states.current.name.should.equal "test" layer.stateCycle(options) layer.once Events.StateDidSwitch, -> layer.x.should.equal 0 layer.states.current.name.should.equal "default" done() it "should cycle three with options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "testA" layer.stateCycle onEnd: -> layer.x.should.equal 400 layer.states.current.name.should.equal "testB" layer.stateCycle onEnd: -> layer.x.should.equal 0 layer.states.current.name.should.equal "default" done() it "should cycle two out of three in a list", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle ["testA", "testB"], onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "PI:NAME:<NAME>END_PI" layer.stateCycle ["testA", "testB"], onEnd: -> layer.x.should.equal 400 layer.states.current.name.should.equal "PI:NAME:<NAME>END_PI" layer.stateCycle ["testA", "testB"], onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "PI:NAME:<NAME>END_PI" done() it "should cycle list without options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "PI:NAME:<NAME>END_PI" layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "PI:NAME:<NAME>END_PI" done() layer.stateCycle ["testB", "testA"] layer.stateCycle ["testB", "testA"] it "should cycle multiple arguments without options", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "PI:NAME:<NAME>END_PI" layer.once Events.StateSwitchEnd, -> layer.states.current.name.should.equal "PI:NAME:<NAME>END_PI" done() layer.stateCycle "testB", "testA" layer.stateCycle "testB", "testA" it "should cycle two out of three in arguments", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle "testA", "testB", onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "testA" layer.stateCycle "testA", "testB", onEnd: -> layer.x.should.equal 400 layer.states.current.name.should.equal "testB" layer.stateCycle "testA", "testB", onEnd: -> layer.x.should.equal 200 layer.states.current.name.should.equal "testA" done() it "should cycle all without state list", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testA" layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testB" layer.stateCycle onEnd: -> layer.states.current.name.should.equal "default" done() it "should listen to animationOptions defined in a state", (done) -> layer = new Layer layer.animationOptions.time = AnimationTime layer.states.testA = {x: 200, animationOptions: curve: Bezier.easeOut} cycle = layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testA" cycle2 = layer.stateCycle onEnd: -> layer.states.current.name.should.equal "default" cycle3 = layer.stateCycle onEnd: -> layer.states.current.name.should.equal "testA" done() cycle3.options.curve.should.equal Bezier.easeOut layer.animationOptions.should.eql {time: AnimationTime} cycle2.options.curve.should.equal Bezier.ease layer.animationOptions.should.eql {time: AnimationTime} cycle.options.curve.should.equal Bezier.easeOut layer.animationOptions.should.eql {time: AnimationTime} describe "Switch", -> it "should switch", -> layer = new Layer layer.states.testA = {x: 200} layer.states.testB = {x: 400} layer.states.current.name.should.equal "default" layer.stateSwitch("testA") layer.states.current.name.should.equal "testA" layer.x.should.equal 200 layer.stateSwitch("testB") layer.x.should.equal 400 layer.states.current.name.should.equal "testB" it "should throw an error when called without a stateName", -> layer = new Layer layer.states.testA = {x: 200} expect(-> layer.stateSwitch()).to.throw("Missing required argument 'stateName' in stateSwitch()") describe "Options", -> it "should listen to layer.options", -> layer = new Layer layer.animationOptions = time: 4 animation = layer.animate x: 100 animation.options.time.should.equal 4 it "should listen to layer.animate options", -> layer = new Layer layer.states.test = {x: 100} animation = layer.animate "test", time: 4 animation.options.time.should.equal 4 it "should listen to layer.animate options.start", -> layer = new Layer layer.states.test = {x: 100} animation = layer.animate "test", start: false animation.isAnimating.should.equal false animation.start() animation.isAnimating.should.equal true describe "Callbacks", -> it "should call start", (done) -> layer = new Layer layer.states.test = x: 300 onStart = -> layer.x.should.eql 0 done() animation = layer.animate "test", onStart: onStart animation.options.onStart.should.equal onStart it "should call stop", (done) -> layer = new Layer layer.states.test = x: 300 onStop = -> layer.x.should.eql 300 done() animation = layer.animate "test", onStop: onStop time: AnimationTime animation.options.onStop.should.equal onStop it "should call end", (done) -> layer = new Layer layer.states.test = x: 300 onEnd = -> layer.x.should.eql 300 done() animation = layer.animate "test", onEnd: onEnd time: AnimationTime animation.options.onEnd.should.equal onEnd
[ { "context": "t\n\t\tusername: knexfile.connection.user\n\t\tpassword: knexfile.connection.password\n\t\tdatabase: knexfile.connection.database\n\t\tdebug:", "end": 2653, "score": 0.9991934895515442, "start": 2625, "tag": "PASSWORD", "value": "knexfile.connection.password" } ]
app.coffee
joepie91/pdfy2
11
express = require('express') uuid = require "uuid" fs = require "fs" domain = require "domain" app = express() reportError = (err, type = "error", sync = false) -> if err.code == "ECONNRESET" # We're not interested in these for now, they're just aborted requests. # TODO: Investigate whether there may also be other scenarios where an ECONNRESET is raised. return errorPayload = {} Object.getOwnPropertyNames(err).forEach (key) -> errorPayload[key] = err[key] filename = "errors/#{type}-#{Date.now()}-#{uuid.v4()}.json" if sync fs.writeFileSync filename, JSON.stringify(errorPayload) else fs.writeFile filename, JSON.stringify(errorPayload) # To make absolutely sure that we can log and exit on all uncaught errors. if app.get("env") == "production" logAndExit = (err) -> reportError(err, "error", true) process.exit(1) rootDomain = domain.create() rootDomain.on "error", logAndExit runWrapper = (func) -> rootDomain.run -> try func() catch err logAndExit(err) else # In development, we don't have to catch uncaught errors. Just run the specified function directly. runWrapper = (func) -> func() runWrapper -> path = require('path') favicon = require('serve-favicon') logger = require('morgan') cookieParser = require('cookie-parser') bodyParser = require('body-parser') fancyshelf = require "fancyshelf" session = require "express-session" csurf = require "csurf" fileStreamRotator = require "file-stream-rotator" domainMiddleware = require("express-domain-middleware") errors = require "errors" PrettyError = require "pretty-error" Convert = require "ansi-to-html" marked = require "marked" moment = require "moment" persist = require "./lib/persist" useCsrf = require "./lib/use-csrf" templateUtil = require("./lib/template-util") sessionStore = require("./lib/persist-session")(session) config = require "./config.json" knexfile = require("./knexfile").development ansiHTML = new Convert(escapeXML: true, newline: true) # Error handling pe = PrettyError.start() pe.skipPackage "bluebird", "coffee-script", "express", "express-promise-router", "jade" pe.skipNodeFiles() errors.create name: "UploadError" errors.create name: "UploadTooLarge" parents: errors.UploadError status: 413 errors.create name: "InvalidFiletype" parents: errors.UploadError status: 415 errors.create name: "NotAuthenticated" status: 403 errors.create name: "InvalidInput" status: 422 # Database setup shelf = fancyshelf engine: knexfile.client host: knexfile.connection.host username: knexfile.connection.user password: knexfile.connection.password database: knexfile.connection.database debug: (app.get("env") == "development") # Task runner TaskRunner = require("./lib/task-runner") runner = new TaskRunner(app: app, db: shelf, config: config, thumbnailPath: path.join(__dirname, 'thumbnails')) runner.addTask "mirror", require("./tasks/mirror"), maxConcurrency: 5 runner.addTask "thumbnail", require("./tasks/thumbnail") runner.run() runner.on "taskQueued", (taskType, task) -> persist.increment "task:#{taskType}:queued" runner.on "taskStarted", (taskType, task) -> persist.decrement "task:#{taskType}:queued" persist.increment "task:#{taskType}:running" runner.on "taskFailed", (taskType, task) -> persist.decrement "task:#{taskType}:running" persist.increment "task:#{taskType}:failed" runner.on "taskCompleted", (taskType, task) -> persist.decrement "task:#{taskType}:running" persist.increment "task:#{taskType}:completed" if app.get("env") == "development" runner.on "taskFailed", (taskType, task, err) -> console.log err.stack else runner.on "taskFailed", (taskType, task, err) -> reportError err, "taskFailed" # Configure Express app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'jade') # Middleware if app.get("env") == "development" app.use(logger('dev')) else accessLogStream = fileStreamRotator.getStream frequency: (config.accessLog.frequency ? "24h"), filename: config.accessLog.filename app.use logger (config.accessLog.format ? "combined"), stream: accessLogStream app.use (req, res, next) -> if config.ssl?.key? if req.secure res.set "Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload" next() else res.redirect "https://pdf.yt/" else next() # Using /static/ paths to maintain backwards compatibility. app.use("/static/thumbs", express.static(path.join(__dirname, 'thumbnails'))) app.use("/static/pdfjs", express.static(path.join(__dirname, 'public/pdfjs'))) app.use(express.static(path.join(__dirname, 'public'))) #app.use(favicon(__dirname + '/public/favicon.ico')) app.use domainMiddleware app.use templateUtil app.use shelf.express app.use session store: new sessionStore persist: persist secret: config.session.signingKey resave: true # TODO: Implement `touch` for the session store, and/or switch to a different store. saveUninitialized: false # Load models require("./models")(shelf) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: false })) app.use(cookieParser()) app.use (req, res, next) -> res.locals.md = marked req.appConfig = config req.persist = persist jadeExports = [ "announcementVisible" "announcementText" "announcementLinkText" "announcementLink" "maintenanceMode" "maintenanceModeText" "donationGoal" "donationTotal" "showNotice" ] for key in jadeExports res.locals[key] = persist.getItem "var:#{key}" res.locals.bitcoinAddress = config.donations.bitcoinAddress res.locals.isAdmin = req.session.isAdmin # This is for logging/reporting errors that should not occur, but that are known to not cause any adverse side-effects. # This should NOT be used for errors that could leave the application in an undefined state! req.reportError = reportError req.taskRunner = runner next() app.use "/", require("./routes/index") app.use "/donate", require("./routes/donate") app.use "/d", require("./routes/document") app.use "/upload", require("./routes/upload") app.use "/gallery", require("./routes/gallery") app.use "/blog", require("./routes/blog") app.use "/admin", csurf(), useCsrf, require("./routes/admin") # If no routes match, cause a 404 app.use (req, res, next) -> next new errors.Http404Error("The requested page was not found.") # Error handling middleware app.use "/static/thumbs", (err, req, res, next) -> # TODO: For some reason, Chrome doesn't always display images that are sent with a 404 status code. Let's stick with 200 for now... #res.status 404 if err.status == '404' fs.createReadStream path.join(__dirname, "public/images/no-thumbnail.png") .pipe res else next(err) app.use (err, req, res, next) -> statusCode = err.status || 500 res.status(statusCode) # Dump the error to disk if it's a 500, so that the error reporter can deal with it. if app.get("env") != "development" and statusCode == 500 reportError(err) # Display the error to the user - amount of details depending on whether the application is running in production mode or not. if (app.get('env') == 'development') stack = err else if statusCode == 500 errorMessage = "An unknown error occurred." stack = {stack: "An administrator has been notified, and the error will be resolved as soon as possible. Apologies for the inconvenience."} else errorMessage = err.message stack = {stack: err.explanation, subMessage: err.subMessage} if req.headers["X-Requested-With"] == "XMLHttpRequest" res.send { message: errorMessage, error: stack } else if err instanceof errors.NotAuthenticated res.redirect "/admin/login" else if app.get("env") == "development" htmlStack = ansiHTML.toHtml(stack.stack) .replace /#555/g, "#b5b5b5" # TODO: It seems aborted responses will result in an attempt to send an error page/header - of course this can't succeed, as the headers have already been sent by that time, and an error is thrown. res.render('error', { message: errorMessage, error: stack, statusCode: statusCode, htmlStack: htmlStack }) module.exports = app
146900
express = require('express') uuid = require "uuid" fs = require "fs" domain = require "domain" app = express() reportError = (err, type = "error", sync = false) -> if err.code == "ECONNRESET" # We're not interested in these for now, they're just aborted requests. # TODO: Investigate whether there may also be other scenarios where an ECONNRESET is raised. return errorPayload = {} Object.getOwnPropertyNames(err).forEach (key) -> errorPayload[key] = err[key] filename = "errors/#{type}-#{Date.now()}-#{uuid.v4()}.json" if sync fs.writeFileSync filename, JSON.stringify(errorPayload) else fs.writeFile filename, JSON.stringify(errorPayload) # To make absolutely sure that we can log and exit on all uncaught errors. if app.get("env") == "production" logAndExit = (err) -> reportError(err, "error", true) process.exit(1) rootDomain = domain.create() rootDomain.on "error", logAndExit runWrapper = (func) -> rootDomain.run -> try func() catch err logAndExit(err) else # In development, we don't have to catch uncaught errors. Just run the specified function directly. runWrapper = (func) -> func() runWrapper -> path = require('path') favicon = require('serve-favicon') logger = require('morgan') cookieParser = require('cookie-parser') bodyParser = require('body-parser') fancyshelf = require "fancyshelf" session = require "express-session" csurf = require "csurf" fileStreamRotator = require "file-stream-rotator" domainMiddleware = require("express-domain-middleware") errors = require "errors" PrettyError = require "pretty-error" Convert = require "ansi-to-html" marked = require "marked" moment = require "moment" persist = require "./lib/persist" useCsrf = require "./lib/use-csrf" templateUtil = require("./lib/template-util") sessionStore = require("./lib/persist-session")(session) config = require "./config.json" knexfile = require("./knexfile").development ansiHTML = new Convert(escapeXML: true, newline: true) # Error handling pe = PrettyError.start() pe.skipPackage "bluebird", "coffee-script", "express", "express-promise-router", "jade" pe.skipNodeFiles() errors.create name: "UploadError" errors.create name: "UploadTooLarge" parents: errors.UploadError status: 413 errors.create name: "InvalidFiletype" parents: errors.UploadError status: 415 errors.create name: "NotAuthenticated" status: 403 errors.create name: "InvalidInput" status: 422 # Database setup shelf = fancyshelf engine: knexfile.client host: knexfile.connection.host username: knexfile.connection.user password: <PASSWORD> database: knexfile.connection.database debug: (app.get("env") == "development") # Task runner TaskRunner = require("./lib/task-runner") runner = new TaskRunner(app: app, db: shelf, config: config, thumbnailPath: path.join(__dirname, 'thumbnails')) runner.addTask "mirror", require("./tasks/mirror"), maxConcurrency: 5 runner.addTask "thumbnail", require("./tasks/thumbnail") runner.run() runner.on "taskQueued", (taskType, task) -> persist.increment "task:#{taskType}:queued" runner.on "taskStarted", (taskType, task) -> persist.decrement "task:#{taskType}:queued" persist.increment "task:#{taskType}:running" runner.on "taskFailed", (taskType, task) -> persist.decrement "task:#{taskType}:running" persist.increment "task:#{taskType}:failed" runner.on "taskCompleted", (taskType, task) -> persist.decrement "task:#{taskType}:running" persist.increment "task:#{taskType}:completed" if app.get("env") == "development" runner.on "taskFailed", (taskType, task, err) -> console.log err.stack else runner.on "taskFailed", (taskType, task, err) -> reportError err, "taskFailed" # Configure Express app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'jade') # Middleware if app.get("env") == "development" app.use(logger('dev')) else accessLogStream = fileStreamRotator.getStream frequency: (config.accessLog.frequency ? "24h"), filename: config.accessLog.filename app.use logger (config.accessLog.format ? "combined"), stream: accessLogStream app.use (req, res, next) -> if config.ssl?.key? if req.secure res.set "Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload" next() else res.redirect "https://pdf.yt/" else next() # Using /static/ paths to maintain backwards compatibility. app.use("/static/thumbs", express.static(path.join(__dirname, 'thumbnails'))) app.use("/static/pdfjs", express.static(path.join(__dirname, 'public/pdfjs'))) app.use(express.static(path.join(__dirname, 'public'))) #app.use(favicon(__dirname + '/public/favicon.ico')) app.use domainMiddleware app.use templateUtil app.use shelf.express app.use session store: new sessionStore persist: persist secret: config.session.signingKey resave: true # TODO: Implement `touch` for the session store, and/or switch to a different store. saveUninitialized: false # Load models require("./models")(shelf) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: false })) app.use(cookieParser()) app.use (req, res, next) -> res.locals.md = marked req.appConfig = config req.persist = persist jadeExports = [ "announcementVisible" "announcementText" "announcementLinkText" "announcementLink" "maintenanceMode" "maintenanceModeText" "donationGoal" "donationTotal" "showNotice" ] for key in jadeExports res.locals[key] = persist.getItem "var:#{key}" res.locals.bitcoinAddress = config.donations.bitcoinAddress res.locals.isAdmin = req.session.isAdmin # This is for logging/reporting errors that should not occur, but that are known to not cause any adverse side-effects. # This should NOT be used for errors that could leave the application in an undefined state! req.reportError = reportError req.taskRunner = runner next() app.use "/", require("./routes/index") app.use "/donate", require("./routes/donate") app.use "/d", require("./routes/document") app.use "/upload", require("./routes/upload") app.use "/gallery", require("./routes/gallery") app.use "/blog", require("./routes/blog") app.use "/admin", csurf(), useCsrf, require("./routes/admin") # If no routes match, cause a 404 app.use (req, res, next) -> next new errors.Http404Error("The requested page was not found.") # Error handling middleware app.use "/static/thumbs", (err, req, res, next) -> # TODO: For some reason, Chrome doesn't always display images that are sent with a 404 status code. Let's stick with 200 for now... #res.status 404 if err.status == '404' fs.createReadStream path.join(__dirname, "public/images/no-thumbnail.png") .pipe res else next(err) app.use (err, req, res, next) -> statusCode = err.status || 500 res.status(statusCode) # Dump the error to disk if it's a 500, so that the error reporter can deal with it. if app.get("env") != "development" and statusCode == 500 reportError(err) # Display the error to the user - amount of details depending on whether the application is running in production mode or not. if (app.get('env') == 'development') stack = err else if statusCode == 500 errorMessage = "An unknown error occurred." stack = {stack: "An administrator has been notified, and the error will be resolved as soon as possible. Apologies for the inconvenience."} else errorMessage = err.message stack = {stack: err.explanation, subMessage: err.subMessage} if req.headers["X-Requested-With"] == "XMLHttpRequest" res.send { message: errorMessage, error: stack } else if err instanceof errors.NotAuthenticated res.redirect "/admin/login" else if app.get("env") == "development" htmlStack = ansiHTML.toHtml(stack.stack) .replace /#555/g, "#b5b5b5" # TODO: It seems aborted responses will result in an attempt to send an error page/header - of course this can't succeed, as the headers have already been sent by that time, and an error is thrown. res.render('error', { message: errorMessage, error: stack, statusCode: statusCode, htmlStack: htmlStack }) module.exports = app
true
express = require('express') uuid = require "uuid" fs = require "fs" domain = require "domain" app = express() reportError = (err, type = "error", sync = false) -> if err.code == "ECONNRESET" # We're not interested in these for now, they're just aborted requests. # TODO: Investigate whether there may also be other scenarios where an ECONNRESET is raised. return errorPayload = {} Object.getOwnPropertyNames(err).forEach (key) -> errorPayload[key] = err[key] filename = "errors/#{type}-#{Date.now()}-#{uuid.v4()}.json" if sync fs.writeFileSync filename, JSON.stringify(errorPayload) else fs.writeFile filename, JSON.stringify(errorPayload) # To make absolutely sure that we can log and exit on all uncaught errors. if app.get("env") == "production" logAndExit = (err) -> reportError(err, "error", true) process.exit(1) rootDomain = domain.create() rootDomain.on "error", logAndExit runWrapper = (func) -> rootDomain.run -> try func() catch err logAndExit(err) else # In development, we don't have to catch uncaught errors. Just run the specified function directly. runWrapper = (func) -> func() runWrapper -> path = require('path') favicon = require('serve-favicon') logger = require('morgan') cookieParser = require('cookie-parser') bodyParser = require('body-parser') fancyshelf = require "fancyshelf" session = require "express-session" csurf = require "csurf" fileStreamRotator = require "file-stream-rotator" domainMiddleware = require("express-domain-middleware") errors = require "errors" PrettyError = require "pretty-error" Convert = require "ansi-to-html" marked = require "marked" moment = require "moment" persist = require "./lib/persist" useCsrf = require "./lib/use-csrf" templateUtil = require("./lib/template-util") sessionStore = require("./lib/persist-session")(session) config = require "./config.json" knexfile = require("./knexfile").development ansiHTML = new Convert(escapeXML: true, newline: true) # Error handling pe = PrettyError.start() pe.skipPackage "bluebird", "coffee-script", "express", "express-promise-router", "jade" pe.skipNodeFiles() errors.create name: "UploadError" errors.create name: "UploadTooLarge" parents: errors.UploadError status: 413 errors.create name: "InvalidFiletype" parents: errors.UploadError status: 415 errors.create name: "NotAuthenticated" status: 403 errors.create name: "InvalidInput" status: 422 # Database setup shelf = fancyshelf engine: knexfile.client host: knexfile.connection.host username: knexfile.connection.user password: PI:PASSWORD:<PASSWORD>END_PI database: knexfile.connection.database debug: (app.get("env") == "development") # Task runner TaskRunner = require("./lib/task-runner") runner = new TaskRunner(app: app, db: shelf, config: config, thumbnailPath: path.join(__dirname, 'thumbnails')) runner.addTask "mirror", require("./tasks/mirror"), maxConcurrency: 5 runner.addTask "thumbnail", require("./tasks/thumbnail") runner.run() runner.on "taskQueued", (taskType, task) -> persist.increment "task:#{taskType}:queued" runner.on "taskStarted", (taskType, task) -> persist.decrement "task:#{taskType}:queued" persist.increment "task:#{taskType}:running" runner.on "taskFailed", (taskType, task) -> persist.decrement "task:#{taskType}:running" persist.increment "task:#{taskType}:failed" runner.on "taskCompleted", (taskType, task) -> persist.decrement "task:#{taskType}:running" persist.increment "task:#{taskType}:completed" if app.get("env") == "development" runner.on "taskFailed", (taskType, task, err) -> console.log err.stack else runner.on "taskFailed", (taskType, task, err) -> reportError err, "taskFailed" # Configure Express app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'jade') # Middleware if app.get("env") == "development" app.use(logger('dev')) else accessLogStream = fileStreamRotator.getStream frequency: (config.accessLog.frequency ? "24h"), filename: config.accessLog.filename app.use logger (config.accessLog.format ? "combined"), stream: accessLogStream app.use (req, res, next) -> if config.ssl?.key? if req.secure res.set "Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload" next() else res.redirect "https://pdf.yt/" else next() # Using /static/ paths to maintain backwards compatibility. app.use("/static/thumbs", express.static(path.join(__dirname, 'thumbnails'))) app.use("/static/pdfjs", express.static(path.join(__dirname, 'public/pdfjs'))) app.use(express.static(path.join(__dirname, 'public'))) #app.use(favicon(__dirname + '/public/favicon.ico')) app.use domainMiddleware app.use templateUtil app.use shelf.express app.use session store: new sessionStore persist: persist secret: config.session.signingKey resave: true # TODO: Implement `touch` for the session store, and/or switch to a different store. saveUninitialized: false # Load models require("./models")(shelf) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: false })) app.use(cookieParser()) app.use (req, res, next) -> res.locals.md = marked req.appConfig = config req.persist = persist jadeExports = [ "announcementVisible" "announcementText" "announcementLinkText" "announcementLink" "maintenanceMode" "maintenanceModeText" "donationGoal" "donationTotal" "showNotice" ] for key in jadeExports res.locals[key] = persist.getItem "var:#{key}" res.locals.bitcoinAddress = config.donations.bitcoinAddress res.locals.isAdmin = req.session.isAdmin # This is for logging/reporting errors that should not occur, but that are known to not cause any adverse side-effects. # This should NOT be used for errors that could leave the application in an undefined state! req.reportError = reportError req.taskRunner = runner next() app.use "/", require("./routes/index") app.use "/donate", require("./routes/donate") app.use "/d", require("./routes/document") app.use "/upload", require("./routes/upload") app.use "/gallery", require("./routes/gallery") app.use "/blog", require("./routes/blog") app.use "/admin", csurf(), useCsrf, require("./routes/admin") # If no routes match, cause a 404 app.use (req, res, next) -> next new errors.Http404Error("The requested page was not found.") # Error handling middleware app.use "/static/thumbs", (err, req, res, next) -> # TODO: For some reason, Chrome doesn't always display images that are sent with a 404 status code. Let's stick with 200 for now... #res.status 404 if err.status == '404' fs.createReadStream path.join(__dirname, "public/images/no-thumbnail.png") .pipe res else next(err) app.use (err, req, res, next) -> statusCode = err.status || 500 res.status(statusCode) # Dump the error to disk if it's a 500, so that the error reporter can deal with it. if app.get("env") != "development" and statusCode == 500 reportError(err) # Display the error to the user - amount of details depending on whether the application is running in production mode or not. if (app.get('env') == 'development') stack = err else if statusCode == 500 errorMessage = "An unknown error occurred." stack = {stack: "An administrator has been notified, and the error will be resolved as soon as possible. Apologies for the inconvenience."} else errorMessage = err.message stack = {stack: err.explanation, subMessage: err.subMessage} if req.headers["X-Requested-With"] == "XMLHttpRequest" res.send { message: errorMessage, error: stack } else if err instanceof errors.NotAuthenticated res.redirect "/admin/login" else if app.get("env") == "development" htmlStack = ansiHTML.toHtml(stack.stack) .replace /#555/g, "#b5b5b5" # TODO: It seems aborted responses will result in an attempt to send an error page/header - of course this can't succeed, as the headers have already been sent by that time, and an error is thrown. res.render('error', { message: errorMessage, error: stack, statusCode: statusCode, htmlStack: htmlStack }) module.exports = app
[ { "context": "es/CDS-411/instructors\"\n ]\n }\n {\n title: \"Spyns\"\n group: \"Development\"\n paths: [\n \"~/D", "end": 142, "score": 0.9786941409111023, "start": 137, "tag": "NAME", "value": "Spyns" } ]
atom/dot-atom/projects.glasbren-oryxpro.cson
jkglasbrenner/dotfiles
0
[ { title: "CDS-411 Instructors" group: "CDS-411" paths: [ "~/Courses/CDS-411/instructors" ] } { title: "Spyns" group: "Development" paths: [ "~/Development/spyns" ] } { title: "CSI-702 Spr17: Homework02 Instructor Attempt" group: "CSI-702" paths: [ "~/Documents/work/teaching/2017_Spring_Semester/CSI-702_High_Performance_Computing/assignments/homework02-instructor-attempt" ] } { title: "ising.js" group: "teaching" paths: [ "~/Courses/CDS-101/simulations/ising-model" ] } ]
155854
[ { title: "CDS-411 Instructors" group: "CDS-411" paths: [ "~/Courses/CDS-411/instructors" ] } { title: "<NAME>" group: "Development" paths: [ "~/Development/spyns" ] } { title: "CSI-702 Spr17: Homework02 Instructor Attempt" group: "CSI-702" paths: [ "~/Documents/work/teaching/2017_Spring_Semester/CSI-702_High_Performance_Computing/assignments/homework02-instructor-attempt" ] } { title: "ising.js" group: "teaching" paths: [ "~/Courses/CDS-101/simulations/ising-model" ] } ]
true
[ { title: "CDS-411 Instructors" group: "CDS-411" paths: [ "~/Courses/CDS-411/instructors" ] } { title: "PI:NAME:<NAME>END_PI" group: "Development" paths: [ "~/Development/spyns" ] } { title: "CSI-702 Spr17: Homework02 Instructor Attempt" group: "CSI-702" paths: [ "~/Documents/work/teaching/2017_Spring_Semester/CSI-702_High_Performance_Computing/assignments/homework02-instructor-attempt" ] } { title: "ising.js" group: "teaching" paths: [ "~/Courses/CDS-101/simulations/ising-model" ] } ]
[ { "context": "ers'\n Users.identifier 'user_id'\n Users.unique 'username'\n Users.index 'email'\n Users = client.get 'user", "end": 240, "score": 0.9965708255767822, "start": 232, "tag": "USERNAME", "value": "username" }, { "context": "r', (next) ->\n Users.create {\n username: 'my_username'\n email: 'my@email.com'\n password: 'my_", "end": 641, "score": 0.9995881915092468, "start": 630, "tag": "USERNAME", "value": "my_username" }, { "context": "ate {\n username: 'my_username'\n email: 'my@email.com'\n password: 'my_password'\n }, (err, user)", "end": 669, "score": 0.999911904335022, "start": 657, "tag": "EMAIL", "value": "my@email.com" }, { "context": "ame'\n email: 'my@email.com'\n password: 'my_password'\n }, (err, user) ->\n # Delete record base", "end": 699, "score": 0.9993801116943359, "start": 688, "tag": "PASSWORD", "value": "my_password" } ]
test/remove.coffee
wdavidw/node-ron
14
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config Users = client.get 'users' Users.identifier 'user_id' Users.unique 'username' Users.index 'email' Users = client.get 'users' next() beforeEach (next) -> Users.clear next afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'remove', -> it 'should remove a record if providing an identifier', (next) -> Users.create { username: 'my_username' email: 'my@email.com' password: 'my_password' }, (err, user) -> # Delete record based on identifier Users.remove user.user_id, (err, count) -> should.not.exist err count.should.eql 1 # Check record doesn't exist Users.exists user.user_id, (err, exists) -> should.not.exist exists Users.clear next it 'should not remove a missing record', (next) -> # Delete record based on identifier Users.remove -1, (err, count) -> should.not.exist err # Count shouldn't be incremented count.should.eql 0 Users.clear next
178057
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config Users = client.get 'users' Users.identifier 'user_id' Users.unique 'username' Users.index 'email' Users = client.get 'users' next() beforeEach (next) -> Users.clear next afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'remove', -> it 'should remove a record if providing an identifier', (next) -> Users.create { username: 'my_username' email: '<EMAIL>' password: '<PASSWORD>' }, (err, user) -> # Delete record based on identifier Users.remove user.user_id, (err, count) -> should.not.exist err count.should.eql 1 # Check record doesn't exist Users.exists user.user_id, (err, exists) -> should.not.exist exists Users.clear next it 'should not remove a missing record', (next) -> # Delete record based on identifier Users.remove -1, (err, count) -> should.not.exist err # Count shouldn't be incremented count.should.eql 0 Users.clear next
true
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config Users = client.get 'users' Users.identifier 'user_id' Users.unique 'username' Users.index 'email' Users = client.get 'users' next() beforeEach (next) -> Users.clear next afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'remove', -> it 'should remove a record if providing an identifier', (next) -> Users.create { username: 'my_username' email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' }, (err, user) -> # Delete record based on identifier Users.remove user.user_id, (err, count) -> should.not.exist err count.should.eql 1 # Check record doesn't exist Users.exists user.user_id, (err, exists) -> should.not.exist exists Users.clear next it 'should not remove a missing record', (next) -> # Delete record based on identifier Users.remove -1, (err, count) -> should.not.exist err # Count shouldn't be incremented count.should.eql 0 Users.clear next
[ { "context": "body': '''\n ${1:\\$this->email}->bcc(${2:'${3:you@example.com}'});\n '''\n 'E-mail Carbon Copy':\n 'prefix'", "end": 276, "score": 0.9994802474975586, "start": 261, "tag": "EMAIL", "value": "you@example.com" }, { "context": "'body': '''\n ${1:\\$this->email}->cc(${2:'${3:you@example.com}'});\n '''\n 'E-mail Clear':\n 'prefix': 'cim", "end": 408, "score": 0.9995201230049133, "start": 393, "tag": "EMAIL", "value": "you@example.com" }, { "context": "ody': '''\n ${1:\\$this->email}->from(${2:'${3:you@example.com}'}, ${4:'${5:Your Name}'});\n '''\n 'E-mail Ini", "end": 642, "score": 0.9997018575668335, "start": 627, "tag": "EMAIL", "value": "you@example.com" }, { "context": "': '''\n ${1:\\$this->email}->message(${2:'${3:you@example.com}'});\n '''\n 'E-mail Print Debugger':\n 'pref", "end": 926, "score": 0.9990442395210266, "start": 911, "tag": "EMAIL", "value": "you@example.com" }, { "context": ": '''\n ${1:\\$this->email}->reply_to(${2:'${3:you@example.com}'}, ${4:'${5:Your Name}'});\n '''\n 'E-mail Sen", "end": 1187, "score": 0.9995983839035034, "start": 1172, "tag": "EMAIL", "value": "you@example.com" }, { "context": " ${1:\\$this->email}->set_alt_message(${2:'${3:you@example.com}'});\n '''\n 'E-mail Subject':\n '", "end": 1461, "score": 0.7304123640060425, "start": 1458, "tag": "EMAIL", "value": "you" }, { "context": "this->email}->set_alt_message(${2:'${3:you@example.com}'});\n '''\n 'E-mail Subject':\n 'prefix': 'c", "end": 1473, "score": 0.9998465776443481, "start": 1470, "tag": "EMAIL", "value": "com" }, { "context": "'body': '''\n ${1:\\$this->email}->to(${2:'${3:you@example.com}'});\n '''\n", "end": 1727, "score": 0.9986199140548706, "start": 1712, "tag": "EMAIL", "value": "you@example.com" } ]
snippets/email.cson
femi-dd/codeigniter-atom
1
'.source.php': 'E-mail Attach File': 'prefix': 'cimailatt' 'body': ''' ${1:\$this->email}->attach(${2:'${3:/path/to/file}'}); ''' 'E-mail Blind Carbon Copy': 'prefix': 'cimailbcc' 'body': ''' ${1:\$this->email}->bcc(${2:'${3:you@example.com}'}); ''' 'E-mail Carbon Copy': 'prefix': 'cimailcc' 'body': ''' ${1:\$this->email}->cc(${2:'${3:you@example.com}'}); ''' 'E-mail Clear': 'prefix': 'cimailclear' 'body': ''' ${1:\$this->email}->clear(); ''' 'E-mail From': 'prefix': 'cimailfrom' 'body': ''' ${1:\$this->email}->from(${2:'${3:you@example.com}'}, ${4:'${5:Your Name}'}); ''' 'E-mail Initialize': 'prefix': 'cimailinit' 'body': ''' ${1:\$this->email}->initialize(${2:\$config}); ''' 'E-mail Message': 'prefix': 'cimailmsg' 'body': ''' ${1:\$this->email}->message(${2:'${3:you@example.com}'}); ''' 'E-mail Print Debugger': 'prefix': 'cimailprint' 'body': ''' ${1:\$this->email}->print_debugger(); ''' 'E-mail Reply To': 'prefix': 'cimailreply' 'body': ''' ${1:\$this->email}->reply_to(${2:'${3:you@example.com}'}, ${4:'${5:Your Name}'}); ''' 'E-mail Send': 'prefix': 'cimailsend' 'body': ''' ${1:\$this->email}->send(); ''' 'E-mail Set Alternative Message': 'prefix': 'cimailaltmsg' 'body': ''' ${1:\$this->email}->set_alt_message(${2:'${3:you@example.com}'}); ''' 'E-mail Subject': 'prefix': 'cimailsub' 'body': ''' ${1:\$this->email}->subject(${2:'${3:mail subject}'}); ''' 'E-mail To': 'prefix': 'cimailto' 'body': ''' ${1:\$this->email}->to(${2:'${3:you@example.com}'}); '''
193159
'.source.php': 'E-mail Attach File': 'prefix': 'cimailatt' 'body': ''' ${1:\$this->email}->attach(${2:'${3:/path/to/file}'}); ''' 'E-mail Blind Carbon Copy': 'prefix': 'cimailbcc' 'body': ''' ${1:\$this->email}->bcc(${2:'${3:<EMAIL>}'}); ''' 'E-mail Carbon Copy': 'prefix': 'cimailcc' 'body': ''' ${1:\$this->email}->cc(${2:'${3:<EMAIL>}'}); ''' 'E-mail Clear': 'prefix': 'cimailclear' 'body': ''' ${1:\$this->email}->clear(); ''' 'E-mail From': 'prefix': 'cimailfrom' 'body': ''' ${1:\$this->email}->from(${2:'${3:<EMAIL>}'}, ${4:'${5:Your Name}'}); ''' 'E-mail Initialize': 'prefix': 'cimailinit' 'body': ''' ${1:\$this->email}->initialize(${2:\$config}); ''' 'E-mail Message': 'prefix': 'cimailmsg' 'body': ''' ${1:\$this->email}->message(${2:'${3:<EMAIL>}'}); ''' 'E-mail Print Debugger': 'prefix': 'cimailprint' 'body': ''' ${1:\$this->email}->print_debugger(); ''' 'E-mail Reply To': 'prefix': 'cimailreply' 'body': ''' ${1:\$this->email}->reply_to(${2:'${3:<EMAIL>}'}, ${4:'${5:Your Name}'}); ''' 'E-mail Send': 'prefix': 'cimailsend' 'body': ''' ${1:\$this->email}->send(); ''' 'E-mail Set Alternative Message': 'prefix': 'cimailaltmsg' 'body': ''' ${1:\$this->email}->set_alt_message(${2:'${3:<EMAIL>@example.<EMAIL>}'}); ''' 'E-mail Subject': 'prefix': 'cimailsub' 'body': ''' ${1:\$this->email}->subject(${2:'${3:mail subject}'}); ''' 'E-mail To': 'prefix': 'cimailto' 'body': ''' ${1:\$this->email}->to(${2:'${3:<EMAIL>}'}); '''
true
'.source.php': 'E-mail Attach File': 'prefix': 'cimailatt' 'body': ''' ${1:\$this->email}->attach(${2:'${3:/path/to/file}'}); ''' 'E-mail Blind Carbon Copy': 'prefix': 'cimailbcc' 'body': ''' ${1:\$this->email}->bcc(${2:'${3:PI:EMAIL:<EMAIL>END_PI}'}); ''' 'E-mail Carbon Copy': 'prefix': 'cimailcc' 'body': ''' ${1:\$this->email}->cc(${2:'${3:PI:EMAIL:<EMAIL>END_PI}'}); ''' 'E-mail Clear': 'prefix': 'cimailclear' 'body': ''' ${1:\$this->email}->clear(); ''' 'E-mail From': 'prefix': 'cimailfrom' 'body': ''' ${1:\$this->email}->from(${2:'${3:PI:EMAIL:<EMAIL>END_PI}'}, ${4:'${5:Your Name}'}); ''' 'E-mail Initialize': 'prefix': 'cimailinit' 'body': ''' ${1:\$this->email}->initialize(${2:\$config}); ''' 'E-mail Message': 'prefix': 'cimailmsg' 'body': ''' ${1:\$this->email}->message(${2:'${3:PI:EMAIL:<EMAIL>END_PI}'}); ''' 'E-mail Print Debugger': 'prefix': 'cimailprint' 'body': ''' ${1:\$this->email}->print_debugger(); ''' 'E-mail Reply To': 'prefix': 'cimailreply' 'body': ''' ${1:\$this->email}->reply_to(${2:'${3:PI:EMAIL:<EMAIL>END_PI}'}, ${4:'${5:Your Name}'}); ''' 'E-mail Send': 'prefix': 'cimailsend' 'body': ''' ${1:\$this->email}->send(); ''' 'E-mail Set Alternative Message': 'prefix': 'cimailaltmsg' 'body': ''' ${1:\$this->email}->set_alt_message(${2:'${3:PI:EMAIL:<EMAIL>END_PI@example.PI:EMAIL:<EMAIL>END_PI}'}); ''' 'E-mail Subject': 'prefix': 'cimailsub' 'body': ''' ${1:\$this->email}->subject(${2:'${3:mail subject}'}); ''' 'E-mail To': 'prefix': 'cimailto' 'body': ''' ${1:\$this->email}->to(${2:'${3:PI:EMAIL:<EMAIL>END_PI}'}); '''
[ { "context": "ebkit api and the new standard api.\n #\n # THANKS OBAMA!\n patchWindow_: ->\n # Treat all context's equ", "end": 2420, "score": 0.9812248349189758, "start": 2415, "tag": "NAME", "value": "OBAMA" } ]
coffee/SoundManager.coffee
ndrwhr/tumbler
20
SoundManager = initialize: -> this.patchWindow_(); @isSupported = Modernizr.webaudio @context_ = new AudioContext() @masterGainNode_ = @context_.createGain() @masterGainNode_.gain.value = 1 @compressorNode_ = @context_.createDynamicsCompressor() @convolverNode_ = @context_.createConvolver() @buffers_ = {} @loadingProgress_ = 0 load: () -> audioType = if Modernizr.audio.ogg then "ogg" else ( if Modernizr.audio.mp3 then "mp3" else "wav") sounds = "convolver": "dining-living-true-stereo.#{audioType}" "glock-0": "glockenspiel/#{audioType}/f7.#{audioType}" "glock-1": "glockenspiel/#{audioType}/e7.#{audioType}" "glock-2": "glockenspiel/#{audioType}/d7.#{audioType}" "glock-3": "glockenspiel/#{audioType}/c7.#{audioType}" "glock-4": "glockenspiel/#{audioType}/b6.#{audioType}" "glock-5": "glockenspiel/#{audioType}/a6.#{audioType}" "glock-6": "glockenspiel/#{audioType}/g6.#{audioType}" "glock-7": "glockenspiel/#{audioType}/f6.#{audioType}" "glock-8": "glockenspiel/#{audioType}/e6.#{audioType}" "glock-9": "glockenspiel/#{audioType}/d6.#{audioType}" "glock-10":"glockenspiel/#{audioType}/c6.#{audioType}" @buffers_ = {} @buffersToLoad_ = Object.keys(sounds) for soundName in @buffersToLoad_ @loadSound_(soundName, 'sounds/' + sounds[soundName]) # Simple getter for the AudioContext object. getContext: -> @context_ mute: (doit) -> @masterGainNode_.gain.value = if doit then 0 else 1 getLoadedProgress: -> return if @isSupported then @loadingProgress_ else 1 createBufferSource: -> source = @context_.createBufferSource() source.playbackRate.value = Utilities.range(Config.MIN_AUDIO_PLAYBACK_RATE, Config.MAX_AUDIO_PLAYBACK_RATE, Config.SIMULATION_RATE) source connectToDestination: (node) -> if @convolverNode_.buffer node.connect(@convolverNode_) node = @convolverNode_ else # If we can't load the convolver then everything sounds terrible. Might # as well leave the user in silence. return node.connect(@masterGainNode_) @masterGainNode_.connect(@compressorNode_) @compressorNode_.connect(@context_.destination) getBuffer: (soundName) -> @buffers_[soundName] # Patch inconsistencies between the old webkit api and the new standard api. # # THANKS OBAMA! patchWindow_: -> # Treat all context's equally. window.AudioContext = (window.AudioContext or window.webkitAudioContext) # An object that contains mappings from the old webkit API over to the new # standard API for certain objects. patches = "AudioContext": "createGain": "createGainNode" "AudioBufferSourceNode": "start": "noteOn" "off": "noteOff" for objectName in Object.keys(patches) objPatches = patches[objectName] for standardMethod in Object.keys(objPatches) oldMethod = objPatches[standardMethod] if not window[objectName][standardMethod] window[objectName][standardMethod] = window[objectName][oldMethod] loadSound_: (name, file) -> request = new XMLHttpRequest() request.open('GET', file, true) request.responseType = 'arraybuffer' request.onload = => @context_.decodeAudioData(request.response, (buffer) => @saveBuffer_(name, buffer) ) request.send(); saveBuffer_: (name, buffer) -> @buffers_[name] = buffer if name == "convolver" @convolverNode_.buffer = buffer @loadingProgress_ = Object.keys(@buffers_).length / @buffersToLoad_.length # export the class. window.SoundManager = SoundManager
87452
SoundManager = initialize: -> this.patchWindow_(); @isSupported = Modernizr.webaudio @context_ = new AudioContext() @masterGainNode_ = @context_.createGain() @masterGainNode_.gain.value = 1 @compressorNode_ = @context_.createDynamicsCompressor() @convolverNode_ = @context_.createConvolver() @buffers_ = {} @loadingProgress_ = 0 load: () -> audioType = if Modernizr.audio.ogg then "ogg" else ( if Modernizr.audio.mp3 then "mp3" else "wav") sounds = "convolver": "dining-living-true-stereo.#{audioType}" "glock-0": "glockenspiel/#{audioType}/f7.#{audioType}" "glock-1": "glockenspiel/#{audioType}/e7.#{audioType}" "glock-2": "glockenspiel/#{audioType}/d7.#{audioType}" "glock-3": "glockenspiel/#{audioType}/c7.#{audioType}" "glock-4": "glockenspiel/#{audioType}/b6.#{audioType}" "glock-5": "glockenspiel/#{audioType}/a6.#{audioType}" "glock-6": "glockenspiel/#{audioType}/g6.#{audioType}" "glock-7": "glockenspiel/#{audioType}/f6.#{audioType}" "glock-8": "glockenspiel/#{audioType}/e6.#{audioType}" "glock-9": "glockenspiel/#{audioType}/d6.#{audioType}" "glock-10":"glockenspiel/#{audioType}/c6.#{audioType}" @buffers_ = {} @buffersToLoad_ = Object.keys(sounds) for soundName in @buffersToLoad_ @loadSound_(soundName, 'sounds/' + sounds[soundName]) # Simple getter for the AudioContext object. getContext: -> @context_ mute: (doit) -> @masterGainNode_.gain.value = if doit then 0 else 1 getLoadedProgress: -> return if @isSupported then @loadingProgress_ else 1 createBufferSource: -> source = @context_.createBufferSource() source.playbackRate.value = Utilities.range(Config.MIN_AUDIO_PLAYBACK_RATE, Config.MAX_AUDIO_PLAYBACK_RATE, Config.SIMULATION_RATE) source connectToDestination: (node) -> if @convolverNode_.buffer node.connect(@convolverNode_) node = @convolverNode_ else # If we can't load the convolver then everything sounds terrible. Might # as well leave the user in silence. return node.connect(@masterGainNode_) @masterGainNode_.connect(@compressorNode_) @compressorNode_.connect(@context_.destination) getBuffer: (soundName) -> @buffers_[soundName] # Patch inconsistencies between the old webkit api and the new standard api. # # THANKS <NAME>! patchWindow_: -> # Treat all context's equally. window.AudioContext = (window.AudioContext or window.webkitAudioContext) # An object that contains mappings from the old webkit API over to the new # standard API for certain objects. patches = "AudioContext": "createGain": "createGainNode" "AudioBufferSourceNode": "start": "noteOn" "off": "noteOff" for objectName in Object.keys(patches) objPatches = patches[objectName] for standardMethod in Object.keys(objPatches) oldMethod = objPatches[standardMethod] if not window[objectName][standardMethod] window[objectName][standardMethod] = window[objectName][oldMethod] loadSound_: (name, file) -> request = new XMLHttpRequest() request.open('GET', file, true) request.responseType = 'arraybuffer' request.onload = => @context_.decodeAudioData(request.response, (buffer) => @saveBuffer_(name, buffer) ) request.send(); saveBuffer_: (name, buffer) -> @buffers_[name] = buffer if name == "convolver" @convolverNode_.buffer = buffer @loadingProgress_ = Object.keys(@buffers_).length / @buffersToLoad_.length # export the class. window.SoundManager = SoundManager
true
SoundManager = initialize: -> this.patchWindow_(); @isSupported = Modernizr.webaudio @context_ = new AudioContext() @masterGainNode_ = @context_.createGain() @masterGainNode_.gain.value = 1 @compressorNode_ = @context_.createDynamicsCompressor() @convolverNode_ = @context_.createConvolver() @buffers_ = {} @loadingProgress_ = 0 load: () -> audioType = if Modernizr.audio.ogg then "ogg" else ( if Modernizr.audio.mp3 then "mp3" else "wav") sounds = "convolver": "dining-living-true-stereo.#{audioType}" "glock-0": "glockenspiel/#{audioType}/f7.#{audioType}" "glock-1": "glockenspiel/#{audioType}/e7.#{audioType}" "glock-2": "glockenspiel/#{audioType}/d7.#{audioType}" "glock-3": "glockenspiel/#{audioType}/c7.#{audioType}" "glock-4": "glockenspiel/#{audioType}/b6.#{audioType}" "glock-5": "glockenspiel/#{audioType}/a6.#{audioType}" "glock-6": "glockenspiel/#{audioType}/g6.#{audioType}" "glock-7": "glockenspiel/#{audioType}/f6.#{audioType}" "glock-8": "glockenspiel/#{audioType}/e6.#{audioType}" "glock-9": "glockenspiel/#{audioType}/d6.#{audioType}" "glock-10":"glockenspiel/#{audioType}/c6.#{audioType}" @buffers_ = {} @buffersToLoad_ = Object.keys(sounds) for soundName in @buffersToLoad_ @loadSound_(soundName, 'sounds/' + sounds[soundName]) # Simple getter for the AudioContext object. getContext: -> @context_ mute: (doit) -> @masterGainNode_.gain.value = if doit then 0 else 1 getLoadedProgress: -> return if @isSupported then @loadingProgress_ else 1 createBufferSource: -> source = @context_.createBufferSource() source.playbackRate.value = Utilities.range(Config.MIN_AUDIO_PLAYBACK_RATE, Config.MAX_AUDIO_PLAYBACK_RATE, Config.SIMULATION_RATE) source connectToDestination: (node) -> if @convolverNode_.buffer node.connect(@convolverNode_) node = @convolverNode_ else # If we can't load the convolver then everything sounds terrible. Might # as well leave the user in silence. return node.connect(@masterGainNode_) @masterGainNode_.connect(@compressorNode_) @compressorNode_.connect(@context_.destination) getBuffer: (soundName) -> @buffers_[soundName] # Patch inconsistencies between the old webkit api and the new standard api. # # THANKS PI:NAME:<NAME>END_PI! patchWindow_: -> # Treat all context's equally. window.AudioContext = (window.AudioContext or window.webkitAudioContext) # An object that contains mappings from the old webkit API over to the new # standard API for certain objects. patches = "AudioContext": "createGain": "createGainNode" "AudioBufferSourceNode": "start": "noteOn" "off": "noteOff" for objectName in Object.keys(patches) objPatches = patches[objectName] for standardMethod in Object.keys(objPatches) oldMethod = objPatches[standardMethod] if not window[objectName][standardMethod] window[objectName][standardMethod] = window[objectName][oldMethod] loadSound_: (name, file) -> request = new XMLHttpRequest() request.open('GET', file, true) request.responseType = 'arraybuffer' request.onload = => @context_.decodeAudioData(request.response, (buffer) => @saveBuffer_(name, buffer) ) request.send(); saveBuffer_: (name, buffer) -> @buffers_[name] = buffer if name == "convolver" @convolverNode_.buffer = buffer @loadingProgress_ = Object.keys(@buffers_).length / @buffersToLoad_.length # export the class. window.SoundManager = SoundManager
[ { "context": "id: 8\nname: \"Carer’s Allowance Digital Service\"\ndescription: \"Lets use", "end": 20, "score": 0.9325408935546875, "start": 13, "tag": "NAME", "value": "Carer’s" }, { "context": "sability\"\nlocation: \"Preston\"\nphase: \"live\"\nsro: \"Derek Hobbs\"\nservice_man: \"Pete Desmond\"\nphase_history:\n dis", "end": 273, "score": 0.999886691570282, "start": 262, "tag": "NAME", "value": "Derek Hobbs" }, { "context": "n\"\nphase: \"live\"\nsro: \"Derek Hobbs\"\nservice_man: \"Pete Desmond\"\nphase_history:\n discovery: [\n {\n label:", "end": 301, "score": 0.9998831748962402, "start": 289, "tag": "NAME", "value": "Pete Desmond" } ]
app/data/projects/carers-allowance.cson
tsmorgan/dwp-ux-work
0
id: 8 name: "Carer’s Allowance Digital Service" description: "Lets users who care for another person for more than 35 hours a week get a regular payment so that they can carry on giving care." theme: "Health & Disability" location: "Preston" phase: "live" sro: "Derek Hobbs" service_man: "Pete Desmond" phase_history: discovery: [ { label: "Completed" date: "September 2012" } ] alpha: [ { label: "Completed" date: "December 2012" } ] beta: [ { label: "Private beta completed" date: "July 2013" } { label: "Public beta released" date: "October 2013" } ] live: [ { label: "Live service assessment" date: "November 2014" report: "https://gdsdata.blog.gov.uk/carers-allowance-service-assessment/" } ] priority: "" service_assessment_live: "https://gdsdata.blog.gov.uk/carers-allowance-service-assessment" prototype: "https://dwp-story.3cbeta.co.uk/URSept/" video: "IYBLX3V8ek4" liveservice: "https://www.gov.uk/carers-allowance"
148408
id: 8 name: "<NAME> Allowance Digital Service" description: "Lets users who care for another person for more than 35 hours a week get a regular payment so that they can carry on giving care." theme: "Health & Disability" location: "Preston" phase: "live" sro: "<NAME>" service_man: "<NAME>" phase_history: discovery: [ { label: "Completed" date: "September 2012" } ] alpha: [ { label: "Completed" date: "December 2012" } ] beta: [ { label: "Private beta completed" date: "July 2013" } { label: "Public beta released" date: "October 2013" } ] live: [ { label: "Live service assessment" date: "November 2014" report: "https://gdsdata.blog.gov.uk/carers-allowance-service-assessment/" } ] priority: "" service_assessment_live: "https://gdsdata.blog.gov.uk/carers-allowance-service-assessment" prototype: "https://dwp-story.3cbeta.co.uk/URSept/" video: "IYBLX3V8ek4" liveservice: "https://www.gov.uk/carers-allowance"
true
id: 8 name: "PI:NAME:<NAME>END_PI Allowance Digital Service" description: "Lets users who care for another person for more than 35 hours a week get a regular payment so that they can carry on giving care." theme: "Health & Disability" location: "Preston" phase: "live" sro: "PI:NAME:<NAME>END_PI" service_man: "PI:NAME:<NAME>END_PI" phase_history: discovery: [ { label: "Completed" date: "September 2012" } ] alpha: [ { label: "Completed" date: "December 2012" } ] beta: [ { label: "Private beta completed" date: "July 2013" } { label: "Public beta released" date: "October 2013" } ] live: [ { label: "Live service assessment" date: "November 2014" report: "https://gdsdata.blog.gov.uk/carers-allowance-service-assessment/" } ] priority: "" service_assessment_live: "https://gdsdata.blog.gov.uk/carers-allowance-service-assessment" prototype: "https://dwp-story.3cbeta.co.uk/URSept/" video: "IYBLX3V8ek4" liveservice: "https://www.gov.uk/carers-allowance"
[ { "context": "on occurs\ntmp.setGracefulCleanup()\nCHANNEL_KEY = 'retailerA'\n\n{ client_id, client_secret, project_key } = Con", "end": 503, "score": 0.9958871006965637, "start": 494, "tag": "KEY", "value": "retailerA" }, { "context": "Type\",\"name\",\"variantId\",\"slug\",\"prices\"],\n [@productType.id,@newProductName,1,@newProductSlug,\"EUR 899;CH-", "end": 4042, "score": 0.8452252745628357, "start": 4029, "tag": "USERNAME", "value": "[@productType" }, { "context": "ariantId\",\"slug\",\"prices\"],\n [@productType.id,@newProductName,1,@newProductSlug,\"EUR 899;CH-EUR", "end": 4045, "score": 0.5142833590507507, "start": 4043, "tag": "USERNAME", "value": "id" }, { "context": "iantId\",\"slug\",\"prices\"],\n [@productType.id,@newProductName,1,@newProductSlug,\"EUR 899;CH-EUR 999;DE-EUR 999|", "end": 4061, "score": 0.9245104193687439, "start": 4046, "tag": "USERNAME", "value": "@newProductName" }, { "context": "],\n [@productType.id,@newProductName,1,@newProductSlug,\"EUR 899;CH-EUR 999;DE-EUR 999|799;CH-USD 777", "end": 4075, "score": 0.7046306133270264, "start": 4068, "tag": "USERNAME", "value": "Product" }, { "context": "roductType\",\"name\",\"variantId\",\"slug\"],\n [@productType.id,@newProductName,1,@newProductSlug]\n ]\n\n ", "end": 5622, "score": 0.7288366556167603, "start": 5608, "tag": "USERNAME", "value": "productType.id" }, { "context": "ame\",\"variantId\",\"slug\"],\n [@productType.id,@newProductName,1,@newProductSlug]\n ]\n\n writeXlsx(fileP", "end": 5638, "score": 0.91905277967453, "start": 5623, "tag": "USERNAME", "value": "@newProductName" }, { "context": "],\n [@productType.id,@newProductName,1,@newProductSlug]\n ]\n\n writeXlsx(filePath, data)\n ", "end": 5652, "score": 0.5912939310073853, "start": 5645, "tag": "USERNAME", "value": "Product" }, { "context": "tType\",\"name\",\"sku\",\"variantId\",\"prices\"],\n [@productType.id,@newProductName,@newProductSku+1,1,\"EUR 999\"],\n ", "end": 6378, "score": 0.8723125457763672, "start": 6362, "tag": "USERNAME", "value": "[@productType.id" }, { "context": ",\"variantId\",\"prices\"],\n [@productType.id,@newProductName,@newProductSku+1,1,\"EUR 999\"],\n [null,null", "end": 6394, "score": 0.6567547917366028, "start": 6380, "tag": "USERNAME", "value": "newProductName" } ]
src/spec/integration/importXlsx.spec.coffee
daern91/sphere-node-product-csv-sync
0
Promise = require 'bluebird' _ = require 'underscore' archiver = require 'archiver' _.mixin require('underscore-mixins') iconv = require 'iconv-lite' {Import} = require '../../lib/main' Config = require '../../config' TestHelpers = require './testhelpers' Excel = require 'exceljs' cuid = require 'cuid' path = require 'path' tmp = require 'tmp' fs = Promise.promisifyAll require('fs') # will clean temporary files even when an uncaught exception occurs tmp.setGracefulCleanup() CHANNEL_KEY = 'retailerA' { client_id, client_secret, project_key } = Config.config authConfig = { host: 'https://auth.sphere.io' projectKey: project_key credentials: { clientId: client_id clientSecret: client_secret } } httpConfig = { host: 'https://api.sphere.io' } userAgentConfig = {} writeXlsx = (filePath, data) -> workbook = new Excel.Workbook() workbook.created = new Date() worksheet = workbook.addWorksheet('Products') console.log "Generating Xlsx file" data.forEach (items, index) -> if index worksheet.addRow items else headers = [] for i of items headers.push { header: items[i] } worksheet.columns = headers workbook.xlsx.writeFile(filePath) createImporter = -> Config.importFormat = "xlsx" im = new Import { authConfig: authConfig httpConfig: httpConfig userAgentConfig: userAgentConfig } im.matchBy = 'sku' im.allowRemovalOfVariants = true im.suppressMissingHeaderWarning = true im describe 'Import integration test', -> beforeEach (done) -> jasmine.getEnv().defaultTimeoutInterval = 90000 # 90 sec @importer = createImporter() @client = @importer.client @productType = TestHelpers.mockProductType() TestHelpers.setupProductType(@client, @productType, null, project_key) .then (result) => @productType = result # Check if channel exists service = TestHelpers.createService(project_key, 'channels') request = { uri: service .where("key=\"#{CHANNEL_KEY}\"") .build() method: 'GET' } @client.execute request .then (result) => # Create the channel if it doesn't exist else ignore if (!result.body.total) service = TestHelpers.createService(project_key, 'channels') request = { uri: service.build() method: 'POST' body: key: CHANNEL_KEY roles: ['InventorySupply'] } @client.execute request .then -> done() .catch (err) -> done _.prettify(err.body) , 120000 # 2min describe '#importXlsx', -> beforeEach -> @newProductName = TestHelpers.uniqueId 'name-' @newProductSlug = TestHelpers.uniqueId 'slug-' @newProductSku = TestHelpers.uniqueId 'sku-' it 'should import a simple product from xlsx', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","variantId","slug"], [@productType.id,@newProductName,1,@newProductSlug] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' service = TestHelpers.createService(project_key, 'productProjections') request = { uri: service .where("productType(id=\"#{@productType.id}\")") .staged(true) .build() method: 'GET' } @client.execute request .then (result) => expect(_.size result.body.results).toBe 1 p = result.body.results[0] expect(p.name).toEqual en: @newProductName expect(p.slug).toEqual en: @newProductSlug done() .catch (err) -> done _.prettify(err) it 'should import a product with prices (even when one of them is discounted)', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","variantId","slug","prices"], [@productType.id,@newProductName,1,@newProductSlug,"EUR 899;CH-EUR 999;DE-EUR 999|799;CH-USD 77777700 ##{CHANNEL_KEY}"] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' service = TestHelpers.createService(project_key, 'productProjections') request = { uri: service .where("productType(id=\"#{@productType.id}\")") .staged(true) .build() method: 'GET' } @client.execute request .then (result) -> expect(_.size result.body.results).toBe 1 p = result.body.results[0] expect(_.size p.masterVariant.prices).toBe 4 prices = p.masterVariant.prices expect(prices[0].value).toEqual jasmine.objectContaining(currencyCode: 'EUR', centAmount: 899) expect(prices[1].value).toEqual jasmine.objectContaining(currencyCode: 'EUR', centAmount: 999) expect(prices[1].country).toBe 'CH' expect(prices[2].country).toBe 'DE' expect(prices[2].value).toEqual jasmine.objectContaining(currencyCode: 'EUR', centAmount: 999) expect(prices[3].channel.typeId).toBe 'channel' expect(prices[3].channel.id).toBeDefined() done() .catch (err) -> done _.prettify(err) it 'should do nothing on 2nd import run', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","variantId","slug"], [@productType.id,@newProductName,1,@newProductSlug] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) -> expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' im = createImporter() im.matchBy = 'slug' im.importManager(filePath) .then (result) -> expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] Product update not necessary.' done() .catch (err) -> done _.prettify(err) it 'should do a partial update of prices based on SKUs', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","sku","variantId","prices"], [@productType.id,@newProductName,@newProductSku+1,1,"EUR 999"], [null,null,@newProductSku+2,2,"USD 70000"] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' csv = """ sku,prices,productType #{@newProductSku+1},EUR 1999,#{@productType.name} #{@newProductSku+2},USD 80000,#{@productType.name} """ im = createImporter() im.allowRemovalOfVariants = false im.updatesOnly = true im.import(csv) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] Product updated.' service = TestHelpers.createService(project_key, 'productProjections') request = { uri: service .where("productType(id=\"#{@productType.id}\")") .staged(true) .build() method: 'GET' } @client.execute request .then (result) => expect(_.size result.body.results).toBe 1 p = result.body.results[0] expect(p.name).toEqual {en: @newProductName} expect(p.masterVariant.sku).toBe "#{@newProductSku}1" expect(p.masterVariant.prices[0].value).toEqual jasmine.objectContaining(centAmount: 1999, currencyCode: 'EUR') expect(p.variants[0].sku).toBe "#{@newProductSku}2" expect(p.variants[0].prices[0].value).toEqual jasmine.objectContaining(centAmount: 80000, currencyCode: 'USD') done() .catch (err) -> done _.prettify(err)
74508
Promise = require 'bluebird' _ = require 'underscore' archiver = require 'archiver' _.mixin require('underscore-mixins') iconv = require 'iconv-lite' {Import} = require '../../lib/main' Config = require '../../config' TestHelpers = require './testhelpers' Excel = require 'exceljs' cuid = require 'cuid' path = require 'path' tmp = require 'tmp' fs = Promise.promisifyAll require('fs') # will clean temporary files even when an uncaught exception occurs tmp.setGracefulCleanup() CHANNEL_KEY = '<KEY>' { client_id, client_secret, project_key } = Config.config authConfig = { host: 'https://auth.sphere.io' projectKey: project_key credentials: { clientId: client_id clientSecret: client_secret } } httpConfig = { host: 'https://api.sphere.io' } userAgentConfig = {} writeXlsx = (filePath, data) -> workbook = new Excel.Workbook() workbook.created = new Date() worksheet = workbook.addWorksheet('Products') console.log "Generating Xlsx file" data.forEach (items, index) -> if index worksheet.addRow items else headers = [] for i of items headers.push { header: items[i] } worksheet.columns = headers workbook.xlsx.writeFile(filePath) createImporter = -> Config.importFormat = "xlsx" im = new Import { authConfig: authConfig httpConfig: httpConfig userAgentConfig: userAgentConfig } im.matchBy = 'sku' im.allowRemovalOfVariants = true im.suppressMissingHeaderWarning = true im describe 'Import integration test', -> beforeEach (done) -> jasmine.getEnv().defaultTimeoutInterval = 90000 # 90 sec @importer = createImporter() @client = @importer.client @productType = TestHelpers.mockProductType() TestHelpers.setupProductType(@client, @productType, null, project_key) .then (result) => @productType = result # Check if channel exists service = TestHelpers.createService(project_key, 'channels') request = { uri: service .where("key=\"#{CHANNEL_KEY}\"") .build() method: 'GET' } @client.execute request .then (result) => # Create the channel if it doesn't exist else ignore if (!result.body.total) service = TestHelpers.createService(project_key, 'channels') request = { uri: service.build() method: 'POST' body: key: CHANNEL_KEY roles: ['InventorySupply'] } @client.execute request .then -> done() .catch (err) -> done _.prettify(err.body) , 120000 # 2min describe '#importXlsx', -> beforeEach -> @newProductName = TestHelpers.uniqueId 'name-' @newProductSlug = TestHelpers.uniqueId 'slug-' @newProductSku = TestHelpers.uniqueId 'sku-' it 'should import a simple product from xlsx', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","variantId","slug"], [@productType.id,@newProductName,1,@newProductSlug] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' service = TestHelpers.createService(project_key, 'productProjections') request = { uri: service .where("productType(id=\"#{@productType.id}\")") .staged(true) .build() method: 'GET' } @client.execute request .then (result) => expect(_.size result.body.results).toBe 1 p = result.body.results[0] expect(p.name).toEqual en: @newProductName expect(p.slug).toEqual en: @newProductSlug done() .catch (err) -> done _.prettify(err) it 'should import a product with prices (even when one of them is discounted)', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","variantId","slug","prices"], [@productType.id,@newProductName,1,@newProductSlug,"EUR 899;CH-EUR 999;DE-EUR 999|799;CH-USD 77777700 ##{CHANNEL_KEY}"] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' service = TestHelpers.createService(project_key, 'productProjections') request = { uri: service .where("productType(id=\"#{@productType.id}\")") .staged(true) .build() method: 'GET' } @client.execute request .then (result) -> expect(_.size result.body.results).toBe 1 p = result.body.results[0] expect(_.size p.masterVariant.prices).toBe 4 prices = p.masterVariant.prices expect(prices[0].value).toEqual jasmine.objectContaining(currencyCode: 'EUR', centAmount: 899) expect(prices[1].value).toEqual jasmine.objectContaining(currencyCode: 'EUR', centAmount: 999) expect(prices[1].country).toBe 'CH' expect(prices[2].country).toBe 'DE' expect(prices[2].value).toEqual jasmine.objectContaining(currencyCode: 'EUR', centAmount: 999) expect(prices[3].channel.typeId).toBe 'channel' expect(prices[3].channel.id).toBeDefined() done() .catch (err) -> done _.prettify(err) it 'should do nothing on 2nd import run', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","variantId","slug"], [@productType.id,@newProductName,1,@newProductSlug] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) -> expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' im = createImporter() im.matchBy = 'slug' im.importManager(filePath) .then (result) -> expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] Product update not necessary.' done() .catch (err) -> done _.prettify(err) it 'should do a partial update of prices based on SKUs', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","sku","variantId","prices"], [@productType.id,@newProductName,@newProductSku+1,1,"EUR 999"], [null,null,@newProductSku+2,2,"USD 70000"] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' csv = """ sku,prices,productType #{@newProductSku+1},EUR 1999,#{@productType.name} #{@newProductSku+2},USD 80000,#{@productType.name} """ im = createImporter() im.allowRemovalOfVariants = false im.updatesOnly = true im.import(csv) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] Product updated.' service = TestHelpers.createService(project_key, 'productProjections') request = { uri: service .where("productType(id=\"#{@productType.id}\")") .staged(true) .build() method: 'GET' } @client.execute request .then (result) => expect(_.size result.body.results).toBe 1 p = result.body.results[0] expect(p.name).toEqual {en: @newProductName} expect(p.masterVariant.sku).toBe "#{@newProductSku}1" expect(p.masterVariant.prices[0].value).toEqual jasmine.objectContaining(centAmount: 1999, currencyCode: 'EUR') expect(p.variants[0].sku).toBe "#{@newProductSku}2" expect(p.variants[0].prices[0].value).toEqual jasmine.objectContaining(centAmount: 80000, currencyCode: 'USD') done() .catch (err) -> done _.prettify(err)
true
Promise = require 'bluebird' _ = require 'underscore' archiver = require 'archiver' _.mixin require('underscore-mixins') iconv = require 'iconv-lite' {Import} = require '../../lib/main' Config = require '../../config' TestHelpers = require './testhelpers' Excel = require 'exceljs' cuid = require 'cuid' path = require 'path' tmp = require 'tmp' fs = Promise.promisifyAll require('fs') # will clean temporary files even when an uncaught exception occurs tmp.setGracefulCleanup() CHANNEL_KEY = 'PI:KEY:<KEY>END_PI' { client_id, client_secret, project_key } = Config.config authConfig = { host: 'https://auth.sphere.io' projectKey: project_key credentials: { clientId: client_id clientSecret: client_secret } } httpConfig = { host: 'https://api.sphere.io' } userAgentConfig = {} writeXlsx = (filePath, data) -> workbook = new Excel.Workbook() workbook.created = new Date() worksheet = workbook.addWorksheet('Products') console.log "Generating Xlsx file" data.forEach (items, index) -> if index worksheet.addRow items else headers = [] for i of items headers.push { header: items[i] } worksheet.columns = headers workbook.xlsx.writeFile(filePath) createImporter = -> Config.importFormat = "xlsx" im = new Import { authConfig: authConfig httpConfig: httpConfig userAgentConfig: userAgentConfig } im.matchBy = 'sku' im.allowRemovalOfVariants = true im.suppressMissingHeaderWarning = true im describe 'Import integration test', -> beforeEach (done) -> jasmine.getEnv().defaultTimeoutInterval = 90000 # 90 sec @importer = createImporter() @client = @importer.client @productType = TestHelpers.mockProductType() TestHelpers.setupProductType(@client, @productType, null, project_key) .then (result) => @productType = result # Check if channel exists service = TestHelpers.createService(project_key, 'channels') request = { uri: service .where("key=\"#{CHANNEL_KEY}\"") .build() method: 'GET' } @client.execute request .then (result) => # Create the channel if it doesn't exist else ignore if (!result.body.total) service = TestHelpers.createService(project_key, 'channels') request = { uri: service.build() method: 'POST' body: key: CHANNEL_KEY roles: ['InventorySupply'] } @client.execute request .then -> done() .catch (err) -> done _.prettify(err.body) , 120000 # 2min describe '#importXlsx', -> beforeEach -> @newProductName = TestHelpers.uniqueId 'name-' @newProductSlug = TestHelpers.uniqueId 'slug-' @newProductSku = TestHelpers.uniqueId 'sku-' it 'should import a simple product from xlsx', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","variantId","slug"], [@productType.id,@newProductName,1,@newProductSlug] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' service = TestHelpers.createService(project_key, 'productProjections') request = { uri: service .where("productType(id=\"#{@productType.id}\")") .staged(true) .build() method: 'GET' } @client.execute request .then (result) => expect(_.size result.body.results).toBe 1 p = result.body.results[0] expect(p.name).toEqual en: @newProductName expect(p.slug).toEqual en: @newProductSlug done() .catch (err) -> done _.prettify(err) it 'should import a product with prices (even when one of them is discounted)', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","variantId","slug","prices"], [@productType.id,@newProductName,1,@newProductSlug,"EUR 899;CH-EUR 999;DE-EUR 999|799;CH-USD 77777700 ##{CHANNEL_KEY}"] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' service = TestHelpers.createService(project_key, 'productProjections') request = { uri: service .where("productType(id=\"#{@productType.id}\")") .staged(true) .build() method: 'GET' } @client.execute request .then (result) -> expect(_.size result.body.results).toBe 1 p = result.body.results[0] expect(_.size p.masterVariant.prices).toBe 4 prices = p.masterVariant.prices expect(prices[0].value).toEqual jasmine.objectContaining(currencyCode: 'EUR', centAmount: 899) expect(prices[1].value).toEqual jasmine.objectContaining(currencyCode: 'EUR', centAmount: 999) expect(prices[1].country).toBe 'CH' expect(prices[2].country).toBe 'DE' expect(prices[2].value).toEqual jasmine.objectContaining(currencyCode: 'EUR', centAmount: 999) expect(prices[3].channel.typeId).toBe 'channel' expect(prices[3].channel.id).toBeDefined() done() .catch (err) -> done _.prettify(err) it 'should do nothing on 2nd import run', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","variantId","slug"], [@productType.id,@newProductName,1,@newProductSlug] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) -> expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' im = createImporter() im.matchBy = 'slug' im.importManager(filePath) .then (result) -> expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] Product update not necessary.' done() .catch (err) -> done _.prettify(err) it 'should do a partial update of prices based on SKUs', (done) -> filePath = "/tmp/test-import.xlsx" data = [ ["productType","name","sku","variantId","prices"], [@productType.id,@newProductName,@newProductSku+1,1,"EUR 999"], [null,null,@newProductSku+2,2,"USD 70000"] ] writeXlsx(filePath, data) .then () => @importer.importManager(filePath) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] New product created.' csv = """ sku,prices,productType #{@newProductSku+1},EUR 1999,#{@productType.name} #{@newProductSku+2},USD 80000,#{@productType.name} """ im = createImporter() im.allowRemovalOfVariants = false im.updatesOnly = true im.import(csv) .then (result) => expect(_.size result).toBe 1 expect(result[0]).toBe '[row 2] Product updated.' service = TestHelpers.createService(project_key, 'productProjections') request = { uri: service .where("productType(id=\"#{@productType.id}\")") .staged(true) .build() method: 'GET' } @client.execute request .then (result) => expect(_.size result.body.results).toBe 1 p = result.body.results[0] expect(p.name).toEqual {en: @newProductName} expect(p.masterVariant.sku).toBe "#{@newProductSku}1" expect(p.masterVariant.prices[0].value).toEqual jasmine.objectContaining(centAmount: 1999, currencyCode: 'EUR') expect(p.variants[0].sku).toBe "#{@newProductSku}2" expect(p.variants[0].prices[0].value).toEqual jasmine.objectContaining(centAmount: 80000, currencyCode: 'USD') done() .catch (err) -> done _.prettify(err)
[ { "context": "pponentName: @nameMap[session.get('creator')] or 'Anoner'\n opponentID: session.get('creator')\n ", "end": 4541, "score": 0.5210468769073486, "start": 4539, "tag": "NAME", "value": "An" }, { "context": "onentName: @nameMap[session.get('creator')] or 'Anoner'\n opponentID: session.get('creator')\n }\n\n", "end": 4545, "score": 0.6814329624176025, "start": 4541, "tag": "USERNAME", "value": "oner" }, { "context": "ssionID\n opponentName: opponent.userName or 'Anoner'\n opponentID: opponent.userID\n }\n\n rankS", "end": 4830, "score": 0.9443225860595703, "start": 4824, "tag": "USERNAME", "value": "Anoner" } ]
app/views/play/ladder/team_view.coffee
vyz1194/codecombat
0
RootView = require 'views/kinds/RootView' Level = require 'models/Level' LevelSession = require 'models/LevelSession' LeaderboardCollection = require 'collections/LeaderboardCollection' module.exports = class LadderTeamView extends RootView id: 'ladder-team-view' template: require 'templates/play/ladder/team' startsLoading: true events: 'click #rank-button': 'rankSession' # PART 1: Loading Level/Session constructor: (options, @levelID, @team) -> super(options) @otherTeam = if team is 'ogres' then 'humans' else 'ogres' @level = new Level(_id:@levelID) @level.fetch() @level.once 'sync', @onLevelLoaded, @ url = "/db/level/#{@levelID}/session?team=#{@team}" @session = new LevelSession() @session.url = -> url @session.fetch() @session.once 'sync', @onSessionLoaded, @ onLevelLoaded: -> @startLoadingChallengersMaybe() onSessionLoaded: -> @startLoadingChallengersMaybe() # PART 2: Loading some challengers if we don't have any matches yet startLoadingChallengersMaybe: -> return unless @level.loaded and @session.loaded matches = @session.get('matches') if matches?.length then @loadNames() else @loadChallengers() loadChallengers: -> @challengers = new ChallengersData(@level, @team, @otherTeam, @session) @challengers.on 'sync', @loadNames, @ # PART 3: Loading the names of the other users loadNames: -> ids = [] ids.push match.opponents[0].userID for match in @session.get('matches') or [] ids = ids.concat(@challengers.playerIDs()) if @challengers success = (@nameMap) => for match in @session.get('matches') or [] opponent = match.opponents[0] opponent.userName = @nameMap[opponent.userID] @finishRendering() $.ajax('/db/user/-/names', { data: {ids: ids} type: 'POST' success: success }) # PART 4: Rendering finishRendering: -> @startsLoading = false @render() getRenderData: -> ctx = super() ctx.level = @level ctx.levelID = @levelID ctx.teamName = _.string.titleize @team ctx.teamID = @team ctx.otherTeamID = @otherTeam ctx.challengers = if not @startsLoading then @getChallengers() else {} ctx.readyToRank = @readyToRank() convertMatch = (match) => opponent = match.opponents[0] state = 'win' state = 'loss' if match.metrics.rank > opponent.metrics.rank state = 'tie' if match.metrics.rank is opponent.metrics.rank { state: state opponentName: @nameMap[opponent.userID] opponentID: opponent.userID when: moment(match.date).fromNow() sessionID: opponent.sessionID } ctx.matches = (convertMatch(match) for match in @session.get('matches') or []) ctx.matches.reverse() ctx.score = (@session.get('totalScore') or 10).toFixed(2) ctx afterRender: -> super() @setRankingButtonText(if @readyToRank() then 'rank' else 'unavailable') readyToRank: -> c1 = @session.get('code') c2 = @session.get('submittedCode') c1 and not _.isEqual(c1, c2) getChallengers: -> # make an object of challengers to everything needed to link to them challengers = {} if @challengers easyInfo = @challengeInfoFromSession(@challengers.easyPlayer.models[0]) mediumInfo = @challengeInfoFromSession(@challengers.mediumPlayer.models[0]) hardInfo = @challengeInfoFromSession(@challengers.hardPlayer.models[0]) else matches = @session.get('matches') won = (m for m in matches when m.metrics.rank < m.opponents[0].metrics.rank) lost = (m for m in matches when m.metrics.rank > m.opponents[0].metrics.rank) tied = (m for m in matches when m.metrics.rank is m.opponents[0].metrics.rank) easyInfo = @challengeInfoFromMatches(won) mediumInfo = @challengeInfoFromMatches(tied) hardInfo = @challengeInfoFromMatches(lost) @addChallenger easyInfo, challengers, 'easy' @addChallenger mediumInfo, challengers, 'medium' @addChallenger hardInfo, challengers, 'hard' challengers addChallenger: (info, challengers, title) -> # check for duplicates first return unless info for key, value of challengers return if value.sessionID is info.sessionID challengers[title] = info challengeInfoFromSession: (session) -> # given a model from the db, return info needed for a link to the match return unless session return { sessionID: session.id opponentName: @nameMap[session.get('creator')] or 'Anoner' opponentID: session.get('creator') } challengeInfoFromMatches: (matches) -> return unless matches?.length match = _.sample matches opponent = match.opponents[0] return { sessionID: opponent.sessionID opponentName: opponent.userName or 'Anoner' opponentID: opponent.userID } rankSession: -> return unless @readyToRank() @setRankingButtonText('ranking') success = => @setRankingButtonText('ranked') failure = => @setRankingButtonText('failed') $.ajax '/queue/scoring', { type: 'POST' data: { session: @session.id } success: success failure: failure } setRankingButtonText: (spanClass) -> rankButton = $('#rank-button') rankButton.find('span').addClass('hidden') rankButton.find(".#{spanClass}").removeClass('hidden') rankButton.toggleClass 'disabled', spanClass isnt 'rank' class ChallengersData constructor: (@level, @team, @otherTeam, @session) -> _.extend @, Backbone.Events score = @session?.get('totalScore') or 25 @easyPlayer = new LeaderboardCollection(@level, {order:1, scoreOffset: score - 5, limit: 1, team: @otherTeam}) @easyPlayer.fetch() @easyPlayer.once 'sync', @challengerLoaded, @ @mediumPlayer = new LeaderboardCollection(@level, {order:1, scoreOffset: score, limit: 1, team: @otherTeam}) @mediumPlayer.fetch() @mediumPlayer.once 'sync', @challengerLoaded, @ @hardPlayer = new LeaderboardCollection(@level, {order:-1, scoreOffset: score + 5, limit: 1, team: @otherTeam}) @hardPlayer.fetch() @hardPlayer.once 'sync', @challengerLoaded, @ challengerLoaded: -> if @allLoaded() @loaded = true @trigger 'sync' playerIDs: -> collections = [@easyPlayer, @mediumPlayer, @hardPlayer] (c.models[0].get('creator') for c in collections when c?.models[0]) allLoaded: -> _.all [@easyPlayer.loaded, @mediumPlayer.loaded, @hardPlayer.loaded]
174012
RootView = require 'views/kinds/RootView' Level = require 'models/Level' LevelSession = require 'models/LevelSession' LeaderboardCollection = require 'collections/LeaderboardCollection' module.exports = class LadderTeamView extends RootView id: 'ladder-team-view' template: require 'templates/play/ladder/team' startsLoading: true events: 'click #rank-button': 'rankSession' # PART 1: Loading Level/Session constructor: (options, @levelID, @team) -> super(options) @otherTeam = if team is 'ogres' then 'humans' else 'ogres' @level = new Level(_id:@levelID) @level.fetch() @level.once 'sync', @onLevelLoaded, @ url = "/db/level/#{@levelID}/session?team=#{@team}" @session = new LevelSession() @session.url = -> url @session.fetch() @session.once 'sync', @onSessionLoaded, @ onLevelLoaded: -> @startLoadingChallengersMaybe() onSessionLoaded: -> @startLoadingChallengersMaybe() # PART 2: Loading some challengers if we don't have any matches yet startLoadingChallengersMaybe: -> return unless @level.loaded and @session.loaded matches = @session.get('matches') if matches?.length then @loadNames() else @loadChallengers() loadChallengers: -> @challengers = new ChallengersData(@level, @team, @otherTeam, @session) @challengers.on 'sync', @loadNames, @ # PART 3: Loading the names of the other users loadNames: -> ids = [] ids.push match.opponents[0].userID for match in @session.get('matches') or [] ids = ids.concat(@challengers.playerIDs()) if @challengers success = (@nameMap) => for match in @session.get('matches') or [] opponent = match.opponents[0] opponent.userName = @nameMap[opponent.userID] @finishRendering() $.ajax('/db/user/-/names', { data: {ids: ids} type: 'POST' success: success }) # PART 4: Rendering finishRendering: -> @startsLoading = false @render() getRenderData: -> ctx = super() ctx.level = @level ctx.levelID = @levelID ctx.teamName = _.string.titleize @team ctx.teamID = @team ctx.otherTeamID = @otherTeam ctx.challengers = if not @startsLoading then @getChallengers() else {} ctx.readyToRank = @readyToRank() convertMatch = (match) => opponent = match.opponents[0] state = 'win' state = 'loss' if match.metrics.rank > opponent.metrics.rank state = 'tie' if match.metrics.rank is opponent.metrics.rank { state: state opponentName: @nameMap[opponent.userID] opponentID: opponent.userID when: moment(match.date).fromNow() sessionID: opponent.sessionID } ctx.matches = (convertMatch(match) for match in @session.get('matches') or []) ctx.matches.reverse() ctx.score = (@session.get('totalScore') or 10).toFixed(2) ctx afterRender: -> super() @setRankingButtonText(if @readyToRank() then 'rank' else 'unavailable') readyToRank: -> c1 = @session.get('code') c2 = @session.get('submittedCode') c1 and not _.isEqual(c1, c2) getChallengers: -> # make an object of challengers to everything needed to link to them challengers = {} if @challengers easyInfo = @challengeInfoFromSession(@challengers.easyPlayer.models[0]) mediumInfo = @challengeInfoFromSession(@challengers.mediumPlayer.models[0]) hardInfo = @challengeInfoFromSession(@challengers.hardPlayer.models[0]) else matches = @session.get('matches') won = (m for m in matches when m.metrics.rank < m.opponents[0].metrics.rank) lost = (m for m in matches when m.metrics.rank > m.opponents[0].metrics.rank) tied = (m for m in matches when m.metrics.rank is m.opponents[0].metrics.rank) easyInfo = @challengeInfoFromMatches(won) mediumInfo = @challengeInfoFromMatches(tied) hardInfo = @challengeInfoFromMatches(lost) @addChallenger easyInfo, challengers, 'easy' @addChallenger mediumInfo, challengers, 'medium' @addChallenger hardInfo, challengers, 'hard' challengers addChallenger: (info, challengers, title) -> # check for duplicates first return unless info for key, value of challengers return if value.sessionID is info.sessionID challengers[title] = info challengeInfoFromSession: (session) -> # given a model from the db, return info needed for a link to the match return unless session return { sessionID: session.id opponentName: @nameMap[session.get('creator')] or '<NAME>oner' opponentID: session.get('creator') } challengeInfoFromMatches: (matches) -> return unless matches?.length match = _.sample matches opponent = match.opponents[0] return { sessionID: opponent.sessionID opponentName: opponent.userName or 'Anoner' opponentID: opponent.userID } rankSession: -> return unless @readyToRank() @setRankingButtonText('ranking') success = => @setRankingButtonText('ranked') failure = => @setRankingButtonText('failed') $.ajax '/queue/scoring', { type: 'POST' data: { session: @session.id } success: success failure: failure } setRankingButtonText: (spanClass) -> rankButton = $('#rank-button') rankButton.find('span').addClass('hidden') rankButton.find(".#{spanClass}").removeClass('hidden') rankButton.toggleClass 'disabled', spanClass isnt 'rank' class ChallengersData constructor: (@level, @team, @otherTeam, @session) -> _.extend @, Backbone.Events score = @session?.get('totalScore') or 25 @easyPlayer = new LeaderboardCollection(@level, {order:1, scoreOffset: score - 5, limit: 1, team: @otherTeam}) @easyPlayer.fetch() @easyPlayer.once 'sync', @challengerLoaded, @ @mediumPlayer = new LeaderboardCollection(@level, {order:1, scoreOffset: score, limit: 1, team: @otherTeam}) @mediumPlayer.fetch() @mediumPlayer.once 'sync', @challengerLoaded, @ @hardPlayer = new LeaderboardCollection(@level, {order:-1, scoreOffset: score + 5, limit: 1, team: @otherTeam}) @hardPlayer.fetch() @hardPlayer.once 'sync', @challengerLoaded, @ challengerLoaded: -> if @allLoaded() @loaded = true @trigger 'sync' playerIDs: -> collections = [@easyPlayer, @mediumPlayer, @hardPlayer] (c.models[0].get('creator') for c in collections when c?.models[0]) allLoaded: -> _.all [@easyPlayer.loaded, @mediumPlayer.loaded, @hardPlayer.loaded]
true
RootView = require 'views/kinds/RootView' Level = require 'models/Level' LevelSession = require 'models/LevelSession' LeaderboardCollection = require 'collections/LeaderboardCollection' module.exports = class LadderTeamView extends RootView id: 'ladder-team-view' template: require 'templates/play/ladder/team' startsLoading: true events: 'click #rank-button': 'rankSession' # PART 1: Loading Level/Session constructor: (options, @levelID, @team) -> super(options) @otherTeam = if team is 'ogres' then 'humans' else 'ogres' @level = new Level(_id:@levelID) @level.fetch() @level.once 'sync', @onLevelLoaded, @ url = "/db/level/#{@levelID}/session?team=#{@team}" @session = new LevelSession() @session.url = -> url @session.fetch() @session.once 'sync', @onSessionLoaded, @ onLevelLoaded: -> @startLoadingChallengersMaybe() onSessionLoaded: -> @startLoadingChallengersMaybe() # PART 2: Loading some challengers if we don't have any matches yet startLoadingChallengersMaybe: -> return unless @level.loaded and @session.loaded matches = @session.get('matches') if matches?.length then @loadNames() else @loadChallengers() loadChallengers: -> @challengers = new ChallengersData(@level, @team, @otherTeam, @session) @challengers.on 'sync', @loadNames, @ # PART 3: Loading the names of the other users loadNames: -> ids = [] ids.push match.opponents[0].userID for match in @session.get('matches') or [] ids = ids.concat(@challengers.playerIDs()) if @challengers success = (@nameMap) => for match in @session.get('matches') or [] opponent = match.opponents[0] opponent.userName = @nameMap[opponent.userID] @finishRendering() $.ajax('/db/user/-/names', { data: {ids: ids} type: 'POST' success: success }) # PART 4: Rendering finishRendering: -> @startsLoading = false @render() getRenderData: -> ctx = super() ctx.level = @level ctx.levelID = @levelID ctx.teamName = _.string.titleize @team ctx.teamID = @team ctx.otherTeamID = @otherTeam ctx.challengers = if not @startsLoading then @getChallengers() else {} ctx.readyToRank = @readyToRank() convertMatch = (match) => opponent = match.opponents[0] state = 'win' state = 'loss' if match.metrics.rank > opponent.metrics.rank state = 'tie' if match.metrics.rank is opponent.metrics.rank { state: state opponentName: @nameMap[opponent.userID] opponentID: opponent.userID when: moment(match.date).fromNow() sessionID: opponent.sessionID } ctx.matches = (convertMatch(match) for match in @session.get('matches') or []) ctx.matches.reverse() ctx.score = (@session.get('totalScore') or 10).toFixed(2) ctx afterRender: -> super() @setRankingButtonText(if @readyToRank() then 'rank' else 'unavailable') readyToRank: -> c1 = @session.get('code') c2 = @session.get('submittedCode') c1 and not _.isEqual(c1, c2) getChallengers: -> # make an object of challengers to everything needed to link to them challengers = {} if @challengers easyInfo = @challengeInfoFromSession(@challengers.easyPlayer.models[0]) mediumInfo = @challengeInfoFromSession(@challengers.mediumPlayer.models[0]) hardInfo = @challengeInfoFromSession(@challengers.hardPlayer.models[0]) else matches = @session.get('matches') won = (m for m in matches when m.metrics.rank < m.opponents[0].metrics.rank) lost = (m for m in matches when m.metrics.rank > m.opponents[0].metrics.rank) tied = (m for m in matches when m.metrics.rank is m.opponents[0].metrics.rank) easyInfo = @challengeInfoFromMatches(won) mediumInfo = @challengeInfoFromMatches(tied) hardInfo = @challengeInfoFromMatches(lost) @addChallenger easyInfo, challengers, 'easy' @addChallenger mediumInfo, challengers, 'medium' @addChallenger hardInfo, challengers, 'hard' challengers addChallenger: (info, challengers, title) -> # check for duplicates first return unless info for key, value of challengers return if value.sessionID is info.sessionID challengers[title] = info challengeInfoFromSession: (session) -> # given a model from the db, return info needed for a link to the match return unless session return { sessionID: session.id opponentName: @nameMap[session.get('creator')] or 'PI:NAME:<NAME>END_PIoner' opponentID: session.get('creator') } challengeInfoFromMatches: (matches) -> return unless matches?.length match = _.sample matches opponent = match.opponents[0] return { sessionID: opponent.sessionID opponentName: opponent.userName or 'Anoner' opponentID: opponent.userID } rankSession: -> return unless @readyToRank() @setRankingButtonText('ranking') success = => @setRankingButtonText('ranked') failure = => @setRankingButtonText('failed') $.ajax '/queue/scoring', { type: 'POST' data: { session: @session.id } success: success failure: failure } setRankingButtonText: (spanClass) -> rankButton = $('#rank-button') rankButton.find('span').addClass('hidden') rankButton.find(".#{spanClass}").removeClass('hidden') rankButton.toggleClass 'disabled', spanClass isnt 'rank' class ChallengersData constructor: (@level, @team, @otherTeam, @session) -> _.extend @, Backbone.Events score = @session?.get('totalScore') or 25 @easyPlayer = new LeaderboardCollection(@level, {order:1, scoreOffset: score - 5, limit: 1, team: @otherTeam}) @easyPlayer.fetch() @easyPlayer.once 'sync', @challengerLoaded, @ @mediumPlayer = new LeaderboardCollection(@level, {order:1, scoreOffset: score, limit: 1, team: @otherTeam}) @mediumPlayer.fetch() @mediumPlayer.once 'sync', @challengerLoaded, @ @hardPlayer = new LeaderboardCollection(@level, {order:-1, scoreOffset: score + 5, limit: 1, team: @otherTeam}) @hardPlayer.fetch() @hardPlayer.once 'sync', @challengerLoaded, @ challengerLoaded: -> if @allLoaded() @loaded = true @trigger 'sync' playerIDs: -> collections = [@easyPlayer, @mediumPlayer, @hardPlayer] (c.models[0].get('creator') for c in collections when c?.models[0]) allLoaded: -> _.all [@easyPlayer.loaded, @mediumPlayer.loaded, @hardPlayer.loaded]
[ { "context": "zych\"\n it_it: -> \"Nuova griglia da guide esistenti\"\n\n # Label for the “column width” field in t", "end": 8340, "score": 0.92681884765625, "start": 8333, "tag": "NAME", "value": "istenti" }, { "context": "e\"\n pt_br: -> \"Direita\"\n es_es: -> \"Derecha\"\n pl_pl: -> \"Prawa\"\n it_it: -> \"Des", "end": 11801, "score": 0.6833423376083374, "start": 11794, "tag": "NAME", "value": "Derecha" } ]
src/messages.coffee
JeemeJH/messages
1
define -> Messages = locale: "en_us" supportedLocales: [ "en_us" "fr_fr" "pt_br" "es_es" "pl_pl" "it_it" ] # Get a localized string. # # key - key to find in in @library # data - data passed to the message that can be used in the template # # Returns a String. get: (key, data) -> return @library[key][@locale](data) if @library[key]?[@locale] return @library[key]["en_us"](data) if @library[key]?["en_us"] "" # Localized strings for each message. # # Example: # # foo: # en_us: (data) -> "Bar #{ bat }" # library: # Label for the first tab in the UI. Refers to the grid form. tabForm: en_us: -> "Form" fr_fr: -> "Création" pt_br: -> "Formulário" es_es: -> "Formulario" pl_pl: -> "Układ" it_it: -> "Crea" # Lable for the second tab in the UI. Refers to the grid notation form for # "custom" grids. tabCustom: en_us: -> "Custom" fr_fr: -> "Code" pt_br: -> "Customizado" es_es: -> "Personalizado" pl_pl: -> "Własne" it_it: -> "Personalizzato" # Label for the third tab in the UI. Refers to the saved grid list. tabSaved: en_us: -> "Saved" fr_fr: -> "Collection" pt_br: -> "Salvo" es_es: -> "Guardado" pl_pl: -> "Zapisane" it_it: -> "Preferiti" # Label for the button that appears on part of the UI that applies the # guides of the form, grid notation, or selected grid. btnAddGuides: en_us: -> "Add guides" fr_fr: -> "Ajouter les repères" pt_br: -> "Adicionar guias" es_es: -> "Añadir guías" pl_pl: -> "Dodaj linie pomocnicze" it_it: -> "Aggiungi guide" # Label for the default button for alert modals. btnOk: en_us: -> "Ok" fr_fr: -> "Ok" pt_br: -> "Ok" es_es: -> "Ok" pl_pl: -> "OK" it_it: -> "Ok" # Label for confirmation modals. Clicking agrees. btnYes: en_us: -> "Yes" fr_fr: -> "Oui" pt_br: -> "Sim" es_es: -> "Si" pl_pl: -> "Tak" it_it: -> "Sì" # Label for the confirmation modals. Clicking rejects. btnNo: en_us: -> "No" fr_fr: -> "Non" pt_br: -> "Não" es_es: -> "No" pl_pl: -> "Nie" it_it: -> "No" # Label for the button that explains what grid notation is. Appears in the # “more” menu on the Custom tab. btnWhatIsThis: en_us: -> "What is this?" fr_fr: -> "Qu'est-ce que c'est ?" pt_br: -> "O que é isso?" es_es: -> "¿Qué es esto?" pl_pl: -> "Co to jest?" it_it: -> "Cos'è questo?" # Label for the button that opens the form that allows you to save a grid. # Appears in the “more” menu on the Grid and Custom tabs. btnSaveGrid: en_us: -> "Save grid" fr_fr: -> "Enregistrer la grille" pt_br: -> "Salvar grid" es_es: -> "Guardar retícula" pl_pl: -> "Zapisz wzorzec" it_it: -> "Salva griglia" # Label for the confirmation modals. Clicking cancels the current action. btnCancel: en_us: -> "Cancel" fr_fr: -> "Annuler" pt_br: -> "Cancelar" es_es: -> "Cancelar" pl_pl: -> "Anuluj" it_it: -> "Annulla" # Label for the button that resets the contents of the current form to # their default values. Appears in the “more” menu on the Grid and Custom # tabs. btnResetForm: en_us: -> "Reset form" fr_fr: -> "Effacer" pt_br: -> "Resetar formulário" es_es: -> "Resetear formulario" pl_pl: -> "Zresetuj układ" it_it: -> "Resetta i campi" # Label for the button that encourages upgrading to the paid version of # GuideGuide. Appears in the “more” on all tabs when the trial mode has # expired. btnLearnMore: en_us: -> "Learn more" fr_fr: -> "En savoir plus" pt_br: -> "Aprenda mais" es_es: -> "Saber más" pl_pl: -> "Dowiedz się więcej" it_it: -> "Per saperne di più" # Label for the button that allows editing a selected saved grid. Appears # in the “more” menu on the Saved tab. inputColumns: en_us: -> "Columns" fr_fr: -> "Colonnes" pt_br: -> "Colunas" es_es: -> "Colunas" pl_pl: -> "Kolumny" it_it: -> "Colonne" btnEditSelected: en_us: -> "Edit selected" fr_fr: -> "Modifier la sélection" pt_br: -> "Editar selecionados" es_es: -> "Editar seleccionados" pl_pl: -> "Edytuj zaznaczone" it_it: -> "Modifica la selezione" # Label for the button that deletes the selected saved grid. Appears in # the “more” menu on the Saved tab. btnDeleteSelected: en_us: -> "Delete selected" fr_fr: -> "Supprimer la sélection" pt_br: -> "Deletar selecionados" es_es: -> "Borrar seleccionados" pl_pl: -> "Skasuj zaznaczone" it_it: -> "Cancella selezionati" # Label for the button that opens the import modal. Appears in the “more” # menu on the Saved tab. btnImport: en_us: -> "Import" fr_fr: -> "Importation" pt_br: -> "Importar" es_es: -> "Importar" pl_pl: -> "Import" it_it: -> "Importa" # Label for the button that opens the export modal Appears in the “more” # menu on the Saved tab. btnExport: en_us: -> "Export" fr_fr: -> "Exportation" pt_br: -> "Exportar" es_es: -> "Exportar" pl_pl: -> "Eksport" it_it: -> "Esporta" # Label for the button that bootstaps the default grids. Appears in the # blankslate view when all saved grids are removed. btnAddDefaultGrids: en_us: -> "Add default grids" fr_fr: -> "Ajouter les grilles par défaut" pt_br: -> "Adicionar grids padrões" es_es: -> "Añadir retículas por defecto" pl_pl: -> "Dodaj domyślne wzorce" it_it: -> "Aggiungi griglie di default" # Label for the button that allows for importing data from a file. Appears # in the import modal. btnFromAFile: en_us: -> "From a file" fr_fr: -> "À partir d'un fichier" pt_br: -> "A partir de um arquivo" es_es: -> "Desde un fichero" pl_pl: -> "Z pliku" it_it: -> "Da un file" # Label for the button that allows for importing data from a GitHub Gist. # Appears in the import modal. # # https://gist.github.com/ btnFromAGitHubGist: en_us: -> "From a GitHub Gist" fr_fr: -> "À partir d'un Gist de GitHub" pt_br: -> "A partir de um Gist do GitHub" es_es: -> "Desde un Gist de GitHub" pl_pl: -> "Z Gistu GitHub" it_it: -> "Da un Gist Github" # Label for the button that allows for exporting data to a file. Appears # in the export modal. btnToAFile: en_us: -> "To a file" fr_fr: -> "Dans un fichier" pt_br: -> "Para um arquivo" es_es: -> "A un fichero" pl_pl: -> "Do pliku" it_it: -> "In un file" # Label for the button that allows for exporting data to a GitHub Gist. # Appears in the export modal. # # https://gist.github.com/ btnToAGitHubGist: en_us: -> "To a GitHub Gist" fr_fr: -> "Vers un Gist de GitHub" pt_br: -> "Para um Gist do GitHub" es_es: -> "A un Gist de GitHub" pl_pl: -> "Do Gistu GitHub" it_it: -> "In un Gist di Github" # Label for the button that creates a new grid from guides that exist in # the document. Appears in the “more” menu on the Saved tab. btnNewFromExisting: en_us: -> "New grid from existing guides" fr_fr: -> "Nouvelle grille à partir des repères existants" pt_br: -> "Novo grid a partir de um grid já existente" es_es: -> "Nueva retícula a partir de las guías existentes" pl_pl: -> "Nowy wzorzec z aktualnych linii pomocniczych" it_it: -> "Nuova griglia da guide esistenti" # Label for the “column width” field in the grid form. Width refers to how # wide each individual column is. inputWidth: en_us: -> "Width" fr_fr: -> "Largeur" pt_br: -> "Largura" es_es: -> "Anchura" pl_pl: -> "Szerokość" it_it: -> "Larghezza" # Label for the “row height” field in the grid form. Height refers to how # tall each individual row is. inputHeight: en_us: -> "Height" fr_fr: -> "Hauteur" pt_br: -> "Altura" es_es: -> "Altura" pl_pl: -> "Wysokość" it_it: -> "Altezza" # Label for the “horizontal gutter” and “vertical gutter” fields in the # grid form. Gutter refers to the space between the columns or rows. inputGutter: en_us: -> "Gutter" fr_fr: -> "Gouttière" pt_br: -> "Gutter" es_es: -> "Gutter" pl_pl: -> "Odstęp" it_it: -> "Spaziatura" # Label for the “margin” fields in the grid form. Margin refers to the # space at the top, left, bottom, and right sides of the context. inputMargin: en_us: -> "Margin" fr_fr: -> "Marge" pt_br: -> "Margem" es_es: -> "Margen" pl_pl: -> "Margines" it_it: -> "Margini" # Label for the “number of columns” field in the grid form. Column refers # to a repeating squence of uniformely sized vertical spaces. inputColumns: en_us: -> "Columns" fr_fr: -> "Colonnes" pt_br: -> "Colunas" es_es: -> "Colunas" pl_pl: -> "Kolumny" it_it: -> "Colonne" # Label for the “number of rows field in the grid form. Row refers # to a repeating squence of uniformely sized horizontal spaces. inputRows: en_us: -> "Rows" fr_fr: -> "Rangées" pt_br: -> "Linhas" es_es: -> "Filas" pl_pl: -> "Wiersze" it_it: -> "Righe" # Label for the field that lets you define a GitHub Gist url from which to # import data. Appears in the import modal after “From a GitHub Gist” is # clicked. # # https://gist.github.com inputGitHubGistURL: en_us: -> "GitHub Gist URL or ID" fr_fr: -> "URL ou ID du Gist de GitHub" pt_br: -> "URL ou ID de um Gist do GitHub" es_es: -> "URL o ID de un Gist de GitHub" pl_pl: -> "URL lub ID Gistu GitHub" it_it: -> "URL o ID del Gist di Github" # Label for the item that positions grids to the left. Appears in the # Position dropdown which appears when a column width is specified. dropdownLeft: en_us: -> "Left" fr_fr: -> "Gauche" pt_br: -> "Esquerda" es_es: -> "Izquierda" pl_pl: -> "Lewa" it_it: -> "Sinistra" # Label for the item that centers horizontal or veritcal grids. Appears in # the Position dropdown which appears when a column width or row height. # is specified. dropdownCenter: en_us: -> "Center" fr_fr: -> "Centre" pt_br: -> "Centro" es_es: -> "Centro" pl_pl: -> "Środkowa" it_it: -> "Centro" # Label for the item that positions grids to the right. Appears in the # Position dropdown which appears when a column width is specified. dropdownRight: en_us: -> "Right" fr_fr: -> "Droite" pt_br: -> "Direita" es_es: -> "Derecha" pl_pl: -> "Prawa" it_it: -> "Destra" # Label for the item that positions grids to the top. Appears in the # Position dropdown which appears when a row height is specified. dropdownTop: en_us: -> "Top" fr_fr: -> "Haut" pt_br: -> "Topo" es_es: -> "Arriba" pl_pl: -> "Górna" it_it: -> "Sopra" # Label for the item that positions grids to the bottom. Appears in the # Position dropdown which appears when a row height is specified. dropdownBottom: en_us: -> "Bottom" fr_fr: -> "Bas" pt_br: -> "Baixo" es_es: -> "Abajo" pl_pl: -> "Dolna" it_it: -> "Sotto" # Message that appears in the blankslate view when no grids are saved. # Prompts the user to create a grid or bootstap the default grids. blankslateGrids: en_us: -> "You have no grids yet! Save your own or…" fr_fr: -> "Vous n'avez aucune grille ! Enregistrer la vôtre ou…" pt_br: -> "Você ainda não tem nenhum grid! Crie os seus próprios…" es_es: -> "¡No hay ninguna retícula definida! Guarda la tuya o…" pl_pl: -> "Nie masz jeszcze wzorców! Zapisz swój własny lub…" it_it: -> "Non hai ancora alcuna griglia. Salvane una o…" # Message that appears in the grid notation field when it is empty. It # explains to the user what the field is for. # # http://guideguide.me/documentation/grid-notation/ placeholderCustom: en_us: -> "Write grid notation here" fr_fr: -> "Écriver ici la synthaxe de votre grille" pt_br: -> "Escreva anotações sobre o seu grid aqui" es_es: -> "Escribe aquí la notación de retícula" pl_pl: -> "Wpisz tutaj definicję w odpowiedniej notacji" it_it: -> "Scrivi qui il codice della tua griglia" # Message that appears when the grid name field is empty. Appears when # saving a grid. placeholderName: en_us: -> "Name your grid" fr_fr: -> "Nommer votre grille" pt_br: -> "Nomeie o seu grid" es_es: -> "Nombra tu retícula" pl_pl: -> "Nazwij swój wzorzec" it_it: -> "Dai un nome alla tua griglia" # Default title for new grids. Appears when saving a grid. titleUntitledGrid: en_us: -> "Untitled Grid" fr_fr: -> "Sans titre" pt_br: -> "Grid sem Nome" es_es: -> "Retícula Sin Título" pl_pl: -> "Nienazwany wzorzec" it_it: -> "Griglia senza titolo" # Name for a default grid which “outlines” the context by placing guides # on the top, left, right, and bottom sides. titleOutline: en_us: -> "Outline" fr_fr: -> "Contours" pt_br: -> "Contorno" es_es: -> "Contorno" pl_pl: -> "Kontur" it_it: -> "Contorno" # Name for the default two column grid. titleTwoColumnGrid: en_us: -> "Two column grid" fr_fr: -> "Deux colonnes" pt_br: -> "Grid com duas colunas" es_es: -> "Retícula de dos columnas" pl_pl: -> "Dwie kolumny" it_it: -> "Griglia a due colonne" # Name for the default three column grid. titleThreeColumnGrid: en_us: -> "Three column grid" fr_fr: -> "Trois colonnes" pt_br: -> "Grid com três colunas" es_es: -> "Retícula de tres columnas" pl_pl: -> "Trzy kolumny" it_it: -> "Griglia a tre colonne" # Title that appears at the top of the panel while saving a grid. titleSaveYourGrid: en_us: -> "Save your grid" fr_fr: -> "Enregistrer votre grille" pt_br: -> "Salve o seu grid" es_es: -> "Guarda tu retícula" pl_pl: -> "Zapisz swój wzorzec" it_it: -> "Salva la tua griglia" # Title that appears at the top of the panel while the import modal is # active. titleImportGrids: en_us: -> "Import grids" fr_fr: -> "Importer des grilles" pt_br: -> "Importe grids" es_es: -> "Importar reticulas" pl_pl: -> "Importuj wzorce" it_it: -> "Importa griglie" # Title that appears at the top of the panel while the export modal is # active. titleExportGrids: en_us: -> "Export grids" fr_fr: -> "Exporter des grilles" pt_br: -> "Exporte grids" es_es: -> "Exportar retículas" pl_pl: -> "Eksportuj wzorce" it_it: -> "Esporta griglie" # Title that appears at the top alert message that will appear if there is # an error while exporting grid data. titleExportError: en_us: -> "Export error" fr_fr: -> "Erreur lors de l'export" pt_br: -> "Exporte o erro" es_es: -> "Error de exportación" pl_pl: -> "Błąd podczas eksportu" it_it: -> "Errore durante l'esportazione" # Tooltip for the button at the bottom of the panel which places a guide # on the left side of the context. tooltipLeftBorder: en_us: -> "Left border" fr_fr: -> "Bord gauche" pt_br: -> "Borda da esquerda" es_es: -> "Borde izquierdo" pl_pl: -> "Lewy margines" it_it: -> "Bordo sinistro" # Tooltip for the button at the bottom of the panel which places a guide # on the right side of the context. tooltipRightBorder: en_us: -> "Right border" fr_fr: -> "Bord droite" pt_br: -> "Borda da direita" es_es: -> "Borde derecho" pl_pl: -> "Prawy margines" it_it: -> "Bordo destro" # Tooltip for the button at the bottom of the panel which places a guide # on the top of the context. tooltipTopBorder: en_us: -> "Top border" fr_fr: -> "Bord supérieur" pt_br: -> "Borda superior" es_es: -> "Borde superior" pl_pl: -> "Górny margines" it_it: -> "Bordo superiore" # Tooltip for the button at the bottom of the panel which places a guide # on the bottom of the context. tooltipBottomBorder: en_us: -> "Bottom border" fr_fr: -> "Bord inférieur" pt_br: -> "Borda inferior" es_es: -> "Borde inferior" pl_pl: -> "Dolny margines" it_it: -> "Bordo inferiore" # Tooltip for the button at the bottom of the panel which places a guide # in the middle of the context. tooltipMidpoint: en_us: -> "Midpoint" fr_fr: -> "Centre" pt_br: -> "Ponto médio" es_es: -> "Punto medio" pl_pl: -> "Środek" it_it: -> "Centro" # Tooltip for the button at the bottom of the panel which clears all # guides within the context. tooltipClearGuides: en_us: -> "Clear guides" fr_fr: -> "Effacer les repères" pt_br: -> "Limpar guias" es_es: -> "Limpiar guías" pl_pl: -> "Skasuj linie pomocnicze" it_it: -> "Cancella guide" # Tooltip for the “eye” button to the right of the tabs at the top of the # panel which toggles the guide visibility setting. tooltipToggleGuideVisibility: en_us: -> "Toggle guide visibility" fr_fr: -> "Afficher/masquer les repères" pt_br: -> "Alternar a visibilidade da guia" es_es: -> "Alternar visibilidad de guías" pl_pl: -> "Przełącz widoczność wzorca" it_it: -> "Mostra/nascondi guide" # Message that appears in the description of a GitHub Gist that contains # exported guide data. # # Example: https://gist.github.com/20c8e33534459c722888 msgGistDescription: en_us: -> "This is grid data exported by the GuideGuide plugin." fr_fr: -> " Voici les données d'une grille exportées par le plugin GuideGuide. " pt_br: -> " Estes são os dados de grids exportados pelo plugin GuideGuide. " es_es: -> " Estos son datos de retícula exportados por el plugin GuideGuide. " pl_pl: -> "To są dane wzorca wyeksportowane przez wtyczkę GuideGuide." it_it: -> "Dati griglia esportati dal plugin GuideGuide" # Message that encourages people to buy GuideGuide. Appears in place of # the Custom tab after the trial has expired. msgCustomUpsell: en_us: -> "Buy the full version to create any grid you can think of." fr_fr: -> " Acheter la version complète pour créer toutes les grilles que vous pouvez imaginer. " pt_br: -> " Compre a versão completa para criar qualquer tipo de grid que você puder imaginar. " es_es: -> " Compra la versión completa para crear cualquier retícula que puedas imaginar. " pl_pl: -> "Kup pełną wersję i twórz wzorce jakie tylko zapragniesz." it_it: -> " Acquista la versione completa per creare qualsiai griglia desideri " # Message that encourages people to buy GuideGuide. Appears in place of # the Saved tab after the trial has expired. msgSavedUpsell: en_us: -> "Buy the full version to save the grids you use the most." fr_fr: -> " Acheter la version complète pour enregistrer les grilles que vous utiliser fréquemment. " pt_br: -> " Compre a versão completa para salvar quais grids você mais utiliza. " es_es: -> " Compra la versión completa para guardar tus retículas más habituales. " pl_pl: -> " Kup pełną wersję by móc zapisywać najczęściej używane wzorce. " it_it: -> " Acquista la versione completa per salvare le griglie che usi più spesso " # Message that encourages people to buy GuideGuide. Appears at the bottom # of all tabs after the trial has expired. msgQuickUpsell: en_us: -> "Buy the full version to clear and add guides quickly." fr_fr: -> " Acheter la verison complète pour effacer et ajouter des repères facilement. " pt_br: -> " Compre a versão completa para criar e deletar guias de maneira mais rápida. " es_es: -> " Compra la versión completa para borrar y añadir guías rápidamente. " pl_pl: -> " Kup pełną wersję by szybko usuwać i dodawać linie pomocnicze. " it_it: -> " Acquista la versione completa per cancellare e aggiungere griglie a piacimento " # Title for the alert message that appears at launch after the trial # expires. titleFreeVersion: en_us: -> "Free version" fr_fr: -> "Version gratuite" pt_br: -> "Versão de graça" es_es: -> "Versión gratuita" pl_pl: -> "Wersja bezpłatna" it_it: -> "Versione gratuita" # Message that appears in the alert message that appears at launch after # the trial expires. msgFreeVersionEnabled: en_us: -> " You’ve used GuideGuide 30 times! You can buy the full version to renable the full features. " fr_fr: -> " Vous avez utilisé GuideGuide 30 fois ! Vous pouvez acheter la version complète pour réactiver toutes les fonctionnalités. " pt_br: -> " Você já usou GuideGuide 30 vezes! Você pode comprar a versão completa para reabilitar todas as funcionalidades. " es_es: -> " ¡Has usado GuideGuide 30 veces! Puedes comprar la versión completa para reactivar todas las funcionalidades. " pl_pl: -> " Użyto GuideGuide 30 razy! Możesz teraz kupić pełną wersją. " it_it: -> " Hai usato GuideGuide 30 volte! Puoi comprare la versione completa per sbloccare nuovamente tutte le funzionalità " # Title of the alert that appears on first launch that requests permission # to submit usage data via Google Analytics. titleGoogleAnalytics: en_us: -> "Submit usage data" fr_fr: -> "Collecte des données d'utilisation" pt_br: -> "Enviar dados de uso" es_es: -> "Enviar datos de uso" pl_pl: -> "Wysyłaj informacje o używaniu" it_it: -> "Invia statistiche di utilizzo" # Message for the alert that appears on first launch that requests permission # to submit usage data via Google Analytics. msgGoogleAnalytics: en_us: -> " Will you allow GuideGuide to use Google Analytics to track anonymous usage information to help improve the product? " fr_fr: -> " Autoriser GuideGuide à utiliser Google Analytics pour collecter anonymement des informations d'utilisation et aider à améliorer le plugin ? " pt_br: -> " Você vai permitir que GuideGuide use o Google Analytics para acompanhar, de forma anônima, informações da utilização do produto para para ajudar a melhorá-lo? " es_es: -> " ¿Permitir a GuideGuide utilizar Google Analytics para mantener un registro anónimo de uso con el fin de ayudar a mejorar el producto? " pl_pl: -> " Czy pozwolisz GuideGuide używać Google Analytics do śledzenia anonimowych danych używania, aby ulepszyć produkt? " it_it: -> "Autorizzi GuideGuide all'uso di Google Analytics per raccogliere anonimamente statistiche di utilizzo, allo scopo migliorare il plugin?" # Menu item that duplicates all guides in the selected contexts to all # documents. Appears in the flyout menu and the history state that results # from the action. menuDuplicateToOpenDocuments: en_us: -> "Duplicate guides to open documents" fr_fr: -> "Dupliquer les repères vers les documents ouverts" pt_br: -> "Duplique os guias para os documentos abertos" # TODO: es_es pl_pl: -> "Powiel linie pomocnicze w otwartych dokumentach" it_it: -> "Duplica guide nei documenti aperti" # Menu item that duplicates all guides in the selected contexts to all # artboards. Appears in the flyout menu and the history state that results # from the action. menuDuplicateToArtboards: en_us: -> "Duplicate guides to artboards" fr_fr: -> "Dupliquer les repères vers les plans de travail" pt_br: -> "Duplique as guias para as áreas de trabalho" # TODO: es_es pl_pl: -> "Powiel linie pomocnicze do obszaru kompozycji" it_it: -> "Duplica guide nelle tavole da disegno" # Menu item that clears all guides in the document. Appears in the flyout # menu and the history state that results from the action. menuClearAllGuides: en_us: -> "Clear all guides" fr_fr: -> "Effacer tous les repères" pt_br: -> "Limpar todos as guias" # TODO: es_es pl_pl: -> "Skasuj wszystkie linie pomocnicze" it_it: -> "Cancella tutte le guide" # Menu item that clears all guides in the currently selected artboards. # Appears in the flyout menu and the history state that results from the # action. menuClearArtboardGuides: en_us: -> "Clear selected artboard guides" fr_fr: -> "Effacer les repères du plan de travail" pt_br: -> "Limpar todas as guias selecionadas da area de trabalho" # TODO: es_es pl_pl: -> "Skasuj wszystkie linie pomocnicze na zaznaczonym obszarze kompozycji" it_it: -> "Cancella le guide nelle tavole da disegno selezionate" # Menu item that clears canvas guides. Appears in the flyout menu and the # history state that results from the action. menuClearCanvasGuides: en_us: -> "Clear canvas guides" fr_fr: -> "Effacer les repères de la zone de travail" pt_br: -> "Limpar todas as guias da tela" # TODO: es_es pl_pl: -> "Skasuj linie pomocnicze na obszarze roboczym" it_it: -> "Cancella le guide nell'area di lavoro" # Menu item that clears all vertical guides in a given context. Appears # in the flyout menu and the history state that results from the action. menuClearVerticalGuides: en_us: -> "Clear vertical guides" fr_fr: -> "Effacer les repères verticaux" pt_br: -> "Limpar todas as guias verticais" # TODO: es_es pl_pl: -> "Skasuj pionowe linie pomocnicze" it_it: -> "Cancella guide verticali" # Menu item that clears all horizontal guides in a given context. Appears # in the flyout menu and the history state that results from the action. menuClearHorizontalGuides: en_us: -> "Clear horizontal guides" fr_fr: -> "Effacer les repères horizontaux" pt_br: -> "Limpar todas as guias horizontais" # TODO: es_es pl_pl: -> "Skasuj poziome linie pomocnicze" it_it: -> "Cancella guide orizzontali" # Menu item that triggers the Google Analytics tracking setting prompt. # Appears in the flyout menu. menuTrackingSettings: en_us: -> "Tracking settings" fr_fr: -> "Préférences de suivi" pt_br: -> "Configurações de rastreamento" # TODO: es_es pl_pl: -> "Ustawienia śledzenia" it_it: -> "Opzioni di condivisione" # Menu item that opens the GuideGuide installation directory. Appears in # the flyout menu. menuUninstall: en_us: -> "Uninstall" fr_fr: -> "Désinstaller" pt_br: -> "Desinstalar" # TODO: es_es pl_pl: -> "Odinstaluj" it_it: -> "Disinstalla" # Menu item that toggles debug logging. Appears in the flyout menu. menuDebug: en_us: -> "Debug" fr_fr: -> "Débogage" pt_br: -> "Depurar" # TODO: es_es pl_pl: -> "Debug" it_it: -> "Debug" # Menu item that toggles using selected layers. Appears in the flyout menu # in Photoshop only. menuUseLayers: en_us: -> "Use selected layers" fr_fr: -> "Utiliser les calques sélectionnés" pt_br: -> "User as camadas selecionadas" # TODO: es_es # TODO: pl_pl # Menu item that will open guideguide.me. Appears in the flyout menu of # the trial version. menuBuyGuideGuide: en_us: -> "Buy GuideGuide" fr_fr: -> "Acheter GuideGuide" pt_br: -> "Comprar GuideGuide" # TODO: es_es pl_pl: -> "Kup GuideGuide" it_it: -> "Acquista GuideGuide" # Change the folder where GuideGuide stores its data. Appears in the # flyout menu. menuChangeDataFolder: en_us: -> "Change data folder" fr_fr: -> "Modifier l'emplacement des données" pt_br: -> "Alterar a pasta de dados" # TODO: es_es # TODO: pl_pl # Convert selected paths to guides. Appears in the flyout menu in # Illustrator only. menuConvertSelectionToGuides: en_us: -> "Convert selection to guides" fr_fr: -> "Convertir la sélection en repères" pt_br: -> "Converter os guias selecionados" # TODO: es_es # TODO: pl_pl it_it: -> "Cambia cartella delle preferenze" # Label for the history state that appears in documents in which guides # have been copied *to*. Will appear like: # # “Duplicate guides from MyCoolDoc.psd” historyDuplicateGuidesFrom: en_us: -> "Duplicate guides from" fr_fr: -> "Dupliquer les repères à partir de" pt_br: -> "Duplicar guias de" # TODO: es_es pl_pl: -> "Powiel linie pomocnicze z" it_it: -> "Duplica guide da" # Error message that appears when a user attempts to import a non-json # file. Appears in the import modal. errNotJSON: en_us: -> "Selected file must be a .json file" fr_fr: -> "Le fichier doit être au format .json" pt_br: -> "O arquivo selecionado tem que ser um arquivo .json" es_es: -> "El fichero seleccionado debe ser un fichero .json" pl_pl: -> "Wybrany plik musi być plikiem .json" it_it: -> "Il file selezionato deve essere un .json" # Error message that appears when when a chosen import file cannot be # read. Appears in the import modal. errFileRead: en_us: -> "Selected file could not be read" fr_fr: -> "Le fichier n'a pas pu être lu" pt_br: -> "O arquivo selecionado não pode ser lido" es_es: -> "El fichero seleccionado no pudo leerse" pl_pl: -> "Nie można odczytać wybranego pliku" it_it: -> "Il file selezionato non può essere letto" # Error that appears when grid notation does not recognize a command. # # http://guideguide.me/documentation/grid-notation#errors gnError1: en_us: -> "Unrecognized command" fr_fr: -> "Commande inconnue" pt_br: -> "Comando não reconhecido" es_es: -> "Comando no reconocido" pl_pl: -> "Nierozpoznana komenda" it_it: -> "Comando sconosciuto" # Error that appears when a user attempts to use an empty string in the # custom form. # # http://guideguide.me/documentation/grid-notation#errors gnError2: en_us: -> "This string does not contain any grids" fr_fr: -> "La synthaxe ne contient aucune grille" pt_br: -> "Este arquivo não contém nenhum grid" es_es: -> "Esta cadena no contiene ninguna retícula" pl_pl: -> "Ten ciąg znaków nie zawiera żadnych wzorców" it_it: -> "Questa stringa non contiene alcuna griglia" # Error that appears when a grid notation variable contains a wildcard. # Variable refers to a property that is defined with a dynamic value, # similar to a variable in code. Wildard refers to a value which has no # intrinsic measuremnt until the grid notation is processed. It # effectively means “divide the left over space evenly between this and # all other wildcards like it.” # # http://guideguide.me/documentation/grid-notation#errors gnError3: en_us: -> "Variables used as fills cannot contain wildcards" fr_fr: -> " Les variables utilisées comme itération ne peuvent pas contient de métacaractère " pt_br: -> "As variáveis não podem conter wildcards (*)" es_es: -> " Las variables usadas como relleno no pueden contener wildcards " pl_pl: -> "Zmienne używane do wypełniania nie mogą zawierać wieloznaczników" it_it: -> "Le variabili usate come ripetizioni non possono contenere caratteri jolly" # Error that appears when a grid notation string contains more than one # fill. Fill refers to a command that effectively means “Do this thing as # many times as will fit.” For example, a 3px fill can fit 3 time in a # 10px area. # # http://guideguide.me/documentation/grid-notation#errors gnError4: en_us: -> "A grid cannot contain more than one fill" fr_fr: -> "Une grille ne peut contenir qu'une seule itération" pt_br: -> "Um grid não pode conter mais do que um valor" es_es: -> "Una retícula no puede contener más de un relleno" pl_pl: -> "Wzorzec nie może zawierać więcej niż jednego wypełnienia" it_it: -> "Una griglia non può contenere più di un riempimento" # Error that appears when a grid notation variable contains a fill # command. Variable refers to a property that is defined with a dynamic # value, similar to a variable in code. Fill refers to a command that # effectively means “Do this thing as many times as will fit.” For # example, a 3px fill can fit 3 time in a 10px area. # # http://guideguide.me/documentation/grid-notation#errors gnError5: en_us: -> "Variables cannot contain fills" fr_fr: -> "Les variables ne peuvent pas contenir d'itération" pt_br: -> "As variáveis não podem ser preenchidas" es_es: -> "Las variables no pueden contener rellenos" pl_pl: -> "Zmienne nie mogą zawierać wypełnień" it_it: -> "Le variabili non possono contenere riempimenti" # Error that appears when a variable is used before its value has been # defined. Variable refers to a property that is defined with a dynamic # value, similar to a variable in code. # # http://guideguide.me/documentation/grid-notation#errors gnError6: en_us: -> "Undefined variable" fr_fr: -> "Variable indéfinie" pt_br: -> "Variável indefinida" es_es: -> "Variable indefinida" pl_pl: -> "Niezdefiniowana zmienna" it_it: -> "Variabile non definita"
102725
define -> Messages = locale: "en_us" supportedLocales: [ "en_us" "fr_fr" "pt_br" "es_es" "pl_pl" "it_it" ] # Get a localized string. # # key - key to find in in @library # data - data passed to the message that can be used in the template # # Returns a String. get: (key, data) -> return @library[key][@locale](data) if @library[key]?[@locale] return @library[key]["en_us"](data) if @library[key]?["en_us"] "" # Localized strings for each message. # # Example: # # foo: # en_us: (data) -> "Bar #{ bat }" # library: # Label for the first tab in the UI. Refers to the grid form. tabForm: en_us: -> "Form" fr_fr: -> "Création" pt_br: -> "Formulário" es_es: -> "Formulario" pl_pl: -> "Układ" it_it: -> "Crea" # Lable for the second tab in the UI. Refers to the grid notation form for # "custom" grids. tabCustom: en_us: -> "Custom" fr_fr: -> "Code" pt_br: -> "Customizado" es_es: -> "Personalizado" pl_pl: -> "Własne" it_it: -> "Personalizzato" # Label for the third tab in the UI. Refers to the saved grid list. tabSaved: en_us: -> "Saved" fr_fr: -> "Collection" pt_br: -> "Salvo" es_es: -> "Guardado" pl_pl: -> "Zapisane" it_it: -> "Preferiti" # Label for the button that appears on part of the UI that applies the # guides of the form, grid notation, or selected grid. btnAddGuides: en_us: -> "Add guides" fr_fr: -> "Ajouter les repères" pt_br: -> "Adicionar guias" es_es: -> "Añadir guías" pl_pl: -> "Dodaj linie pomocnicze" it_it: -> "Aggiungi guide" # Label for the default button for alert modals. btnOk: en_us: -> "Ok" fr_fr: -> "Ok" pt_br: -> "Ok" es_es: -> "Ok" pl_pl: -> "OK" it_it: -> "Ok" # Label for confirmation modals. Clicking agrees. btnYes: en_us: -> "Yes" fr_fr: -> "Oui" pt_br: -> "Sim" es_es: -> "Si" pl_pl: -> "Tak" it_it: -> "Sì" # Label for the confirmation modals. Clicking rejects. btnNo: en_us: -> "No" fr_fr: -> "Non" pt_br: -> "Não" es_es: -> "No" pl_pl: -> "Nie" it_it: -> "No" # Label for the button that explains what grid notation is. Appears in the # “more” menu on the Custom tab. btnWhatIsThis: en_us: -> "What is this?" fr_fr: -> "Qu'est-ce que c'est ?" pt_br: -> "O que é isso?" es_es: -> "¿Qué es esto?" pl_pl: -> "Co to jest?" it_it: -> "Cos'è questo?" # Label for the button that opens the form that allows you to save a grid. # Appears in the “more” menu on the Grid and Custom tabs. btnSaveGrid: en_us: -> "Save grid" fr_fr: -> "Enregistrer la grille" pt_br: -> "Salvar grid" es_es: -> "Guardar retícula" pl_pl: -> "Zapisz wzorzec" it_it: -> "Salva griglia" # Label for the confirmation modals. Clicking cancels the current action. btnCancel: en_us: -> "Cancel" fr_fr: -> "Annuler" pt_br: -> "Cancelar" es_es: -> "Cancelar" pl_pl: -> "Anuluj" it_it: -> "Annulla" # Label for the button that resets the contents of the current form to # their default values. Appears in the “more” menu on the Grid and Custom # tabs. btnResetForm: en_us: -> "Reset form" fr_fr: -> "Effacer" pt_br: -> "Resetar formulário" es_es: -> "Resetear formulario" pl_pl: -> "Zresetuj układ" it_it: -> "Resetta i campi" # Label for the button that encourages upgrading to the paid version of # GuideGuide. Appears in the “more” on all tabs when the trial mode has # expired. btnLearnMore: en_us: -> "Learn more" fr_fr: -> "En savoir plus" pt_br: -> "Aprenda mais" es_es: -> "Saber más" pl_pl: -> "Dowiedz się więcej" it_it: -> "Per saperne di più" # Label for the button that allows editing a selected saved grid. Appears # in the “more” menu on the Saved tab. inputColumns: en_us: -> "Columns" fr_fr: -> "Colonnes" pt_br: -> "Colunas" es_es: -> "Colunas" pl_pl: -> "Kolumny" it_it: -> "Colonne" btnEditSelected: en_us: -> "Edit selected" fr_fr: -> "Modifier la sélection" pt_br: -> "Editar selecionados" es_es: -> "Editar seleccionados" pl_pl: -> "Edytuj zaznaczone" it_it: -> "Modifica la selezione" # Label for the button that deletes the selected saved grid. Appears in # the “more” menu on the Saved tab. btnDeleteSelected: en_us: -> "Delete selected" fr_fr: -> "Supprimer la sélection" pt_br: -> "Deletar selecionados" es_es: -> "Borrar seleccionados" pl_pl: -> "Skasuj zaznaczone" it_it: -> "Cancella selezionati" # Label for the button that opens the import modal. Appears in the “more” # menu on the Saved tab. btnImport: en_us: -> "Import" fr_fr: -> "Importation" pt_br: -> "Importar" es_es: -> "Importar" pl_pl: -> "Import" it_it: -> "Importa" # Label for the button that opens the export modal Appears in the “more” # menu on the Saved tab. btnExport: en_us: -> "Export" fr_fr: -> "Exportation" pt_br: -> "Exportar" es_es: -> "Exportar" pl_pl: -> "Eksport" it_it: -> "Esporta" # Label for the button that bootstaps the default grids. Appears in the # blankslate view when all saved grids are removed. btnAddDefaultGrids: en_us: -> "Add default grids" fr_fr: -> "Ajouter les grilles par défaut" pt_br: -> "Adicionar grids padrões" es_es: -> "Añadir retículas por defecto" pl_pl: -> "Dodaj domyślne wzorce" it_it: -> "Aggiungi griglie di default" # Label for the button that allows for importing data from a file. Appears # in the import modal. btnFromAFile: en_us: -> "From a file" fr_fr: -> "À partir d'un fichier" pt_br: -> "A partir de um arquivo" es_es: -> "Desde un fichero" pl_pl: -> "Z pliku" it_it: -> "Da un file" # Label for the button that allows for importing data from a GitHub Gist. # Appears in the import modal. # # https://gist.github.com/ btnFromAGitHubGist: en_us: -> "From a GitHub Gist" fr_fr: -> "À partir d'un Gist de GitHub" pt_br: -> "A partir de um Gist do GitHub" es_es: -> "Desde un Gist de GitHub" pl_pl: -> "Z Gistu GitHub" it_it: -> "Da un Gist Github" # Label for the button that allows for exporting data to a file. Appears # in the export modal. btnToAFile: en_us: -> "To a file" fr_fr: -> "Dans un fichier" pt_br: -> "Para um arquivo" es_es: -> "A un fichero" pl_pl: -> "Do pliku" it_it: -> "In un file" # Label for the button that allows for exporting data to a GitHub Gist. # Appears in the export modal. # # https://gist.github.com/ btnToAGitHubGist: en_us: -> "To a GitHub Gist" fr_fr: -> "Vers un Gist de GitHub" pt_br: -> "Para um Gist do GitHub" es_es: -> "A un Gist de GitHub" pl_pl: -> "Do Gistu GitHub" it_it: -> "In un Gist di Github" # Label for the button that creates a new grid from guides that exist in # the document. Appears in the “more” menu on the Saved tab. btnNewFromExisting: en_us: -> "New grid from existing guides" fr_fr: -> "Nouvelle grille à partir des repères existants" pt_br: -> "Novo grid a partir de um grid já existente" es_es: -> "Nueva retícula a partir de las guías existentes" pl_pl: -> "Nowy wzorzec z aktualnych linii pomocniczych" it_it: -> "Nuova griglia da guide es<NAME>" # Label for the “column width” field in the grid form. Width refers to how # wide each individual column is. inputWidth: en_us: -> "Width" fr_fr: -> "Largeur" pt_br: -> "Largura" es_es: -> "Anchura" pl_pl: -> "Szerokość" it_it: -> "Larghezza" # Label for the “row height” field in the grid form. Height refers to how # tall each individual row is. inputHeight: en_us: -> "Height" fr_fr: -> "Hauteur" pt_br: -> "Altura" es_es: -> "Altura" pl_pl: -> "Wysokość" it_it: -> "Altezza" # Label for the “horizontal gutter” and “vertical gutter” fields in the # grid form. Gutter refers to the space between the columns or rows. inputGutter: en_us: -> "Gutter" fr_fr: -> "Gouttière" pt_br: -> "Gutter" es_es: -> "Gutter" pl_pl: -> "Odstęp" it_it: -> "Spaziatura" # Label for the “margin” fields in the grid form. Margin refers to the # space at the top, left, bottom, and right sides of the context. inputMargin: en_us: -> "Margin" fr_fr: -> "Marge" pt_br: -> "Margem" es_es: -> "Margen" pl_pl: -> "Margines" it_it: -> "Margini" # Label for the “number of columns” field in the grid form. Column refers # to a repeating squence of uniformely sized vertical spaces. inputColumns: en_us: -> "Columns" fr_fr: -> "Colonnes" pt_br: -> "Colunas" es_es: -> "Colunas" pl_pl: -> "Kolumny" it_it: -> "Colonne" # Label for the “number of rows field in the grid form. Row refers # to a repeating squence of uniformely sized horizontal spaces. inputRows: en_us: -> "Rows" fr_fr: -> "Rangées" pt_br: -> "Linhas" es_es: -> "Filas" pl_pl: -> "Wiersze" it_it: -> "Righe" # Label for the field that lets you define a GitHub Gist url from which to # import data. Appears in the import modal after “From a GitHub Gist” is # clicked. # # https://gist.github.com inputGitHubGistURL: en_us: -> "GitHub Gist URL or ID" fr_fr: -> "URL ou ID du Gist de GitHub" pt_br: -> "URL ou ID de um Gist do GitHub" es_es: -> "URL o ID de un Gist de GitHub" pl_pl: -> "URL lub ID Gistu GitHub" it_it: -> "URL o ID del Gist di Github" # Label for the item that positions grids to the left. Appears in the # Position dropdown which appears when a column width is specified. dropdownLeft: en_us: -> "Left" fr_fr: -> "Gauche" pt_br: -> "Esquerda" es_es: -> "Izquierda" pl_pl: -> "Lewa" it_it: -> "Sinistra" # Label for the item that centers horizontal or veritcal grids. Appears in # the Position dropdown which appears when a column width or row height. # is specified. dropdownCenter: en_us: -> "Center" fr_fr: -> "Centre" pt_br: -> "Centro" es_es: -> "Centro" pl_pl: -> "Środkowa" it_it: -> "Centro" # Label for the item that positions grids to the right. Appears in the # Position dropdown which appears when a column width is specified. dropdownRight: en_us: -> "Right" fr_fr: -> "Droite" pt_br: -> "Direita" es_es: -> "<NAME>" pl_pl: -> "Prawa" it_it: -> "Destra" # Label for the item that positions grids to the top. Appears in the # Position dropdown which appears when a row height is specified. dropdownTop: en_us: -> "Top" fr_fr: -> "Haut" pt_br: -> "Topo" es_es: -> "Arriba" pl_pl: -> "Górna" it_it: -> "Sopra" # Label for the item that positions grids to the bottom. Appears in the # Position dropdown which appears when a row height is specified. dropdownBottom: en_us: -> "Bottom" fr_fr: -> "Bas" pt_br: -> "Baixo" es_es: -> "Abajo" pl_pl: -> "Dolna" it_it: -> "Sotto" # Message that appears in the blankslate view when no grids are saved. # Prompts the user to create a grid or bootstap the default grids. blankslateGrids: en_us: -> "You have no grids yet! Save your own or…" fr_fr: -> "Vous n'avez aucune grille ! Enregistrer la vôtre ou…" pt_br: -> "Você ainda não tem nenhum grid! Crie os seus próprios…" es_es: -> "¡No hay ninguna retícula definida! Guarda la tuya o…" pl_pl: -> "Nie masz jeszcze wzorców! Zapisz swój własny lub…" it_it: -> "Non hai ancora alcuna griglia. Salvane una o…" # Message that appears in the grid notation field when it is empty. It # explains to the user what the field is for. # # http://guideguide.me/documentation/grid-notation/ placeholderCustom: en_us: -> "Write grid notation here" fr_fr: -> "Écriver ici la synthaxe de votre grille" pt_br: -> "Escreva anotações sobre o seu grid aqui" es_es: -> "Escribe aquí la notación de retícula" pl_pl: -> "Wpisz tutaj definicję w odpowiedniej notacji" it_it: -> "Scrivi qui il codice della tua griglia" # Message that appears when the grid name field is empty. Appears when # saving a grid. placeholderName: en_us: -> "Name your grid" fr_fr: -> "Nommer votre grille" pt_br: -> "Nomeie o seu grid" es_es: -> "Nombra tu retícula" pl_pl: -> "Nazwij swój wzorzec" it_it: -> "Dai un nome alla tua griglia" # Default title for new grids. Appears when saving a grid. titleUntitledGrid: en_us: -> "Untitled Grid" fr_fr: -> "Sans titre" pt_br: -> "Grid sem Nome" es_es: -> "Retícula Sin Título" pl_pl: -> "Nienazwany wzorzec" it_it: -> "Griglia senza titolo" # Name for a default grid which “outlines” the context by placing guides # on the top, left, right, and bottom sides. titleOutline: en_us: -> "Outline" fr_fr: -> "Contours" pt_br: -> "Contorno" es_es: -> "Contorno" pl_pl: -> "Kontur" it_it: -> "Contorno" # Name for the default two column grid. titleTwoColumnGrid: en_us: -> "Two column grid" fr_fr: -> "Deux colonnes" pt_br: -> "Grid com duas colunas" es_es: -> "Retícula de dos columnas" pl_pl: -> "Dwie kolumny" it_it: -> "Griglia a due colonne" # Name for the default three column grid. titleThreeColumnGrid: en_us: -> "Three column grid" fr_fr: -> "Trois colonnes" pt_br: -> "Grid com três colunas" es_es: -> "Retícula de tres columnas" pl_pl: -> "Trzy kolumny" it_it: -> "Griglia a tre colonne" # Title that appears at the top of the panel while saving a grid. titleSaveYourGrid: en_us: -> "Save your grid" fr_fr: -> "Enregistrer votre grille" pt_br: -> "Salve o seu grid" es_es: -> "Guarda tu retícula" pl_pl: -> "Zapisz swój wzorzec" it_it: -> "Salva la tua griglia" # Title that appears at the top of the panel while the import modal is # active. titleImportGrids: en_us: -> "Import grids" fr_fr: -> "Importer des grilles" pt_br: -> "Importe grids" es_es: -> "Importar reticulas" pl_pl: -> "Importuj wzorce" it_it: -> "Importa griglie" # Title that appears at the top of the panel while the export modal is # active. titleExportGrids: en_us: -> "Export grids" fr_fr: -> "Exporter des grilles" pt_br: -> "Exporte grids" es_es: -> "Exportar retículas" pl_pl: -> "Eksportuj wzorce" it_it: -> "Esporta griglie" # Title that appears at the top alert message that will appear if there is # an error while exporting grid data. titleExportError: en_us: -> "Export error" fr_fr: -> "Erreur lors de l'export" pt_br: -> "Exporte o erro" es_es: -> "Error de exportación" pl_pl: -> "Błąd podczas eksportu" it_it: -> "Errore durante l'esportazione" # Tooltip for the button at the bottom of the panel which places a guide # on the left side of the context. tooltipLeftBorder: en_us: -> "Left border" fr_fr: -> "Bord gauche" pt_br: -> "Borda da esquerda" es_es: -> "Borde izquierdo" pl_pl: -> "Lewy margines" it_it: -> "Bordo sinistro" # Tooltip for the button at the bottom of the panel which places a guide # on the right side of the context. tooltipRightBorder: en_us: -> "Right border" fr_fr: -> "Bord droite" pt_br: -> "Borda da direita" es_es: -> "Borde derecho" pl_pl: -> "Prawy margines" it_it: -> "Bordo destro" # Tooltip for the button at the bottom of the panel which places a guide # on the top of the context. tooltipTopBorder: en_us: -> "Top border" fr_fr: -> "Bord supérieur" pt_br: -> "Borda superior" es_es: -> "Borde superior" pl_pl: -> "Górny margines" it_it: -> "Bordo superiore" # Tooltip for the button at the bottom of the panel which places a guide # on the bottom of the context. tooltipBottomBorder: en_us: -> "Bottom border" fr_fr: -> "Bord inférieur" pt_br: -> "Borda inferior" es_es: -> "Borde inferior" pl_pl: -> "Dolny margines" it_it: -> "Bordo inferiore" # Tooltip for the button at the bottom of the panel which places a guide # in the middle of the context. tooltipMidpoint: en_us: -> "Midpoint" fr_fr: -> "Centre" pt_br: -> "Ponto médio" es_es: -> "Punto medio" pl_pl: -> "Środek" it_it: -> "Centro" # Tooltip for the button at the bottom of the panel which clears all # guides within the context. tooltipClearGuides: en_us: -> "Clear guides" fr_fr: -> "Effacer les repères" pt_br: -> "Limpar guias" es_es: -> "Limpiar guías" pl_pl: -> "Skasuj linie pomocnicze" it_it: -> "Cancella guide" # Tooltip for the “eye” button to the right of the tabs at the top of the # panel which toggles the guide visibility setting. tooltipToggleGuideVisibility: en_us: -> "Toggle guide visibility" fr_fr: -> "Afficher/masquer les repères" pt_br: -> "Alternar a visibilidade da guia" es_es: -> "Alternar visibilidad de guías" pl_pl: -> "Przełącz widoczność wzorca" it_it: -> "Mostra/nascondi guide" # Message that appears in the description of a GitHub Gist that contains # exported guide data. # # Example: https://gist.github.com/20c8e33534459c722888 msgGistDescription: en_us: -> "This is grid data exported by the GuideGuide plugin." fr_fr: -> " Voici les données d'une grille exportées par le plugin GuideGuide. " pt_br: -> " Estes são os dados de grids exportados pelo plugin GuideGuide. " es_es: -> " Estos son datos de retícula exportados por el plugin GuideGuide. " pl_pl: -> "To są dane wzorca wyeksportowane przez wtyczkę GuideGuide." it_it: -> "Dati griglia esportati dal plugin GuideGuide" # Message that encourages people to buy GuideGuide. Appears in place of # the Custom tab after the trial has expired. msgCustomUpsell: en_us: -> "Buy the full version to create any grid you can think of." fr_fr: -> " Acheter la version complète pour créer toutes les grilles que vous pouvez imaginer. " pt_br: -> " Compre a versão completa para criar qualquer tipo de grid que você puder imaginar. " es_es: -> " Compra la versión completa para crear cualquier retícula que puedas imaginar. " pl_pl: -> "Kup pełną wersję i twórz wzorce jakie tylko zapragniesz." it_it: -> " Acquista la versione completa per creare qualsiai griglia desideri " # Message that encourages people to buy GuideGuide. Appears in place of # the Saved tab after the trial has expired. msgSavedUpsell: en_us: -> "Buy the full version to save the grids you use the most." fr_fr: -> " Acheter la version complète pour enregistrer les grilles que vous utiliser fréquemment. " pt_br: -> " Compre a versão completa para salvar quais grids você mais utiliza. " es_es: -> " Compra la versión completa para guardar tus retículas más habituales. " pl_pl: -> " Kup pełną wersję by móc zapisywać najczęściej używane wzorce. " it_it: -> " Acquista la versione completa per salvare le griglie che usi più spesso " # Message that encourages people to buy GuideGuide. Appears at the bottom # of all tabs after the trial has expired. msgQuickUpsell: en_us: -> "Buy the full version to clear and add guides quickly." fr_fr: -> " Acheter la verison complète pour effacer et ajouter des repères facilement. " pt_br: -> " Compre a versão completa para criar e deletar guias de maneira mais rápida. " es_es: -> " Compra la versión completa para borrar y añadir guías rápidamente. " pl_pl: -> " Kup pełną wersję by szybko usuwać i dodawać linie pomocnicze. " it_it: -> " Acquista la versione completa per cancellare e aggiungere griglie a piacimento " # Title for the alert message that appears at launch after the trial # expires. titleFreeVersion: en_us: -> "Free version" fr_fr: -> "Version gratuite" pt_br: -> "Versão de graça" es_es: -> "Versión gratuita" pl_pl: -> "Wersja bezpłatna" it_it: -> "Versione gratuita" # Message that appears in the alert message that appears at launch after # the trial expires. msgFreeVersionEnabled: en_us: -> " You’ve used GuideGuide 30 times! You can buy the full version to renable the full features. " fr_fr: -> " Vous avez utilisé GuideGuide 30 fois ! Vous pouvez acheter la version complète pour réactiver toutes les fonctionnalités. " pt_br: -> " Você já usou GuideGuide 30 vezes! Você pode comprar a versão completa para reabilitar todas as funcionalidades. " es_es: -> " ¡Has usado GuideGuide 30 veces! Puedes comprar la versión completa para reactivar todas las funcionalidades. " pl_pl: -> " Użyto GuideGuide 30 razy! Możesz teraz kupić pełną wersją. " it_it: -> " Hai usato GuideGuide 30 volte! Puoi comprare la versione completa per sbloccare nuovamente tutte le funzionalità " # Title of the alert that appears on first launch that requests permission # to submit usage data via Google Analytics. titleGoogleAnalytics: en_us: -> "Submit usage data" fr_fr: -> "Collecte des données d'utilisation" pt_br: -> "Enviar dados de uso" es_es: -> "Enviar datos de uso" pl_pl: -> "Wysyłaj informacje o używaniu" it_it: -> "Invia statistiche di utilizzo" # Message for the alert that appears on first launch that requests permission # to submit usage data via Google Analytics. msgGoogleAnalytics: en_us: -> " Will you allow GuideGuide to use Google Analytics to track anonymous usage information to help improve the product? " fr_fr: -> " Autoriser GuideGuide à utiliser Google Analytics pour collecter anonymement des informations d'utilisation et aider à améliorer le plugin ? " pt_br: -> " Você vai permitir que GuideGuide use o Google Analytics para acompanhar, de forma anônima, informações da utilização do produto para para ajudar a melhorá-lo? " es_es: -> " ¿Permitir a GuideGuide utilizar Google Analytics para mantener un registro anónimo de uso con el fin de ayudar a mejorar el producto? " pl_pl: -> " Czy pozwolisz GuideGuide używać Google Analytics do śledzenia anonimowych danych używania, aby ulepszyć produkt? " it_it: -> "Autorizzi GuideGuide all'uso di Google Analytics per raccogliere anonimamente statistiche di utilizzo, allo scopo migliorare il plugin?" # Menu item that duplicates all guides in the selected contexts to all # documents. Appears in the flyout menu and the history state that results # from the action. menuDuplicateToOpenDocuments: en_us: -> "Duplicate guides to open documents" fr_fr: -> "Dupliquer les repères vers les documents ouverts" pt_br: -> "Duplique os guias para os documentos abertos" # TODO: es_es pl_pl: -> "Powiel linie pomocnicze w otwartych dokumentach" it_it: -> "Duplica guide nei documenti aperti" # Menu item that duplicates all guides in the selected contexts to all # artboards. Appears in the flyout menu and the history state that results # from the action. menuDuplicateToArtboards: en_us: -> "Duplicate guides to artboards" fr_fr: -> "Dupliquer les repères vers les plans de travail" pt_br: -> "Duplique as guias para as áreas de trabalho" # TODO: es_es pl_pl: -> "Powiel linie pomocnicze do obszaru kompozycji" it_it: -> "Duplica guide nelle tavole da disegno" # Menu item that clears all guides in the document. Appears in the flyout # menu and the history state that results from the action. menuClearAllGuides: en_us: -> "Clear all guides" fr_fr: -> "Effacer tous les repères" pt_br: -> "Limpar todos as guias" # TODO: es_es pl_pl: -> "Skasuj wszystkie linie pomocnicze" it_it: -> "Cancella tutte le guide" # Menu item that clears all guides in the currently selected artboards. # Appears in the flyout menu and the history state that results from the # action. menuClearArtboardGuides: en_us: -> "Clear selected artboard guides" fr_fr: -> "Effacer les repères du plan de travail" pt_br: -> "Limpar todas as guias selecionadas da area de trabalho" # TODO: es_es pl_pl: -> "Skasuj wszystkie linie pomocnicze na zaznaczonym obszarze kompozycji" it_it: -> "Cancella le guide nelle tavole da disegno selezionate" # Menu item that clears canvas guides. Appears in the flyout menu and the # history state that results from the action. menuClearCanvasGuides: en_us: -> "Clear canvas guides" fr_fr: -> "Effacer les repères de la zone de travail" pt_br: -> "Limpar todas as guias da tela" # TODO: es_es pl_pl: -> "Skasuj linie pomocnicze na obszarze roboczym" it_it: -> "Cancella le guide nell'area di lavoro" # Menu item that clears all vertical guides in a given context. Appears # in the flyout menu and the history state that results from the action. menuClearVerticalGuides: en_us: -> "Clear vertical guides" fr_fr: -> "Effacer les repères verticaux" pt_br: -> "Limpar todas as guias verticais" # TODO: es_es pl_pl: -> "Skasuj pionowe linie pomocnicze" it_it: -> "Cancella guide verticali" # Menu item that clears all horizontal guides in a given context. Appears # in the flyout menu and the history state that results from the action. menuClearHorizontalGuides: en_us: -> "Clear horizontal guides" fr_fr: -> "Effacer les repères horizontaux" pt_br: -> "Limpar todas as guias horizontais" # TODO: es_es pl_pl: -> "Skasuj poziome linie pomocnicze" it_it: -> "Cancella guide orizzontali" # Menu item that triggers the Google Analytics tracking setting prompt. # Appears in the flyout menu. menuTrackingSettings: en_us: -> "Tracking settings" fr_fr: -> "Préférences de suivi" pt_br: -> "Configurações de rastreamento" # TODO: es_es pl_pl: -> "Ustawienia śledzenia" it_it: -> "Opzioni di condivisione" # Menu item that opens the GuideGuide installation directory. Appears in # the flyout menu. menuUninstall: en_us: -> "Uninstall" fr_fr: -> "Désinstaller" pt_br: -> "Desinstalar" # TODO: es_es pl_pl: -> "Odinstaluj" it_it: -> "Disinstalla" # Menu item that toggles debug logging. Appears in the flyout menu. menuDebug: en_us: -> "Debug" fr_fr: -> "Débogage" pt_br: -> "Depurar" # TODO: es_es pl_pl: -> "Debug" it_it: -> "Debug" # Menu item that toggles using selected layers. Appears in the flyout menu # in Photoshop only. menuUseLayers: en_us: -> "Use selected layers" fr_fr: -> "Utiliser les calques sélectionnés" pt_br: -> "User as camadas selecionadas" # TODO: es_es # TODO: pl_pl # Menu item that will open guideguide.me. Appears in the flyout menu of # the trial version. menuBuyGuideGuide: en_us: -> "Buy GuideGuide" fr_fr: -> "Acheter GuideGuide" pt_br: -> "Comprar GuideGuide" # TODO: es_es pl_pl: -> "Kup GuideGuide" it_it: -> "Acquista GuideGuide" # Change the folder where GuideGuide stores its data. Appears in the # flyout menu. menuChangeDataFolder: en_us: -> "Change data folder" fr_fr: -> "Modifier l'emplacement des données" pt_br: -> "Alterar a pasta de dados" # TODO: es_es # TODO: pl_pl # Convert selected paths to guides. Appears in the flyout menu in # Illustrator only. menuConvertSelectionToGuides: en_us: -> "Convert selection to guides" fr_fr: -> "Convertir la sélection en repères" pt_br: -> "Converter os guias selecionados" # TODO: es_es # TODO: pl_pl it_it: -> "Cambia cartella delle preferenze" # Label for the history state that appears in documents in which guides # have been copied *to*. Will appear like: # # “Duplicate guides from MyCoolDoc.psd” historyDuplicateGuidesFrom: en_us: -> "Duplicate guides from" fr_fr: -> "Dupliquer les repères à partir de" pt_br: -> "Duplicar guias de" # TODO: es_es pl_pl: -> "Powiel linie pomocnicze z" it_it: -> "Duplica guide da" # Error message that appears when a user attempts to import a non-json # file. Appears in the import modal. errNotJSON: en_us: -> "Selected file must be a .json file" fr_fr: -> "Le fichier doit être au format .json" pt_br: -> "O arquivo selecionado tem que ser um arquivo .json" es_es: -> "El fichero seleccionado debe ser un fichero .json" pl_pl: -> "Wybrany plik musi być plikiem .json" it_it: -> "Il file selezionato deve essere un .json" # Error message that appears when when a chosen import file cannot be # read. Appears in the import modal. errFileRead: en_us: -> "Selected file could not be read" fr_fr: -> "Le fichier n'a pas pu être lu" pt_br: -> "O arquivo selecionado não pode ser lido" es_es: -> "El fichero seleccionado no pudo leerse" pl_pl: -> "Nie można odczytać wybranego pliku" it_it: -> "Il file selezionato non può essere letto" # Error that appears when grid notation does not recognize a command. # # http://guideguide.me/documentation/grid-notation#errors gnError1: en_us: -> "Unrecognized command" fr_fr: -> "Commande inconnue" pt_br: -> "Comando não reconhecido" es_es: -> "Comando no reconocido" pl_pl: -> "Nierozpoznana komenda" it_it: -> "Comando sconosciuto" # Error that appears when a user attempts to use an empty string in the # custom form. # # http://guideguide.me/documentation/grid-notation#errors gnError2: en_us: -> "This string does not contain any grids" fr_fr: -> "La synthaxe ne contient aucune grille" pt_br: -> "Este arquivo não contém nenhum grid" es_es: -> "Esta cadena no contiene ninguna retícula" pl_pl: -> "Ten ciąg znaków nie zawiera żadnych wzorców" it_it: -> "Questa stringa non contiene alcuna griglia" # Error that appears when a grid notation variable contains a wildcard. # Variable refers to a property that is defined with a dynamic value, # similar to a variable in code. Wildard refers to a value which has no # intrinsic measuremnt until the grid notation is processed. It # effectively means “divide the left over space evenly between this and # all other wildcards like it.” # # http://guideguide.me/documentation/grid-notation#errors gnError3: en_us: -> "Variables used as fills cannot contain wildcards" fr_fr: -> " Les variables utilisées comme itération ne peuvent pas contient de métacaractère " pt_br: -> "As variáveis não podem conter wildcards (*)" es_es: -> " Las variables usadas como relleno no pueden contener wildcards " pl_pl: -> "Zmienne używane do wypełniania nie mogą zawierać wieloznaczników" it_it: -> "Le variabili usate come ripetizioni non possono contenere caratteri jolly" # Error that appears when a grid notation string contains more than one # fill. Fill refers to a command that effectively means “Do this thing as # many times as will fit.” For example, a 3px fill can fit 3 time in a # 10px area. # # http://guideguide.me/documentation/grid-notation#errors gnError4: en_us: -> "A grid cannot contain more than one fill" fr_fr: -> "Une grille ne peut contenir qu'une seule itération" pt_br: -> "Um grid não pode conter mais do que um valor" es_es: -> "Una retícula no puede contener más de un relleno" pl_pl: -> "Wzorzec nie może zawierać więcej niż jednego wypełnienia" it_it: -> "Una griglia non può contenere più di un riempimento" # Error that appears when a grid notation variable contains a fill # command. Variable refers to a property that is defined with a dynamic # value, similar to a variable in code. Fill refers to a command that # effectively means “Do this thing as many times as will fit.” For # example, a 3px fill can fit 3 time in a 10px area. # # http://guideguide.me/documentation/grid-notation#errors gnError5: en_us: -> "Variables cannot contain fills" fr_fr: -> "Les variables ne peuvent pas contenir d'itération" pt_br: -> "As variáveis não podem ser preenchidas" es_es: -> "Las variables no pueden contener rellenos" pl_pl: -> "Zmienne nie mogą zawierać wypełnień" it_it: -> "Le variabili non possono contenere riempimenti" # Error that appears when a variable is used before its value has been # defined. Variable refers to a property that is defined with a dynamic # value, similar to a variable in code. # # http://guideguide.me/documentation/grid-notation#errors gnError6: en_us: -> "Undefined variable" fr_fr: -> "Variable indéfinie" pt_br: -> "Variável indefinida" es_es: -> "Variable indefinida" pl_pl: -> "Niezdefiniowana zmienna" it_it: -> "Variabile non definita"
true
define -> Messages = locale: "en_us" supportedLocales: [ "en_us" "fr_fr" "pt_br" "es_es" "pl_pl" "it_it" ] # Get a localized string. # # key - key to find in in @library # data - data passed to the message that can be used in the template # # Returns a String. get: (key, data) -> return @library[key][@locale](data) if @library[key]?[@locale] return @library[key]["en_us"](data) if @library[key]?["en_us"] "" # Localized strings for each message. # # Example: # # foo: # en_us: (data) -> "Bar #{ bat }" # library: # Label for the first tab in the UI. Refers to the grid form. tabForm: en_us: -> "Form" fr_fr: -> "Création" pt_br: -> "Formulário" es_es: -> "Formulario" pl_pl: -> "Układ" it_it: -> "Crea" # Lable for the second tab in the UI. Refers to the grid notation form for # "custom" grids. tabCustom: en_us: -> "Custom" fr_fr: -> "Code" pt_br: -> "Customizado" es_es: -> "Personalizado" pl_pl: -> "Własne" it_it: -> "Personalizzato" # Label for the third tab in the UI. Refers to the saved grid list. tabSaved: en_us: -> "Saved" fr_fr: -> "Collection" pt_br: -> "Salvo" es_es: -> "Guardado" pl_pl: -> "Zapisane" it_it: -> "Preferiti" # Label for the button that appears on part of the UI that applies the # guides of the form, grid notation, or selected grid. btnAddGuides: en_us: -> "Add guides" fr_fr: -> "Ajouter les repères" pt_br: -> "Adicionar guias" es_es: -> "Añadir guías" pl_pl: -> "Dodaj linie pomocnicze" it_it: -> "Aggiungi guide" # Label for the default button for alert modals. btnOk: en_us: -> "Ok" fr_fr: -> "Ok" pt_br: -> "Ok" es_es: -> "Ok" pl_pl: -> "OK" it_it: -> "Ok" # Label for confirmation modals. Clicking agrees. btnYes: en_us: -> "Yes" fr_fr: -> "Oui" pt_br: -> "Sim" es_es: -> "Si" pl_pl: -> "Tak" it_it: -> "Sì" # Label for the confirmation modals. Clicking rejects. btnNo: en_us: -> "No" fr_fr: -> "Non" pt_br: -> "Não" es_es: -> "No" pl_pl: -> "Nie" it_it: -> "No" # Label for the button that explains what grid notation is. Appears in the # “more” menu on the Custom tab. btnWhatIsThis: en_us: -> "What is this?" fr_fr: -> "Qu'est-ce que c'est ?" pt_br: -> "O que é isso?" es_es: -> "¿Qué es esto?" pl_pl: -> "Co to jest?" it_it: -> "Cos'è questo?" # Label for the button that opens the form that allows you to save a grid. # Appears in the “more” menu on the Grid and Custom tabs. btnSaveGrid: en_us: -> "Save grid" fr_fr: -> "Enregistrer la grille" pt_br: -> "Salvar grid" es_es: -> "Guardar retícula" pl_pl: -> "Zapisz wzorzec" it_it: -> "Salva griglia" # Label for the confirmation modals. Clicking cancels the current action. btnCancel: en_us: -> "Cancel" fr_fr: -> "Annuler" pt_br: -> "Cancelar" es_es: -> "Cancelar" pl_pl: -> "Anuluj" it_it: -> "Annulla" # Label for the button that resets the contents of the current form to # their default values. Appears in the “more” menu on the Grid and Custom # tabs. btnResetForm: en_us: -> "Reset form" fr_fr: -> "Effacer" pt_br: -> "Resetar formulário" es_es: -> "Resetear formulario" pl_pl: -> "Zresetuj układ" it_it: -> "Resetta i campi" # Label for the button that encourages upgrading to the paid version of # GuideGuide. Appears in the “more” on all tabs when the trial mode has # expired. btnLearnMore: en_us: -> "Learn more" fr_fr: -> "En savoir plus" pt_br: -> "Aprenda mais" es_es: -> "Saber más" pl_pl: -> "Dowiedz się więcej" it_it: -> "Per saperne di più" # Label for the button that allows editing a selected saved grid. Appears # in the “more” menu on the Saved tab. inputColumns: en_us: -> "Columns" fr_fr: -> "Colonnes" pt_br: -> "Colunas" es_es: -> "Colunas" pl_pl: -> "Kolumny" it_it: -> "Colonne" btnEditSelected: en_us: -> "Edit selected" fr_fr: -> "Modifier la sélection" pt_br: -> "Editar selecionados" es_es: -> "Editar seleccionados" pl_pl: -> "Edytuj zaznaczone" it_it: -> "Modifica la selezione" # Label for the button that deletes the selected saved grid. Appears in # the “more” menu on the Saved tab. btnDeleteSelected: en_us: -> "Delete selected" fr_fr: -> "Supprimer la sélection" pt_br: -> "Deletar selecionados" es_es: -> "Borrar seleccionados" pl_pl: -> "Skasuj zaznaczone" it_it: -> "Cancella selezionati" # Label for the button that opens the import modal. Appears in the “more” # menu on the Saved tab. btnImport: en_us: -> "Import" fr_fr: -> "Importation" pt_br: -> "Importar" es_es: -> "Importar" pl_pl: -> "Import" it_it: -> "Importa" # Label for the button that opens the export modal Appears in the “more” # menu on the Saved tab. btnExport: en_us: -> "Export" fr_fr: -> "Exportation" pt_br: -> "Exportar" es_es: -> "Exportar" pl_pl: -> "Eksport" it_it: -> "Esporta" # Label for the button that bootstaps the default grids. Appears in the # blankslate view when all saved grids are removed. btnAddDefaultGrids: en_us: -> "Add default grids" fr_fr: -> "Ajouter les grilles par défaut" pt_br: -> "Adicionar grids padrões" es_es: -> "Añadir retículas por defecto" pl_pl: -> "Dodaj domyślne wzorce" it_it: -> "Aggiungi griglie di default" # Label for the button that allows for importing data from a file. Appears # in the import modal. btnFromAFile: en_us: -> "From a file" fr_fr: -> "À partir d'un fichier" pt_br: -> "A partir de um arquivo" es_es: -> "Desde un fichero" pl_pl: -> "Z pliku" it_it: -> "Da un file" # Label for the button that allows for importing data from a GitHub Gist. # Appears in the import modal. # # https://gist.github.com/ btnFromAGitHubGist: en_us: -> "From a GitHub Gist" fr_fr: -> "À partir d'un Gist de GitHub" pt_br: -> "A partir de um Gist do GitHub" es_es: -> "Desde un Gist de GitHub" pl_pl: -> "Z Gistu GitHub" it_it: -> "Da un Gist Github" # Label for the button that allows for exporting data to a file. Appears # in the export modal. btnToAFile: en_us: -> "To a file" fr_fr: -> "Dans un fichier" pt_br: -> "Para um arquivo" es_es: -> "A un fichero" pl_pl: -> "Do pliku" it_it: -> "In un file" # Label for the button that allows for exporting data to a GitHub Gist. # Appears in the export modal. # # https://gist.github.com/ btnToAGitHubGist: en_us: -> "To a GitHub Gist" fr_fr: -> "Vers un Gist de GitHub" pt_br: -> "Para um Gist do GitHub" es_es: -> "A un Gist de GitHub" pl_pl: -> "Do Gistu GitHub" it_it: -> "In un Gist di Github" # Label for the button that creates a new grid from guides that exist in # the document. Appears in the “more” menu on the Saved tab. btnNewFromExisting: en_us: -> "New grid from existing guides" fr_fr: -> "Nouvelle grille à partir des repères existants" pt_br: -> "Novo grid a partir de um grid já existente" es_es: -> "Nueva retícula a partir de las guías existentes" pl_pl: -> "Nowy wzorzec z aktualnych linii pomocniczych" it_it: -> "Nuova griglia da guide esPI:NAME:<NAME>END_PI" # Label for the “column width” field in the grid form. Width refers to how # wide each individual column is. inputWidth: en_us: -> "Width" fr_fr: -> "Largeur" pt_br: -> "Largura" es_es: -> "Anchura" pl_pl: -> "Szerokość" it_it: -> "Larghezza" # Label for the “row height” field in the grid form. Height refers to how # tall each individual row is. inputHeight: en_us: -> "Height" fr_fr: -> "Hauteur" pt_br: -> "Altura" es_es: -> "Altura" pl_pl: -> "Wysokość" it_it: -> "Altezza" # Label for the “horizontal gutter” and “vertical gutter” fields in the # grid form. Gutter refers to the space between the columns or rows. inputGutter: en_us: -> "Gutter" fr_fr: -> "Gouttière" pt_br: -> "Gutter" es_es: -> "Gutter" pl_pl: -> "Odstęp" it_it: -> "Spaziatura" # Label for the “margin” fields in the grid form. Margin refers to the # space at the top, left, bottom, and right sides of the context. inputMargin: en_us: -> "Margin" fr_fr: -> "Marge" pt_br: -> "Margem" es_es: -> "Margen" pl_pl: -> "Margines" it_it: -> "Margini" # Label for the “number of columns” field in the grid form. Column refers # to a repeating squence of uniformely sized vertical spaces. inputColumns: en_us: -> "Columns" fr_fr: -> "Colonnes" pt_br: -> "Colunas" es_es: -> "Colunas" pl_pl: -> "Kolumny" it_it: -> "Colonne" # Label for the “number of rows field in the grid form. Row refers # to a repeating squence of uniformely sized horizontal spaces. inputRows: en_us: -> "Rows" fr_fr: -> "Rangées" pt_br: -> "Linhas" es_es: -> "Filas" pl_pl: -> "Wiersze" it_it: -> "Righe" # Label for the field that lets you define a GitHub Gist url from which to # import data. Appears in the import modal after “From a GitHub Gist” is # clicked. # # https://gist.github.com inputGitHubGistURL: en_us: -> "GitHub Gist URL or ID" fr_fr: -> "URL ou ID du Gist de GitHub" pt_br: -> "URL ou ID de um Gist do GitHub" es_es: -> "URL o ID de un Gist de GitHub" pl_pl: -> "URL lub ID Gistu GitHub" it_it: -> "URL o ID del Gist di Github" # Label for the item that positions grids to the left. Appears in the # Position dropdown which appears when a column width is specified. dropdownLeft: en_us: -> "Left" fr_fr: -> "Gauche" pt_br: -> "Esquerda" es_es: -> "Izquierda" pl_pl: -> "Lewa" it_it: -> "Sinistra" # Label for the item that centers horizontal or veritcal grids. Appears in # the Position dropdown which appears when a column width or row height. # is specified. dropdownCenter: en_us: -> "Center" fr_fr: -> "Centre" pt_br: -> "Centro" es_es: -> "Centro" pl_pl: -> "Środkowa" it_it: -> "Centro" # Label for the item that positions grids to the right. Appears in the # Position dropdown which appears when a column width is specified. dropdownRight: en_us: -> "Right" fr_fr: -> "Droite" pt_br: -> "Direita" es_es: -> "PI:NAME:<NAME>END_PI" pl_pl: -> "Prawa" it_it: -> "Destra" # Label for the item that positions grids to the top. Appears in the # Position dropdown which appears when a row height is specified. dropdownTop: en_us: -> "Top" fr_fr: -> "Haut" pt_br: -> "Topo" es_es: -> "Arriba" pl_pl: -> "Górna" it_it: -> "Sopra" # Label for the item that positions grids to the bottom. Appears in the # Position dropdown which appears when a row height is specified. dropdownBottom: en_us: -> "Bottom" fr_fr: -> "Bas" pt_br: -> "Baixo" es_es: -> "Abajo" pl_pl: -> "Dolna" it_it: -> "Sotto" # Message that appears in the blankslate view when no grids are saved. # Prompts the user to create a grid or bootstap the default grids. blankslateGrids: en_us: -> "You have no grids yet! Save your own or…" fr_fr: -> "Vous n'avez aucune grille ! Enregistrer la vôtre ou…" pt_br: -> "Você ainda não tem nenhum grid! Crie os seus próprios…" es_es: -> "¡No hay ninguna retícula definida! Guarda la tuya o…" pl_pl: -> "Nie masz jeszcze wzorców! Zapisz swój własny lub…" it_it: -> "Non hai ancora alcuna griglia. Salvane una o…" # Message that appears in the grid notation field when it is empty. It # explains to the user what the field is for. # # http://guideguide.me/documentation/grid-notation/ placeholderCustom: en_us: -> "Write grid notation here" fr_fr: -> "Écriver ici la synthaxe de votre grille" pt_br: -> "Escreva anotações sobre o seu grid aqui" es_es: -> "Escribe aquí la notación de retícula" pl_pl: -> "Wpisz tutaj definicję w odpowiedniej notacji" it_it: -> "Scrivi qui il codice della tua griglia" # Message that appears when the grid name field is empty. Appears when # saving a grid. placeholderName: en_us: -> "Name your grid" fr_fr: -> "Nommer votre grille" pt_br: -> "Nomeie o seu grid" es_es: -> "Nombra tu retícula" pl_pl: -> "Nazwij swój wzorzec" it_it: -> "Dai un nome alla tua griglia" # Default title for new grids. Appears when saving a grid. titleUntitledGrid: en_us: -> "Untitled Grid" fr_fr: -> "Sans titre" pt_br: -> "Grid sem Nome" es_es: -> "Retícula Sin Título" pl_pl: -> "Nienazwany wzorzec" it_it: -> "Griglia senza titolo" # Name for a default grid which “outlines” the context by placing guides # on the top, left, right, and bottom sides. titleOutline: en_us: -> "Outline" fr_fr: -> "Contours" pt_br: -> "Contorno" es_es: -> "Contorno" pl_pl: -> "Kontur" it_it: -> "Contorno" # Name for the default two column grid. titleTwoColumnGrid: en_us: -> "Two column grid" fr_fr: -> "Deux colonnes" pt_br: -> "Grid com duas colunas" es_es: -> "Retícula de dos columnas" pl_pl: -> "Dwie kolumny" it_it: -> "Griglia a due colonne" # Name for the default three column grid. titleThreeColumnGrid: en_us: -> "Three column grid" fr_fr: -> "Trois colonnes" pt_br: -> "Grid com três colunas" es_es: -> "Retícula de tres columnas" pl_pl: -> "Trzy kolumny" it_it: -> "Griglia a tre colonne" # Title that appears at the top of the panel while saving a grid. titleSaveYourGrid: en_us: -> "Save your grid" fr_fr: -> "Enregistrer votre grille" pt_br: -> "Salve o seu grid" es_es: -> "Guarda tu retícula" pl_pl: -> "Zapisz swój wzorzec" it_it: -> "Salva la tua griglia" # Title that appears at the top of the panel while the import modal is # active. titleImportGrids: en_us: -> "Import grids" fr_fr: -> "Importer des grilles" pt_br: -> "Importe grids" es_es: -> "Importar reticulas" pl_pl: -> "Importuj wzorce" it_it: -> "Importa griglie" # Title that appears at the top of the panel while the export modal is # active. titleExportGrids: en_us: -> "Export grids" fr_fr: -> "Exporter des grilles" pt_br: -> "Exporte grids" es_es: -> "Exportar retículas" pl_pl: -> "Eksportuj wzorce" it_it: -> "Esporta griglie" # Title that appears at the top alert message that will appear if there is # an error while exporting grid data. titleExportError: en_us: -> "Export error" fr_fr: -> "Erreur lors de l'export" pt_br: -> "Exporte o erro" es_es: -> "Error de exportación" pl_pl: -> "Błąd podczas eksportu" it_it: -> "Errore durante l'esportazione" # Tooltip for the button at the bottom of the panel which places a guide # on the left side of the context. tooltipLeftBorder: en_us: -> "Left border" fr_fr: -> "Bord gauche" pt_br: -> "Borda da esquerda" es_es: -> "Borde izquierdo" pl_pl: -> "Lewy margines" it_it: -> "Bordo sinistro" # Tooltip for the button at the bottom of the panel which places a guide # on the right side of the context. tooltipRightBorder: en_us: -> "Right border" fr_fr: -> "Bord droite" pt_br: -> "Borda da direita" es_es: -> "Borde derecho" pl_pl: -> "Prawy margines" it_it: -> "Bordo destro" # Tooltip for the button at the bottom of the panel which places a guide # on the top of the context. tooltipTopBorder: en_us: -> "Top border" fr_fr: -> "Bord supérieur" pt_br: -> "Borda superior" es_es: -> "Borde superior" pl_pl: -> "Górny margines" it_it: -> "Bordo superiore" # Tooltip for the button at the bottom of the panel which places a guide # on the bottom of the context. tooltipBottomBorder: en_us: -> "Bottom border" fr_fr: -> "Bord inférieur" pt_br: -> "Borda inferior" es_es: -> "Borde inferior" pl_pl: -> "Dolny margines" it_it: -> "Bordo inferiore" # Tooltip for the button at the bottom of the panel which places a guide # in the middle of the context. tooltipMidpoint: en_us: -> "Midpoint" fr_fr: -> "Centre" pt_br: -> "Ponto médio" es_es: -> "Punto medio" pl_pl: -> "Środek" it_it: -> "Centro" # Tooltip for the button at the bottom of the panel which clears all # guides within the context. tooltipClearGuides: en_us: -> "Clear guides" fr_fr: -> "Effacer les repères" pt_br: -> "Limpar guias" es_es: -> "Limpiar guías" pl_pl: -> "Skasuj linie pomocnicze" it_it: -> "Cancella guide" # Tooltip for the “eye” button to the right of the tabs at the top of the # panel which toggles the guide visibility setting. tooltipToggleGuideVisibility: en_us: -> "Toggle guide visibility" fr_fr: -> "Afficher/masquer les repères" pt_br: -> "Alternar a visibilidade da guia" es_es: -> "Alternar visibilidad de guías" pl_pl: -> "Przełącz widoczność wzorca" it_it: -> "Mostra/nascondi guide" # Message that appears in the description of a GitHub Gist that contains # exported guide data. # # Example: https://gist.github.com/20c8e33534459c722888 msgGistDescription: en_us: -> "This is grid data exported by the GuideGuide plugin." fr_fr: -> " Voici les données d'une grille exportées par le plugin GuideGuide. " pt_br: -> " Estes são os dados de grids exportados pelo plugin GuideGuide. " es_es: -> " Estos son datos de retícula exportados por el plugin GuideGuide. " pl_pl: -> "To są dane wzorca wyeksportowane przez wtyczkę GuideGuide." it_it: -> "Dati griglia esportati dal plugin GuideGuide" # Message that encourages people to buy GuideGuide. Appears in place of # the Custom tab after the trial has expired. msgCustomUpsell: en_us: -> "Buy the full version to create any grid you can think of." fr_fr: -> " Acheter la version complète pour créer toutes les grilles que vous pouvez imaginer. " pt_br: -> " Compre a versão completa para criar qualquer tipo de grid que você puder imaginar. " es_es: -> " Compra la versión completa para crear cualquier retícula que puedas imaginar. " pl_pl: -> "Kup pełną wersję i twórz wzorce jakie tylko zapragniesz." it_it: -> " Acquista la versione completa per creare qualsiai griglia desideri " # Message that encourages people to buy GuideGuide. Appears in place of # the Saved tab after the trial has expired. msgSavedUpsell: en_us: -> "Buy the full version to save the grids you use the most." fr_fr: -> " Acheter la version complète pour enregistrer les grilles que vous utiliser fréquemment. " pt_br: -> " Compre a versão completa para salvar quais grids você mais utiliza. " es_es: -> " Compra la versión completa para guardar tus retículas más habituales. " pl_pl: -> " Kup pełną wersję by móc zapisywać najczęściej używane wzorce. " it_it: -> " Acquista la versione completa per salvare le griglie che usi più spesso " # Message that encourages people to buy GuideGuide. Appears at the bottom # of all tabs after the trial has expired. msgQuickUpsell: en_us: -> "Buy the full version to clear and add guides quickly." fr_fr: -> " Acheter la verison complète pour effacer et ajouter des repères facilement. " pt_br: -> " Compre a versão completa para criar e deletar guias de maneira mais rápida. " es_es: -> " Compra la versión completa para borrar y añadir guías rápidamente. " pl_pl: -> " Kup pełną wersję by szybko usuwać i dodawać linie pomocnicze. " it_it: -> " Acquista la versione completa per cancellare e aggiungere griglie a piacimento " # Title for the alert message that appears at launch after the trial # expires. titleFreeVersion: en_us: -> "Free version" fr_fr: -> "Version gratuite" pt_br: -> "Versão de graça" es_es: -> "Versión gratuita" pl_pl: -> "Wersja bezpłatna" it_it: -> "Versione gratuita" # Message that appears in the alert message that appears at launch after # the trial expires. msgFreeVersionEnabled: en_us: -> " You’ve used GuideGuide 30 times! You can buy the full version to renable the full features. " fr_fr: -> " Vous avez utilisé GuideGuide 30 fois ! Vous pouvez acheter la version complète pour réactiver toutes les fonctionnalités. " pt_br: -> " Você já usou GuideGuide 30 vezes! Você pode comprar a versão completa para reabilitar todas as funcionalidades. " es_es: -> " ¡Has usado GuideGuide 30 veces! Puedes comprar la versión completa para reactivar todas las funcionalidades. " pl_pl: -> " Użyto GuideGuide 30 razy! Możesz teraz kupić pełną wersją. " it_it: -> " Hai usato GuideGuide 30 volte! Puoi comprare la versione completa per sbloccare nuovamente tutte le funzionalità " # Title of the alert that appears on first launch that requests permission # to submit usage data via Google Analytics. titleGoogleAnalytics: en_us: -> "Submit usage data" fr_fr: -> "Collecte des données d'utilisation" pt_br: -> "Enviar dados de uso" es_es: -> "Enviar datos de uso" pl_pl: -> "Wysyłaj informacje o używaniu" it_it: -> "Invia statistiche di utilizzo" # Message for the alert that appears on first launch that requests permission # to submit usage data via Google Analytics. msgGoogleAnalytics: en_us: -> " Will you allow GuideGuide to use Google Analytics to track anonymous usage information to help improve the product? " fr_fr: -> " Autoriser GuideGuide à utiliser Google Analytics pour collecter anonymement des informations d'utilisation et aider à améliorer le plugin ? " pt_br: -> " Você vai permitir que GuideGuide use o Google Analytics para acompanhar, de forma anônima, informações da utilização do produto para para ajudar a melhorá-lo? " es_es: -> " ¿Permitir a GuideGuide utilizar Google Analytics para mantener un registro anónimo de uso con el fin de ayudar a mejorar el producto? " pl_pl: -> " Czy pozwolisz GuideGuide używać Google Analytics do śledzenia anonimowych danych używania, aby ulepszyć produkt? " it_it: -> "Autorizzi GuideGuide all'uso di Google Analytics per raccogliere anonimamente statistiche di utilizzo, allo scopo migliorare il plugin?" # Menu item that duplicates all guides in the selected contexts to all # documents. Appears in the flyout menu and the history state that results # from the action. menuDuplicateToOpenDocuments: en_us: -> "Duplicate guides to open documents" fr_fr: -> "Dupliquer les repères vers les documents ouverts" pt_br: -> "Duplique os guias para os documentos abertos" # TODO: es_es pl_pl: -> "Powiel linie pomocnicze w otwartych dokumentach" it_it: -> "Duplica guide nei documenti aperti" # Menu item that duplicates all guides in the selected contexts to all # artboards. Appears in the flyout menu and the history state that results # from the action. menuDuplicateToArtboards: en_us: -> "Duplicate guides to artboards" fr_fr: -> "Dupliquer les repères vers les plans de travail" pt_br: -> "Duplique as guias para as áreas de trabalho" # TODO: es_es pl_pl: -> "Powiel linie pomocnicze do obszaru kompozycji" it_it: -> "Duplica guide nelle tavole da disegno" # Menu item that clears all guides in the document. Appears in the flyout # menu and the history state that results from the action. menuClearAllGuides: en_us: -> "Clear all guides" fr_fr: -> "Effacer tous les repères" pt_br: -> "Limpar todos as guias" # TODO: es_es pl_pl: -> "Skasuj wszystkie linie pomocnicze" it_it: -> "Cancella tutte le guide" # Menu item that clears all guides in the currently selected artboards. # Appears in the flyout menu and the history state that results from the # action. menuClearArtboardGuides: en_us: -> "Clear selected artboard guides" fr_fr: -> "Effacer les repères du plan de travail" pt_br: -> "Limpar todas as guias selecionadas da area de trabalho" # TODO: es_es pl_pl: -> "Skasuj wszystkie linie pomocnicze na zaznaczonym obszarze kompozycji" it_it: -> "Cancella le guide nelle tavole da disegno selezionate" # Menu item that clears canvas guides. Appears in the flyout menu and the # history state that results from the action. menuClearCanvasGuides: en_us: -> "Clear canvas guides" fr_fr: -> "Effacer les repères de la zone de travail" pt_br: -> "Limpar todas as guias da tela" # TODO: es_es pl_pl: -> "Skasuj linie pomocnicze na obszarze roboczym" it_it: -> "Cancella le guide nell'area di lavoro" # Menu item that clears all vertical guides in a given context. Appears # in the flyout menu and the history state that results from the action. menuClearVerticalGuides: en_us: -> "Clear vertical guides" fr_fr: -> "Effacer les repères verticaux" pt_br: -> "Limpar todas as guias verticais" # TODO: es_es pl_pl: -> "Skasuj pionowe linie pomocnicze" it_it: -> "Cancella guide verticali" # Menu item that clears all horizontal guides in a given context. Appears # in the flyout menu and the history state that results from the action. menuClearHorizontalGuides: en_us: -> "Clear horizontal guides" fr_fr: -> "Effacer les repères horizontaux" pt_br: -> "Limpar todas as guias horizontais" # TODO: es_es pl_pl: -> "Skasuj poziome linie pomocnicze" it_it: -> "Cancella guide orizzontali" # Menu item that triggers the Google Analytics tracking setting prompt. # Appears in the flyout menu. menuTrackingSettings: en_us: -> "Tracking settings" fr_fr: -> "Préférences de suivi" pt_br: -> "Configurações de rastreamento" # TODO: es_es pl_pl: -> "Ustawienia śledzenia" it_it: -> "Opzioni di condivisione" # Menu item that opens the GuideGuide installation directory. Appears in # the flyout menu. menuUninstall: en_us: -> "Uninstall" fr_fr: -> "Désinstaller" pt_br: -> "Desinstalar" # TODO: es_es pl_pl: -> "Odinstaluj" it_it: -> "Disinstalla" # Menu item that toggles debug logging. Appears in the flyout menu. menuDebug: en_us: -> "Debug" fr_fr: -> "Débogage" pt_br: -> "Depurar" # TODO: es_es pl_pl: -> "Debug" it_it: -> "Debug" # Menu item that toggles using selected layers. Appears in the flyout menu # in Photoshop only. menuUseLayers: en_us: -> "Use selected layers" fr_fr: -> "Utiliser les calques sélectionnés" pt_br: -> "User as camadas selecionadas" # TODO: es_es # TODO: pl_pl # Menu item that will open guideguide.me. Appears in the flyout menu of # the trial version. menuBuyGuideGuide: en_us: -> "Buy GuideGuide" fr_fr: -> "Acheter GuideGuide" pt_br: -> "Comprar GuideGuide" # TODO: es_es pl_pl: -> "Kup GuideGuide" it_it: -> "Acquista GuideGuide" # Change the folder where GuideGuide stores its data. Appears in the # flyout menu. menuChangeDataFolder: en_us: -> "Change data folder" fr_fr: -> "Modifier l'emplacement des données" pt_br: -> "Alterar a pasta de dados" # TODO: es_es # TODO: pl_pl # Convert selected paths to guides. Appears in the flyout menu in # Illustrator only. menuConvertSelectionToGuides: en_us: -> "Convert selection to guides" fr_fr: -> "Convertir la sélection en repères" pt_br: -> "Converter os guias selecionados" # TODO: es_es # TODO: pl_pl it_it: -> "Cambia cartella delle preferenze" # Label for the history state that appears in documents in which guides # have been copied *to*. Will appear like: # # “Duplicate guides from MyCoolDoc.psd” historyDuplicateGuidesFrom: en_us: -> "Duplicate guides from" fr_fr: -> "Dupliquer les repères à partir de" pt_br: -> "Duplicar guias de" # TODO: es_es pl_pl: -> "Powiel linie pomocnicze z" it_it: -> "Duplica guide da" # Error message that appears when a user attempts to import a non-json # file. Appears in the import modal. errNotJSON: en_us: -> "Selected file must be a .json file" fr_fr: -> "Le fichier doit être au format .json" pt_br: -> "O arquivo selecionado tem que ser um arquivo .json" es_es: -> "El fichero seleccionado debe ser un fichero .json" pl_pl: -> "Wybrany plik musi być plikiem .json" it_it: -> "Il file selezionato deve essere un .json" # Error message that appears when when a chosen import file cannot be # read. Appears in the import modal. errFileRead: en_us: -> "Selected file could not be read" fr_fr: -> "Le fichier n'a pas pu être lu" pt_br: -> "O arquivo selecionado não pode ser lido" es_es: -> "El fichero seleccionado no pudo leerse" pl_pl: -> "Nie można odczytać wybranego pliku" it_it: -> "Il file selezionato non può essere letto" # Error that appears when grid notation does not recognize a command. # # http://guideguide.me/documentation/grid-notation#errors gnError1: en_us: -> "Unrecognized command" fr_fr: -> "Commande inconnue" pt_br: -> "Comando não reconhecido" es_es: -> "Comando no reconocido" pl_pl: -> "Nierozpoznana komenda" it_it: -> "Comando sconosciuto" # Error that appears when a user attempts to use an empty string in the # custom form. # # http://guideguide.me/documentation/grid-notation#errors gnError2: en_us: -> "This string does not contain any grids" fr_fr: -> "La synthaxe ne contient aucune grille" pt_br: -> "Este arquivo não contém nenhum grid" es_es: -> "Esta cadena no contiene ninguna retícula" pl_pl: -> "Ten ciąg znaków nie zawiera żadnych wzorców" it_it: -> "Questa stringa non contiene alcuna griglia" # Error that appears when a grid notation variable contains a wildcard. # Variable refers to a property that is defined with a dynamic value, # similar to a variable in code. Wildard refers to a value which has no # intrinsic measuremnt until the grid notation is processed. It # effectively means “divide the left over space evenly between this and # all other wildcards like it.” # # http://guideguide.me/documentation/grid-notation#errors gnError3: en_us: -> "Variables used as fills cannot contain wildcards" fr_fr: -> " Les variables utilisées comme itération ne peuvent pas contient de métacaractère " pt_br: -> "As variáveis não podem conter wildcards (*)" es_es: -> " Las variables usadas como relleno no pueden contener wildcards " pl_pl: -> "Zmienne używane do wypełniania nie mogą zawierać wieloznaczników" it_it: -> "Le variabili usate come ripetizioni non possono contenere caratteri jolly" # Error that appears when a grid notation string contains more than one # fill. Fill refers to a command that effectively means “Do this thing as # many times as will fit.” For example, a 3px fill can fit 3 time in a # 10px area. # # http://guideguide.me/documentation/grid-notation#errors gnError4: en_us: -> "A grid cannot contain more than one fill" fr_fr: -> "Une grille ne peut contenir qu'une seule itération" pt_br: -> "Um grid não pode conter mais do que um valor" es_es: -> "Una retícula no puede contener más de un relleno" pl_pl: -> "Wzorzec nie może zawierać więcej niż jednego wypełnienia" it_it: -> "Una griglia non può contenere più di un riempimento" # Error that appears when a grid notation variable contains a fill # command. Variable refers to a property that is defined with a dynamic # value, similar to a variable in code. Fill refers to a command that # effectively means “Do this thing as many times as will fit.” For # example, a 3px fill can fit 3 time in a 10px area. # # http://guideguide.me/documentation/grid-notation#errors gnError5: en_us: -> "Variables cannot contain fills" fr_fr: -> "Les variables ne peuvent pas contenir d'itération" pt_br: -> "As variáveis não podem ser preenchidas" es_es: -> "Las variables no pueden contener rellenos" pl_pl: -> "Zmienne nie mogą zawierać wypełnień" it_it: -> "Le variabili non possono contenere riempimenti" # Error that appears when a variable is used before its value has been # defined. Variable refers to a property that is defined with a dynamic # value, similar to a variable in code. # # http://guideguide.me/documentation/grid-notation#errors gnError6: en_us: -> "Undefined variable" fr_fr: -> "Variable indéfinie" pt_br: -> "Variável indefinida" es_es: -> "Variable indefinida" pl_pl: -> "Niezdefiniowana zmienna" it_it: -> "Variabile non definita"
[ { "context": "iew Rule to flag use constant conditions\n# @author Christian Schulz <http://rndm.de>\n###\n\n'use strict'\n\n#------------", "end": 84, "score": 0.9997936487197876, "start": 68, "tag": "NAME", "value": "Christian Schulz" } ]
src/rules/no-constant-condition.coffee
danielbayley/eslint-plugin-coffee
0
###* # @fileoverview Rule to flag use constant conditions # @author Christian Schulz <http://rndm.de> ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow constant expressions in conditions' category: 'Possible Errors' recommended: yes url: 'https://eslint.org/docs/rules/no-constant-condition' schema: [ type: 'object' properties: checkLoops: type: 'boolean' additionalProperties: no ] messages: unexpected: 'Unexpected constant condition.' create: (context) -> options = context.options[0] or {} checkLoops = options.checkLoops isnt no loopSetStack = [] loopsInCurrentScope = new Set() #-------------------------------------------------------------------------- # Helpers #-------------------------------------------------------------------------- ###* # Checks if a branch node of LogicalExpression short circuits the whole condition # @param {ASTNode} node The branch of main condition which needs to be checked # @param {string} operator The operator of the main LogicalExpression. # @returns {boolean} true when condition short circuits whole condition ### isLogicalIdentity = (node, operator) -> switch node.type when 'Literal' return ( (operator in ['||', 'or'] and node.value is yes) or (operator in ['&&', 'and'] and node.value is no) ) when 'UnaryExpression' return operator in ['&&', 'and'] and node.operator is 'void' when 'LogicalExpression' return ( isLogicalIdentity(node.left, node.operator) or isLogicalIdentity node.right, node.operator ) # no default no ###* # Checks if a node has a constant truthiness value. # @param {ASTNode} node The AST node to check. # @param {boolean} inBooleanPosition `false` if checking branch of a condition. # `true` in all other cases # @returns {Bool} true when node's truthiness is constant # @private ### isConstant = (node, inBooleanPosition) -> switch node.type when 'Literal', 'ArrowFunctionExpression', 'FunctionExpression', 'ObjectExpression', 'ArrayExpression' return yes when 'UnaryExpression' return yes if node.operator is 'void' return ( (node.operator is 'typeof' and inBooleanPosition) or isConstant node.argument, yes ) when 'BinaryExpression' return ( isConstant(node.left, no) and isConstant(node.right, no) and node.operator isnt 'of' ) when 'LogicalExpression' isLeftConstant = isConstant node.left, inBooleanPosition isRightConstant = isConstant node.right, inBooleanPosition isLeftShortCircuit = isLeftConstant and isLogicalIdentity node.left, node.operator isRightShortCircuit = isRightConstant and isLogicalIdentity node.right, node.operator return ( (isLeftConstant and isRightConstant) or isLeftShortCircuit or isRightShortCircuit ) when 'AssignmentExpression' return ( node.operator is '=' and isConstant node.right, inBooleanPosition ) when 'SequenceExpression' return isConstant( node.expressions[node.expressions.length - 1] inBooleanPosition ) # no default no ###* # Tracks when the given node contains a constant condition. # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### trackConstantConditionLoop = (node) -> if node.test and isConstant node.test, yes loopsInCurrentScope.add node ###* # Reports when the set contains the given constant condition node # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### checkConstantConditionLoopInSet = (node) -> if loopsInCurrentScope.has node loopsInCurrentScope.delete node context.report node: node.test, messageId: 'unexpected' ###* # Reports when the given node contains a constant condition. # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### reportIfConstant = (node) -> if node.test and isConstant node.test, yes context.report node: node.test, messageId: 'unexpected' ###* # Stores current set of constant loops in loopSetStack temporarily # and uses a new set to track constant loops # @returns {void} # @private ### enterFunction = -> loopSetStack.push loopsInCurrentScope loopsInCurrentScope ###:### = new Set() ###* # Reports when the set still contains stored constant conditions # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### exitFunction = -> loopsInCurrentScope ###:### = loopSetStack.pop() ###* # Checks node when checkLoops option is enabled # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### checkLoop = (node) -> if checkLoops then trackConstantConditionLoop node #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- ConditionalExpression: reportIfConstant IfStatement: reportIfConstant WhileStatement: checkLoop 'WhileStatement:exit': checkConstantConditionLoopInSet DoWhileStatement: checkLoop 'DoWhileStatement:exit': checkConstantConditionLoopInSet ForStatement: checkLoop 'ForStatement > .test': (node) -> checkLoop node.parent 'ForStatement:exit': checkConstantConditionLoopInSet FunctionDeclaration: enterFunction 'FunctionDeclaration:exit': exitFunction FunctionExpression: enterFunction 'FunctionExpression:exit': exitFunction YieldExpression: -> loopsInCurrentScope.clear()
140016
###* # @fileoverview Rule to flag use constant conditions # @author <NAME> <http://rndm.de> ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow constant expressions in conditions' category: 'Possible Errors' recommended: yes url: 'https://eslint.org/docs/rules/no-constant-condition' schema: [ type: 'object' properties: checkLoops: type: 'boolean' additionalProperties: no ] messages: unexpected: 'Unexpected constant condition.' create: (context) -> options = context.options[0] or {} checkLoops = options.checkLoops isnt no loopSetStack = [] loopsInCurrentScope = new Set() #-------------------------------------------------------------------------- # Helpers #-------------------------------------------------------------------------- ###* # Checks if a branch node of LogicalExpression short circuits the whole condition # @param {ASTNode} node The branch of main condition which needs to be checked # @param {string} operator The operator of the main LogicalExpression. # @returns {boolean} true when condition short circuits whole condition ### isLogicalIdentity = (node, operator) -> switch node.type when 'Literal' return ( (operator in ['||', 'or'] and node.value is yes) or (operator in ['&&', 'and'] and node.value is no) ) when 'UnaryExpression' return operator in ['&&', 'and'] and node.operator is 'void' when 'LogicalExpression' return ( isLogicalIdentity(node.left, node.operator) or isLogicalIdentity node.right, node.operator ) # no default no ###* # Checks if a node has a constant truthiness value. # @param {ASTNode} node The AST node to check. # @param {boolean} inBooleanPosition `false` if checking branch of a condition. # `true` in all other cases # @returns {Bool} true when node's truthiness is constant # @private ### isConstant = (node, inBooleanPosition) -> switch node.type when 'Literal', 'ArrowFunctionExpression', 'FunctionExpression', 'ObjectExpression', 'ArrayExpression' return yes when 'UnaryExpression' return yes if node.operator is 'void' return ( (node.operator is 'typeof' and inBooleanPosition) or isConstant node.argument, yes ) when 'BinaryExpression' return ( isConstant(node.left, no) and isConstant(node.right, no) and node.operator isnt 'of' ) when 'LogicalExpression' isLeftConstant = isConstant node.left, inBooleanPosition isRightConstant = isConstant node.right, inBooleanPosition isLeftShortCircuit = isLeftConstant and isLogicalIdentity node.left, node.operator isRightShortCircuit = isRightConstant and isLogicalIdentity node.right, node.operator return ( (isLeftConstant and isRightConstant) or isLeftShortCircuit or isRightShortCircuit ) when 'AssignmentExpression' return ( node.operator is '=' and isConstant node.right, inBooleanPosition ) when 'SequenceExpression' return isConstant( node.expressions[node.expressions.length - 1] inBooleanPosition ) # no default no ###* # Tracks when the given node contains a constant condition. # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### trackConstantConditionLoop = (node) -> if node.test and isConstant node.test, yes loopsInCurrentScope.add node ###* # Reports when the set contains the given constant condition node # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### checkConstantConditionLoopInSet = (node) -> if loopsInCurrentScope.has node loopsInCurrentScope.delete node context.report node: node.test, messageId: 'unexpected' ###* # Reports when the given node contains a constant condition. # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### reportIfConstant = (node) -> if node.test and isConstant node.test, yes context.report node: node.test, messageId: 'unexpected' ###* # Stores current set of constant loops in loopSetStack temporarily # and uses a new set to track constant loops # @returns {void} # @private ### enterFunction = -> loopSetStack.push loopsInCurrentScope loopsInCurrentScope ###:### = new Set() ###* # Reports when the set still contains stored constant conditions # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### exitFunction = -> loopsInCurrentScope ###:### = loopSetStack.pop() ###* # Checks node when checkLoops option is enabled # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### checkLoop = (node) -> if checkLoops then trackConstantConditionLoop node #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- ConditionalExpression: reportIfConstant IfStatement: reportIfConstant WhileStatement: checkLoop 'WhileStatement:exit': checkConstantConditionLoopInSet DoWhileStatement: checkLoop 'DoWhileStatement:exit': checkConstantConditionLoopInSet ForStatement: checkLoop 'ForStatement > .test': (node) -> checkLoop node.parent 'ForStatement:exit': checkConstantConditionLoopInSet FunctionDeclaration: enterFunction 'FunctionDeclaration:exit': exitFunction FunctionExpression: enterFunction 'FunctionExpression:exit': exitFunction YieldExpression: -> loopsInCurrentScope.clear()
true
###* # @fileoverview Rule to flag use constant conditions # @author PI:NAME:<NAME>END_PI <http://rndm.de> ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow constant expressions in conditions' category: 'Possible Errors' recommended: yes url: 'https://eslint.org/docs/rules/no-constant-condition' schema: [ type: 'object' properties: checkLoops: type: 'boolean' additionalProperties: no ] messages: unexpected: 'Unexpected constant condition.' create: (context) -> options = context.options[0] or {} checkLoops = options.checkLoops isnt no loopSetStack = [] loopsInCurrentScope = new Set() #-------------------------------------------------------------------------- # Helpers #-------------------------------------------------------------------------- ###* # Checks if a branch node of LogicalExpression short circuits the whole condition # @param {ASTNode} node The branch of main condition which needs to be checked # @param {string} operator The operator of the main LogicalExpression. # @returns {boolean} true when condition short circuits whole condition ### isLogicalIdentity = (node, operator) -> switch node.type when 'Literal' return ( (operator in ['||', 'or'] and node.value is yes) or (operator in ['&&', 'and'] and node.value is no) ) when 'UnaryExpression' return operator in ['&&', 'and'] and node.operator is 'void' when 'LogicalExpression' return ( isLogicalIdentity(node.left, node.operator) or isLogicalIdentity node.right, node.operator ) # no default no ###* # Checks if a node has a constant truthiness value. # @param {ASTNode} node The AST node to check. # @param {boolean} inBooleanPosition `false` if checking branch of a condition. # `true` in all other cases # @returns {Bool} true when node's truthiness is constant # @private ### isConstant = (node, inBooleanPosition) -> switch node.type when 'Literal', 'ArrowFunctionExpression', 'FunctionExpression', 'ObjectExpression', 'ArrayExpression' return yes when 'UnaryExpression' return yes if node.operator is 'void' return ( (node.operator is 'typeof' and inBooleanPosition) or isConstant node.argument, yes ) when 'BinaryExpression' return ( isConstant(node.left, no) and isConstant(node.right, no) and node.operator isnt 'of' ) when 'LogicalExpression' isLeftConstant = isConstant node.left, inBooleanPosition isRightConstant = isConstant node.right, inBooleanPosition isLeftShortCircuit = isLeftConstant and isLogicalIdentity node.left, node.operator isRightShortCircuit = isRightConstant and isLogicalIdentity node.right, node.operator return ( (isLeftConstant and isRightConstant) or isLeftShortCircuit or isRightShortCircuit ) when 'AssignmentExpression' return ( node.operator is '=' and isConstant node.right, inBooleanPosition ) when 'SequenceExpression' return isConstant( node.expressions[node.expressions.length - 1] inBooleanPosition ) # no default no ###* # Tracks when the given node contains a constant condition. # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### trackConstantConditionLoop = (node) -> if node.test and isConstant node.test, yes loopsInCurrentScope.add node ###* # Reports when the set contains the given constant condition node # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### checkConstantConditionLoopInSet = (node) -> if loopsInCurrentScope.has node loopsInCurrentScope.delete node context.report node: node.test, messageId: 'unexpected' ###* # Reports when the given node contains a constant condition. # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### reportIfConstant = (node) -> if node.test and isConstant node.test, yes context.report node: node.test, messageId: 'unexpected' ###* # Stores current set of constant loops in loopSetStack temporarily # and uses a new set to track constant loops # @returns {void} # @private ### enterFunction = -> loopSetStack.push loopsInCurrentScope loopsInCurrentScope ###:### = new Set() ###* # Reports when the set still contains stored constant conditions # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### exitFunction = -> loopsInCurrentScope ###:### = loopSetStack.pop() ###* # Checks node when checkLoops option is enabled # @param {ASTNode} node The AST node to check. # @returns {void} # @private ### checkLoop = (node) -> if checkLoops then trackConstantConditionLoop node #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- ConditionalExpression: reportIfConstant IfStatement: reportIfConstant WhileStatement: checkLoop 'WhileStatement:exit': checkConstantConditionLoopInSet DoWhileStatement: checkLoop 'DoWhileStatement:exit': checkConstantConditionLoopInSet ForStatement: checkLoop 'ForStatement > .test': (node) -> checkLoop node.parent 'ForStatement:exit': checkConstantConditionLoopInSet FunctionDeclaration: enterFunction 'FunctionDeclaration:exit': exitFunction FunctionExpression: enterFunction 'FunctionExpression:exit': exitFunction YieldExpression: -> loopsInCurrentScope.clear()
[ { "context": " this\n\n # users = [{\n # username : \"gokmen\"\n # email : \"gokmen@koding.com\"\n ", "end": 2829, "score": 0.9995869994163513, "start": 2823, "tag": "USERNAME", "value": "gokmen" }, { "context": "ername : \"gokmen\"\n # email : \"gokmen@koding.com\"\n # password : \"gokmen\"\n # passwo", "end": 2874, "score": 0.9999285936355591, "start": 2857, "tag": "EMAIL", "value": "gokmen@koding.com" }, { "context": " : \"gokmen@koding.com\"\n # password : \"gokmen\"\n # passwordStatus : \"valid\"\n # firstNa", "end": 2908, "score": 0.9991693496704102, "start": 2902, "tag": "PASSWORD", "value": "gokmen" }, { "context": "asswordStatus : \"valid\"\n # firstName : \"Gokmen\"\n # lastName : \"Goksel\"\n # group ", "end": 2975, "score": 0.9996941089630127, "start": 2969, "tag": "NAME", "value": "Gokmen" }, { "context": "rstName : \"Gokmen\"\n # lastName : \"Goksel\"\n # group : \"koding\"\n # foreig", "end": 3009, "score": 0.999751091003418, "start": 3003, "tag": "NAME", "value": "Goksel" } ]
scripts/user-importer/main.coffee
ezgikaysi/koding
1
createUsers = (users)-> Bongo = require 'bongo' { join: joinPath } = require 'path' { v4: createId } = require 'node-uuid' KONFIG = require 'koding-config-manager' mongo = "mongodb://#{KONFIG.mongo}" if process.env.MONGO_URL mongo = process.env.MONGO_URL modelPath = '../../workers/social/lib/social/models' rekuire = (p)-> require joinPath modelPath, p koding = new Bongo root : __dirname mongo : mongo models : modelPath console.log "Trying to connect #{mongo} ..." koding.once 'dbClientReady', -> ComputeProvider = rekuire 'computeproviders/computeprovider.coffee' JUser = rekuire 'user/index.coffee' createUser = (u, next)-> console.log "\nCreating #{u.username} ... " JUser.count username: u.username, (err, count)-> if err then return console.error "Failed to query count:", err if count > 0 console.log " User #{u.username} already exists, passing." return next() JUser.createUser u, (err, user, account)-> if err console.log "Failed to create #{u.username}: ", err if err.errors? console.log "VALIDATION ERRORS: ", err.errors return next() account.update { $set : type : 'registered' globalFlags : ['super-admin'] }, (err)-> if err? console.log " Failed to activate #{u.username}:", err return next() console.log " User #{user.username} created." console.log "\n - Verifying email ..." user.confirmEmail (err)-> if err # RabbitMQ client is required to be initialized to send emails; # however send welcome emails is not reuqired here, so we silence it. if !/RabbitMQ client not found in Email/.test err console.log " Failed to verify: ", err else console.log " Email verified." console.log "\n - Adding to group #{u.group} ..." JUser.addToGroup account, u.group, u.email, null, (err)-> if err then console.log " Failed to add: ", err else console.log " Joined to group #{u.group}." client = connection : delegate : account context : group : u.group ComputeProvider.createGroupStack client, (err)-> if err then console.log " Failed to create stack: ", err else console.log " Default stack created for #{u.group}." next() # An array like this # users = [{ # username : "gokmen" # email : "gokmen@koding.com" # password : "gokmen" # passwordStatus : "valid" # firstName : "Gokmen" # lastName : "Goksel" # group : "koding" # foreignAuth : null # silence : no # }] createUser users.shift(), createHelper = -> if nextUser = users.shift() then createUser nextUser, createHelper else setTimeout -> console.log "\nALL DONE." process.exit 0 , 10000 csv = require 'csv' try console.log "Reading ./scripts/user-importer/team.csv ..." csv() .from.options trim: yes .from './scripts/user-importer/team.csv' .to.array (team)-> header = team.shift() users = [] team.forEach (member)-> item = { passwordStatus : "valid" foreignAuth : null silence : no } for column, i in header item[column] = member[i] users.push item console.log "Read completed, #{users.length} item found." createUsers users console.log 'User import completed' catch e console.log "Failed to parse team.csv", e process.exit 0
32952
createUsers = (users)-> Bongo = require 'bongo' { join: joinPath } = require 'path' { v4: createId } = require 'node-uuid' KONFIG = require 'koding-config-manager' mongo = "mongodb://#{KONFIG.mongo}" if process.env.MONGO_URL mongo = process.env.MONGO_URL modelPath = '../../workers/social/lib/social/models' rekuire = (p)-> require joinPath modelPath, p koding = new Bongo root : __dirname mongo : mongo models : modelPath console.log "Trying to connect #{mongo} ..." koding.once 'dbClientReady', -> ComputeProvider = rekuire 'computeproviders/computeprovider.coffee' JUser = rekuire 'user/index.coffee' createUser = (u, next)-> console.log "\nCreating #{u.username} ... " JUser.count username: u.username, (err, count)-> if err then return console.error "Failed to query count:", err if count > 0 console.log " User #{u.username} already exists, passing." return next() JUser.createUser u, (err, user, account)-> if err console.log "Failed to create #{u.username}: ", err if err.errors? console.log "VALIDATION ERRORS: ", err.errors return next() account.update { $set : type : 'registered' globalFlags : ['super-admin'] }, (err)-> if err? console.log " Failed to activate #{u.username}:", err return next() console.log " User #{user.username} created." console.log "\n - Verifying email ..." user.confirmEmail (err)-> if err # RabbitMQ client is required to be initialized to send emails; # however send welcome emails is not reuqired here, so we silence it. if !/RabbitMQ client not found in Email/.test err console.log " Failed to verify: ", err else console.log " Email verified." console.log "\n - Adding to group #{u.group} ..." JUser.addToGroup account, u.group, u.email, null, (err)-> if err then console.log " Failed to add: ", err else console.log " Joined to group #{u.group}." client = connection : delegate : account context : group : u.group ComputeProvider.createGroupStack client, (err)-> if err then console.log " Failed to create stack: ", err else console.log " Default stack created for #{u.group}." next() # An array like this # users = [{ # username : "gokmen" # email : "<EMAIL>" # password : "<PASSWORD>" # passwordStatus : "valid" # firstName : "<NAME>" # lastName : "<NAME>" # group : "koding" # foreignAuth : null # silence : no # }] createUser users.shift(), createHelper = -> if nextUser = users.shift() then createUser nextUser, createHelper else setTimeout -> console.log "\nALL DONE." process.exit 0 , 10000 csv = require 'csv' try console.log "Reading ./scripts/user-importer/team.csv ..." csv() .from.options trim: yes .from './scripts/user-importer/team.csv' .to.array (team)-> header = team.shift() users = [] team.forEach (member)-> item = { passwordStatus : "valid" foreignAuth : null silence : no } for column, i in header item[column] = member[i] users.push item console.log "Read completed, #{users.length} item found." createUsers users console.log 'User import completed' catch e console.log "Failed to parse team.csv", e process.exit 0
true
createUsers = (users)-> Bongo = require 'bongo' { join: joinPath } = require 'path' { v4: createId } = require 'node-uuid' KONFIG = require 'koding-config-manager' mongo = "mongodb://#{KONFIG.mongo}" if process.env.MONGO_URL mongo = process.env.MONGO_URL modelPath = '../../workers/social/lib/social/models' rekuire = (p)-> require joinPath modelPath, p koding = new Bongo root : __dirname mongo : mongo models : modelPath console.log "Trying to connect #{mongo} ..." koding.once 'dbClientReady', -> ComputeProvider = rekuire 'computeproviders/computeprovider.coffee' JUser = rekuire 'user/index.coffee' createUser = (u, next)-> console.log "\nCreating #{u.username} ... " JUser.count username: u.username, (err, count)-> if err then return console.error "Failed to query count:", err if count > 0 console.log " User #{u.username} already exists, passing." return next() JUser.createUser u, (err, user, account)-> if err console.log "Failed to create #{u.username}: ", err if err.errors? console.log "VALIDATION ERRORS: ", err.errors return next() account.update { $set : type : 'registered' globalFlags : ['super-admin'] }, (err)-> if err? console.log " Failed to activate #{u.username}:", err return next() console.log " User #{user.username} created." console.log "\n - Verifying email ..." user.confirmEmail (err)-> if err # RabbitMQ client is required to be initialized to send emails; # however send welcome emails is not reuqired here, so we silence it. if !/RabbitMQ client not found in Email/.test err console.log " Failed to verify: ", err else console.log " Email verified." console.log "\n - Adding to group #{u.group} ..." JUser.addToGroup account, u.group, u.email, null, (err)-> if err then console.log " Failed to add: ", err else console.log " Joined to group #{u.group}." client = connection : delegate : account context : group : u.group ComputeProvider.createGroupStack client, (err)-> if err then console.log " Failed to create stack: ", err else console.log " Default stack created for #{u.group}." next() # An array like this # users = [{ # username : "gokmen" # email : "PI:EMAIL:<EMAIL>END_PI" # password : "PI:PASSWORD:<PASSWORD>END_PI" # passwordStatus : "valid" # firstName : "PI:NAME:<NAME>END_PI" # lastName : "PI:NAME:<NAME>END_PI" # group : "koding" # foreignAuth : null # silence : no # }] createUser users.shift(), createHelper = -> if nextUser = users.shift() then createUser nextUser, createHelper else setTimeout -> console.log "\nALL DONE." process.exit 0 , 10000 csv = require 'csv' try console.log "Reading ./scripts/user-importer/team.csv ..." csv() .from.options trim: yes .from './scripts/user-importer/team.csv' .to.array (team)-> header = team.shift() users = [] team.forEach (member)-> item = { passwordStatus : "valid" foreignAuth : null silence : no } for column, i in header item[column] = member[i] users.push item console.log "Read completed, #{users.length} item found." createUsers users console.log 'User import completed' catch e console.log "Failed to parse team.csv", e process.exit 0
[ { "context": "(@robot)\n\n setTimeout done, 100\n room.user.say 'alice', 'hubot graf db monitoring-default:network serve", "end": 699, "score": 0.995623767375946, "start": 694, "tag": "USERNAME", "value": "alice" }, { "context": "'\n process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID='99999999999999999'\n process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_K", "end": 994, "score": 0.9985960721969604, "start": 977, "tag": "KEY", "value": "99999999999999999" }, { "context": " process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY='9999999999999999999999'\n process.env.HUBOT_GRAFANA_API_KEY='xxxxxxxxx", "end": 1070, "score": 0.9988341927528381, "start": 1048, "tag": "KEY", "value": "9999999999999999999999" }, { "context": "999999999'\n process.env.HUBOT_GRAFANA_API_KEY='xxxxxxxxxxxxxxxxxxxxxxxxx'\n do nock.disableNetConnect\n\n nock('http://", "end": 1136, "score": 0.9949063658714294, "start": 1111, "tag": "KEY", "value": "xxxxxxxxxxxxxxxxxxxxxxxxx" } ]
test/grafana-s3-test.coffee
shonenada/hubot-grafana
0
Helper = require('hubot-test-helper') chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' nock = require('nock') helper = new Helper('./../src/grafana.coffee') expect = chai.expect room = null before -> matchesBlanket = (path) -> path.match /node_modules\/blanket/ runningTestCoverage = Object.keys(require.cache).filter(matchesBlanket).length > 0 if runningTestCoverage require('require-dir')("#{__dirname}/../src", {recurse: true, duplicates: true}) setupRoomAndRequestGraph = (done) -> room = helper.createRoom() @robot = respond: sinon.spy() hear: sinon.spy() require('../src/grafana')(@robot) setTimeout done, 100 room.user.say 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' describe 's3 enabled', -> beforeEach -> process.env.HUBOT_GRAFANA_HOST = 'http://play.grafana.org' process.env.HUBOT_GRAFANA_S3_BUCKET='graf' process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID='99999999999999999' process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY='9999999999999999999999' process.env.HUBOT_GRAFANA_API_KEY='xxxxxxxxxxxxxxxxxxxxxxxxx' do nock.disableNetConnect nock('http://play.grafana.org') .get('/api/dashboards/db/monitoring-default') .replyWithFile(200, __dirname + '/fixtures/dashboard-monitoring-default.json') nock('http://play.grafana.org') .get('/render/dashboard-solo/db/monitoring-default/?panelId=7&width=1000&height=500&from=now-6h&to=now&var-server=ww3.example.com') .replyWithFile(200, __dirname + '/fixtures/dashboard-monitoring-default.png') afterEach -> room.destroy() nock.cleanAll() delete process.env.HUBOT_GRAFANA_HOST delete process.env.HUBOT_GRAFANA_S3_BUCKET delete process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID delete process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY delete process.env.HUBOT_GRAFANA_API_KEY context 'no region provided', -> beforeEach (done) -> nock('https://graf.s3.amazonaws.com:443') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) setupRoomAndRequestGraph(done) it 'should respond with a png graph in the default s3 region', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: https:\/\/graf\.s3\.amazonaws\.com\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ ) context 'custom s3 endpoint provided', -> beforeEach (done) -> nock('https://graf.custom.s3.endpoint.com:443') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) process.env.HUBOT_GRAFANA_S3_ENDPOINT = 'custom.s3.endpoint.com' setupRoomAndRequestGraph(done) afterEach -> delete process.env.HUBOT_GRAFANA_S3_ENDPOINT it 'should respond with a png graph stored at a custom endpoint', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: https:\/\/graf\.custom\.s3\.endpoint\.com\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ ) context 'custom s3 endpoint and port provided', -> beforeEach (done) -> nock('http://graf.custom.s3.endpoint.com:4430') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) process.env.HUBOT_GRAFANA_S3_ENDPOINT = 'custom.s3.endpoint.com' process.env.HUBOT_GRAFANA_S3_PORT = 4430 setupRoomAndRequestGraph(done) afterEach -> delete process.env.HUBOT_GRAFANA_S3_ENDPOINT delete process.env.HUBOT_GRAFANA_S3_PORT it 'should respond with a png graph stored at a custom endpoint', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: http:\/\/graf\.custom\.s3\.endpoint\.com:4430\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ ) context 's3 path style provided', -> beforeEach (done) -> nock('https://s3.amazonaws.com:443') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/graf/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) process.env.HUBOT_GRAFANA_S3_STYLE = 'path' setupRoomAndRequestGraph(done) afterEach -> delete process.env.HUBOT_GRAFANA_S3_STYLE it 'should respond with a png graph stored at a custom endpoint', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: https:\/\/s3\.amazonaws\.com\/graf\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ )
140511
Helper = require('hubot-test-helper') chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' nock = require('nock') helper = new Helper('./../src/grafana.coffee') expect = chai.expect room = null before -> matchesBlanket = (path) -> path.match /node_modules\/blanket/ runningTestCoverage = Object.keys(require.cache).filter(matchesBlanket).length > 0 if runningTestCoverage require('require-dir')("#{__dirname}/../src", {recurse: true, duplicates: true}) setupRoomAndRequestGraph = (done) -> room = helper.createRoom() @robot = respond: sinon.spy() hear: sinon.spy() require('../src/grafana')(@robot) setTimeout done, 100 room.user.say 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' describe 's3 enabled', -> beforeEach -> process.env.HUBOT_GRAFANA_HOST = 'http://play.grafana.org' process.env.HUBOT_GRAFANA_S3_BUCKET='graf' process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID='<KEY>' process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY='<KEY>' process.env.HUBOT_GRAFANA_API_KEY='<KEY>' do nock.disableNetConnect nock('http://play.grafana.org') .get('/api/dashboards/db/monitoring-default') .replyWithFile(200, __dirname + '/fixtures/dashboard-monitoring-default.json') nock('http://play.grafana.org') .get('/render/dashboard-solo/db/monitoring-default/?panelId=7&width=1000&height=500&from=now-6h&to=now&var-server=ww3.example.com') .replyWithFile(200, __dirname + '/fixtures/dashboard-monitoring-default.png') afterEach -> room.destroy() nock.cleanAll() delete process.env.HUBOT_GRAFANA_HOST delete process.env.HUBOT_GRAFANA_S3_BUCKET delete process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID delete process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY delete process.env.HUBOT_GRAFANA_API_KEY context 'no region provided', -> beforeEach (done) -> nock('https://graf.s3.amazonaws.com:443') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) setupRoomAndRequestGraph(done) it 'should respond with a png graph in the default s3 region', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: https:\/\/graf\.s3\.amazonaws\.com\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ ) context 'custom s3 endpoint provided', -> beforeEach (done) -> nock('https://graf.custom.s3.endpoint.com:443') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) process.env.HUBOT_GRAFANA_S3_ENDPOINT = 'custom.s3.endpoint.com' setupRoomAndRequestGraph(done) afterEach -> delete process.env.HUBOT_GRAFANA_S3_ENDPOINT it 'should respond with a png graph stored at a custom endpoint', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: https:\/\/graf\.custom\.s3\.endpoint\.com\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ ) context 'custom s3 endpoint and port provided', -> beforeEach (done) -> nock('http://graf.custom.s3.endpoint.com:4430') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) process.env.HUBOT_GRAFANA_S3_ENDPOINT = 'custom.s3.endpoint.com' process.env.HUBOT_GRAFANA_S3_PORT = 4430 setupRoomAndRequestGraph(done) afterEach -> delete process.env.HUBOT_GRAFANA_S3_ENDPOINT delete process.env.HUBOT_GRAFANA_S3_PORT it 'should respond with a png graph stored at a custom endpoint', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: http:\/\/graf\.custom\.s3\.endpoint\.com:4430\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ ) context 's3 path style provided', -> beforeEach (done) -> nock('https://s3.amazonaws.com:443') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/graf/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) process.env.HUBOT_GRAFANA_S3_STYLE = 'path' setupRoomAndRequestGraph(done) afterEach -> delete process.env.HUBOT_GRAFANA_S3_STYLE it 'should respond with a png graph stored at a custom endpoint', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: https:\/\/s3\.amazonaws\.com\/graf\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ )
true
Helper = require('hubot-test-helper') chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' nock = require('nock') helper = new Helper('./../src/grafana.coffee') expect = chai.expect room = null before -> matchesBlanket = (path) -> path.match /node_modules\/blanket/ runningTestCoverage = Object.keys(require.cache).filter(matchesBlanket).length > 0 if runningTestCoverage require('require-dir')("#{__dirname}/../src", {recurse: true, duplicates: true}) setupRoomAndRequestGraph = (done) -> room = helper.createRoom() @robot = respond: sinon.spy() hear: sinon.spy() require('../src/grafana')(@robot) setTimeout done, 100 room.user.say 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' describe 's3 enabled', -> beforeEach -> process.env.HUBOT_GRAFANA_HOST = 'http://play.grafana.org' process.env.HUBOT_GRAFANA_S3_BUCKET='graf' process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID='PI:KEY:<KEY>END_PI' process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY='PI:KEY:<KEY>END_PI' process.env.HUBOT_GRAFANA_API_KEY='PI:KEY:<KEY>END_PI' do nock.disableNetConnect nock('http://play.grafana.org') .get('/api/dashboards/db/monitoring-default') .replyWithFile(200, __dirname + '/fixtures/dashboard-monitoring-default.json') nock('http://play.grafana.org') .get('/render/dashboard-solo/db/monitoring-default/?panelId=7&width=1000&height=500&from=now-6h&to=now&var-server=ww3.example.com') .replyWithFile(200, __dirname + '/fixtures/dashboard-monitoring-default.png') afterEach -> room.destroy() nock.cleanAll() delete process.env.HUBOT_GRAFANA_HOST delete process.env.HUBOT_GRAFANA_S3_BUCKET delete process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID delete process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY delete process.env.HUBOT_GRAFANA_API_KEY context 'no region provided', -> beforeEach (done) -> nock('https://graf.s3.amazonaws.com:443') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) setupRoomAndRequestGraph(done) it 'should respond with a png graph in the default s3 region', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: https:\/\/graf\.s3\.amazonaws\.com\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ ) context 'custom s3 endpoint provided', -> beforeEach (done) -> nock('https://graf.custom.s3.endpoint.com:443') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) process.env.HUBOT_GRAFANA_S3_ENDPOINT = 'custom.s3.endpoint.com' setupRoomAndRequestGraph(done) afterEach -> delete process.env.HUBOT_GRAFANA_S3_ENDPOINT it 'should respond with a png graph stored at a custom endpoint', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: https:\/\/graf\.custom\.s3\.endpoint\.com\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ ) context 'custom s3 endpoint and port provided', -> beforeEach (done) -> nock('http://graf.custom.s3.endpoint.com:4430') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) process.env.HUBOT_GRAFANA_S3_ENDPOINT = 'custom.s3.endpoint.com' process.env.HUBOT_GRAFANA_S3_PORT = 4430 setupRoomAndRequestGraph(done) afterEach -> delete process.env.HUBOT_GRAFANA_S3_ENDPOINT delete process.env.HUBOT_GRAFANA_S3_PORT it 'should respond with a png graph stored at a custom endpoint', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: http:\/\/graf\.custom\.s3\.endpoint\.com:4430\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ ) context 's3 path style provided', -> beforeEach (done) -> nock('https://s3.amazonaws.com:443') .filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .put('/graf/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png') .reply(200) process.env.HUBOT_GRAFANA_S3_STYLE = 'path' setupRoomAndRequestGraph(done) afterEach -> delete process.env.HUBOT_GRAFANA_S3_STYLE it 'should respond with a png graph stored at a custom endpoint', -> expect(room.messages[0]).to.eql( [ 'alice', 'hubot graf db monitoring-default:network server=ww3.example.com now-6h' ] ) expect(room.messages[1][0]).to.eql( 'hubot' ) expect(room.messages[1][1]).to.match( /ww3.example.com network: https:\/\/s3\.amazonaws\.com\/graf\/grafana\/[a-z0-9]+\.png - http:\/\/play\.grafana\.org\/dashboard\/db\/monitoring-default\/\?panelId=7\&fullscreen\&from=now-6h\&to=now\&var-server=ww3.example.com/ )
[ { "context": "init = =>\n this.pusher = new Pusher '2d212b249c84f8c7ba5c',\n encrypted: tru", "end": 283, "score": 0.5166587829589844, "start": 282, "tag": "PASSWORD", "value": "2" }, { "context": " =>\n this.pusher = new Pusher '2d212b249c84f8c7ba5c',\n encrypted: true\n ", "end": 292, "score": 0.5042783617973328, "start": 288, "tag": "PASSWORD", "value": "9c84" }, { "context": " this.pusher = new Pusher '2d212b249c84f8c7ba5c',\n encrypted: true\n ", "end": 296, "score": 0.49288761615753174, "start": 295, "tag": "PASSWORD", "value": "7" }, { "context": " this.pusher = new Pusher '2d212b249c84f8c7ba5c',\n encrypted: true\n ", "end": 300, "score": 0.5113272070884705, "start": 298, "tag": "PASSWORD", "value": "5c" } ]
resources/assets/coffee/services/pusher.coffee
maxflex/egerep
0
angular.module 'Egerep' .service 'PusherService', ($http) -> this.bind = (channel, callback) -> init() if this.pusher is undefined this.channel.bind "App\\Events\\#{ channel }", callback init = => this.pusher = new Pusher '2d212b249c84f8c7ba5c', encrypted: true cluster: 'eu' this.channel = this.pusher.subscribe 'egerep' this
166597
angular.module 'Egerep' .service 'PusherService', ($http) -> this.bind = (channel, callback) -> init() if this.pusher is undefined this.channel.bind "App\\Events\\#{ channel }", callback init = => this.pusher = new Pusher '2d<PASSWORD>12b24<PASSWORD>f8c<PASSWORD>ba<PASSWORD>', encrypted: true cluster: 'eu' this.channel = this.pusher.subscribe 'egerep' this
true
angular.module 'Egerep' .service 'PusherService', ($http) -> this.bind = (channel, callback) -> init() if this.pusher is undefined this.channel.bind "App\\Events\\#{ channel }", callback init = => this.pusher = new Pusher '2dPI:PASSWORD:<PASSWORD>END_PI12b24PI:PASSWORD:<PASSWORD>END_PIf8cPI:PASSWORD:<PASSWORD>END_PIbaPI:PASSWORD:<PASSWORD>END_PI', encrypted: true cluster: 'eu' this.channel = this.pusher.subscribe 'egerep' this
[ { "context": "tockpile, Fairgrounds, Hamlet, Jester, Journeyman, Taxman\"\n \"Thrill of the Hunt: Way of the Rat, Pursue, ", "end": 3334, "score": 0.8563030362129211, "start": 3328, "tag": "NAME", "value": "Taxman" } ]
process/kingdoms.coffee
davidtorosyan/KingdomCreator
27
Loader = require('./loader') sets = Loader.loadSets() findCardByShortId = (shortId) -> for setId, set of sets for card in set.cards if shortId == card.shortId return card if set.events for event in set.events if shortId == event.shortId return event if set.landmarks for landmark in set.landmarks if shortId == landmark.shortId return landmark if set.projects for project in set.projects if shortId == project.shortId return project if set.boons for boon in set.boons if shortId == boon.shortId return boon if set.ways for way in set.ways if shortId == way.shortId return way throw Error('Card not found: ' + shortId) getSetsForCards = (cards) -> setIdsMap = {} for card in cards setIdsMap[card.setId] = true setIds = (set for set of setIdsMap) setIds.sort() return setIds parseSupplyString = (supplyString) -> split = supplyString.split(":") kingdomName = split[0].trim() cardNames = split[1] .replace(/\//g, ',') .replace(/\(/g, ',') .replace(/\)/g, '') .replace(/•/g, ',') .split(',') cards = [] for cardName in cardNames tokenized = Loader.tokenize(cardName) if tokenized cards.push(findCardByShortId(tokenized)) return { name: kingdomName cards: cards } strings = [ "Intro to Horses: Way of the Sheep, Enhance, Animal Fair, Barge, Destrier, Goatherd, Hostelry, Livery, Paddock, Scrap, Sheepdog, Supplies" "Intro to Exile: Way of the Worm, March, Black Cat, Bounty Hunter, Camel Train, Cardinal, Falconer, Mastermind, Sanctuary, Snowy Village, Stockpile, Wayfarer" "Pony Express: Way of the Seal, Stampede, Barge, Destrier, Paddock, Stockpile, Supplies, Artisan, Cellar, Market, Mine, Village" "Garden of Cats: Way of the Mole, Toil, Black Cat, Displace, Sanctuary, Scrap, Snowy Village, Bandit, Gardens, Harbinger, Merchant, Moat" "Dog & Pony Show: Way of the Horse, Commerce, Camel Train, Cavalry, Goatherd, Paddock, Sheepdog, Mill, Nobles, Pawn, Torturer, Upgrade" "Explosions: Way of the Squirrel, Populate, Animal Fair, Bounty Hunter, Coven, Hunting Lodge, Scrap, Courtyard, Diplomat, Lurker, Replace, Wishing Well" "Innsmouth: Way of the Goat, Invest, Animal Fair, Barge, Coven, Fisherman, Sheepdog, Caravan, Explorer, Fishing Village, Haven, Treasure Map" "Ruritania: Way of the Monkey, Alliance, Bounty Hunter, Cavalry, Falconer, Sleigh, Village Green, Lookout, Smugglers, Outpost, Tactician, Warehouse" "Class of '20: Way of the Owl, Delay, Cavalry, Coven, Hunting Lodge, Kiln, Livery, Snowy Village, Wayfarer, Transmute, Vineyard, University" "Limited Time Offer: Way of the Frog, Desperation, Destrier, Displace, Fisherman, Supplies, Wayfarer, Grand Market, Mint, Peddler, Talisman, Worker's Village" "Birth of a Nation: Way of the Otter, Reap, Animal Fair, Camel Train, Mastermind, Paddock, Stockpile, City, Monument, Quarry, Rabble, Trade Route" "Living in Exile: Way of the Mule, Enclave, Gatekeeper, Hostelry, Livery, Scrap, Stockpile, Fairgrounds, Hamlet, Jester, Journeyman, Taxman" "Thrill of the Hunt: Way of the Rat, Pursue, Black Cat, Bounty Hunter, Camel Train, Mastermind, Village Green, Butcher, Horse Traders, Hunting Party, Menagerie, Tournament" "Big Blue: Way of the Turtle, Banish, Black Cat, Falconer, Sheepdog, Sleigh, Village Green, Cartographer, Fool's Gold, Margrave, Trader, Tunnel" "Intersection: Way of the Mouse, Crossroads, Gamble, Cardinal, Hostelry, Livery, Mastermind, Supplies, Develop, Farmland, Haggler, Nomad Camp, Stables" "Friendly Carnage: Way of the Camel, Ride, Animal Fair, Cardinal, Falconer, Goatherd, Hunting Lodge, Altar, Beggar, Catacombs, Fortress, Market Square•" "Gift Horses: Way of the Butterfly, Bargain, Camel Train, Destrier, Displace, Paddock, Scrap, Hunting Grounds, Pillage, Rats, Sage, Squire" "Horse Feathers: Way of the Ox, Pilgrimage, Destrier, Displace, Falconer, Sleigh, Stockpile, Magpie, Ranger, Ratcatcher, Relic, Royal Carriage" "Sooner or Later: Toil, Mission, Barge, Gatekeeper, Groom, Mastermind, Village Green, Amulet, Caravan Guard, Dungeon, Giant, Raze" "No Money Down: Way of the Pig, Advance, Animal Fair, Cavalry, Sleigh, Stockpile, Wayfarer, CatapultRocks, City Quarter, Crown, Engineer, Villa" "Detours and Shortcuts: Transport, Triumphal Arch, Camel Train, Fisherman, Gatekeeper, Sanctuary, Snowy Village, Enchantress, Overlord, Sacrifice, SettlersBustling Village, Wild Hunt" "Seize the Night: Way of the Sheep, Seize the Day, Barge, Falconer, Hostelry, Sheepdog, Supplies, Cobbler, Devil's Workshop, Exorcist, Monastery, Skulk" "Animal Crackers: Way of the Chameleon, Enhance, Black Cat, Goatherd, Groom, Hunting Lodge, Kiln, Faithful Hound, Pixie, Pooka, Sacred Grove, Shepherd" "Biding Time: Way of the Turtle, Sinister Plot, Cavalry, Coven, Displace, Fisherman, Goatherd, Ducat, Priest, Recruiter, Scepter, Swashbuckler" "Villager Madness: Demand, Academy, Cardinal, Groom, Kiln, Livery, Wayfarer, Border Guard, Flag Bearer, Patron, Silk Merchant, Spices" ] for string in strings kingdom = parseSupplyString(string) console.log(" - name: " + kingdom.name) setIds = getSetsForCards(kingdom.cards) console.log(' sets:') for setId in setIds console.log(' - ' + setId) console.log(' supply:') cardIds = (card.id for card in kingdom.cards) cardIds.sort() for cardId in cardIds console.log(' - ' + cardId) console.log("")
58846
Loader = require('./loader') sets = Loader.loadSets() findCardByShortId = (shortId) -> for setId, set of sets for card in set.cards if shortId == card.shortId return card if set.events for event in set.events if shortId == event.shortId return event if set.landmarks for landmark in set.landmarks if shortId == landmark.shortId return landmark if set.projects for project in set.projects if shortId == project.shortId return project if set.boons for boon in set.boons if shortId == boon.shortId return boon if set.ways for way in set.ways if shortId == way.shortId return way throw Error('Card not found: ' + shortId) getSetsForCards = (cards) -> setIdsMap = {} for card in cards setIdsMap[card.setId] = true setIds = (set for set of setIdsMap) setIds.sort() return setIds parseSupplyString = (supplyString) -> split = supplyString.split(":") kingdomName = split[0].trim() cardNames = split[1] .replace(/\//g, ',') .replace(/\(/g, ',') .replace(/\)/g, '') .replace(/•/g, ',') .split(',') cards = [] for cardName in cardNames tokenized = Loader.tokenize(cardName) if tokenized cards.push(findCardByShortId(tokenized)) return { name: kingdomName cards: cards } strings = [ "Intro to Horses: Way of the Sheep, Enhance, Animal Fair, Barge, Destrier, Goatherd, Hostelry, Livery, Paddock, Scrap, Sheepdog, Supplies" "Intro to Exile: Way of the Worm, March, Black Cat, Bounty Hunter, Camel Train, Cardinal, Falconer, Mastermind, Sanctuary, Snowy Village, Stockpile, Wayfarer" "Pony Express: Way of the Seal, Stampede, Barge, Destrier, Paddock, Stockpile, Supplies, Artisan, Cellar, Market, Mine, Village" "Garden of Cats: Way of the Mole, Toil, Black Cat, Displace, Sanctuary, Scrap, Snowy Village, Bandit, Gardens, Harbinger, Merchant, Moat" "Dog & Pony Show: Way of the Horse, Commerce, Camel Train, Cavalry, Goatherd, Paddock, Sheepdog, Mill, Nobles, Pawn, Torturer, Upgrade" "Explosions: Way of the Squirrel, Populate, Animal Fair, Bounty Hunter, Coven, Hunting Lodge, Scrap, Courtyard, Diplomat, Lurker, Replace, Wishing Well" "Innsmouth: Way of the Goat, Invest, Animal Fair, Barge, Coven, Fisherman, Sheepdog, Caravan, Explorer, Fishing Village, Haven, Treasure Map" "Ruritania: Way of the Monkey, Alliance, Bounty Hunter, Cavalry, Falconer, Sleigh, Village Green, Lookout, Smugglers, Outpost, Tactician, Warehouse" "Class of '20: Way of the Owl, Delay, Cavalry, Coven, Hunting Lodge, Kiln, Livery, Snowy Village, Wayfarer, Transmute, Vineyard, University" "Limited Time Offer: Way of the Frog, Desperation, Destrier, Displace, Fisherman, Supplies, Wayfarer, Grand Market, Mint, Peddler, Talisman, Worker's Village" "Birth of a Nation: Way of the Otter, Reap, Animal Fair, Camel Train, Mastermind, Paddock, Stockpile, City, Monument, Quarry, Rabble, Trade Route" "Living in Exile: Way of the Mule, Enclave, Gatekeeper, Hostelry, Livery, Scrap, Stockpile, Fairgrounds, Hamlet, Jester, Journeyman, <NAME>" "Thrill of the Hunt: Way of the Rat, Pursue, Black Cat, Bounty Hunter, Camel Train, Mastermind, Village Green, Butcher, Horse Traders, Hunting Party, Menagerie, Tournament" "Big Blue: Way of the Turtle, Banish, Black Cat, Falconer, Sheepdog, Sleigh, Village Green, Cartographer, Fool's Gold, Margrave, Trader, Tunnel" "Intersection: Way of the Mouse, Crossroads, Gamble, Cardinal, Hostelry, Livery, Mastermind, Supplies, Develop, Farmland, Haggler, Nomad Camp, Stables" "Friendly Carnage: Way of the Camel, Ride, Animal Fair, Cardinal, Falconer, Goatherd, Hunting Lodge, Altar, Beggar, Catacombs, Fortress, Market Square•" "Gift Horses: Way of the Butterfly, Bargain, Camel Train, Destrier, Displace, Paddock, Scrap, Hunting Grounds, Pillage, Rats, Sage, Squire" "Horse Feathers: Way of the Ox, Pilgrimage, Destrier, Displace, Falconer, Sleigh, Stockpile, Magpie, Ranger, Ratcatcher, Relic, Royal Carriage" "Sooner or Later: Toil, Mission, Barge, Gatekeeper, Groom, Mastermind, Village Green, Amulet, Caravan Guard, Dungeon, Giant, Raze" "No Money Down: Way of the Pig, Advance, Animal Fair, Cavalry, Sleigh, Stockpile, Wayfarer, CatapultRocks, City Quarter, Crown, Engineer, Villa" "Detours and Shortcuts: Transport, Triumphal Arch, Camel Train, Fisherman, Gatekeeper, Sanctuary, Snowy Village, Enchantress, Overlord, Sacrifice, SettlersBustling Village, Wild Hunt" "Seize the Night: Way of the Sheep, Seize the Day, Barge, Falconer, Hostelry, Sheepdog, Supplies, Cobbler, Devil's Workshop, Exorcist, Monastery, Skulk" "Animal Crackers: Way of the Chameleon, Enhance, Black Cat, Goatherd, Groom, Hunting Lodge, Kiln, Faithful Hound, Pixie, Pooka, Sacred Grove, Shepherd" "Biding Time: Way of the Turtle, Sinister Plot, Cavalry, Coven, Displace, Fisherman, Goatherd, Ducat, Priest, Recruiter, Scepter, Swashbuckler" "Villager Madness: Demand, Academy, Cardinal, Groom, Kiln, Livery, Wayfarer, Border Guard, Flag Bearer, Patron, Silk Merchant, Spices" ] for string in strings kingdom = parseSupplyString(string) console.log(" - name: " + kingdom.name) setIds = getSetsForCards(kingdom.cards) console.log(' sets:') for setId in setIds console.log(' - ' + setId) console.log(' supply:') cardIds = (card.id for card in kingdom.cards) cardIds.sort() for cardId in cardIds console.log(' - ' + cardId) console.log("")
true
Loader = require('./loader') sets = Loader.loadSets() findCardByShortId = (shortId) -> for setId, set of sets for card in set.cards if shortId == card.shortId return card if set.events for event in set.events if shortId == event.shortId return event if set.landmarks for landmark in set.landmarks if shortId == landmark.shortId return landmark if set.projects for project in set.projects if shortId == project.shortId return project if set.boons for boon in set.boons if shortId == boon.shortId return boon if set.ways for way in set.ways if shortId == way.shortId return way throw Error('Card not found: ' + shortId) getSetsForCards = (cards) -> setIdsMap = {} for card in cards setIdsMap[card.setId] = true setIds = (set for set of setIdsMap) setIds.sort() return setIds parseSupplyString = (supplyString) -> split = supplyString.split(":") kingdomName = split[0].trim() cardNames = split[1] .replace(/\//g, ',') .replace(/\(/g, ',') .replace(/\)/g, '') .replace(/•/g, ',') .split(',') cards = [] for cardName in cardNames tokenized = Loader.tokenize(cardName) if tokenized cards.push(findCardByShortId(tokenized)) return { name: kingdomName cards: cards } strings = [ "Intro to Horses: Way of the Sheep, Enhance, Animal Fair, Barge, Destrier, Goatherd, Hostelry, Livery, Paddock, Scrap, Sheepdog, Supplies" "Intro to Exile: Way of the Worm, March, Black Cat, Bounty Hunter, Camel Train, Cardinal, Falconer, Mastermind, Sanctuary, Snowy Village, Stockpile, Wayfarer" "Pony Express: Way of the Seal, Stampede, Barge, Destrier, Paddock, Stockpile, Supplies, Artisan, Cellar, Market, Mine, Village" "Garden of Cats: Way of the Mole, Toil, Black Cat, Displace, Sanctuary, Scrap, Snowy Village, Bandit, Gardens, Harbinger, Merchant, Moat" "Dog & Pony Show: Way of the Horse, Commerce, Camel Train, Cavalry, Goatherd, Paddock, Sheepdog, Mill, Nobles, Pawn, Torturer, Upgrade" "Explosions: Way of the Squirrel, Populate, Animal Fair, Bounty Hunter, Coven, Hunting Lodge, Scrap, Courtyard, Diplomat, Lurker, Replace, Wishing Well" "Innsmouth: Way of the Goat, Invest, Animal Fair, Barge, Coven, Fisherman, Sheepdog, Caravan, Explorer, Fishing Village, Haven, Treasure Map" "Ruritania: Way of the Monkey, Alliance, Bounty Hunter, Cavalry, Falconer, Sleigh, Village Green, Lookout, Smugglers, Outpost, Tactician, Warehouse" "Class of '20: Way of the Owl, Delay, Cavalry, Coven, Hunting Lodge, Kiln, Livery, Snowy Village, Wayfarer, Transmute, Vineyard, University" "Limited Time Offer: Way of the Frog, Desperation, Destrier, Displace, Fisherman, Supplies, Wayfarer, Grand Market, Mint, Peddler, Talisman, Worker's Village" "Birth of a Nation: Way of the Otter, Reap, Animal Fair, Camel Train, Mastermind, Paddock, Stockpile, City, Monument, Quarry, Rabble, Trade Route" "Living in Exile: Way of the Mule, Enclave, Gatekeeper, Hostelry, Livery, Scrap, Stockpile, Fairgrounds, Hamlet, Jester, Journeyman, PI:NAME:<NAME>END_PI" "Thrill of the Hunt: Way of the Rat, Pursue, Black Cat, Bounty Hunter, Camel Train, Mastermind, Village Green, Butcher, Horse Traders, Hunting Party, Menagerie, Tournament" "Big Blue: Way of the Turtle, Banish, Black Cat, Falconer, Sheepdog, Sleigh, Village Green, Cartographer, Fool's Gold, Margrave, Trader, Tunnel" "Intersection: Way of the Mouse, Crossroads, Gamble, Cardinal, Hostelry, Livery, Mastermind, Supplies, Develop, Farmland, Haggler, Nomad Camp, Stables" "Friendly Carnage: Way of the Camel, Ride, Animal Fair, Cardinal, Falconer, Goatherd, Hunting Lodge, Altar, Beggar, Catacombs, Fortress, Market Square•" "Gift Horses: Way of the Butterfly, Bargain, Camel Train, Destrier, Displace, Paddock, Scrap, Hunting Grounds, Pillage, Rats, Sage, Squire" "Horse Feathers: Way of the Ox, Pilgrimage, Destrier, Displace, Falconer, Sleigh, Stockpile, Magpie, Ranger, Ratcatcher, Relic, Royal Carriage" "Sooner or Later: Toil, Mission, Barge, Gatekeeper, Groom, Mastermind, Village Green, Amulet, Caravan Guard, Dungeon, Giant, Raze" "No Money Down: Way of the Pig, Advance, Animal Fair, Cavalry, Sleigh, Stockpile, Wayfarer, CatapultRocks, City Quarter, Crown, Engineer, Villa" "Detours and Shortcuts: Transport, Triumphal Arch, Camel Train, Fisherman, Gatekeeper, Sanctuary, Snowy Village, Enchantress, Overlord, Sacrifice, SettlersBustling Village, Wild Hunt" "Seize the Night: Way of the Sheep, Seize the Day, Barge, Falconer, Hostelry, Sheepdog, Supplies, Cobbler, Devil's Workshop, Exorcist, Monastery, Skulk" "Animal Crackers: Way of the Chameleon, Enhance, Black Cat, Goatherd, Groom, Hunting Lodge, Kiln, Faithful Hound, Pixie, Pooka, Sacred Grove, Shepherd" "Biding Time: Way of the Turtle, Sinister Plot, Cavalry, Coven, Displace, Fisherman, Goatherd, Ducat, Priest, Recruiter, Scepter, Swashbuckler" "Villager Madness: Demand, Academy, Cardinal, Groom, Kiln, Livery, Wayfarer, Border Guard, Flag Bearer, Patron, Silk Merchant, Spices" ] for string in strings kingdom = parseSupplyString(string) console.log(" - name: " + kingdom.name) setIds = getSetsForCards(kingdom.cards) console.log(' sets:') for setId in setIds console.log(' - ' + setId) console.log(' supply:') cardIds = (card.id for card in kingdom.cards) cardIds.sort() for cardId in cardIds console.log(' - ' + cardId) console.log("")
[ { "context": "bre\"\n contact: \"Contacto\"\n twitter_follow: \"Seguir\"\n teachers: \"Profesores\"\n\n modal:\n close: ", "end": 1668, "score": 0.9994849562644958, "start": 1662, "tag": "USERNAME", "value": "Seguir" }, { "context": "spectate: \"Observar\" # Ladder page\n players: \"jugadores\" # Hover over a level on /play\n hours_played: ", "end": 2703, "score": 0.6668711304664612, "start": 2695, "tag": "USERNAME", "value": "ugadores" }, { "context": "der_campaigns: \"Campañas previas\"\n anonymous: \"Jugador Anónimo\"\n level_difficulty: \"Dificultad: \"\n campaig", "end": 3934, "score": 0.9997349381446838, "start": 3919, "tag": "NAME", "value": "Jugador Anónimo" }, { "context": "unt_title: \"recuperar cuenta\"\n send_password: \"Enviar Contraseña de Recuperación\"\n recovery_sent: \"Correo de recuperación envia", "end": 6359, "score": 0.999017596244812, "start": 6326, "tag": "PASSWORD", "value": "Enviar Contraseña de Recuperación" }, { "context": "bject: \"Asunto\"\n email: \"Email\"\n password: \"Contraseña\"\n message: \"Mensaje\"\n code: \"Código\"\n la", "end": 7379, "score": 0.9987789392471313, "start": 7369, "tag": "PASSWORD", "value": "Contraseña" }, { "context": " medium: \"Medio\"\n hard: \"Difícil\"\n player: \"Jugador\"\n# player_level: \"Level\" # Like player level 5", "end": 7669, "score": 0.9974185824394226, "start": 7662, "tag": "NAME", "value": "Jugador" }, { "context": "ir\"\n game_menu: \"Menu del Juego\"\n guide: \"Guia\"\n restart: \"Reiniciar\"\n goals: \"Objetivos\"\n", "end": 8256, "score": 0.8632689714431763, "start": 8254, "tag": "NAME", "value": "ia" }, { "context": "a y la práctica. Pero en la práctica, si la hay. - Yogi Berra\"\n tip_error_free: \"Hay dos formas de escribir ", "end": 11813, "score": 0.9997988939285278, "start": 11803, "tag": "NAME", "value": "Yogi Berra" }, { "context": "mas libres de errores; sólo la tercera funciona. - Alan Perlis\"\n tip_debugging_program: \"Si depurar es el pro", "end": 11931, "score": 0.9998883008956909, "start": 11920, "tag": "NAME", "value": "Alan Perlis" }, { "context": "ces programar debe ser el proceso de colocarlos. - Edsger W. Dijkstra\"\n tip_forums: \"¡Dirígite a los foros y dinos l", "end": 12080, "score": 0.9998584985733032, "start": 12062, "tag": "NAME", "value": "Edsger W. Dijkstra" }, { "context": "le: \"Siempre parece imposible hasta que se hace. - Nelson Mandela\"\n tip_talk_is_cheap: \"Hablar es barato. Muestr", "end": 13203, "score": 0.9998971819877625, "start": 13189, "tag": "NAME", "value": "Nelson Mandela" }, { "context": "s_cheap: \"Hablar es barato. Muestrame el código. - Linus Torvalds\"\n tip_first_language: \"La cosa más desastroza ", "end": 13284, "score": 0.9998764991760254, "start": 13270, "tag": "NAME", "value": "Linus Torvalds" }, { "context": " aprender es tu primer lenguaje de programación. - Alan Kay\"\n tip_hardware_problem: \"P: ¿Cuántos programad", "end": 13403, "score": 0.9997038245201111, "start": 13395, "tag": "NAME", "value": "Alan Kay" }, { "context": "a de hardware.\"\n tip_hofstadters_law: \"Ley de Hofstadter: Siempre toma más tiempo del que esperas, ", "end": 13588, "score": 0.7419605851173401, "start": 13586, "tag": "NAME", "value": "of" }, { "context": " optimización prematura es la raíz de la maldad. - Donald Knuth\"\n tip_brute_force: \"Cuando tengas duda, usa la", "end": 13790, "score": 0.9991409182548523, "start": 13778, "tag": "NAME", "value": "Donald Knuth" }, { "context": "force: \"Cuando tengas duda, usa la fuerza bruta. - Ken Thompson\"\n# tip_extrapolation: \"There are only two kind", "end": 13869, "score": 0.9997596740722656, "start": 13857, "tag": "NAME", "value": "Ken Thompson" }, { "context": "e\"\n nick_title: \"Programador\"\n nick_blurb: \"Gurú motivacional\"\n michael_title: \"Programador\"\n michael_blu", "end": 20878, "score": 0.9840680956840515, "start": 20861, "tag": "NAME", "value": "Gurú motivacional" }, { "context": ": \"Correos\"\n admin: \"Admin\"\n new_password: \"Nueva Contraseña\"\n new_password_verify: \"Verificar\"\n email_s", "end": 22558, "score": 0.9989369511604309, "start": 22542, "tag": "PASSWORD", "value": "Nueva Contraseña" }, { "context": "ord: \"Nueva Contraseña\"\n new_password_verify: \"Verificar\"\n email_subscriptions: \"Suscripciones de Email", "end": 22595, "score": 0.999069333076477, "start": 22586, "tag": "PASSWORD", "value": "Verificar" }, { "context": "n our party!\"\n# introduction_desc_signature: \"- Nick, George, Scott, Michael, Jeremy and Matt\"\n# ale", "end": 31012, "score": 0.9534057378768921, "start": 31008, "tag": "NAME", "value": "Nick" }, { "context": "party!\"\n# introduction_desc_signature: \"- Nick, George, Scott, Michael, Jeremy and Matt\"\n# alert_accou", "end": 31020, "score": 0.8113697171211243, "start": 31014, "tag": "NAME", "value": "George" }, { "context": "# introduction_desc_signature: \"- Nick, George, Scott, Michael, Jeremy and Matt\"\n# alert_account_mess", "end": 31027, "score": 0.8968431949615479, "start": 31022, "tag": "NAME", "value": "Scott" }, { "context": "troduction_desc_signature: \"- Nick, George, Scott, Michael, Jeremy and Matt\"\n# alert_account_message_intro", "end": 31036, "score": 0.8699924945831299, "start": 31029, "tag": "NAME", "value": "Michael" }, { "context": "n_desc_signature: \"- Nick, George, Scott, Michael, Jeremy and Matt\"\n# alert_account_message_intro: \"Hey ", "end": 31044, "score": 0.9677343368530273, "start": 31038, "tag": "NAME", "value": "Jeremy" }, { "context": "ature: \"- Nick, George, Scott, Michael, Jeremy and Matt\"\n# alert_account_message_intro: \"Hey there!\"\n#", "end": 31053, "score": 0.9962669610977173, "start": 31049, "tag": "NAME", "value": "Matt" }, { "context": " \"Esquema de Usuario\"\n user_profile: \"Perfil de Usuario\"\n patches: \"Parches\"\n# patched_model: \"Sour", "end": 47288, "score": 0.6170400381088257, "start": 47281, "tag": "USERNAME", "value": "Usuario" }, { "context": "ession\"\n# article: \"Article\"\n# user_names: \"User Names\"\n# thang_names: \"Thang Names\"\n# files: \"Fil", "end": 47646, "score": 0.5546814799308777, "start": 47636, "tag": "NAME", "value": "User Names" }, { "context": "\n# user_names: \"User Names\"\n# thang_names: \"Thang Names\"\n# files: \"Files\"\n# top_simulators: \"", "end": 47672, "score": 0.6202279329299927, "start": 47667, "tag": "NAME", "value": "Thang" }, { "context": "_header: \"Escribe tu nombre\"\n name_anonymous: \"Desarrollador anónimo\"\n name_help: \"El nombre que los empleadores ve", "end": 58294, "score": 0.9905056953430176, "start": 58273, "tag": "NAME", "value": "Desarrollador anónimo" }, { "context": "El nombre que los empleadores verán, por ejemplo 'Max Power'.\"\n short_description_header: \"Descríbet", "end": 58365, "score": 0.5334490537643433, "start": 58362, "tag": "NAME", "value": "Max" }, { "context": "nombre que los empleadores verán, por ejemplo 'Max Power'.\"\n short_description_header: \"Descríbete en p", "end": 58371, "score": 0.7403627038002014, "start": 58366, "tag": "USERNAME", "value": "Power" }, { "context": "rma activa por tu compañia.\"\n candidate_name: \"Nombre\"\n candidate_location: \"Ubicación\"\n candidat", "end": 64278, "score": 0.9973928332328796, "start": 64272, "tag": "NAME", "value": "Nombre" } ]
app/locale/es-419.coffee
rishiloyola/codecombat
0
module.exports = nativeDescription: "español (América Latina)", englishDescription: "Spanish (Latin America)", translation: home: slogan: "Aprende a programar jugando" no_ie: "¡Lo sentimos! CodeCombat no funciona en Internet Explorer 8 o versiones anteriores." # Warning that only shows up in IE8 and older no_mobile: "¡CodeCombat no fue diseñado para dispositivos móviles y quizás no funcione!" # Warning that shows up on mobile devices play: "Jugar" # The big play button that just starts playing a level # try_it: "Try It" # Alternate wording for Play button old_browser: "¡Oh! ¡Oh! Tu navegador es muy antiguo para correr CodeCombat. ¡Lo Sentimos!" # Warning that shows up on really old Firefox/Chrome/Safari old_browser_suffix: "Puedes probar de todas formas, pero probablemente no funcione." # ipad_browser: "Bad news: CodeCombat doesn't run on iPad in the browser. Good news: our native iPad app is awaiting Apple approval." campaign: "Campaña" for_beginners: "Para Principiantes" multiplayer: "Multijugador" # Not currently shown on home page for_developers: "Para Desarrolladores" # Not currently shown on home page. # or_ipad: "Or download for iPad" nav: play: "Jugar" # The top nav bar entry where players choose which levels to play community: "Comunidad" editor: "Editor" blog: "Blog" forum: "Foro" account: "Cuenta" profile: "Perfil" stats: "Stadísticas" code: "Cógigo" admin: "Admin" # Only shows up when you are an admin home: "Inicio" contribute: "Contribuir" legal: "Legal" about: "Sobre" contact: "Contacto" twitter_follow: "Seguir" teachers: "Profesores" modal: close: "Cerrar" okay: "OK" not_found: page_not_found: "Página no encontrada" diplomat_suggestion: title: "¡Ayuda a traducir CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Necesitamos tus habilidades de idioma." pitch_body: "Desarrollamos CodeCombat en inglés, pero ya tenemos jugadores por todo el mundo. Muchos de ellos quieren jugar en español pero no hablan inglés, así que si puedes hablar ambos, por favor considera registrarte pare ser un Diplomático y ayudar a traducir tanto el sitio de CodeCombat como todos los niveles al español." missing_translations: "Hasta que podamos traducir todo al español, verás inglés cuando el español no esté disponible." learn_more: "Aprende más sobre ser un Diplomático" subscribe_as_diplomat: "Suscribete como un Diplomático" play: play_as: "Jugar Como " # Ladder page spectate: "Observar" # Ladder page players: "jugadores" # Hover over a level on /play hours_played: "horas jugadas" # Hover over a level on /play items: "Objetos" # Tooltip on item shop button from /play # unlock: "Unlock" # For purchasing items and heroes # confirm: "Confirm" # owned: "Owned" # For items you own # locked: "Locked" # purchasable: "Purchasable" # For a hero you unlocked but haven't purchased # available: "Available" # skills_granted: "Skills Granted" # Property documentation details heroes: "Héroes" # Tooltip on hero shop button from /play achievements: "Logros" # Tooltip on achievement list button from /play account: "Cuenta" # Tooltip on account button from /play settings: "Configuración" # Tooltip on settings button from /play next: "Próximo" # Go from choose hero to choose inventory before playing a level change_hero: "Cambiar héroe" # Go back from choose inventory to choose hero choose_inventory: "Equipar objetos" # buy_gems: "Buy Gems" # campaign_forest: "Forest Campaign" # campaign_dungeon: "Dungeon Campaign" # subscription_required: "Subscription Required" # free: "Free" # subscribed: "Subscribed" older_campaigns: "Campañas previas" anonymous: "Jugador Anónimo" level_difficulty: "Dificultad: " campaign_beginner: "Campaña para principiantes" # awaiting_levels_adventurer_prefix: "We release five levels per week." # awaiting_levels_adventurer: "Sign up as an Adventurer" # awaiting_levels_adventurer_suffix: "to be the first to play new levels." choose_your_level: "Elige tu nivel" # The rest of this section is the old play view at /play-old and isn't very important. adventurer_prefix: "Puedes saltar a cualquier nivel de abajo, o discutir los niveles en " adventurer_forum: "el foro del aventurero" adventurer_suffix: "." campaign_old_beginner: "Campaña anterior de principiante" campaign_old_beginner_description: "... en la que aprendes la hechicería de la programación." campaign_dev: "Niveles aleatorios más difíciles" campaign_dev_description: "... en los que aprendes sobre la interfaz mientras haces algo un poco más difícil." campaign_multiplayer: "Arenas Multijugador" campaign_multiplayer_description: "... en las que programas cara-a-cara contra otros jugadores." campaign_player_created: "Creados-Por-Jugadores" campaign_player_created_description: "... en los que luchas contra la creatividad de tus compañeros <a href=\"/contribute#artisan\">Hechiceros Artesanales</a>." campaign_classic_algorithms: "Algorítmos Clásicos" campaign_classic_algorithms_description: "... en la cual aprendes los algorítmos más populares en las Ciencias de la Computación." login: sign_up: "Crear Cuenta" log_in: "Entrar" logging_in: "Entrando" log_out: "Salir" recover: "recuperar cuenta" # authenticate_gplus: "Authenticate G+" # load_profile: "Load G+ Profile" # load_email: "Load G+ Email" # finishing: "Finishing" signup: create_account_title: "Crear Cuenta para Guardar el Progreso" description: "Es gratis. Solo necesitas un par de cosas y estarás listo para comenzar:" email_announcements: "Recibe noticias por email" coppa: "más de 13 años o fuera de los Estados Unidos" coppa_why: "(¿Por qué?)" creating: "Creando Cuenta..." sign_up: "Registrarse" log_in: "Inicia sesión con tu contraseña" social_signup: "O, puedes conectarte a través de Facebook o G+:" required: "Necesitas entrar a tu cuenta antes de continuar." recover: recover_account_title: "recuperar cuenta" send_password: "Enviar Contraseña de Recuperación" recovery_sent: "Correo de recuperación enviado." items: # primary: "Primary" # secondary: "Secondary" armor: "Armadura" accessories: "Accesorios" misc: "Misc" # books: "Books" common: loading: "Cargando..." saving: "Guardando..." sending: "Enviando..." send: "Enviar" cancel: "Cancelar" save: "Guardar" publish: "Publicar" create: "Crear" manual: "Manual" fork: "Bifurcar" play: "Jugar" # When used as an action verb, like "Play next level" retry: "Reintentar" watch: "Seguir" unwatch: "No seguir" submit_patch: "Enviar Parche" general: and: "y" name: "Nombre" date: "Fecha" body: "Cuerpo" version: "Versión" commit_msg: "Enviar mensaje" version_history: "Historial de Versiones" version_history_for: "Historial de Versiones para: " result: "Resultado" results: "Resultados" description: "Descripción" or: "o" subject: "Asunto" email: "Email" password: "Contraseña" message: "Mensaje" code: "Código" ladder: "Escalera" when: "Cuando" opponent: "Oponente" rank: "Posición" score: "Puntuación" win: "Ganada" loss: "Perdida" tie: "Empate" easy: "Fácil" medium: "Medio" hard: "Difícil" player: "Jugador" # player_level: "Level" # Like player level 5, not like level: Dungeons of Kithgard units: second: "segundo" seconds: "segundos" minute: "minuto" minutes: "minutos" hour: "hora" hours: "horas" day: "día" days: "días" week: "semana" weeks: "semanas" month: "mes" months: "meses" year: "año" years: "años" play_level: done: "Listo" home: "Inicio" # Not used any more, will be removed soon. # level: "Level" # Like "Level: Dungeons of Kithgard" skip: "Omitir" game_menu: "Menu del Juego" guide: "Guia" restart: "Reiniciar" goals: "Objetivos" goal: "Objetivo" # running: "Running..." success: "¡Éxito!" incomplete: "Incompleto" timed_out: "Se te acabo el tiempo" failing: "Fallando" action_timeline: "Cronologia de Accion" click_to_select: "Has click en una unidad para seleccionarla." # control_bar_multiplayer: "Multiplayer" # control_bar_join_game: "Join Game" # reload: "Reload" reload_title: "¿Recargar Todo el Código?" reload_really: "¿Estás seguro de que quieres empezar este nivel desde el principio?" reload_confirm: "Recargar Todo" victory_title_prefix: "¡" victory_title_suffix: " Completo!" victory_sign_up: "Registrate para recibir actualizaciones" victory_sign_up_poke: "¿Quieres recibir las ultimas noticias por correo? ¡Crea una cuenta gratuita y te mantendremos informado!" victory_rate_the_level: "Valora el nivel: " # Only in old-style levels. victory_return_to_ladder: "Volver a la escalera" victory_play_continue: "Continuar" # victory_play_skip: "Skip Ahead" victory_play_next_level: "Jugar Próximo Nivel" # victory_play_more_practice: "More Practice" # victory_play_too_easy: "Too Easy" # victory_play_just_right: "Just Right" # victory_play_too_hard: "Too Hard" # victory_saving_progress: "Saving Progress" victory_go_home: "Ir al Inicio" # Only in old-style levels. victory_review: "¡Cuéntanos más!" # Only in old-style levels. victory_hour_of_code_done: "¿Has acabado?" victory_hour_of_code_done_yes: "¡Si, he terminado con mi Hora de Código!" guide_title: "Guía" tome_minion_spells: "Hechizos de tus Secuaces" # Only in old-style levels. tome_read_only_spells: "Hechizos de Sólo Lectura" # Only in old-style levels. tome_other_units: "Otras Unidades" # Only in old-style levels. tome_cast_button_run: "Ejecutar" tome_cast_button_running: "Ejecutando" tome_cast_button_ran: "Ejecutado" tome_submit_button: "Enviar" tome_reload_method: "Recargar código original para este método" # Title text for individual method reload button. tome_select_method: "Seleccionar un Método" tome_see_all_methods: "Ver todos los métodos que puedes editar" # Title text for method list selector (shown when there are multiple programmable methdos). tome_select_a_thang: "Selecciona Alguien para " tome_available_spells: "Hechizos Disponibles" tome_your_skills: "Tus habilidades" # tome_help: "Help" # tome_current_method: "Current Method" # hud_continue_short: "Continue" # code_saved: "Code Saved" skip_tutorial: "Saltar (esc)" keyboard_shortcuts: "Atajos de teclado" loading_ready: "¡Listo!" loading_start: "Iniciar nivel" # problem_alert_title: "Fix Your Code" time_current: "Ahora:" time_total: "Max:" time_goto: "Ir a:" infinite_loop_try_again: "Intentar nuevamente" infinite_loop_reset_level: "Reiniciar Nivel" infinite_loop_comment_out: "Comente Mi Código" tip_toggle_play: "Activa jugar/pausa con Ctrl+P." tip_scrub_shortcut: "Ctrl+[ y Ctrl+] rebobina y avance rápido." tip_guide_exists: "Clique la guía en la parte superior de la página para obtener información útil" tip_open_source: "¡CodeCombat es 100% código abierto!" tip_beta_launch: "CodeCombat lanzó su beta en Octubre del 2013." tip_think_solution: "Piensa en la solución, no en el problema." tip_theory_practice: "En teoría, no hay diferencia entre la teoría y la práctica. Pero en la práctica, si la hay. - Yogi Berra" tip_error_free: "Hay dos formas de escribir programas libres de errores; sólo la tercera funciona. - Alan Perlis" tip_debugging_program: "Si depurar es el proceso de remover errores, entonces programar debe ser el proceso de colocarlos. - Edsger W. Dijkstra" tip_forums: "¡Dirígite a los foros y dinos lo que piensas!" tip_baby_coders: "En el futuro, incluso los bebés serán Archimagos." tip_morale_improves: "La carga continuará hasta que la moral mejore." tip_all_species: "Creemos en la igualdad de oportunidades para aprender a programar para todas las especies." tip_reticulating: "Espinas reticulantes." tip_harry: "Eres un Hechicero, " tip_great_responsibility: "Con una gran habilidad de hacer código viene una gran responsabilidad de depuración." tip_munchkin: "Si no comes tus verduras, un enano vendrá por ti mientras estés dormido." tip_binary: "Sólo hay 10 tipos de personas en el mundo: aquellas que entienden binario y las que no." tip_commitment_yoda: "Un programador debe tener el compromiso más profundo, la mente más seria. ~ Yoda" tip_no_try: "Haz. O no hagas. No hay intento. - Yoda" tip_patience: "Paciencia debes tener, joven Padawan. - Yoda" tip_documented_bug: "Un error documentad no es un error; es una característica." tip_impossible: "Siempre parece imposible hasta que se hace. - Nelson Mandela" tip_talk_is_cheap: "Hablar es barato. Muestrame el código. - Linus Torvalds" tip_first_language: "La cosa más desastroza que puedes aprender es tu primer lenguaje de programación. - Alan Kay" tip_hardware_problem: "P: ¿Cuántos programadores son necesarios para cambiar una bombilla eléctrica? R: Ninguno, es un problema de hardware." tip_hofstadters_law: "Ley de Hofstadter: Siempre toma más tiempo del que esperas, inclso cuando tienes en cuenta la ley de Hofstadter." tip_premature_optimization: "La optimización prematura es la raíz de la maldad. - Donald Knuth" tip_brute_force: "Cuando tengas duda, usa la fuerza bruta. - Ken Thompson" # tip_extrapolation: "There are only two kinds of people: those that can extrapolate from incomplete data..." customize_wizard: "Personalizar Hechicero" game_menu: inventory_tab: "Inventario" save_load_tab: "Guardar/Cargar" options_tab: "Opciones" guide_tab: "Guía" multiplayer_tab: "Multijugador" # auth_tab: "Sign Up" inventory_caption: "Equipar tu héroe" choose_hero_caption: "Elegir héroe, lenguaje" save_load_caption: "... y ver historia" options_caption: "Hacer ajustes" guide_caption: "Documentos y consejos" multiplayer_caption: "¡Jugar con amigos!" # auth_caption: "Save your progress." inventory: choose_inventory: "Elegir artículos" # equipped_item: "Equipped" # available_item: "Available" # restricted_title: "Restricted" # should_equip: "(double-click to equip)" # equipped: "(equipped)" # locked: "(locked)" # restricted: "(restricted in this level)" # equip: "Equip" # unequip: "Unequip" # buy_gems: # few_gems: "A few gems" # pile_gems: "Pile of gems" # chest_gems: "Chest of gems" # purchasing: "Purchasing..." # declined: "Your card was declined" # retrying: "Server error, retrying." # prompt_title: "Not Enough Gems" # prompt_body: "Do you want to get more?" # prompt_button: "Enter Shop" # subscribe: # subscribe_title: "Subscribe" # levels: "Unlock 25 levels! With 5 new ones every week!" # heroes: "More powerful heroes!" # gems: "3500 bonus gems every month!" # items: "Over 250 bonus items!" # parents: "For Parents" # parents_title: "Your child will learn to code." # parents_blurb1: "With CodeCombat, your child learns by writing real code. They start by learning simple commands, and progress to more advanced topics." # parents_blurb2: "For $9.99 USD/mo, they get new challenges every week and personal email support from professional programmers." # parents_blurb3: "No Risk: 100% money back guarantee, easy 1-click unsubscribe." # subscribe_button: "Subscribe Now" # stripe_description: "Monthly Subscription" # subscription_required_to_play: "You'll need a subscription to play this level." choose_hero: choose_hero: "Elige tu héroe" programming_language: "Lenguaje de programación" programming_language_description: "¿Qué lenguaje de programación vas a elegir?" # default: "Default" # experimental: "Experimental" python_blurb: "Simple pero poderoso." javascript_blurb: "El lenguaje de la web." coffeescript_blurb: "Mejor JavaScript." clojure_blurb: "Un Lisp moderno." lua_blurb: "Para Juegos." io_blurb: "Simple pero oscuro." status: "Estado" weapons: "Armas" # weapons_warrior: "Swords - Short Range, No Magic" # weapons_ranger: "Crossbows, Guns - Long Range, No Magic" # weapons_wizard: "Wands, Staffs - Long Range, Magic" # attack: "Damage" # Can also translate as "Attack" health: "Salud" speed: "Velocidad" # regeneration: "Regeneration" # range: "Range" # As in "attack or visual range" # blocks: "Blocks" # As in "this shield blocks this much damage" # skills: "Skills" # available_for_purchase: "Available for Purchase" # level_to_unlock: "Level to unlock:" # restricted_to_certain_heroes: "Only certain heroes can play this level." # skill_docs: # writable: "writable" # Hover over "attack" in Your Skills while playing a level to see most of this # read_only: "read-only" # action_name: "name" # action_cooldown: "Takes" # action_specific_cooldown: "Cooldown" # action_damage: "Damage" # action_range: "Range" # action_radius: "Radius" # action_duration: "Duration" # example: "Example" # ex: "ex" # Abbreviation of "example" # current_value: "Current Value" # default_value: "Default value" # parameters: "Parameters" # returns: "Returns" # granted_by: "Granted by" save_load: granularity_saved_games: "Almacenado" granularity_change_history: "Historia" options: general_options: "Opciones Generales" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volumen" music_label: "Música" music_description: "Música encendida/apagada." autorun_label: "Autoejecutar" autorun_description: "Controlar ejecución automática de código." editor_config: "Config. de Editor" editor_config_title: "Configuración del Editor" editor_config_level_language_label: "Lenguaje para este Nivel" editor_config_level_language_description: "Definir el lenguaje de programación para Este nivel." editor_config_default_language_label: "Lenguaje de Programación Predeterminado" editor_config_default_language_description: "Definir el lenguaje de programación que deseas para codificar cuando inicias nuevos niveles." editor_config_keybindings_label: "Atajos de Teclado" editor_config_keybindings_default: "Default (As)" editor_config_keybindings_description: "Añade atajos adicionales conocidos de los editores comunes." editor_config_livecompletion_label: "Autocompletado automático" editor_config_livecompletion_description: "Despliega sugerencias de autocompletado mientras escribes." editor_config_invisibles_label: "Mostrar Invisibles" editor_config_invisibles_description: "Visualiza invisibles tales como espacios o tabulaciones." editor_config_indentguides_label: "Mostrar guías de indentación" editor_config_indentguides_description: "Visualiza líneas verticales para ver mejor la indentación." editor_config_behaviors_label: "Comportamientos Inteligentes" editor_config_behaviors_description: "Autocompleta corchetes, llaves y comillas." about: why_codecombat: "¿Por qué CodeCombat?" why_paragraph_1: "Si quieres aprender a programar, no necesitas lecciones. Necesitas escribir mucho código y disfrutarlo mucho haciéndolo." why_paragraph_2_prefix: "De eso se trata la programación. Será divertido. No casi divertido" why_paragraph_2_italic: "bien un premio" why_paragraph_2_center: "pero algo divertido" why_paragraph_2_italic_caps: "¡NO MAMÁ, TENGO QUE FINALIZAR EL NIVEL!" why_paragraph_2_suffix: "Por tal motivo CodeCombat es un juego multiusuario, no un curso con gamificación. No finalizaremos hasta que terminos--pero en esta ocasión, es una buena cosa." why_paragraph_3: "si te vas a volver adicto a un juego, hazlo a este y conviértete en un de los magos de la era tecnológica." press_title: "Blogeros/Prensa" press_paragraph_1_prefix: "¿Quieres escribirnos? Descarga y usa con confianza todos los recursos incluídos en nuestro" press_paragraph_1_link: "paquete de prensa" press_paragraph_1_suffix: ". Todos los logos e imágenes pueden ser usados sin contactarnos directamente." team: "Equipo" george_title: "CEO" george_blurb: "Negociante" scott_title: "Programador" scott_blurb: "Razonable" nick_title: "Programador" nick_blurb: "Gurú motivacional" michael_title: "Programador" michael_blurb: "Sys Admin" matt_title: "Programador" matt_blurb: "Bicicletero" versions: save_version_title: "Guardar nueva versión" new_major_version: "Nueva Gran Versión" cla_prefix: "Para guardar los cambios, primero debes estar de acuerdo con nuestro" cla_url: "CLA" cla_suffix: "." cla_agree: "ACEPTO" contact: contact_us: "Contacta a CodeCombat" welcome: "¡Qué bueno es escucharte! Usa este formulario para enviarnos un mensaje" contribute_prefix: "¡Si estas interesado en contribuir, chequea nuestra " contribute_page: "página de contribución" contribute_suffix: "!" forum_prefix: "Para cualquier cosa pública, por favor prueba " forum_page: "nuestro foro " forum_suffix: "en su lugar." send: "Enviar Comentario" contact_candidate: "Contacta un Candidato" # Deprecated recruitment_reminder: "Usa este formulario para llegar a los candidadtos que estés interesado en entrevistar. Recuerda que CodeCombat cobra 18% del primer año de salario. Este honorario se debe a la contratación del empleado y reembolsable por 90 days si el empleado no permanece contratado. Tiempo partcial, remoto, y empleados por contrato son gratiso, como así también internos." # Deprecated account_settings: title: "Configuración de la Cuenta" not_logged_in: "Inicia sesión o crea una cuenta para cambiar tu configuración." autosave: "Cambios Guardados Automáticamente" me_tab: "Yo" picture_tab: "Imagen" upload_picture: "Sube una imagen" password_tab: "Contraseña" emails_tab: "Correos" admin: "Admin" new_password: "Nueva Contraseña" new_password_verify: "Verificar" email_subscriptions: "Suscripciones de Email" email_subscriptions_none: "No tienes suscripciones." email_announcements: "Noticias" email_announcements_description: "Recibe correos electrónicos con las últimas noticias y desarrollos de CodeCombat." email_notifications: "Notificaciones" email_notifications_summary: "Controles para tus notificaciones por correo electrónico automáticas y personalizadas relativas a tu actividad en CodeCombat." email_any_notes: "Algunas notificaciones" email_any_notes_description: "Desactiva para detener toda la actividad de correos de notificaciones." email_news: "Noticias" email_recruit_notes: "Oportunidades Laborales" email_recruit_notes_description: "Si juegas realmente bien podríamos contactarte para ofrecerte un (mejor) trabajo." contributor_emails: "Emails Clase Contribuyente" contribute_prefix: "¡Estamos buscando gente que se una a nuestro grupo! Echa un vistazo a la " contribute_page: "página de contribución" contribute_suffix: "para averiguar más." email_toggle: "Activar Todo" error_saving: "Error al Guardar" saved: "Cambios Guardados" password_mismatch: "La contraseña no coincide." password_repeat: "Por favor repita su contraseña." job_profile: "Perfil de Trabajo" # Rest of this section (the job profile stuff and wizard stuff) is deprecated job_profile_approved: "Tu perfil de trabajo ha sido aprobado por CodeCombat. Los empleadores podrán verlo hasta que lo marques como inactivo o permanezca sin cambios por cuatro semanas." job_profile_explanation: "¡Hola! Llena esto, y te contactaremos acerca de encontrar un trabajo como desarrollador de software." sample_profile: "Mira un perfil de ejemplo" view_profile: "Ver tu perfil" wizard_tab: "Hechicero" wizard_color: "Color de Ropas del Hechicero" keyboard_shortcuts: keyboard_shortcuts: "Keyboard Shortcuts" space: "Barra espaciadora" enter: "Enter" escape: "Escape" shift: "Shift" # run_code: "Run current code." run_real_time: "Ejecutar en tiempo real." continue_script: "Continuar hasta finalizado el script." skip_scripts: "Omitir todos los scripts omitibles." toggle_playback: "Aplicar ejecutar/pausar." scrub_playback: "Devolverse y avanzar en el tiempo." single_scrub_playback: "Devolverse y avanzar en el tiempo de a un cuadro." # scrub_execution: "Scrub through current spell execution." toggle_debug: "Mostrar ocultar depuración." # toggle_grid: "Toggle grid overlay." # toggle_pathfinding: "Toggle pathfinding overlay." beautify: "Hacer bello tu código estandarizando formato." maximize_editor: "Maximizar/minimizar editor de código." move_wizard: "Mover tu hechizero en el nivel." community: main_title: "Comunidad CodeCombat" introduction: "Mira las maneras en las que puedes involucrarte adelante y decide qué es más divertido. ¡Queremos trabajar contigo!" level_editor_prefix: "Usar CodeCombat" level_editor_suffix: "para crear y editar niveles. Los han creado niveles para sus clases, amigos, hackatones, estudiantes, familiares. Si crear un nuevo juego luce intimidante puedes ¡comenzar con base en uno nuestro!" # thang_editor_prefix: "We call units within the game 'thangs'. Use the" # thang_editor_suffix: "to modify the CodeCombat source artwork. Allow units to throw projectiles, alter the direction of an animation, change a unit's hit points, or upload your own vector sprites." # article_editor_prefix: "See a mistake in some of our docs? Want to make some instructions for your own creations? Check out the" # article_editor_suffix: "and help CodeCombat players get the most out of their playtime." # find_us: "Find us on these sites" # social_blog: "Read the CodeCombat blog on Sett" # social_discource: "Join the discussion on our Discourse forum" # social_facebook: "Like CodeCombat on Facebook" # social_twitter: "Follow CodeCombat on Twitter" # social_gplus: "Join CodeCombat on Google+" # social_hipchat: "Chat with us in the public CodeCombat HipChat room" # contribute_to_the_project: "Contribute to the project" classes: archmage_title: "Archimago" archmage_title_description: "(Desarrollador)" artisan_title: "Artesano" artisan_title_description: "(Constructor de Niveles)" adventurer_title: "Aventurero" adventurer_title_description: "(Probador de Niveles)" scribe_title: "Escriba" scribe_title_description: "(Editor de Artículos)" diplomat_title: "Diplomado" diplomat_title_description: "(Traductor)" ambassador_title: "Embajador" ambassador_title_description: "(Soporte)" # editor: # main_title: "CodeCombat Editors" # article_title: "Article Editor" # thang_title: "Thang Editor" # level_title: "Level Editor" # achievement_title: "Achievement Editor" # back: "Back" # revert: "Revert" # revert_models: "Revert Models" # pick_a_terrain: "Pick A Terrain" # small: "Small" # grassy: "Grassy" # fork_title: "Fork New Version" # fork_creating: "Creating Fork..." # generate_terrain: "Generate Terrain" # more: "More" # wiki: "Wiki" # live_chat: "Live Chat" # level_some_options: "Some Options?" # level_tab_thangs: "Thangs" # level_tab_scripts: "Scripts" # level_tab_settings: "Settings" # level_tab_components: "Components" # level_tab_systems: "Systems" # level_tab_docs: "Documentation" # level_tab_thangs_title: "Current Thangs" # level_tab_thangs_all: "All" # level_tab_thangs_conditions: "Starting Conditions" # level_tab_thangs_add: "Add Thangs" # delete: "Delete" # duplicate: "Duplicate" # rotate: "Rotate" # level_settings_title: "Settings" # level_component_tab_title: "Current Components" # level_component_btn_new: "Create New Component" # level_systems_tab_title: "Current Systems" # level_systems_btn_new: "Create New System" # level_systems_btn_add: "Add System" # level_components_title: "Back to All Thangs" # level_components_type: "Type" # level_component_edit_title: "Edit Component" # level_component_config_schema: "Config Schema" # level_component_settings: "Settings" # level_system_edit_title: "Edit System" # create_system_title: "Create New System" # new_component_title: "Create New Component" # new_component_field_system: "System" # new_article_title: "Create a New Article" # new_thang_title: "Create a New Thang Type" # new_level_title: "Create a New Level" # new_article_title_login: "Log In to Create a New Article" # new_thang_title_login: "Log In to Create a New Thang Type" # new_level_title_login: "Log In to Create a New Level" # new_achievement_title: "Create a New Achievement" # new_achievement_title_login: "Log In to Create a New Achievement" # article_search_title: "Search Articles Here" # thang_search_title: "Search Thang Types Here" # level_search_title: "Search Levels Here" # achievement_search_title: "Search Achievements" # read_only_warning2: "Note: you can't save any edits here, because you're not logged in." # no_achievements: "No achievements have been added for this level yet." # achievement_query_misc: "Key achievement off of miscellanea" # achievement_query_goals: "Key achievement off of level goals" # level_completion: "Level Completion" # pop_i18n: "Populate I18N" article: edit_btn_preview: "Vista previa" edit_article_title: "Editar Artículo" # contribute: # page_title: "Contributing" # character_classes_title: "Character Classes" # introduction_desc_intro: "We have high hopes for CodeCombat." # introduction_desc_pref: "We want to be where programmers of all stripes come to learn and play together, introduce others to the wonderful world of coding, and reflect the best parts of the community. We can't and don't want to do that alone; what makes projects like GitHub, Stack Overflow and Linux great are the people who use them and build on them. To that end, " # introduction_desc_github_url: "CodeCombat is totally open source" # introduction_desc_suf: ", and we aim to provide as many ways as possible for you to take part and make this project as much yours as ours." # introduction_desc_ending: "We hope you'll join our party!" # introduction_desc_signature: "- Nick, George, Scott, Michael, Jeremy and Matt" # alert_account_message_intro: "Hey there!" # alert_account_message: "To subscribe for class emails, you'll need to be logged in first." # archmage_summary: "Interested in working on game graphics, user interface design, database and server organization, multiplayer networking, physics, sound, or game engine performance? Want to help build a game to help other people learn what you are good at? We have a lot to do and if you are an experienced programmer and want to develop for CodeCombat, this class is for you. We would love your help building the best programming game ever." # archmage_introduction: "One of the best parts about building games is they synthesize so many different things. Graphics, sound, real-time networking, social networking, and of course many of the more common aspects of programming, from low-level database management, and server administration to user facing design and interface building. There's a lot to do, and if you're an experienced programmer with a hankering to really dive into the nitty-gritty of CodeCombat, this class might be for you. We would love to have your help building the best programming game ever." # class_attributes: "Class Attributes" # archmage_attribute_1_pref: "Knowledge in " # archmage_attribute_1_suf: ", or a desire to learn. Most of our code is in this language. If you're a fan of Ruby or Python, you'll feel right at home. It's JavaScript, but with a nicer syntax." # archmage_attribute_2: "Some experience in programming and personal initiative. We'll help you get oriented, but we can't spend much time training you." # how_to_join: "How To Join" # join_desc_1: "Anyone can help out! Just check out our " # join_desc_2: "to get started, and check the box below to mark yourself as a brave Archmage and get the latest news by email. Want to chat about what to do or how to get more deeply involved? " # join_desc_3: ", or find us in our " # join_desc_4: "and we'll go from there!" # join_url_email: "Email us" # join_url_hipchat: "public HipChat room" # more_about_archmage: "Learn More About Becoming an Archmage" # archmage_subscribe_desc: "Get emails on new coding opportunities and announcements." # artisan_summary_pref: "Want to design levels and expand CodeCombat's arsenal? People are playing through our content at a pace faster than we can build! Right now, our level editor is barebone, so be wary. Making levels will be a little challenging and buggy. If you have visions of campaigns spanning for-loops to" # artisan_summary_suf: ", then this class is for you." # artisan_introduction_pref: "We must construct additional levels! People be clamoring for more content, and we can only build so many ourselves. Right now your workstation is level one; our level editor is barely usable even by its creators, so be wary. If you have visions of campaigns spanning for-loops to" # artisan_introduction_suf: ", then this class might be for you." # artisan_attribute_1: "Any experience in building content like this would be nice, such as using Blizzard's level editors. But not required!" # artisan_attribute_2: "A hankering to do a whole lot of testing and iteration. To make good levels, you need to take it to others and watch them play it, and be prepared to find a lot of things to fix." # artisan_attribute_3: "For the time being, endurance en par with an Adventurer. Our Level Editor is super preliminary and frustrating to use. You have been warned!" # artisan_join_desc: "Use the Level Editor in these steps, give or take:" # artisan_join_step1: "Read the documentation." # artisan_join_step2: "Create a new level and explore existing levels." # artisan_join_step3: "Find us in our public HipChat room for help." # artisan_join_step4: "Post your levels on the forum for feedback." # more_about_artisan: "Learn More About Becoming an Artisan" # artisan_subscribe_desc: "Get emails on level editor updates and announcements." # adventurer_summary: "Let us be clear about your role: you are the tank. You are going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class is for you." # adventurer_introduction: "Let's be clear about your role: you are the tank. You're going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class might be for you." # adventurer_attribute_1: "A thirst for learning. You want to learn how to code and we want to teach you how to code. You'll probably be doing most of the teaching in this case, though." # adventurer_attribute_2: "Charismatic. Be gentle but articulate about what needs improving, and offer suggestions on how to improve." # adventurer_join_pref: "Either get together with (or recruit!) an Artisan and work with them, or check the box below to receive emails when there are new levels to test. We'll also be posting about levels to review on our networks like" # adventurer_forum_url: "our forum" # adventurer_join_suf: "so if you prefer to be notified those ways, sign up there!" # more_about_adventurer: "Learn More About Becoming an Adventurer" # adventurer_subscribe_desc: "Get emails when there are new levels to test." # scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the " # scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you." # scribe_introduction_pref: "CodeCombat isn't just going to be a bunch of levels. It will also include a resource for knowledge, a wiki of programming concepts that levels can hook into. That way rather than each Artisan having to describe in detail what a comparison operator is, they can simply link their level to the Article describing them that is already written for the player's edification. Something along the lines of what the " # scribe_introduction_url_mozilla: "Mozilla Developer Network" # scribe_introduction_suf: " has built. If your idea of fun is articulating the concepts of programming in Markdown form, then this class might be for you." # scribe_attribute_1: "Skill in words is pretty much all you need. Not only grammar and spelling, but able to convey complicated ideas to others." # contact_us_url: "Contact us" # scribe_join_description: "tell us a little about yourself, your experience with programming and what sort of things you'd like to write about. We'll go from there!" # more_about_scribe: "Learn More About Becoming a Scribe" # scribe_subscribe_desc: "Get emails about article writing announcements." # diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you." # diplomat_introduction_pref: "So, if there's one thing we learned from the " # diplomat_launch_url: "launch in October" # diplomat_introduction_suf: "it's that there is sizeable interest in CodeCombat in other countries! We're building a corps of translators eager to turn one set of words into another set of words to get CodeCombat as accessible across the world as possible. If you like getting sneak peeks at upcoming content and getting these levels to your fellow nationals ASAP, then this class might be for you." # diplomat_attribute_1: "Fluency in English and the language you would like to translate to. When conveying complicated ideas, it's important to have a strong grasp in both!" # diplomat_i18n_page_prefix: "You can start translating our levels by going to our" # diplomat_i18n_page: "translations page" # diplomat_i18n_page_suffix: ", or our interface and website on GitHub." # diplomat_join_pref_github: "Find your language locale file " # diplomat_github_url: "on GitHub" # diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!" # more_about_diplomat: "Learn More About Becoming a Diplomat" # diplomat_subscribe_desc: "Get emails about i18n developments and levels to translate." # ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you." # ambassador_introduction: "This is a community we're building, and you are the connections. We've got Olark chats, emails, and social networks with lots of people to talk with and help get acquainted with the game and learn from. If you want to help people get involved and have fun, and get a good feel of the pulse of CodeCombat and where we're going, then this class might be for you." # ambassador_attribute_1: "Communication skills. Be able to identify the problems players are having and help them solve them. Also, keep the rest of us informed about what players are saying, what they like and don't like and want more of!" # ambassador_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll go from there!" # ambassador_join_note_strong: "Note" # ambassador_join_note_desc: "One of our top priorities is to build multiplayer where players having difficulty solving levels can summon higher level wizards to help them. This will be a great way for ambassadors to do their thing. We'll keep you posted!" # more_about_ambassador: "Learn More About Becoming an Ambassador" # ambassador_subscribe_desc: "Get emails on support updates and multiplayer developments." # changes_auto_save: "Changes are saved automatically when you toggle checkboxes." # diligent_scribes: "Our Diligent Scribes:" # powerful_archmages: "Our Powerful Archmages:" # creative_artisans: "Our Creative Artisans:" # brave_adventurers: "Our Brave Adventurers:" # translating_diplomats: "Our Translating Diplomats:" # helpful_ambassadors: "Our Helpful Ambassadors:" ladder: please_login: "Por favor inicia sesión antes de jugar una partida de escalera." my_matches: "Mis Partidas" simulate: "Simular" simulation_explanation: "¡Simulando tus juegos puedes mejorar tu posición más rápido!" simulate_games: "¡Simular Juegos!" simulate_all: "REINICIAR Y SIMULAR JUEGOS" games_simulated_by: "Juegos simulados por ti:" games_simulated_for: "Juegos simulados para ti:" games_simulated: "Juegos simulados" games_played: "Juegos jugados" ratio: "Proporción" leaderboard: "Posiciones" battle_as: "Combate como " summary_your: "Tus " summary_matches: "Partidas - " summary_wins: " Ganadas, " summary_losses: " Perdidas" rank_no_code: "Sin Código Nuevo para Clasificar" rank_my_game: "¡Clasifica Mi Juego!" rank_submitting: "Enviando..." rank_submitted: "Enviado para Clasificación" rank_failed: "Fallo al Clasificar" rank_being_ranked: "Juego Siendo Clasificado" # rank_last_submitted: "submitted " # help_simulate: "Help simulate games?" code_being_simulated: "Tu nuevo código está siendo simulado por otros jugadores para clasificación. Esto se refrescará a medida que vengan nuevas partidas." no_ranked_matches_pre: "Sin partidas clasificadas para el " no_ranked_matches_post: " equipo! Juega en contra de algunos competidores y luego vuelve aquí para ver tu juego clasificado." choose_opponent: "Escoge un Oponente" # select_your_language: "Select your language!" tutorial_play: "Juega el Tutorial" tutorial_recommended: "Recomendado si nunca has jugado antes" tutorial_skip: "Saltar Tutorial" tutorial_not_sure: "¿No estás seguro de que sucede?" tutorial_play_first: "Juega el Tutorial primero." simple_ai: "IA Simple" warmup: "Calentamiento" # friends_playing: "Friends Playing" # log_in_for_friends: "Log in to play with your friends!" # social_connect_blurb: "Connect and play against your friends!" # invite_friends_to_battle: "Invite your friends to join you in battle!" # fight: "Fight!" # watch_victory: "Watch your victory" # defeat_the: "Defeat the" # tournament_ends: "Tournament ends" # tournament_ended: "Tournament ended" # tournament_rules: "Tournament Rules" # tournament_blurb: "Write code, collect gold, build armies, crush foes, win prizes, and upgrade your career in our $40,000 Greed tournament! Check out the details" # tournament_blurb_criss_cross: "Win bids, construct paths, outwit opponents, grab gems, and upgrade your career in our Criss-Cross tournament! Check out the details" # tournament_blurb_blog: "on our blog" # rules: "Rules" # winners: "Winners" # user: # stats: "Stats" # singleplayer_title: "Singleplayer Levels" # multiplayer_title: "Multiplayer Levels" # achievements_title: "Achievements" # last_played: "Last Played" # status: "Status" # status_completed: "Completed" # status_unfinished: "Unfinished" # no_singleplayer: "No Singleplayer games played yet." # no_multiplayer: "No Multiplayer games played yet." # no_achievements: "No Achievements earned yet." # favorite_prefix: "Favorite language is " # favorite_postfix: "." # achievements: # last_earned: "Last Earned" # amount_achieved: "Amount" # achievement: "Achievement" # category_contributor: "Contributor" # category_ladder: "Ladder" # category_level: "Level" # category_miscellaneous: "Miscellaneous" # category_levels: "Levels" # category_undefined: "Uncategorized" # current_xp_prefix: "" # current_xp_postfix: " in total" # new_xp_prefix: "" # new_xp_postfix: " earned" # left_xp_prefix: "" # left_xp_infix: " until level " # left_xp_postfix: "" # account: # recently_played: "Recently Played" # no_recent_games: "No games played during the past two weeks." # payments: "Payments" # service_apple: "Apple" # service_web: "Web" # paid_on: "Paid On" # service: "Service" # price: "Price" # gems: "Gems" # status_subscribed: "You're currently subscribed at $9.99 USD/mo. Thanks for your support!" # status_unsubscribed_active: "You're not subscribed and won't be billed, but your account is still active for now." # status_unsubscribed: "Get access to new levels, heroes, items, and bonus gems with a CodeCombat subscription!" loading_error: could_not_load: "Error cargando del servidor" connection_failure: "Fallo de conexión." unauthorized: "Necesitas acceder. ¿Tienes desabilitadas las cookies?" forbidden: "No tienes los permisos." not_found: "No encontrado." not_allowed: "Método no permitido." timeout: "Expiró el tiempo del servidor." conflict: "Conflicto de recurso." bad_input: "Mala entrada." server_error: "Error de servidor." unknown: "Error desconocido." resources: # sessions: "Sessions" your_sessions: "Tus sesiones" level: "Nivel" social_network_apis: "APIs de Redes Sociales" facebook_status: "Estado de Facebook" facebook_friends: "Amigos de Facebook" facebook_friend_sessions: "Sesiones de Amigos de Facebook" gplus_friends: "Amigos de G+" gplus_friend_sessions: "Sesiones de Amigos de G+" leaderboard: "Clasificación" user_schema: "Esquema de Usuario" user_profile: "Perfil de Usuario" patches: "Parches" # patched_model: "Source Document" model: "Modelo" # system: "System" # systems: "Systems" # component: "Component" # components: "Components" # thang: "Thang" # thangs: "Thangs" # level_session: "Your Session" # opponent_session: "Opponent Session" # article: "Article" # user_names: "User Names" # thang_names: "Thang Names" # files: "Files" # top_simulators: "Top Simulators" # source_document: "Source Document" # document: "Document" # sprite_sheet: "Sprite Sheet" # employers: "Employers" # candidates: "Candidates" # candidate_sessions: "Candidate Sessions" # user_remark: "User Remark" # user_remarks: "User Remarks" # versions: "Versions" # items: "Items" # heroes: "Heroes" # wizard: "Wizard" # achievement: "Achievement" # clas: "CLAs" # play_counts: "Play Counts" # feedback: "Feedback" # delta: # added: "Added" # modified: "Modified" # deleted: "Deleted" # moved_index: "Moved Index" # text_diff: "Text Diff" # merge_conflict_with: "MERGE CONFLICT WITH" # no_changes: "No Changes" # guide: # temp: "Temp" multiplayer: multiplayer_title: "Configuración de Multijugador" # We'll be changing this around significantly soon. Until then, it's not important to translate. # multiplayer_toggle: "Enable multiplayer" # multiplayer_toggle_description: "Allow others to join your game." multiplayer_link_description: "Da este enlace a cualquiera para que se te una." multiplayer_hint_label: "Consejo:" multiplayer_hint: " Cliquea el enlace para seleccionar todo, luego presiona ⌘-C o Ctrl-C para copiar el enlace." multiplayer_coming_soon: "¡Más características de multijugador por venir!" # multiplayer_sign_in_leaderboard: "Sign in or create an account and get your solution on the leaderboard." # legal: # page_title: "Legal" # opensource_intro: "CodeCombat is completely open source." # opensource_description_prefix: "Check out " # github_url: "our GitHub" # opensource_description_center: "and help out if you like! CodeCombat is built on dozens of open source projects, and we love them. See " # archmage_wiki_url: "our Archmage wiki" # opensource_description_suffix: "for a list of the software that makes this game possible." # practices_title: "Respectful Best Practices" # practices_description: "These are our promises to you, the player, in slightly less legalese." # privacy_title: "Privacy" # privacy_description: "We will not sell any of your personal information." # security_title: "Security" # security_description: "We strive to keep your personal information safe. As an open source project, our site is freely open to anyone to review and improve our security systems." # email_title: "Email" # email_description_prefix: "We will not inundate you with spam. Through" # email_settings_url: "your email settings" # email_description_suffix: "or through links in the emails we send, you can change your preferences and easily unsubscribe at any time." # cost_title: "Cost" # cost_description: "CodeCombat is free to play in the dungeon campaign, with a $9.99 USD/mo subscription for access to later campaigns and 3500 bonus gems per month. You can cancel with a click, and we offer a 100% money-back guarantee." # copyrights_title: "Copyrights and Licenses" # contributor_title: "Contributor License Agreement" # contributor_description_prefix: "All contributions, both on the site and on our GitHub repository, are subject to our" # cla_url: "CLA" # contributor_description_suffix: "to which you should agree before contributing." # code_title: "Code - MIT" # code_description_prefix: "All code owned by CodeCombat or hosted on codecombat.com, both in the GitHub repository or in the codecombat.com database, is licensed under the" # mit_license_url: "MIT license" # code_description_suffix: "This includes all code in Systems and Components that are made available by CodeCombat for the purpose of creating levels." # art_title: "Art/Music - Creative Commons " # art_description_prefix: "All common content is available under the" # cc_license_url: "Creative Commons Attribution 4.0 International License" # art_description_suffix: "Common content is anything made generally available by CodeCombat for the purpose of creating Levels. This includes:" # art_music: "Music" # art_sound: "Sound" # art_artwork: "Artwork" # art_sprites: "Sprites" # art_other: "Any and all other non-code creative works that are made available when creating Levels." # art_access: "Currently there is no universal, easy system for fetching these assets. In general, fetch them from the URLs as used by the site, contact us for assistance, or help us in extending the site to make these assets more easily accessible." # art_paragraph_1: "For attribution, please name and link to codecombat.com near where the source is used or where appropriate for the medium. For example:" # use_list_1: "If used in a movie or another game, include codecombat.com in the credits." # use_list_2: "If used on a website, include a link near the usage, for example underneath an image, or in a general attributions page where you might also mention other Creative Commons works and open source software being used on the site. Something that's already clearly referencing CodeCombat, such as a blog post mentioning CodeCombat, does not need some separate attribution." # art_paragraph_2: "If the content being used is created not by CodeCombat but instead by a user of codecombat.com, attribute them instead, and follow attribution directions provided in that resource's description if there are any." # rights_title: "Rights Reserved" # rights_desc: "All rights are reserved for Levels themselves. This includes" # rights_scripts: "Scripts" # rights_unit: "Unit configuration" # rights_description: "Description" # rights_writings: "Writings" # rights_media: "Media (sounds, music) and any other creative content made specifically for that Level and not made generally available when creating Levels." # rights_clarification: "To clarify, anything that is made available in the Level Editor for the purpose of making levels is under CC, whereas the content created with the Level Editor or uploaded in the course of creation of Levels is not." # nutshell_title: "In a Nutshell" # nutshell_description: "Any resources we provide in the Level Editor are free to use as you like for creating Levels. But we reserve the right to restrict distribution of the Levels themselves (that are created on codecombat.com) so that they may be charged for in the future, if that's what ends up happening." # canonical: "The English version of this document is the definitive, canonical version. If there are any discrepencies between translations, the English document takes precedence." # ladder_prizes: # title: "Tournament Prizes" # This section was for an old tournament and doesn't need new translations now. # blurb_1: "These prizes will be awarded according to" # blurb_2: "the tournament rules" # blurb_3: "to the top human and ogre players." # blurb_4: "Two teams means double the prizes!" # blurb_5: "(There will be two first place winners, two second-place winners, etc.)" # rank: "Rank" # prizes: "Prizes" # total_value: "Total Value" # in_cash: "in cash" # custom_wizard: "Custom CodeCombat Wizard" # custom_avatar: "Custom CodeCombat avatar" # heap: "for six months of \"Startup\" access" # credits: "credits" # one_month_coupon: "coupon: choose either Rails or HTML" # one_month_discount: "discount, 30% off: choose either Rails or HTML" # license: "license" # oreilly: "ebook of your choice" wizard_settings: title: "Configuración del mago" customize_avatar: "Personaliza tu avatar" active: "Activo" color: "Color" group: "Grupo" clothes: "Ropa" trim: "Recortar" cloud: "Nube" team: "Equipo" spell: "Hechizo" boots: "Botas" hue: "Matiz" saturation: "Saturación" lightness: "Brillo" account_profile: settings: "Configuración" # We are not actively recruiting right now, so there's no need to add new translations for this section. edit_profile: "Editar Perfil" done_editing: "Terminar Edición" profile_for_prefix: "Perfil para " profile_for_suffix: "" featured: "Soportado" not_featured: "No Soportado" looking_for: "Buscando:" last_updated: "Última Actualización:" contact: "Contacto" active: "En busca de entrevistas ahora mismo" inactive: "No busco entrevistas por ahora" complete: "completado" next: "Siguiente" next_city: "¿Ciudad?" next_country: "selecciona tu país" next_name: "¿Nombre?" next_short_description: "escribe una breve descripción." next_long_description: "describe a que posción aspiras." next_skills: "nombra al menos cinco de tus cualidades." next_work: "detalla tu historial laboral." next_education: "realiza un recuento de tus méritos academicos." next_projects: "exhibe un máximo de tres proyectos en los que hayas participado." next_links: "añade cualquier enlace personal o social" next_photo: "añade una foto profesional (opcional)." next_active: "etiquetate como abierto a ofertas, para aparecer en las busquedas." example_blog: "Blog" example_personal_site: "Sitio Personal" links_header: "Enlaces Personale" links_blurb: "Añade enlaces a cualquier otro sitio o perfil que desees destacar, como tu GitHub, LinkedIn, o blog." links_name: "Nombre del enlace" links_name_help: "¿A que estas enlazando?" links_link_blurb: "URL del enlace" basics_header: "Actualizar información básica" basics_active: "Abierto a ofertas" basics_active_help: "¿Quieres ofertas para entrevistarte ahora mismo?" basics_job_title: "Posición Laboral deseada" basics_job_title_help: "¿Qué posición laboral estas buscando?" basics_city: "Ciudad" basics_city_help: "Ciudad en la que deseas trabajar (o en la que vives ahora)." basics_country: "País" basics_country_help: "País en el que deseas trabajar (o en el que vives ahora)." basics_visa: "Estatus laboral en EEUU" basics_visa_help: "¿Te encuentras autorizado para trabajar en los EEUU, o necesitas un patrocinador de visa? (Si vives en Canada o australia, selecciona autorizado.)" basics_looking_for: "Buscando" basics_looking_for_full_time: "Tiempo completo" basics_looking_for_part_time: "Tiempo parcial" basics_looking_for_remote: "A distacia" basics_looking_for_contracting: "Contratación" basics_looking_for_internship: "Pasantía" basics_looking_for_help: "¿Qué tipo de posición estas buscando como desarrollador?" name_header: "Escribe tu nombre" name_anonymous: "Desarrollador anónimo" name_help: "El nombre que los empleadores verán, por ejemplo 'Max Power'." short_description_header: "Descríbete en pocas palabras" short_description_blurb: "Añade un lema, para que un empleador pueda conocerte mejor facilmente." short_description: "Lema" short_description_help: "¿Quién eres, y que estas buscando? 140 caractéres máximo." skills_header: "Cualidades" skills_help: "Etiqueta tus cualidades más relevantes como desarrollador, en orden de competencia." long_description_header: "Describe tu posición laboral deseada" long_description_blurb: "Dile a los empleadores lo genial que eres, y que rol estas buscando." long_description: "Auto Descripción" long_description_help: "Describete a ti mismo para tus potenciales empleadores. Mantenlo corto y ve al grano. Te recomendamos destacar la posición laboral de mayor interes para ti. Un enfoque reduccionista, de buen gusto, es bienvenido; 600 caracteres mmáximo." work_experience: "Experiencia de Trabajo" work_header: "Detalla tu historial laboral" work_years: "Años de Experiencia" work_years_help: "Cuántos años de experiencia profesional (pagos) desarrollando software tienes?" work_blurb: "Realiza una lista con lo que consideres es tu experiencia laboral relevante, comenzando por la más reciente." work_employer: "Empleador" work_employer_help: "Nombre de tu empleador." work_role: "Nombre de la posición laboral" work_role_help: "¿Cuál era tu posición laboral o rol?" work_duration: "Duración" work_duration_help: "¿Cuál fue la duración de esa experiencia?" work_description: "Descripción" work_description_help: "¿Qué actividades realizabas allí? (140 caracteres; opcional)" education: "Educación" education_header: "Realiza un recuento de tus méritos academicos" education_blurb: "Escribe un recuento de tus méritos academicos." education_school: "Escuela" education_school_help: "Nombre de tu escuela." education_degree: "Título" education_degree_help: "¿Cuál fue tu título y área de estudio" education_duration: "Fechas" education_duration_help: "¿Cuándo?" education_description: "Descripción" education_description_help: "Destaca cualquier cosa acerca de esta experiencia educacional. (140 caracteres; opcional)" our_notes: "Nuestras Notas" remarks: "Observaciones" projects: "Proyectos" projects_header: "Añade 3 proyectos" projects_header_2: "Proyectos (Top 3)" projects_blurb: "Destaca tus proyectos para sorprender a los empleadores." project_name: "Nombre del Proyecto" project_name_help: "¿Cómo se llamaba el proyecto?" project_description: "Descripción" project_description_help: "Describe el proyecto brevemente.." project_picture: "Foto" project_picture_help: "Sube una imagen de 230x115px (o mayor) mostrando el proyecto" project_link: "Enlace" project_link_help: "Enlace al proyecto." player_code: "Código de Jugador" employers: # deprecation_warning_title: "Sorry, CodeCombat is not recruiting right now." # deprecation_warning: "We are focusing on beginner levels instead of finding expert developers for the time being." hire_developers_not_credentials: "Contrata desarrolladores, no credenciales." # We are not actively recruiting right now, so there's no need to add new translations for the rest of this section. get_started: "Comenzar" already_screened: "Ya hemos realizado un monitoreo técnico de todos los candidatos" filter_further: ",pero también puedes hacer un filtrado mas específico:" filter_visa: "Visa" filter_visa_yes: "Autorizado para los EEUU" filter_visa_no: "No autorizado" filter_education_top: "Escuela de elite" filter_education_other: "Otro" filter_role_web_developer: "Desarrollador Web" filter_role_software_developer: "Desarrollador de Software" filter_role_mobile_developer: "Desarrollador Móvil" filter_experience: "Experiencia" filter_experience_senior: "Senior" filter_experience_junior: "Junior" filter_experience_recent_grad: "Grado académico reciente" filter_experience_student: "Estudiante Universitario" filter_results: "resultados" start_hiring: "Comenzar a contratar." reasons: "Tres razones por las cuales deberías contratar a traves de nosotros:" everyone_looking: "Todos aquí estan en busqueda de una oportunidad laboral." everyone_looking_blurb: "Olvidate del 20% de respuestas promedio obtenidas via LinkedIn InMail. Todas las personas listadas en este sitio quieren encontrar su próxima posición laboral y responderan a tu solicitud para concretar una introducción." weeding: "Relajate; ya hemos desmalezado por ti." weeding_blurb: "Todo jugador listado ha sido monitoreado en lo que a su habilidad técnica se refiere. También llevamos a cabo monitoreos telefónicos a los candidatos seleccionados y dejamos notas en sus perfiles para ahorrarte tiempo." pass_screen: "Ell@s superaran tu monitoreo técnico." pass_screen_blurb: "Revisa el código de cada jugador antes de ponerte en contacto. Uno de nuestros empleadores se encontro con una proporción 5 veces mayor de nuestros desarrolladores superando su monitoreo técnico al compararlo con contrataciones realizadas en Hacker News." make_hiring_easier: "Has mi contratación mas simple, por favor." what: "Que es CodeCombat?" what_blurb: "CodeCombat es un juego multijugador de programación para navegadores. Los jugadores escriben un código para medirse en batalla contra otros desarrolladores. Nuestros jugadores cuentan con experiencia en los principales lenguajes técnicos." cost: "¿Cuánto cobramos?" cost_blurb: "Cobramos un 15% del primer salario anual y ofrecemos una garantía de devolución del 100% del dinero por 90 días. No cobramos por candidatos que actualmente se encuentren siendo entrevistados de forma activa por tu compañia." candidate_name: "Nombre" candidate_location: "Ubicación" candidate_looking_for: "Buscando" candidate_role: "Rol" candidate_top_skills: "Mejores Habilidades" candidate_years_experience: "Años de Exp" candidate_last_updated: "Última Actualización" candidate_who: "Quién" featured_developers: "Desarrolladores Destacados" other_developers: "Otros Desarrolladores" inactive_developers: "Desarrolladores Inactivos" admin: # av_espionage: "Espionage" # Really not important to translate /admin controls. # av_espionage_placeholder: "Email or username" # av_usersearch: "User Search" # av_usersearch_placeholder: "Email, username, name, whatever" # av_usersearch_search: "Search" av_title: "Vistas de Admin" av_entities_sub_title: "Entidades" av_entities_users_url: "Usuarios" av_entities_active_instances_url: "Instancias Activas" # av_entities_employer_list_url: "Employer List" # av_entities_candidates_list_url: "Candidate List" # av_entities_user_code_problems_list_url: "User Code Problems List" av_other_sub_title: "Otro" av_other_debug_base_url: "Base (para depurar base.jade)" u_title: "Lista de Usuarios" # ucp_title: "User Code Problems" lg_title: "Últimos Juegos" clas: "CLAs"
188854
module.exports = nativeDescription: "español (América Latina)", englishDescription: "Spanish (Latin America)", translation: home: slogan: "Aprende a programar jugando" no_ie: "¡Lo sentimos! CodeCombat no funciona en Internet Explorer 8 o versiones anteriores." # Warning that only shows up in IE8 and older no_mobile: "¡CodeCombat no fue diseñado para dispositivos móviles y quizás no funcione!" # Warning that shows up on mobile devices play: "Jugar" # The big play button that just starts playing a level # try_it: "Try It" # Alternate wording for Play button old_browser: "¡Oh! ¡Oh! Tu navegador es muy antiguo para correr CodeCombat. ¡Lo Sentimos!" # Warning that shows up on really old Firefox/Chrome/Safari old_browser_suffix: "Puedes probar de todas formas, pero probablemente no funcione." # ipad_browser: "Bad news: CodeCombat doesn't run on iPad in the browser. Good news: our native iPad app is awaiting Apple approval." campaign: "Campaña" for_beginners: "Para Principiantes" multiplayer: "Multijugador" # Not currently shown on home page for_developers: "Para Desarrolladores" # Not currently shown on home page. # or_ipad: "Or download for iPad" nav: play: "Jugar" # The top nav bar entry where players choose which levels to play community: "Comunidad" editor: "Editor" blog: "Blog" forum: "Foro" account: "Cuenta" profile: "Perfil" stats: "Stadísticas" code: "Cógigo" admin: "Admin" # Only shows up when you are an admin home: "Inicio" contribute: "Contribuir" legal: "Legal" about: "Sobre" contact: "Contacto" twitter_follow: "Seguir" teachers: "Profesores" modal: close: "Cerrar" okay: "OK" not_found: page_not_found: "Página no encontrada" diplomat_suggestion: title: "¡Ayuda a traducir CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Necesitamos tus habilidades de idioma." pitch_body: "Desarrollamos CodeCombat en inglés, pero ya tenemos jugadores por todo el mundo. Muchos de ellos quieren jugar en español pero no hablan inglés, así que si puedes hablar ambos, por favor considera registrarte pare ser un Diplomático y ayudar a traducir tanto el sitio de CodeCombat como todos los niveles al español." missing_translations: "Hasta que podamos traducir todo al español, verás inglés cuando el español no esté disponible." learn_more: "Aprende más sobre ser un Diplomático" subscribe_as_diplomat: "Suscribete como un Diplomático" play: play_as: "Jugar Como " # Ladder page spectate: "Observar" # Ladder page players: "jugadores" # Hover over a level on /play hours_played: "horas jugadas" # Hover over a level on /play items: "Objetos" # Tooltip on item shop button from /play # unlock: "Unlock" # For purchasing items and heroes # confirm: "Confirm" # owned: "Owned" # For items you own # locked: "Locked" # purchasable: "Purchasable" # For a hero you unlocked but haven't purchased # available: "Available" # skills_granted: "Skills Granted" # Property documentation details heroes: "Héroes" # Tooltip on hero shop button from /play achievements: "Logros" # Tooltip on achievement list button from /play account: "Cuenta" # Tooltip on account button from /play settings: "Configuración" # Tooltip on settings button from /play next: "Próximo" # Go from choose hero to choose inventory before playing a level change_hero: "Cambiar héroe" # Go back from choose inventory to choose hero choose_inventory: "Equipar objetos" # buy_gems: "Buy Gems" # campaign_forest: "Forest Campaign" # campaign_dungeon: "Dungeon Campaign" # subscription_required: "Subscription Required" # free: "Free" # subscribed: "Subscribed" older_campaigns: "Campañas previas" anonymous: "<NAME>" level_difficulty: "Dificultad: " campaign_beginner: "Campaña para principiantes" # awaiting_levels_adventurer_prefix: "We release five levels per week." # awaiting_levels_adventurer: "Sign up as an Adventurer" # awaiting_levels_adventurer_suffix: "to be the first to play new levels." choose_your_level: "Elige tu nivel" # The rest of this section is the old play view at /play-old and isn't very important. adventurer_prefix: "Puedes saltar a cualquier nivel de abajo, o discutir los niveles en " adventurer_forum: "el foro del aventurero" adventurer_suffix: "." campaign_old_beginner: "Campaña anterior de principiante" campaign_old_beginner_description: "... en la que aprendes la hechicería de la programación." campaign_dev: "Niveles aleatorios más difíciles" campaign_dev_description: "... en los que aprendes sobre la interfaz mientras haces algo un poco más difícil." campaign_multiplayer: "Arenas Multijugador" campaign_multiplayer_description: "... en las que programas cara-a-cara contra otros jugadores." campaign_player_created: "Creados-Por-Jugadores" campaign_player_created_description: "... en los que luchas contra la creatividad de tus compañeros <a href=\"/contribute#artisan\">Hechiceros Artesanales</a>." campaign_classic_algorithms: "Algorítmos Clásicos" campaign_classic_algorithms_description: "... en la cual aprendes los algorítmos más populares en las Ciencias de la Computación." login: sign_up: "Crear Cuenta" log_in: "Entrar" logging_in: "Entrando" log_out: "Salir" recover: "recuperar cuenta" # authenticate_gplus: "Authenticate G+" # load_profile: "Load G+ Profile" # load_email: "Load G+ Email" # finishing: "Finishing" signup: create_account_title: "Crear Cuenta para Guardar el Progreso" description: "Es gratis. Solo necesitas un par de cosas y estarás listo para comenzar:" email_announcements: "Recibe noticias por email" coppa: "más de 13 años o fuera de los Estados Unidos" coppa_why: "(¿Por qué?)" creating: "Creando Cuenta..." sign_up: "Registrarse" log_in: "Inicia sesión con tu contraseña" social_signup: "O, puedes conectarte a través de Facebook o G+:" required: "Necesitas entrar a tu cuenta antes de continuar." recover: recover_account_title: "recuperar cuenta" send_password: "<PASSWORD>" recovery_sent: "Correo de recuperación enviado." items: # primary: "Primary" # secondary: "Secondary" armor: "Armadura" accessories: "Accesorios" misc: "Misc" # books: "Books" common: loading: "Cargando..." saving: "Guardando..." sending: "Enviando..." send: "Enviar" cancel: "Cancelar" save: "Guardar" publish: "Publicar" create: "Crear" manual: "Manual" fork: "Bifurcar" play: "Jugar" # When used as an action verb, like "Play next level" retry: "Reintentar" watch: "Seguir" unwatch: "No seguir" submit_patch: "Enviar Parche" general: and: "y" name: "Nombre" date: "Fecha" body: "Cuerpo" version: "Versión" commit_msg: "Enviar mensaje" version_history: "Historial de Versiones" version_history_for: "Historial de Versiones para: " result: "Resultado" results: "Resultados" description: "Descripción" or: "o" subject: "Asunto" email: "Email" password: "<PASSWORD>" message: "Mensaje" code: "Código" ladder: "Escalera" when: "Cuando" opponent: "Oponente" rank: "Posición" score: "Puntuación" win: "Ganada" loss: "Perdida" tie: "Empate" easy: "Fácil" medium: "Medio" hard: "Difícil" player: "<NAME>" # player_level: "Level" # Like player level 5, not like level: Dungeons of Kithgard units: second: "segundo" seconds: "segundos" minute: "minuto" minutes: "minutos" hour: "hora" hours: "horas" day: "día" days: "días" week: "semana" weeks: "semanas" month: "mes" months: "meses" year: "año" years: "años" play_level: done: "Listo" home: "Inicio" # Not used any more, will be removed soon. # level: "Level" # Like "Level: Dungeons of Kithgard" skip: "Omitir" game_menu: "Menu del Juego" guide: "Gu<NAME>" restart: "Reiniciar" goals: "Objetivos" goal: "Objetivo" # running: "Running..." success: "¡Éxito!" incomplete: "Incompleto" timed_out: "Se te acabo el tiempo" failing: "Fallando" action_timeline: "Cronologia de Accion" click_to_select: "Has click en una unidad para seleccionarla." # control_bar_multiplayer: "Multiplayer" # control_bar_join_game: "Join Game" # reload: "Reload" reload_title: "¿Recargar Todo el Código?" reload_really: "¿Estás seguro de que quieres empezar este nivel desde el principio?" reload_confirm: "Recargar Todo" victory_title_prefix: "¡" victory_title_suffix: " Completo!" victory_sign_up: "Registrate para recibir actualizaciones" victory_sign_up_poke: "¿Quieres recibir las ultimas noticias por correo? ¡Crea una cuenta gratuita y te mantendremos informado!" victory_rate_the_level: "Valora el nivel: " # Only in old-style levels. victory_return_to_ladder: "Volver a la escalera" victory_play_continue: "Continuar" # victory_play_skip: "Skip Ahead" victory_play_next_level: "Jugar Próximo Nivel" # victory_play_more_practice: "More Practice" # victory_play_too_easy: "Too Easy" # victory_play_just_right: "Just Right" # victory_play_too_hard: "Too Hard" # victory_saving_progress: "Saving Progress" victory_go_home: "Ir al Inicio" # Only in old-style levels. victory_review: "¡Cuéntanos más!" # Only in old-style levels. victory_hour_of_code_done: "¿Has acabado?" victory_hour_of_code_done_yes: "¡Si, he terminado con mi Hora de Código!" guide_title: "Guía" tome_minion_spells: "Hechizos de tus Secuaces" # Only in old-style levels. tome_read_only_spells: "Hechizos de Sólo Lectura" # Only in old-style levels. tome_other_units: "Otras Unidades" # Only in old-style levels. tome_cast_button_run: "Ejecutar" tome_cast_button_running: "Ejecutando" tome_cast_button_ran: "Ejecutado" tome_submit_button: "Enviar" tome_reload_method: "Recargar código original para este método" # Title text for individual method reload button. tome_select_method: "Seleccionar un Método" tome_see_all_methods: "Ver todos los métodos que puedes editar" # Title text for method list selector (shown when there are multiple programmable methdos). tome_select_a_thang: "Selecciona Alguien para " tome_available_spells: "Hechizos Disponibles" tome_your_skills: "Tus habilidades" # tome_help: "Help" # tome_current_method: "Current Method" # hud_continue_short: "Continue" # code_saved: "Code Saved" skip_tutorial: "Saltar (esc)" keyboard_shortcuts: "Atajos de teclado" loading_ready: "¡Listo!" loading_start: "Iniciar nivel" # problem_alert_title: "Fix Your Code" time_current: "Ahora:" time_total: "Max:" time_goto: "Ir a:" infinite_loop_try_again: "Intentar nuevamente" infinite_loop_reset_level: "Reiniciar Nivel" infinite_loop_comment_out: "Comente Mi Código" tip_toggle_play: "Activa jugar/pausa con Ctrl+P." tip_scrub_shortcut: "Ctrl+[ y Ctrl+] rebobina y avance rápido." tip_guide_exists: "Clique la guía en la parte superior de la página para obtener información útil" tip_open_source: "¡CodeCombat es 100% código abierto!" tip_beta_launch: "CodeCombat lanzó su beta en Octubre del 2013." tip_think_solution: "Piensa en la solución, no en el problema." tip_theory_practice: "En teoría, no hay diferencia entre la teoría y la práctica. Pero en la práctica, si la hay. - <NAME>" tip_error_free: "Hay dos formas de escribir programas libres de errores; sólo la tercera funciona. - <NAME>" tip_debugging_program: "Si depurar es el proceso de remover errores, entonces programar debe ser el proceso de colocarlos. - <NAME>" tip_forums: "¡Dirígite a los foros y dinos lo que piensas!" tip_baby_coders: "En el futuro, incluso los bebés serán Archimagos." tip_morale_improves: "La carga continuará hasta que la moral mejore." tip_all_species: "Creemos en la igualdad de oportunidades para aprender a programar para todas las especies." tip_reticulating: "Espinas reticulantes." tip_harry: "Eres un Hechicero, " tip_great_responsibility: "Con una gran habilidad de hacer código viene una gran responsabilidad de depuración." tip_munchkin: "Si no comes tus verduras, un enano vendrá por ti mientras estés dormido." tip_binary: "Sólo hay 10 tipos de personas en el mundo: aquellas que entienden binario y las que no." tip_commitment_yoda: "Un programador debe tener el compromiso más profundo, la mente más seria. ~ Yoda" tip_no_try: "Haz. O no hagas. No hay intento. - Yoda" tip_patience: "Paciencia debes tener, joven Padawan. - Yoda" tip_documented_bug: "Un error documentad no es un error; es una característica." tip_impossible: "Siempre parece imposible hasta que se hace. - <NAME>" tip_talk_is_cheap: "Hablar es barato. Muestrame el código. - <NAME>" tip_first_language: "La cosa más desastroza que puedes aprender es tu primer lenguaje de programación. - <NAME>" tip_hardware_problem: "P: ¿Cuántos programadores son necesarios para cambiar una bombilla eléctrica? R: Ninguno, es un problema de hardware." tip_hofstadters_law: "Ley de H<NAME>stadter: Siempre toma más tiempo del que esperas, inclso cuando tienes en cuenta la ley de Hofstadter." tip_premature_optimization: "La optimización prematura es la raíz de la maldad. - <NAME>" tip_brute_force: "Cuando tengas duda, usa la fuerza bruta. - <NAME>" # tip_extrapolation: "There are only two kinds of people: those that can extrapolate from incomplete data..." customize_wizard: "Personalizar Hechicero" game_menu: inventory_tab: "Inventario" save_load_tab: "Guardar/Cargar" options_tab: "Opciones" guide_tab: "Guía" multiplayer_tab: "Multijugador" # auth_tab: "Sign Up" inventory_caption: "Equipar tu héroe" choose_hero_caption: "Elegir héroe, lenguaje" save_load_caption: "... y ver historia" options_caption: "Hacer ajustes" guide_caption: "Documentos y consejos" multiplayer_caption: "¡Jugar con amigos!" # auth_caption: "Save your progress." inventory: choose_inventory: "Elegir artículos" # equipped_item: "Equipped" # available_item: "Available" # restricted_title: "Restricted" # should_equip: "(double-click to equip)" # equipped: "(equipped)" # locked: "(locked)" # restricted: "(restricted in this level)" # equip: "Equip" # unequip: "Unequip" # buy_gems: # few_gems: "A few gems" # pile_gems: "Pile of gems" # chest_gems: "Chest of gems" # purchasing: "Purchasing..." # declined: "Your card was declined" # retrying: "Server error, retrying." # prompt_title: "Not Enough Gems" # prompt_body: "Do you want to get more?" # prompt_button: "Enter Shop" # subscribe: # subscribe_title: "Subscribe" # levels: "Unlock 25 levels! With 5 new ones every week!" # heroes: "More powerful heroes!" # gems: "3500 bonus gems every month!" # items: "Over 250 bonus items!" # parents: "For Parents" # parents_title: "Your child will learn to code." # parents_blurb1: "With CodeCombat, your child learns by writing real code. They start by learning simple commands, and progress to more advanced topics." # parents_blurb2: "For $9.99 USD/mo, they get new challenges every week and personal email support from professional programmers." # parents_blurb3: "No Risk: 100% money back guarantee, easy 1-click unsubscribe." # subscribe_button: "Subscribe Now" # stripe_description: "Monthly Subscription" # subscription_required_to_play: "You'll need a subscription to play this level." choose_hero: choose_hero: "Elige tu héroe" programming_language: "Lenguaje de programación" programming_language_description: "¿Qué lenguaje de programación vas a elegir?" # default: "Default" # experimental: "Experimental" python_blurb: "Simple pero poderoso." javascript_blurb: "El lenguaje de la web." coffeescript_blurb: "Mejor JavaScript." clojure_blurb: "Un Lisp moderno." lua_blurb: "Para Juegos." io_blurb: "Simple pero oscuro." status: "Estado" weapons: "Armas" # weapons_warrior: "Swords - Short Range, No Magic" # weapons_ranger: "Crossbows, Guns - Long Range, No Magic" # weapons_wizard: "Wands, Staffs - Long Range, Magic" # attack: "Damage" # Can also translate as "Attack" health: "Salud" speed: "Velocidad" # regeneration: "Regeneration" # range: "Range" # As in "attack or visual range" # blocks: "Blocks" # As in "this shield blocks this much damage" # skills: "Skills" # available_for_purchase: "Available for Purchase" # level_to_unlock: "Level to unlock:" # restricted_to_certain_heroes: "Only certain heroes can play this level." # skill_docs: # writable: "writable" # Hover over "attack" in Your Skills while playing a level to see most of this # read_only: "read-only" # action_name: "name" # action_cooldown: "Takes" # action_specific_cooldown: "Cooldown" # action_damage: "Damage" # action_range: "Range" # action_radius: "Radius" # action_duration: "Duration" # example: "Example" # ex: "ex" # Abbreviation of "example" # current_value: "Current Value" # default_value: "Default value" # parameters: "Parameters" # returns: "Returns" # granted_by: "Granted by" save_load: granularity_saved_games: "Almacenado" granularity_change_history: "Historia" options: general_options: "Opciones Generales" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volumen" music_label: "Música" music_description: "Música encendida/apagada." autorun_label: "Autoejecutar" autorun_description: "Controlar ejecución automática de código." editor_config: "Config. de Editor" editor_config_title: "Configuración del Editor" editor_config_level_language_label: "Lenguaje para este Nivel" editor_config_level_language_description: "Definir el lenguaje de programación para Este nivel." editor_config_default_language_label: "Lenguaje de Programación Predeterminado" editor_config_default_language_description: "Definir el lenguaje de programación que deseas para codificar cuando inicias nuevos niveles." editor_config_keybindings_label: "Atajos de Teclado" editor_config_keybindings_default: "Default (As)" editor_config_keybindings_description: "Añade atajos adicionales conocidos de los editores comunes." editor_config_livecompletion_label: "Autocompletado automático" editor_config_livecompletion_description: "Despliega sugerencias de autocompletado mientras escribes." editor_config_invisibles_label: "Mostrar Invisibles" editor_config_invisibles_description: "Visualiza invisibles tales como espacios o tabulaciones." editor_config_indentguides_label: "Mostrar guías de indentación" editor_config_indentguides_description: "Visualiza líneas verticales para ver mejor la indentación." editor_config_behaviors_label: "Comportamientos Inteligentes" editor_config_behaviors_description: "Autocompleta corchetes, llaves y comillas." about: why_codecombat: "¿Por qué CodeCombat?" why_paragraph_1: "Si quieres aprender a programar, no necesitas lecciones. Necesitas escribir mucho código y disfrutarlo mucho haciéndolo." why_paragraph_2_prefix: "De eso se trata la programación. Será divertido. No casi divertido" why_paragraph_2_italic: "bien un premio" why_paragraph_2_center: "pero algo divertido" why_paragraph_2_italic_caps: "¡NO MAMÁ, TENGO QUE FINALIZAR EL NIVEL!" why_paragraph_2_suffix: "Por tal motivo CodeCombat es un juego multiusuario, no un curso con gamificación. No finalizaremos hasta que terminos--pero en esta ocasión, es una buena cosa." why_paragraph_3: "si te vas a volver adicto a un juego, hazlo a este y conviértete en un de los magos de la era tecnológica." press_title: "Blogeros/Prensa" press_paragraph_1_prefix: "¿Quieres escribirnos? Descarga y usa con confianza todos los recursos incluídos en nuestro" press_paragraph_1_link: "paquete de prensa" press_paragraph_1_suffix: ". Todos los logos e imágenes pueden ser usados sin contactarnos directamente." team: "Equipo" george_title: "CEO" george_blurb: "Negociante" scott_title: "Programador" scott_blurb: "Razonable" nick_title: "Programador" nick_blurb: "<NAME>" michael_title: "Programador" michael_blurb: "Sys Admin" matt_title: "Programador" matt_blurb: "Bicicletero" versions: save_version_title: "Guardar nueva versión" new_major_version: "Nueva Gran Versión" cla_prefix: "Para guardar los cambios, primero debes estar de acuerdo con nuestro" cla_url: "CLA" cla_suffix: "." cla_agree: "ACEPTO" contact: contact_us: "Contacta a CodeCombat" welcome: "¡Qué bueno es escucharte! Usa este formulario para enviarnos un mensaje" contribute_prefix: "¡Si estas interesado en contribuir, chequea nuestra " contribute_page: "página de contribución" contribute_suffix: "!" forum_prefix: "Para cualquier cosa pública, por favor prueba " forum_page: "nuestro foro " forum_suffix: "en su lugar." send: "Enviar Comentario" contact_candidate: "Contacta un Candidato" # Deprecated recruitment_reminder: "Usa este formulario para llegar a los candidadtos que estés interesado en entrevistar. Recuerda que CodeCombat cobra 18% del primer año de salario. Este honorario se debe a la contratación del empleado y reembolsable por 90 days si el empleado no permanece contratado. Tiempo partcial, remoto, y empleados por contrato son gratiso, como así también internos." # Deprecated account_settings: title: "Configuración de la Cuenta" not_logged_in: "Inicia sesión o crea una cuenta para cambiar tu configuración." autosave: "Cambios Guardados Automáticamente" me_tab: "Yo" picture_tab: "Imagen" upload_picture: "Sube una imagen" password_tab: "Contraseña" emails_tab: "Correos" admin: "Admin" new_password: "<PASSWORD>" new_password_verify: "<PASSWORD>" email_subscriptions: "Suscripciones de Email" email_subscriptions_none: "No tienes suscripciones." email_announcements: "Noticias" email_announcements_description: "Recibe correos electrónicos con las últimas noticias y desarrollos de CodeCombat." email_notifications: "Notificaciones" email_notifications_summary: "Controles para tus notificaciones por correo electrónico automáticas y personalizadas relativas a tu actividad en CodeCombat." email_any_notes: "Algunas notificaciones" email_any_notes_description: "Desactiva para detener toda la actividad de correos de notificaciones." email_news: "Noticias" email_recruit_notes: "Oportunidades Laborales" email_recruit_notes_description: "Si juegas realmente bien podríamos contactarte para ofrecerte un (mejor) trabajo." contributor_emails: "Emails Clase Contribuyente" contribute_prefix: "¡Estamos buscando gente que se una a nuestro grupo! Echa un vistazo a la " contribute_page: "página de contribución" contribute_suffix: "para averiguar más." email_toggle: "Activar Todo" error_saving: "Error al Guardar" saved: "Cambios Guardados" password_mismatch: "La contraseña no coincide." password_repeat: "Por favor repita su contraseña." job_profile: "Perfil de Trabajo" # Rest of this section (the job profile stuff and wizard stuff) is deprecated job_profile_approved: "Tu perfil de trabajo ha sido aprobado por CodeCombat. Los empleadores podrán verlo hasta que lo marques como inactivo o permanezca sin cambios por cuatro semanas." job_profile_explanation: "¡Hola! Llena esto, y te contactaremos acerca de encontrar un trabajo como desarrollador de software." sample_profile: "Mira un perfil de ejemplo" view_profile: "Ver tu perfil" wizard_tab: "Hechicero" wizard_color: "Color de Ropas del Hechicero" keyboard_shortcuts: keyboard_shortcuts: "Keyboard Shortcuts" space: "Barra espaciadora" enter: "Enter" escape: "Escape" shift: "Shift" # run_code: "Run current code." run_real_time: "Ejecutar en tiempo real." continue_script: "Continuar hasta finalizado el script." skip_scripts: "Omitir todos los scripts omitibles." toggle_playback: "Aplicar ejecutar/pausar." scrub_playback: "Devolverse y avanzar en el tiempo." single_scrub_playback: "Devolverse y avanzar en el tiempo de a un cuadro." # scrub_execution: "Scrub through current spell execution." toggle_debug: "Mostrar ocultar depuración." # toggle_grid: "Toggle grid overlay." # toggle_pathfinding: "Toggle pathfinding overlay." beautify: "Hacer bello tu código estandarizando formato." maximize_editor: "Maximizar/minimizar editor de código." move_wizard: "Mover tu hechizero en el nivel." community: main_title: "Comunidad CodeCombat" introduction: "Mira las maneras en las que puedes involucrarte adelante y decide qué es más divertido. ¡Queremos trabajar contigo!" level_editor_prefix: "Usar CodeCombat" level_editor_suffix: "para crear y editar niveles. Los han creado niveles para sus clases, amigos, hackatones, estudiantes, familiares. Si crear un nuevo juego luce intimidante puedes ¡comenzar con base en uno nuestro!" # thang_editor_prefix: "We call units within the game 'thangs'. Use the" # thang_editor_suffix: "to modify the CodeCombat source artwork. Allow units to throw projectiles, alter the direction of an animation, change a unit's hit points, or upload your own vector sprites." # article_editor_prefix: "See a mistake in some of our docs? Want to make some instructions for your own creations? Check out the" # article_editor_suffix: "and help CodeCombat players get the most out of their playtime." # find_us: "Find us on these sites" # social_blog: "Read the CodeCombat blog on Sett" # social_discource: "Join the discussion on our Discourse forum" # social_facebook: "Like CodeCombat on Facebook" # social_twitter: "Follow CodeCombat on Twitter" # social_gplus: "Join CodeCombat on Google+" # social_hipchat: "Chat with us in the public CodeCombat HipChat room" # contribute_to_the_project: "Contribute to the project" classes: archmage_title: "Archimago" archmage_title_description: "(Desarrollador)" artisan_title: "Artesano" artisan_title_description: "(Constructor de Niveles)" adventurer_title: "Aventurero" adventurer_title_description: "(Probador de Niveles)" scribe_title: "Escriba" scribe_title_description: "(Editor de Artículos)" diplomat_title: "Diplomado" diplomat_title_description: "(Traductor)" ambassador_title: "Embajador" ambassador_title_description: "(Soporte)" # editor: # main_title: "CodeCombat Editors" # article_title: "Article Editor" # thang_title: "Thang Editor" # level_title: "Level Editor" # achievement_title: "Achievement Editor" # back: "Back" # revert: "Revert" # revert_models: "Revert Models" # pick_a_terrain: "Pick A Terrain" # small: "Small" # grassy: "Grassy" # fork_title: "Fork New Version" # fork_creating: "Creating Fork..." # generate_terrain: "Generate Terrain" # more: "More" # wiki: "Wiki" # live_chat: "Live Chat" # level_some_options: "Some Options?" # level_tab_thangs: "Thangs" # level_tab_scripts: "Scripts" # level_tab_settings: "Settings" # level_tab_components: "Components" # level_tab_systems: "Systems" # level_tab_docs: "Documentation" # level_tab_thangs_title: "Current Thangs" # level_tab_thangs_all: "All" # level_tab_thangs_conditions: "Starting Conditions" # level_tab_thangs_add: "Add Thangs" # delete: "Delete" # duplicate: "Duplicate" # rotate: "Rotate" # level_settings_title: "Settings" # level_component_tab_title: "Current Components" # level_component_btn_new: "Create New Component" # level_systems_tab_title: "Current Systems" # level_systems_btn_new: "Create New System" # level_systems_btn_add: "Add System" # level_components_title: "Back to All Thangs" # level_components_type: "Type" # level_component_edit_title: "Edit Component" # level_component_config_schema: "Config Schema" # level_component_settings: "Settings" # level_system_edit_title: "Edit System" # create_system_title: "Create New System" # new_component_title: "Create New Component" # new_component_field_system: "System" # new_article_title: "Create a New Article" # new_thang_title: "Create a New Thang Type" # new_level_title: "Create a New Level" # new_article_title_login: "Log In to Create a New Article" # new_thang_title_login: "Log In to Create a New Thang Type" # new_level_title_login: "Log In to Create a New Level" # new_achievement_title: "Create a New Achievement" # new_achievement_title_login: "Log In to Create a New Achievement" # article_search_title: "Search Articles Here" # thang_search_title: "Search Thang Types Here" # level_search_title: "Search Levels Here" # achievement_search_title: "Search Achievements" # read_only_warning2: "Note: you can't save any edits here, because you're not logged in." # no_achievements: "No achievements have been added for this level yet." # achievement_query_misc: "Key achievement off of miscellanea" # achievement_query_goals: "Key achievement off of level goals" # level_completion: "Level Completion" # pop_i18n: "Populate I18N" article: edit_btn_preview: "Vista previa" edit_article_title: "Editar Artículo" # contribute: # page_title: "Contributing" # character_classes_title: "Character Classes" # introduction_desc_intro: "We have high hopes for CodeCombat." # introduction_desc_pref: "We want to be where programmers of all stripes come to learn and play together, introduce others to the wonderful world of coding, and reflect the best parts of the community. We can't and don't want to do that alone; what makes projects like GitHub, Stack Overflow and Linux great are the people who use them and build on them. To that end, " # introduction_desc_github_url: "CodeCombat is totally open source" # introduction_desc_suf: ", and we aim to provide as many ways as possible for you to take part and make this project as much yours as ours." # introduction_desc_ending: "We hope you'll join our party!" # introduction_desc_signature: "- <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME>" # alert_account_message_intro: "Hey there!" # alert_account_message: "To subscribe for class emails, you'll need to be logged in first." # archmage_summary: "Interested in working on game graphics, user interface design, database and server organization, multiplayer networking, physics, sound, or game engine performance? Want to help build a game to help other people learn what you are good at? We have a lot to do and if you are an experienced programmer and want to develop for CodeCombat, this class is for you. We would love your help building the best programming game ever." # archmage_introduction: "One of the best parts about building games is they synthesize so many different things. Graphics, sound, real-time networking, social networking, and of course many of the more common aspects of programming, from low-level database management, and server administration to user facing design and interface building. There's a lot to do, and if you're an experienced programmer with a hankering to really dive into the nitty-gritty of CodeCombat, this class might be for you. We would love to have your help building the best programming game ever." # class_attributes: "Class Attributes" # archmage_attribute_1_pref: "Knowledge in " # archmage_attribute_1_suf: ", or a desire to learn. Most of our code is in this language. If you're a fan of Ruby or Python, you'll feel right at home. It's JavaScript, but with a nicer syntax." # archmage_attribute_2: "Some experience in programming and personal initiative. We'll help you get oriented, but we can't spend much time training you." # how_to_join: "How To Join" # join_desc_1: "Anyone can help out! Just check out our " # join_desc_2: "to get started, and check the box below to mark yourself as a brave Archmage and get the latest news by email. Want to chat about what to do or how to get more deeply involved? " # join_desc_3: ", or find us in our " # join_desc_4: "and we'll go from there!" # join_url_email: "Email us" # join_url_hipchat: "public HipChat room" # more_about_archmage: "Learn More About Becoming an Archmage" # archmage_subscribe_desc: "Get emails on new coding opportunities and announcements." # artisan_summary_pref: "Want to design levels and expand CodeCombat's arsenal? People are playing through our content at a pace faster than we can build! Right now, our level editor is barebone, so be wary. Making levels will be a little challenging and buggy. If you have visions of campaigns spanning for-loops to" # artisan_summary_suf: ", then this class is for you." # artisan_introduction_pref: "We must construct additional levels! People be clamoring for more content, and we can only build so many ourselves. Right now your workstation is level one; our level editor is barely usable even by its creators, so be wary. If you have visions of campaigns spanning for-loops to" # artisan_introduction_suf: ", then this class might be for you." # artisan_attribute_1: "Any experience in building content like this would be nice, such as using Blizzard's level editors. But not required!" # artisan_attribute_2: "A hankering to do a whole lot of testing and iteration. To make good levels, you need to take it to others and watch them play it, and be prepared to find a lot of things to fix." # artisan_attribute_3: "For the time being, endurance en par with an Adventurer. Our Level Editor is super preliminary and frustrating to use. You have been warned!" # artisan_join_desc: "Use the Level Editor in these steps, give or take:" # artisan_join_step1: "Read the documentation." # artisan_join_step2: "Create a new level and explore existing levels." # artisan_join_step3: "Find us in our public HipChat room for help." # artisan_join_step4: "Post your levels on the forum for feedback." # more_about_artisan: "Learn More About Becoming an Artisan" # artisan_subscribe_desc: "Get emails on level editor updates and announcements." # adventurer_summary: "Let us be clear about your role: you are the tank. You are going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class is for you." # adventurer_introduction: "Let's be clear about your role: you are the tank. You're going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class might be for you." # adventurer_attribute_1: "A thirst for learning. You want to learn how to code and we want to teach you how to code. You'll probably be doing most of the teaching in this case, though." # adventurer_attribute_2: "Charismatic. Be gentle but articulate about what needs improving, and offer suggestions on how to improve." # adventurer_join_pref: "Either get together with (or recruit!) an Artisan and work with them, or check the box below to receive emails when there are new levels to test. We'll also be posting about levels to review on our networks like" # adventurer_forum_url: "our forum" # adventurer_join_suf: "so if you prefer to be notified those ways, sign up there!" # more_about_adventurer: "Learn More About Becoming an Adventurer" # adventurer_subscribe_desc: "Get emails when there are new levels to test." # scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the " # scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you." # scribe_introduction_pref: "CodeCombat isn't just going to be a bunch of levels. It will also include a resource for knowledge, a wiki of programming concepts that levels can hook into. That way rather than each Artisan having to describe in detail what a comparison operator is, they can simply link their level to the Article describing them that is already written for the player's edification. Something along the lines of what the " # scribe_introduction_url_mozilla: "Mozilla Developer Network" # scribe_introduction_suf: " has built. If your idea of fun is articulating the concepts of programming in Markdown form, then this class might be for you." # scribe_attribute_1: "Skill in words is pretty much all you need. Not only grammar and spelling, but able to convey complicated ideas to others." # contact_us_url: "Contact us" # scribe_join_description: "tell us a little about yourself, your experience with programming and what sort of things you'd like to write about. We'll go from there!" # more_about_scribe: "Learn More About Becoming a Scribe" # scribe_subscribe_desc: "Get emails about article writing announcements." # diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you." # diplomat_introduction_pref: "So, if there's one thing we learned from the " # diplomat_launch_url: "launch in October" # diplomat_introduction_suf: "it's that there is sizeable interest in CodeCombat in other countries! We're building a corps of translators eager to turn one set of words into another set of words to get CodeCombat as accessible across the world as possible. If you like getting sneak peeks at upcoming content and getting these levels to your fellow nationals ASAP, then this class might be for you." # diplomat_attribute_1: "Fluency in English and the language you would like to translate to. When conveying complicated ideas, it's important to have a strong grasp in both!" # diplomat_i18n_page_prefix: "You can start translating our levels by going to our" # diplomat_i18n_page: "translations page" # diplomat_i18n_page_suffix: ", or our interface and website on GitHub." # diplomat_join_pref_github: "Find your language locale file " # diplomat_github_url: "on GitHub" # diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!" # more_about_diplomat: "Learn More About Becoming a Diplomat" # diplomat_subscribe_desc: "Get emails about i18n developments and levels to translate." # ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you." # ambassador_introduction: "This is a community we're building, and you are the connections. We've got Olark chats, emails, and social networks with lots of people to talk with and help get acquainted with the game and learn from. If you want to help people get involved and have fun, and get a good feel of the pulse of CodeCombat and where we're going, then this class might be for you." # ambassador_attribute_1: "Communication skills. Be able to identify the problems players are having and help them solve them. Also, keep the rest of us informed about what players are saying, what they like and don't like and want more of!" # ambassador_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll go from there!" # ambassador_join_note_strong: "Note" # ambassador_join_note_desc: "One of our top priorities is to build multiplayer where players having difficulty solving levels can summon higher level wizards to help them. This will be a great way for ambassadors to do their thing. We'll keep you posted!" # more_about_ambassador: "Learn More About Becoming an Ambassador" # ambassador_subscribe_desc: "Get emails on support updates and multiplayer developments." # changes_auto_save: "Changes are saved automatically when you toggle checkboxes." # diligent_scribes: "Our Diligent Scribes:" # powerful_archmages: "Our Powerful Archmages:" # creative_artisans: "Our Creative Artisans:" # brave_adventurers: "Our Brave Adventurers:" # translating_diplomats: "Our Translating Diplomats:" # helpful_ambassadors: "Our Helpful Ambassadors:" ladder: please_login: "Por favor inicia sesión antes de jugar una partida de escalera." my_matches: "Mis Partidas" simulate: "Simular" simulation_explanation: "¡Simulando tus juegos puedes mejorar tu posición más rápido!" simulate_games: "¡Simular Juegos!" simulate_all: "REINICIAR Y SIMULAR JUEGOS" games_simulated_by: "Juegos simulados por ti:" games_simulated_for: "Juegos simulados para ti:" games_simulated: "Juegos simulados" games_played: "Juegos jugados" ratio: "Proporción" leaderboard: "Posiciones" battle_as: "Combate como " summary_your: "Tus " summary_matches: "Partidas - " summary_wins: " Ganadas, " summary_losses: " Perdidas" rank_no_code: "Sin Código Nuevo para Clasificar" rank_my_game: "¡Clasifica Mi Juego!" rank_submitting: "Enviando..." rank_submitted: "Enviado para Clasificación" rank_failed: "Fallo al Clasificar" rank_being_ranked: "Juego Siendo Clasificado" # rank_last_submitted: "submitted " # help_simulate: "Help simulate games?" code_being_simulated: "Tu nuevo código está siendo simulado por otros jugadores para clasificación. Esto se refrescará a medida que vengan nuevas partidas." no_ranked_matches_pre: "Sin partidas clasificadas para el " no_ranked_matches_post: " equipo! Juega en contra de algunos competidores y luego vuelve aquí para ver tu juego clasificado." choose_opponent: "Escoge un Oponente" # select_your_language: "Select your language!" tutorial_play: "Juega el Tutorial" tutorial_recommended: "Recomendado si nunca has jugado antes" tutorial_skip: "Saltar Tutorial" tutorial_not_sure: "¿No estás seguro de que sucede?" tutorial_play_first: "Juega el Tutorial primero." simple_ai: "IA Simple" warmup: "Calentamiento" # friends_playing: "Friends Playing" # log_in_for_friends: "Log in to play with your friends!" # social_connect_blurb: "Connect and play against your friends!" # invite_friends_to_battle: "Invite your friends to join you in battle!" # fight: "Fight!" # watch_victory: "Watch your victory" # defeat_the: "Defeat the" # tournament_ends: "Tournament ends" # tournament_ended: "Tournament ended" # tournament_rules: "Tournament Rules" # tournament_blurb: "Write code, collect gold, build armies, crush foes, win prizes, and upgrade your career in our $40,000 Greed tournament! Check out the details" # tournament_blurb_criss_cross: "Win bids, construct paths, outwit opponents, grab gems, and upgrade your career in our Criss-Cross tournament! Check out the details" # tournament_blurb_blog: "on our blog" # rules: "Rules" # winners: "Winners" # user: # stats: "Stats" # singleplayer_title: "Singleplayer Levels" # multiplayer_title: "Multiplayer Levels" # achievements_title: "Achievements" # last_played: "Last Played" # status: "Status" # status_completed: "Completed" # status_unfinished: "Unfinished" # no_singleplayer: "No Singleplayer games played yet." # no_multiplayer: "No Multiplayer games played yet." # no_achievements: "No Achievements earned yet." # favorite_prefix: "Favorite language is " # favorite_postfix: "." # achievements: # last_earned: "Last Earned" # amount_achieved: "Amount" # achievement: "Achievement" # category_contributor: "Contributor" # category_ladder: "Ladder" # category_level: "Level" # category_miscellaneous: "Miscellaneous" # category_levels: "Levels" # category_undefined: "Uncategorized" # current_xp_prefix: "" # current_xp_postfix: " in total" # new_xp_prefix: "" # new_xp_postfix: " earned" # left_xp_prefix: "" # left_xp_infix: " until level " # left_xp_postfix: "" # account: # recently_played: "Recently Played" # no_recent_games: "No games played during the past two weeks." # payments: "Payments" # service_apple: "Apple" # service_web: "Web" # paid_on: "Paid On" # service: "Service" # price: "Price" # gems: "Gems" # status_subscribed: "You're currently subscribed at $9.99 USD/mo. Thanks for your support!" # status_unsubscribed_active: "You're not subscribed and won't be billed, but your account is still active for now." # status_unsubscribed: "Get access to new levels, heroes, items, and bonus gems with a CodeCombat subscription!" loading_error: could_not_load: "Error cargando del servidor" connection_failure: "Fallo de conexión." unauthorized: "Necesitas acceder. ¿Tienes desabilitadas las cookies?" forbidden: "No tienes los permisos." not_found: "No encontrado." not_allowed: "Método no permitido." timeout: "Expiró el tiempo del servidor." conflict: "Conflicto de recurso." bad_input: "Mala entrada." server_error: "Error de servidor." unknown: "Error desconocido." resources: # sessions: "Sessions" your_sessions: "Tus sesiones" level: "Nivel" social_network_apis: "APIs de Redes Sociales" facebook_status: "Estado de Facebook" facebook_friends: "Amigos de Facebook" facebook_friend_sessions: "Sesiones de Amigos de Facebook" gplus_friends: "Amigos de G+" gplus_friend_sessions: "Sesiones de Amigos de G+" leaderboard: "Clasificación" user_schema: "Esquema de Usuario" user_profile: "Perfil de Usuario" patches: "Parches" # patched_model: "Source Document" model: "Modelo" # system: "System" # systems: "Systems" # component: "Component" # components: "Components" # thang: "Thang" # thangs: "Thangs" # level_session: "Your Session" # opponent_session: "Opponent Session" # article: "Article" # user_names: "<NAME>" # thang_names: "<NAME> Names" # files: "Files" # top_simulators: "Top Simulators" # source_document: "Source Document" # document: "Document" # sprite_sheet: "Sprite Sheet" # employers: "Employers" # candidates: "Candidates" # candidate_sessions: "Candidate Sessions" # user_remark: "User Remark" # user_remarks: "User Remarks" # versions: "Versions" # items: "Items" # heroes: "Heroes" # wizard: "Wizard" # achievement: "Achievement" # clas: "CLAs" # play_counts: "Play Counts" # feedback: "Feedback" # delta: # added: "Added" # modified: "Modified" # deleted: "Deleted" # moved_index: "Moved Index" # text_diff: "Text Diff" # merge_conflict_with: "MERGE CONFLICT WITH" # no_changes: "No Changes" # guide: # temp: "Temp" multiplayer: multiplayer_title: "Configuración de Multijugador" # We'll be changing this around significantly soon. Until then, it's not important to translate. # multiplayer_toggle: "Enable multiplayer" # multiplayer_toggle_description: "Allow others to join your game." multiplayer_link_description: "Da este enlace a cualquiera para que se te una." multiplayer_hint_label: "Consejo:" multiplayer_hint: " Cliquea el enlace para seleccionar todo, luego presiona ⌘-C o Ctrl-C para copiar el enlace." multiplayer_coming_soon: "¡Más características de multijugador por venir!" # multiplayer_sign_in_leaderboard: "Sign in or create an account and get your solution on the leaderboard." # legal: # page_title: "Legal" # opensource_intro: "CodeCombat is completely open source." # opensource_description_prefix: "Check out " # github_url: "our GitHub" # opensource_description_center: "and help out if you like! CodeCombat is built on dozens of open source projects, and we love them. See " # archmage_wiki_url: "our Archmage wiki" # opensource_description_suffix: "for a list of the software that makes this game possible." # practices_title: "Respectful Best Practices" # practices_description: "These are our promises to you, the player, in slightly less legalese." # privacy_title: "Privacy" # privacy_description: "We will not sell any of your personal information." # security_title: "Security" # security_description: "We strive to keep your personal information safe. As an open source project, our site is freely open to anyone to review and improve our security systems." # email_title: "Email" # email_description_prefix: "We will not inundate you with spam. Through" # email_settings_url: "your email settings" # email_description_suffix: "or through links in the emails we send, you can change your preferences and easily unsubscribe at any time." # cost_title: "Cost" # cost_description: "CodeCombat is free to play in the dungeon campaign, with a $9.99 USD/mo subscription for access to later campaigns and 3500 bonus gems per month. You can cancel with a click, and we offer a 100% money-back guarantee." # copyrights_title: "Copyrights and Licenses" # contributor_title: "Contributor License Agreement" # contributor_description_prefix: "All contributions, both on the site and on our GitHub repository, are subject to our" # cla_url: "CLA" # contributor_description_suffix: "to which you should agree before contributing." # code_title: "Code - MIT" # code_description_prefix: "All code owned by CodeCombat or hosted on codecombat.com, both in the GitHub repository or in the codecombat.com database, is licensed under the" # mit_license_url: "MIT license" # code_description_suffix: "This includes all code in Systems and Components that are made available by CodeCombat for the purpose of creating levels." # art_title: "Art/Music - Creative Commons " # art_description_prefix: "All common content is available under the" # cc_license_url: "Creative Commons Attribution 4.0 International License" # art_description_suffix: "Common content is anything made generally available by CodeCombat for the purpose of creating Levels. This includes:" # art_music: "Music" # art_sound: "Sound" # art_artwork: "Artwork" # art_sprites: "Sprites" # art_other: "Any and all other non-code creative works that are made available when creating Levels." # art_access: "Currently there is no universal, easy system for fetching these assets. In general, fetch them from the URLs as used by the site, contact us for assistance, or help us in extending the site to make these assets more easily accessible." # art_paragraph_1: "For attribution, please name and link to codecombat.com near where the source is used or where appropriate for the medium. For example:" # use_list_1: "If used in a movie or another game, include codecombat.com in the credits." # use_list_2: "If used on a website, include a link near the usage, for example underneath an image, or in a general attributions page where you might also mention other Creative Commons works and open source software being used on the site. Something that's already clearly referencing CodeCombat, such as a blog post mentioning CodeCombat, does not need some separate attribution." # art_paragraph_2: "If the content being used is created not by CodeCombat but instead by a user of codecombat.com, attribute them instead, and follow attribution directions provided in that resource's description if there are any." # rights_title: "Rights Reserved" # rights_desc: "All rights are reserved for Levels themselves. This includes" # rights_scripts: "Scripts" # rights_unit: "Unit configuration" # rights_description: "Description" # rights_writings: "Writings" # rights_media: "Media (sounds, music) and any other creative content made specifically for that Level and not made generally available when creating Levels." # rights_clarification: "To clarify, anything that is made available in the Level Editor for the purpose of making levels is under CC, whereas the content created with the Level Editor or uploaded in the course of creation of Levels is not." # nutshell_title: "In a Nutshell" # nutshell_description: "Any resources we provide in the Level Editor are free to use as you like for creating Levels. But we reserve the right to restrict distribution of the Levels themselves (that are created on codecombat.com) so that they may be charged for in the future, if that's what ends up happening." # canonical: "The English version of this document is the definitive, canonical version. If there are any discrepencies between translations, the English document takes precedence." # ladder_prizes: # title: "Tournament Prizes" # This section was for an old tournament and doesn't need new translations now. # blurb_1: "These prizes will be awarded according to" # blurb_2: "the tournament rules" # blurb_3: "to the top human and ogre players." # blurb_4: "Two teams means double the prizes!" # blurb_5: "(There will be two first place winners, two second-place winners, etc.)" # rank: "Rank" # prizes: "Prizes" # total_value: "Total Value" # in_cash: "in cash" # custom_wizard: "Custom CodeCombat Wizard" # custom_avatar: "Custom CodeCombat avatar" # heap: "for six months of \"Startup\" access" # credits: "credits" # one_month_coupon: "coupon: choose either Rails or HTML" # one_month_discount: "discount, 30% off: choose either Rails or HTML" # license: "license" # oreilly: "ebook of your choice" wizard_settings: title: "Configuración del mago" customize_avatar: "Personaliza tu avatar" active: "Activo" color: "Color" group: "Grupo" clothes: "Ropa" trim: "Recortar" cloud: "Nube" team: "Equipo" spell: "Hechizo" boots: "Botas" hue: "Matiz" saturation: "Saturación" lightness: "Brillo" account_profile: settings: "Configuración" # We are not actively recruiting right now, so there's no need to add new translations for this section. edit_profile: "Editar Perfil" done_editing: "Terminar Edición" profile_for_prefix: "Perfil para " profile_for_suffix: "" featured: "Soportado" not_featured: "No Soportado" looking_for: "Buscando:" last_updated: "Última Actualización:" contact: "Contacto" active: "En busca de entrevistas ahora mismo" inactive: "No busco entrevistas por ahora" complete: "completado" next: "Siguiente" next_city: "¿Ciudad?" next_country: "selecciona tu país" next_name: "¿Nombre?" next_short_description: "escribe una breve descripción." next_long_description: "describe a que posción aspiras." next_skills: "nombra al menos cinco de tus cualidades." next_work: "detalla tu historial laboral." next_education: "realiza un recuento de tus méritos academicos." next_projects: "exhibe un máximo de tres proyectos en los que hayas participado." next_links: "añade cualquier enlace personal o social" next_photo: "añade una foto profesional (opcional)." next_active: "etiquetate como abierto a ofertas, para aparecer en las busquedas." example_blog: "Blog" example_personal_site: "Sitio Personal" links_header: "Enlaces Personale" links_blurb: "Añade enlaces a cualquier otro sitio o perfil que desees destacar, como tu GitHub, LinkedIn, o blog." links_name: "Nombre del enlace" links_name_help: "¿A que estas enlazando?" links_link_blurb: "URL del enlace" basics_header: "Actualizar información básica" basics_active: "Abierto a ofertas" basics_active_help: "¿Quieres ofertas para entrevistarte ahora mismo?" basics_job_title: "Posición Laboral deseada" basics_job_title_help: "¿Qué posición laboral estas buscando?" basics_city: "Ciudad" basics_city_help: "Ciudad en la que deseas trabajar (o en la que vives ahora)." basics_country: "País" basics_country_help: "País en el que deseas trabajar (o en el que vives ahora)." basics_visa: "Estatus laboral en EEUU" basics_visa_help: "¿Te encuentras autorizado para trabajar en los EEUU, o necesitas un patrocinador de visa? (Si vives en Canada o australia, selecciona autorizado.)" basics_looking_for: "Buscando" basics_looking_for_full_time: "Tiempo completo" basics_looking_for_part_time: "Tiempo parcial" basics_looking_for_remote: "A distacia" basics_looking_for_contracting: "Contratación" basics_looking_for_internship: "Pasantía" basics_looking_for_help: "¿Qué tipo de posición estas buscando como desarrollador?" name_header: "Escribe tu nombre" name_anonymous: "<NAME>" name_help: "El nombre que los empleadores verán, por ejemplo '<NAME> Power'." short_description_header: "Descríbete en pocas palabras" short_description_blurb: "Añade un lema, para que un empleador pueda conocerte mejor facilmente." short_description: "Lema" short_description_help: "¿Quién eres, y que estas buscando? 140 caractéres máximo." skills_header: "Cualidades" skills_help: "Etiqueta tus cualidades más relevantes como desarrollador, en orden de competencia." long_description_header: "Describe tu posición laboral deseada" long_description_blurb: "Dile a los empleadores lo genial que eres, y que rol estas buscando." long_description: "Auto Descripción" long_description_help: "Describete a ti mismo para tus potenciales empleadores. Mantenlo corto y ve al grano. Te recomendamos destacar la posición laboral de mayor interes para ti. Un enfoque reduccionista, de buen gusto, es bienvenido; 600 caracteres mmáximo." work_experience: "Experiencia de Trabajo" work_header: "Detalla tu historial laboral" work_years: "Años de Experiencia" work_years_help: "Cuántos años de experiencia profesional (pagos) desarrollando software tienes?" work_blurb: "Realiza una lista con lo que consideres es tu experiencia laboral relevante, comenzando por la más reciente." work_employer: "Empleador" work_employer_help: "Nombre de tu empleador." work_role: "Nombre de la posición laboral" work_role_help: "¿Cuál era tu posición laboral o rol?" work_duration: "Duración" work_duration_help: "¿Cuál fue la duración de esa experiencia?" work_description: "Descripción" work_description_help: "¿Qué actividades realizabas allí? (140 caracteres; opcional)" education: "Educación" education_header: "Realiza un recuento de tus méritos academicos" education_blurb: "Escribe un recuento de tus méritos academicos." education_school: "Escuela" education_school_help: "Nombre de tu escuela." education_degree: "Título" education_degree_help: "¿Cuál fue tu título y área de estudio" education_duration: "Fechas" education_duration_help: "¿Cuándo?" education_description: "Descripción" education_description_help: "Destaca cualquier cosa acerca de esta experiencia educacional. (140 caracteres; opcional)" our_notes: "Nuestras Notas" remarks: "Observaciones" projects: "Proyectos" projects_header: "Añade 3 proyectos" projects_header_2: "Proyectos (Top 3)" projects_blurb: "Destaca tus proyectos para sorprender a los empleadores." project_name: "Nombre del Proyecto" project_name_help: "¿Cómo se llamaba el proyecto?" project_description: "Descripción" project_description_help: "Describe el proyecto brevemente.." project_picture: "Foto" project_picture_help: "Sube una imagen de 230x115px (o mayor) mostrando el proyecto" project_link: "Enlace" project_link_help: "Enlace al proyecto." player_code: "Código de Jugador" employers: # deprecation_warning_title: "Sorry, CodeCombat is not recruiting right now." # deprecation_warning: "We are focusing on beginner levels instead of finding expert developers for the time being." hire_developers_not_credentials: "Contrata desarrolladores, no credenciales." # We are not actively recruiting right now, so there's no need to add new translations for the rest of this section. get_started: "Comenzar" already_screened: "Ya hemos realizado un monitoreo técnico de todos los candidatos" filter_further: ",pero también puedes hacer un filtrado mas específico:" filter_visa: "Visa" filter_visa_yes: "Autorizado para los EEUU" filter_visa_no: "No autorizado" filter_education_top: "Escuela de elite" filter_education_other: "Otro" filter_role_web_developer: "Desarrollador Web" filter_role_software_developer: "Desarrollador de Software" filter_role_mobile_developer: "Desarrollador Móvil" filter_experience: "Experiencia" filter_experience_senior: "Senior" filter_experience_junior: "Junior" filter_experience_recent_grad: "Grado académico reciente" filter_experience_student: "Estudiante Universitario" filter_results: "resultados" start_hiring: "Comenzar a contratar." reasons: "Tres razones por las cuales deberías contratar a traves de nosotros:" everyone_looking: "Todos aquí estan en busqueda de una oportunidad laboral." everyone_looking_blurb: "Olvidate del 20% de respuestas promedio obtenidas via LinkedIn InMail. Todas las personas listadas en este sitio quieren encontrar su próxima posición laboral y responderan a tu solicitud para concretar una introducción." weeding: "Relajate; ya hemos desmalezado por ti." weeding_blurb: "Todo jugador listado ha sido monitoreado en lo que a su habilidad técnica se refiere. También llevamos a cabo monitoreos telefónicos a los candidatos seleccionados y dejamos notas en sus perfiles para ahorrarte tiempo." pass_screen: "Ell@s superaran tu monitoreo técnico." pass_screen_blurb: "Revisa el código de cada jugador antes de ponerte en contacto. Uno de nuestros empleadores se encontro con una proporción 5 veces mayor de nuestros desarrolladores superando su monitoreo técnico al compararlo con contrataciones realizadas en Hacker News." make_hiring_easier: "Has mi contratación mas simple, por favor." what: "Que es CodeCombat?" what_blurb: "CodeCombat es un juego multijugador de programación para navegadores. Los jugadores escriben un código para medirse en batalla contra otros desarrolladores. Nuestros jugadores cuentan con experiencia en los principales lenguajes técnicos." cost: "¿Cuánto cobramos?" cost_blurb: "Cobramos un 15% del primer salario anual y ofrecemos una garantía de devolución del 100% del dinero por 90 días. No cobramos por candidatos que actualmente se encuentren siendo entrevistados de forma activa por tu compañia." candidate_name: "<NAME>" candidate_location: "Ubicación" candidate_looking_for: "Buscando" candidate_role: "Rol" candidate_top_skills: "Mejores Habilidades" candidate_years_experience: "Años de Exp" candidate_last_updated: "Última Actualización" candidate_who: "Quién" featured_developers: "Desarrolladores Destacados" other_developers: "Otros Desarrolladores" inactive_developers: "Desarrolladores Inactivos" admin: # av_espionage: "Espionage" # Really not important to translate /admin controls. # av_espionage_placeholder: "Email or username" # av_usersearch: "User Search" # av_usersearch_placeholder: "Email, username, name, whatever" # av_usersearch_search: "Search" av_title: "Vistas de Admin" av_entities_sub_title: "Entidades" av_entities_users_url: "Usuarios" av_entities_active_instances_url: "Instancias Activas" # av_entities_employer_list_url: "Employer List" # av_entities_candidates_list_url: "Candidate List" # av_entities_user_code_problems_list_url: "User Code Problems List" av_other_sub_title: "Otro" av_other_debug_base_url: "Base (para depurar base.jade)" u_title: "Lista de Usuarios" # ucp_title: "User Code Problems" lg_title: "Últimos Juegos" clas: "CLAs"
true
module.exports = nativeDescription: "español (América Latina)", englishDescription: "Spanish (Latin America)", translation: home: slogan: "Aprende a programar jugando" no_ie: "¡Lo sentimos! CodeCombat no funciona en Internet Explorer 8 o versiones anteriores." # Warning that only shows up in IE8 and older no_mobile: "¡CodeCombat no fue diseñado para dispositivos móviles y quizás no funcione!" # Warning that shows up on mobile devices play: "Jugar" # The big play button that just starts playing a level # try_it: "Try It" # Alternate wording for Play button old_browser: "¡Oh! ¡Oh! Tu navegador es muy antiguo para correr CodeCombat. ¡Lo Sentimos!" # Warning that shows up on really old Firefox/Chrome/Safari old_browser_suffix: "Puedes probar de todas formas, pero probablemente no funcione." # ipad_browser: "Bad news: CodeCombat doesn't run on iPad in the browser. Good news: our native iPad app is awaiting Apple approval." campaign: "Campaña" for_beginners: "Para Principiantes" multiplayer: "Multijugador" # Not currently shown on home page for_developers: "Para Desarrolladores" # Not currently shown on home page. # or_ipad: "Or download for iPad" nav: play: "Jugar" # The top nav bar entry where players choose which levels to play community: "Comunidad" editor: "Editor" blog: "Blog" forum: "Foro" account: "Cuenta" profile: "Perfil" stats: "Stadísticas" code: "Cógigo" admin: "Admin" # Only shows up when you are an admin home: "Inicio" contribute: "Contribuir" legal: "Legal" about: "Sobre" contact: "Contacto" twitter_follow: "Seguir" teachers: "Profesores" modal: close: "Cerrar" okay: "OK" not_found: page_not_found: "Página no encontrada" diplomat_suggestion: title: "¡Ayuda a traducir CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Necesitamos tus habilidades de idioma." pitch_body: "Desarrollamos CodeCombat en inglés, pero ya tenemos jugadores por todo el mundo. Muchos de ellos quieren jugar en español pero no hablan inglés, así que si puedes hablar ambos, por favor considera registrarte pare ser un Diplomático y ayudar a traducir tanto el sitio de CodeCombat como todos los niveles al español." missing_translations: "Hasta que podamos traducir todo al español, verás inglés cuando el español no esté disponible." learn_more: "Aprende más sobre ser un Diplomático" subscribe_as_diplomat: "Suscribete como un Diplomático" play: play_as: "Jugar Como " # Ladder page spectate: "Observar" # Ladder page players: "jugadores" # Hover over a level on /play hours_played: "horas jugadas" # Hover over a level on /play items: "Objetos" # Tooltip on item shop button from /play # unlock: "Unlock" # For purchasing items and heroes # confirm: "Confirm" # owned: "Owned" # For items you own # locked: "Locked" # purchasable: "Purchasable" # For a hero you unlocked but haven't purchased # available: "Available" # skills_granted: "Skills Granted" # Property documentation details heroes: "Héroes" # Tooltip on hero shop button from /play achievements: "Logros" # Tooltip on achievement list button from /play account: "Cuenta" # Tooltip on account button from /play settings: "Configuración" # Tooltip on settings button from /play next: "Próximo" # Go from choose hero to choose inventory before playing a level change_hero: "Cambiar héroe" # Go back from choose inventory to choose hero choose_inventory: "Equipar objetos" # buy_gems: "Buy Gems" # campaign_forest: "Forest Campaign" # campaign_dungeon: "Dungeon Campaign" # subscription_required: "Subscription Required" # free: "Free" # subscribed: "Subscribed" older_campaigns: "Campañas previas" anonymous: "PI:NAME:<NAME>END_PI" level_difficulty: "Dificultad: " campaign_beginner: "Campaña para principiantes" # awaiting_levels_adventurer_prefix: "We release five levels per week." # awaiting_levels_adventurer: "Sign up as an Adventurer" # awaiting_levels_adventurer_suffix: "to be the first to play new levels." choose_your_level: "Elige tu nivel" # The rest of this section is the old play view at /play-old and isn't very important. adventurer_prefix: "Puedes saltar a cualquier nivel de abajo, o discutir los niveles en " adventurer_forum: "el foro del aventurero" adventurer_suffix: "." campaign_old_beginner: "Campaña anterior de principiante" campaign_old_beginner_description: "... en la que aprendes la hechicería de la programación." campaign_dev: "Niveles aleatorios más difíciles" campaign_dev_description: "... en los que aprendes sobre la interfaz mientras haces algo un poco más difícil." campaign_multiplayer: "Arenas Multijugador" campaign_multiplayer_description: "... en las que programas cara-a-cara contra otros jugadores." campaign_player_created: "Creados-Por-Jugadores" campaign_player_created_description: "... en los que luchas contra la creatividad de tus compañeros <a href=\"/contribute#artisan\">Hechiceros Artesanales</a>." campaign_classic_algorithms: "Algorítmos Clásicos" campaign_classic_algorithms_description: "... en la cual aprendes los algorítmos más populares en las Ciencias de la Computación." login: sign_up: "Crear Cuenta" log_in: "Entrar" logging_in: "Entrando" log_out: "Salir" recover: "recuperar cuenta" # authenticate_gplus: "Authenticate G+" # load_profile: "Load G+ Profile" # load_email: "Load G+ Email" # finishing: "Finishing" signup: create_account_title: "Crear Cuenta para Guardar el Progreso" description: "Es gratis. Solo necesitas un par de cosas y estarás listo para comenzar:" email_announcements: "Recibe noticias por email" coppa: "más de 13 años o fuera de los Estados Unidos" coppa_why: "(¿Por qué?)" creating: "Creando Cuenta..." sign_up: "Registrarse" log_in: "Inicia sesión con tu contraseña" social_signup: "O, puedes conectarte a través de Facebook o G+:" required: "Necesitas entrar a tu cuenta antes de continuar." recover: recover_account_title: "recuperar cuenta" send_password: "PI:PASSWORD:<PASSWORD>END_PI" recovery_sent: "Correo de recuperación enviado." items: # primary: "Primary" # secondary: "Secondary" armor: "Armadura" accessories: "Accesorios" misc: "Misc" # books: "Books" common: loading: "Cargando..." saving: "Guardando..." sending: "Enviando..." send: "Enviar" cancel: "Cancelar" save: "Guardar" publish: "Publicar" create: "Crear" manual: "Manual" fork: "Bifurcar" play: "Jugar" # When used as an action verb, like "Play next level" retry: "Reintentar" watch: "Seguir" unwatch: "No seguir" submit_patch: "Enviar Parche" general: and: "y" name: "Nombre" date: "Fecha" body: "Cuerpo" version: "Versión" commit_msg: "Enviar mensaje" version_history: "Historial de Versiones" version_history_for: "Historial de Versiones para: " result: "Resultado" results: "Resultados" description: "Descripción" or: "o" subject: "Asunto" email: "Email" password: "PI:PASSWORD:<PASSWORD>END_PI" message: "Mensaje" code: "Código" ladder: "Escalera" when: "Cuando" opponent: "Oponente" rank: "Posición" score: "Puntuación" win: "Ganada" loss: "Perdida" tie: "Empate" easy: "Fácil" medium: "Medio" hard: "Difícil" player: "PI:NAME:<NAME>END_PI" # player_level: "Level" # Like player level 5, not like level: Dungeons of Kithgard units: second: "segundo" seconds: "segundos" minute: "minuto" minutes: "minutos" hour: "hora" hours: "horas" day: "día" days: "días" week: "semana" weeks: "semanas" month: "mes" months: "meses" year: "año" years: "años" play_level: done: "Listo" home: "Inicio" # Not used any more, will be removed soon. # level: "Level" # Like "Level: Dungeons of Kithgard" skip: "Omitir" game_menu: "Menu del Juego" guide: "GuPI:NAME:<NAME>END_PI" restart: "Reiniciar" goals: "Objetivos" goal: "Objetivo" # running: "Running..." success: "¡Éxito!" incomplete: "Incompleto" timed_out: "Se te acabo el tiempo" failing: "Fallando" action_timeline: "Cronologia de Accion" click_to_select: "Has click en una unidad para seleccionarla." # control_bar_multiplayer: "Multiplayer" # control_bar_join_game: "Join Game" # reload: "Reload" reload_title: "¿Recargar Todo el Código?" reload_really: "¿Estás seguro de que quieres empezar este nivel desde el principio?" reload_confirm: "Recargar Todo" victory_title_prefix: "¡" victory_title_suffix: " Completo!" victory_sign_up: "Registrate para recibir actualizaciones" victory_sign_up_poke: "¿Quieres recibir las ultimas noticias por correo? ¡Crea una cuenta gratuita y te mantendremos informado!" victory_rate_the_level: "Valora el nivel: " # Only in old-style levels. victory_return_to_ladder: "Volver a la escalera" victory_play_continue: "Continuar" # victory_play_skip: "Skip Ahead" victory_play_next_level: "Jugar Próximo Nivel" # victory_play_more_practice: "More Practice" # victory_play_too_easy: "Too Easy" # victory_play_just_right: "Just Right" # victory_play_too_hard: "Too Hard" # victory_saving_progress: "Saving Progress" victory_go_home: "Ir al Inicio" # Only in old-style levels. victory_review: "¡Cuéntanos más!" # Only in old-style levels. victory_hour_of_code_done: "¿Has acabado?" victory_hour_of_code_done_yes: "¡Si, he terminado con mi Hora de Código!" guide_title: "Guía" tome_minion_spells: "Hechizos de tus Secuaces" # Only in old-style levels. tome_read_only_spells: "Hechizos de Sólo Lectura" # Only in old-style levels. tome_other_units: "Otras Unidades" # Only in old-style levels. tome_cast_button_run: "Ejecutar" tome_cast_button_running: "Ejecutando" tome_cast_button_ran: "Ejecutado" tome_submit_button: "Enviar" tome_reload_method: "Recargar código original para este método" # Title text for individual method reload button. tome_select_method: "Seleccionar un Método" tome_see_all_methods: "Ver todos los métodos que puedes editar" # Title text for method list selector (shown when there are multiple programmable methdos). tome_select_a_thang: "Selecciona Alguien para " tome_available_spells: "Hechizos Disponibles" tome_your_skills: "Tus habilidades" # tome_help: "Help" # tome_current_method: "Current Method" # hud_continue_short: "Continue" # code_saved: "Code Saved" skip_tutorial: "Saltar (esc)" keyboard_shortcuts: "Atajos de teclado" loading_ready: "¡Listo!" loading_start: "Iniciar nivel" # problem_alert_title: "Fix Your Code" time_current: "Ahora:" time_total: "Max:" time_goto: "Ir a:" infinite_loop_try_again: "Intentar nuevamente" infinite_loop_reset_level: "Reiniciar Nivel" infinite_loop_comment_out: "Comente Mi Código" tip_toggle_play: "Activa jugar/pausa con Ctrl+P." tip_scrub_shortcut: "Ctrl+[ y Ctrl+] rebobina y avance rápido." tip_guide_exists: "Clique la guía en la parte superior de la página para obtener información útil" tip_open_source: "¡CodeCombat es 100% código abierto!" tip_beta_launch: "CodeCombat lanzó su beta en Octubre del 2013." tip_think_solution: "Piensa en la solución, no en el problema." tip_theory_practice: "En teoría, no hay diferencia entre la teoría y la práctica. Pero en la práctica, si la hay. - PI:NAME:<NAME>END_PI" tip_error_free: "Hay dos formas de escribir programas libres de errores; sólo la tercera funciona. - PI:NAME:<NAME>END_PI" tip_debugging_program: "Si depurar es el proceso de remover errores, entonces programar debe ser el proceso de colocarlos. - PI:NAME:<NAME>END_PI" tip_forums: "¡Dirígite a los foros y dinos lo que piensas!" tip_baby_coders: "En el futuro, incluso los bebés serán Archimagos." tip_morale_improves: "La carga continuará hasta que la moral mejore." tip_all_species: "Creemos en la igualdad de oportunidades para aprender a programar para todas las especies." tip_reticulating: "Espinas reticulantes." tip_harry: "Eres un Hechicero, " tip_great_responsibility: "Con una gran habilidad de hacer código viene una gran responsabilidad de depuración." tip_munchkin: "Si no comes tus verduras, un enano vendrá por ti mientras estés dormido." tip_binary: "Sólo hay 10 tipos de personas en el mundo: aquellas que entienden binario y las que no." tip_commitment_yoda: "Un programador debe tener el compromiso más profundo, la mente más seria. ~ Yoda" tip_no_try: "Haz. O no hagas. No hay intento. - Yoda" tip_patience: "Paciencia debes tener, joven Padawan. - Yoda" tip_documented_bug: "Un error documentad no es un error; es una característica." tip_impossible: "Siempre parece imposible hasta que se hace. - PI:NAME:<NAME>END_PI" tip_talk_is_cheap: "Hablar es barato. Muestrame el código. - PI:NAME:<NAME>END_PI" tip_first_language: "La cosa más desastroza que puedes aprender es tu primer lenguaje de programación. - PI:NAME:<NAME>END_PI" tip_hardware_problem: "P: ¿Cuántos programadores son necesarios para cambiar una bombilla eléctrica? R: Ninguno, es un problema de hardware." tip_hofstadters_law: "Ley de HPI:NAME:<NAME>END_PIstadter: Siempre toma más tiempo del que esperas, inclso cuando tienes en cuenta la ley de Hofstadter." tip_premature_optimization: "La optimización prematura es la raíz de la maldad. - PI:NAME:<NAME>END_PI" tip_brute_force: "Cuando tengas duda, usa la fuerza bruta. - PI:NAME:<NAME>END_PI" # tip_extrapolation: "There are only two kinds of people: those that can extrapolate from incomplete data..." customize_wizard: "Personalizar Hechicero" game_menu: inventory_tab: "Inventario" save_load_tab: "Guardar/Cargar" options_tab: "Opciones" guide_tab: "Guía" multiplayer_tab: "Multijugador" # auth_tab: "Sign Up" inventory_caption: "Equipar tu héroe" choose_hero_caption: "Elegir héroe, lenguaje" save_load_caption: "... y ver historia" options_caption: "Hacer ajustes" guide_caption: "Documentos y consejos" multiplayer_caption: "¡Jugar con amigos!" # auth_caption: "Save your progress." inventory: choose_inventory: "Elegir artículos" # equipped_item: "Equipped" # available_item: "Available" # restricted_title: "Restricted" # should_equip: "(double-click to equip)" # equipped: "(equipped)" # locked: "(locked)" # restricted: "(restricted in this level)" # equip: "Equip" # unequip: "Unequip" # buy_gems: # few_gems: "A few gems" # pile_gems: "Pile of gems" # chest_gems: "Chest of gems" # purchasing: "Purchasing..." # declined: "Your card was declined" # retrying: "Server error, retrying." # prompt_title: "Not Enough Gems" # prompt_body: "Do you want to get more?" # prompt_button: "Enter Shop" # subscribe: # subscribe_title: "Subscribe" # levels: "Unlock 25 levels! With 5 new ones every week!" # heroes: "More powerful heroes!" # gems: "3500 bonus gems every month!" # items: "Over 250 bonus items!" # parents: "For Parents" # parents_title: "Your child will learn to code." # parents_blurb1: "With CodeCombat, your child learns by writing real code. They start by learning simple commands, and progress to more advanced topics." # parents_blurb2: "For $9.99 USD/mo, they get new challenges every week and personal email support from professional programmers." # parents_blurb3: "No Risk: 100% money back guarantee, easy 1-click unsubscribe." # subscribe_button: "Subscribe Now" # stripe_description: "Monthly Subscription" # subscription_required_to_play: "You'll need a subscription to play this level." choose_hero: choose_hero: "Elige tu héroe" programming_language: "Lenguaje de programación" programming_language_description: "¿Qué lenguaje de programación vas a elegir?" # default: "Default" # experimental: "Experimental" python_blurb: "Simple pero poderoso." javascript_blurb: "El lenguaje de la web." coffeescript_blurb: "Mejor JavaScript." clojure_blurb: "Un Lisp moderno." lua_blurb: "Para Juegos." io_blurb: "Simple pero oscuro." status: "Estado" weapons: "Armas" # weapons_warrior: "Swords - Short Range, No Magic" # weapons_ranger: "Crossbows, Guns - Long Range, No Magic" # weapons_wizard: "Wands, Staffs - Long Range, Magic" # attack: "Damage" # Can also translate as "Attack" health: "Salud" speed: "Velocidad" # regeneration: "Regeneration" # range: "Range" # As in "attack or visual range" # blocks: "Blocks" # As in "this shield blocks this much damage" # skills: "Skills" # available_for_purchase: "Available for Purchase" # level_to_unlock: "Level to unlock:" # restricted_to_certain_heroes: "Only certain heroes can play this level." # skill_docs: # writable: "writable" # Hover over "attack" in Your Skills while playing a level to see most of this # read_only: "read-only" # action_name: "name" # action_cooldown: "Takes" # action_specific_cooldown: "Cooldown" # action_damage: "Damage" # action_range: "Range" # action_radius: "Radius" # action_duration: "Duration" # example: "Example" # ex: "ex" # Abbreviation of "example" # current_value: "Current Value" # default_value: "Default value" # parameters: "Parameters" # returns: "Returns" # granted_by: "Granted by" save_load: granularity_saved_games: "Almacenado" granularity_change_history: "Historia" options: general_options: "Opciones Generales" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volumen" music_label: "Música" music_description: "Música encendida/apagada." autorun_label: "Autoejecutar" autorun_description: "Controlar ejecución automática de código." editor_config: "Config. de Editor" editor_config_title: "Configuración del Editor" editor_config_level_language_label: "Lenguaje para este Nivel" editor_config_level_language_description: "Definir el lenguaje de programación para Este nivel." editor_config_default_language_label: "Lenguaje de Programación Predeterminado" editor_config_default_language_description: "Definir el lenguaje de programación que deseas para codificar cuando inicias nuevos niveles." editor_config_keybindings_label: "Atajos de Teclado" editor_config_keybindings_default: "Default (As)" editor_config_keybindings_description: "Añade atajos adicionales conocidos de los editores comunes." editor_config_livecompletion_label: "Autocompletado automático" editor_config_livecompletion_description: "Despliega sugerencias de autocompletado mientras escribes." editor_config_invisibles_label: "Mostrar Invisibles" editor_config_invisibles_description: "Visualiza invisibles tales como espacios o tabulaciones." editor_config_indentguides_label: "Mostrar guías de indentación" editor_config_indentguides_description: "Visualiza líneas verticales para ver mejor la indentación." editor_config_behaviors_label: "Comportamientos Inteligentes" editor_config_behaviors_description: "Autocompleta corchetes, llaves y comillas." about: why_codecombat: "¿Por qué CodeCombat?" why_paragraph_1: "Si quieres aprender a programar, no necesitas lecciones. Necesitas escribir mucho código y disfrutarlo mucho haciéndolo." why_paragraph_2_prefix: "De eso se trata la programación. Será divertido. No casi divertido" why_paragraph_2_italic: "bien un premio" why_paragraph_2_center: "pero algo divertido" why_paragraph_2_italic_caps: "¡NO MAMÁ, TENGO QUE FINALIZAR EL NIVEL!" why_paragraph_2_suffix: "Por tal motivo CodeCombat es un juego multiusuario, no un curso con gamificación. No finalizaremos hasta que terminos--pero en esta ocasión, es una buena cosa." why_paragraph_3: "si te vas a volver adicto a un juego, hazlo a este y conviértete en un de los magos de la era tecnológica." press_title: "Blogeros/Prensa" press_paragraph_1_prefix: "¿Quieres escribirnos? Descarga y usa con confianza todos los recursos incluídos en nuestro" press_paragraph_1_link: "paquete de prensa" press_paragraph_1_suffix: ". Todos los logos e imágenes pueden ser usados sin contactarnos directamente." team: "Equipo" george_title: "CEO" george_blurb: "Negociante" scott_title: "Programador" scott_blurb: "Razonable" nick_title: "Programador" nick_blurb: "PI:NAME:<NAME>END_PI" michael_title: "Programador" michael_blurb: "Sys Admin" matt_title: "Programador" matt_blurb: "Bicicletero" versions: save_version_title: "Guardar nueva versión" new_major_version: "Nueva Gran Versión" cla_prefix: "Para guardar los cambios, primero debes estar de acuerdo con nuestro" cla_url: "CLA" cla_suffix: "." cla_agree: "ACEPTO" contact: contact_us: "Contacta a CodeCombat" welcome: "¡Qué bueno es escucharte! Usa este formulario para enviarnos un mensaje" contribute_prefix: "¡Si estas interesado en contribuir, chequea nuestra " contribute_page: "página de contribución" contribute_suffix: "!" forum_prefix: "Para cualquier cosa pública, por favor prueba " forum_page: "nuestro foro " forum_suffix: "en su lugar." send: "Enviar Comentario" contact_candidate: "Contacta un Candidato" # Deprecated recruitment_reminder: "Usa este formulario para llegar a los candidadtos que estés interesado en entrevistar. Recuerda que CodeCombat cobra 18% del primer año de salario. Este honorario se debe a la contratación del empleado y reembolsable por 90 days si el empleado no permanece contratado. Tiempo partcial, remoto, y empleados por contrato son gratiso, como así también internos." # Deprecated account_settings: title: "Configuración de la Cuenta" not_logged_in: "Inicia sesión o crea una cuenta para cambiar tu configuración." autosave: "Cambios Guardados Automáticamente" me_tab: "Yo" picture_tab: "Imagen" upload_picture: "Sube una imagen" password_tab: "Contraseña" emails_tab: "Correos" admin: "Admin" new_password: "PI:PASSWORD:<PASSWORD>END_PI" new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI" email_subscriptions: "Suscripciones de Email" email_subscriptions_none: "No tienes suscripciones." email_announcements: "Noticias" email_announcements_description: "Recibe correos electrónicos con las últimas noticias y desarrollos de CodeCombat." email_notifications: "Notificaciones" email_notifications_summary: "Controles para tus notificaciones por correo electrónico automáticas y personalizadas relativas a tu actividad en CodeCombat." email_any_notes: "Algunas notificaciones" email_any_notes_description: "Desactiva para detener toda la actividad de correos de notificaciones." email_news: "Noticias" email_recruit_notes: "Oportunidades Laborales" email_recruit_notes_description: "Si juegas realmente bien podríamos contactarte para ofrecerte un (mejor) trabajo." contributor_emails: "Emails Clase Contribuyente" contribute_prefix: "¡Estamos buscando gente que se una a nuestro grupo! Echa un vistazo a la " contribute_page: "página de contribución" contribute_suffix: "para averiguar más." email_toggle: "Activar Todo" error_saving: "Error al Guardar" saved: "Cambios Guardados" password_mismatch: "La contraseña no coincide." password_repeat: "Por favor repita su contraseña." job_profile: "Perfil de Trabajo" # Rest of this section (the job profile stuff and wizard stuff) is deprecated job_profile_approved: "Tu perfil de trabajo ha sido aprobado por CodeCombat. Los empleadores podrán verlo hasta que lo marques como inactivo o permanezca sin cambios por cuatro semanas." job_profile_explanation: "¡Hola! Llena esto, y te contactaremos acerca de encontrar un trabajo como desarrollador de software." sample_profile: "Mira un perfil de ejemplo" view_profile: "Ver tu perfil" wizard_tab: "Hechicero" wizard_color: "Color de Ropas del Hechicero" keyboard_shortcuts: keyboard_shortcuts: "Keyboard Shortcuts" space: "Barra espaciadora" enter: "Enter" escape: "Escape" shift: "Shift" # run_code: "Run current code." run_real_time: "Ejecutar en tiempo real." continue_script: "Continuar hasta finalizado el script." skip_scripts: "Omitir todos los scripts omitibles." toggle_playback: "Aplicar ejecutar/pausar." scrub_playback: "Devolverse y avanzar en el tiempo." single_scrub_playback: "Devolverse y avanzar en el tiempo de a un cuadro." # scrub_execution: "Scrub through current spell execution." toggle_debug: "Mostrar ocultar depuración." # toggle_grid: "Toggle grid overlay." # toggle_pathfinding: "Toggle pathfinding overlay." beautify: "Hacer bello tu código estandarizando formato." maximize_editor: "Maximizar/minimizar editor de código." move_wizard: "Mover tu hechizero en el nivel." community: main_title: "Comunidad CodeCombat" introduction: "Mira las maneras en las que puedes involucrarte adelante y decide qué es más divertido. ¡Queremos trabajar contigo!" level_editor_prefix: "Usar CodeCombat" level_editor_suffix: "para crear y editar niveles. Los han creado niveles para sus clases, amigos, hackatones, estudiantes, familiares. Si crear un nuevo juego luce intimidante puedes ¡comenzar con base en uno nuestro!" # thang_editor_prefix: "We call units within the game 'thangs'. Use the" # thang_editor_suffix: "to modify the CodeCombat source artwork. Allow units to throw projectiles, alter the direction of an animation, change a unit's hit points, or upload your own vector sprites." # article_editor_prefix: "See a mistake in some of our docs? Want to make some instructions for your own creations? Check out the" # article_editor_suffix: "and help CodeCombat players get the most out of their playtime." # find_us: "Find us on these sites" # social_blog: "Read the CodeCombat blog on Sett" # social_discource: "Join the discussion on our Discourse forum" # social_facebook: "Like CodeCombat on Facebook" # social_twitter: "Follow CodeCombat on Twitter" # social_gplus: "Join CodeCombat on Google+" # social_hipchat: "Chat with us in the public CodeCombat HipChat room" # contribute_to_the_project: "Contribute to the project" classes: archmage_title: "Archimago" archmage_title_description: "(Desarrollador)" artisan_title: "Artesano" artisan_title_description: "(Constructor de Niveles)" adventurer_title: "Aventurero" adventurer_title_description: "(Probador de Niveles)" scribe_title: "Escriba" scribe_title_description: "(Editor de Artículos)" diplomat_title: "Diplomado" diplomat_title_description: "(Traductor)" ambassador_title: "Embajador" ambassador_title_description: "(Soporte)" # editor: # main_title: "CodeCombat Editors" # article_title: "Article Editor" # thang_title: "Thang Editor" # level_title: "Level Editor" # achievement_title: "Achievement Editor" # back: "Back" # revert: "Revert" # revert_models: "Revert Models" # pick_a_terrain: "Pick A Terrain" # small: "Small" # grassy: "Grassy" # fork_title: "Fork New Version" # fork_creating: "Creating Fork..." # generate_terrain: "Generate Terrain" # more: "More" # wiki: "Wiki" # live_chat: "Live Chat" # level_some_options: "Some Options?" # level_tab_thangs: "Thangs" # level_tab_scripts: "Scripts" # level_tab_settings: "Settings" # level_tab_components: "Components" # level_tab_systems: "Systems" # level_tab_docs: "Documentation" # level_tab_thangs_title: "Current Thangs" # level_tab_thangs_all: "All" # level_tab_thangs_conditions: "Starting Conditions" # level_tab_thangs_add: "Add Thangs" # delete: "Delete" # duplicate: "Duplicate" # rotate: "Rotate" # level_settings_title: "Settings" # level_component_tab_title: "Current Components" # level_component_btn_new: "Create New Component" # level_systems_tab_title: "Current Systems" # level_systems_btn_new: "Create New System" # level_systems_btn_add: "Add System" # level_components_title: "Back to All Thangs" # level_components_type: "Type" # level_component_edit_title: "Edit Component" # level_component_config_schema: "Config Schema" # level_component_settings: "Settings" # level_system_edit_title: "Edit System" # create_system_title: "Create New System" # new_component_title: "Create New Component" # new_component_field_system: "System" # new_article_title: "Create a New Article" # new_thang_title: "Create a New Thang Type" # new_level_title: "Create a New Level" # new_article_title_login: "Log In to Create a New Article" # new_thang_title_login: "Log In to Create a New Thang Type" # new_level_title_login: "Log In to Create a New Level" # new_achievement_title: "Create a New Achievement" # new_achievement_title_login: "Log In to Create a New Achievement" # article_search_title: "Search Articles Here" # thang_search_title: "Search Thang Types Here" # level_search_title: "Search Levels Here" # achievement_search_title: "Search Achievements" # read_only_warning2: "Note: you can't save any edits here, because you're not logged in." # no_achievements: "No achievements have been added for this level yet." # achievement_query_misc: "Key achievement off of miscellanea" # achievement_query_goals: "Key achievement off of level goals" # level_completion: "Level Completion" # pop_i18n: "Populate I18N" article: edit_btn_preview: "Vista previa" edit_article_title: "Editar Artículo" # contribute: # page_title: "Contributing" # character_classes_title: "Character Classes" # introduction_desc_intro: "We have high hopes for CodeCombat." # introduction_desc_pref: "We want to be where programmers of all stripes come to learn and play together, introduce others to the wonderful world of coding, and reflect the best parts of the community. We can't and don't want to do that alone; what makes projects like GitHub, Stack Overflow and Linux great are the people who use them and build on them. To that end, " # introduction_desc_github_url: "CodeCombat is totally open source" # introduction_desc_suf: ", and we aim to provide as many ways as possible for you to take part and make this project as much yours as ours." # introduction_desc_ending: "We hope you'll join our party!" # introduction_desc_signature: "- PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI" # alert_account_message_intro: "Hey there!" # alert_account_message: "To subscribe for class emails, you'll need to be logged in first." # archmage_summary: "Interested in working on game graphics, user interface design, database and server organization, multiplayer networking, physics, sound, or game engine performance? Want to help build a game to help other people learn what you are good at? We have a lot to do and if you are an experienced programmer and want to develop for CodeCombat, this class is for you. We would love your help building the best programming game ever." # archmage_introduction: "One of the best parts about building games is they synthesize so many different things. Graphics, sound, real-time networking, social networking, and of course many of the more common aspects of programming, from low-level database management, and server administration to user facing design and interface building. There's a lot to do, and if you're an experienced programmer with a hankering to really dive into the nitty-gritty of CodeCombat, this class might be for you. We would love to have your help building the best programming game ever." # class_attributes: "Class Attributes" # archmage_attribute_1_pref: "Knowledge in " # archmage_attribute_1_suf: ", or a desire to learn. Most of our code is in this language. If you're a fan of Ruby or Python, you'll feel right at home. It's JavaScript, but with a nicer syntax." # archmage_attribute_2: "Some experience in programming and personal initiative. We'll help you get oriented, but we can't spend much time training you." # how_to_join: "How To Join" # join_desc_1: "Anyone can help out! Just check out our " # join_desc_2: "to get started, and check the box below to mark yourself as a brave Archmage and get the latest news by email. Want to chat about what to do or how to get more deeply involved? " # join_desc_3: ", or find us in our " # join_desc_4: "and we'll go from there!" # join_url_email: "Email us" # join_url_hipchat: "public HipChat room" # more_about_archmage: "Learn More About Becoming an Archmage" # archmage_subscribe_desc: "Get emails on new coding opportunities and announcements." # artisan_summary_pref: "Want to design levels and expand CodeCombat's arsenal? People are playing through our content at a pace faster than we can build! Right now, our level editor is barebone, so be wary. Making levels will be a little challenging and buggy. If you have visions of campaigns spanning for-loops to" # artisan_summary_suf: ", then this class is for you." # artisan_introduction_pref: "We must construct additional levels! People be clamoring for more content, and we can only build so many ourselves. Right now your workstation is level one; our level editor is barely usable even by its creators, so be wary. If you have visions of campaigns spanning for-loops to" # artisan_introduction_suf: ", then this class might be for you." # artisan_attribute_1: "Any experience in building content like this would be nice, such as using Blizzard's level editors. But not required!" # artisan_attribute_2: "A hankering to do a whole lot of testing and iteration. To make good levels, you need to take it to others and watch them play it, and be prepared to find a lot of things to fix." # artisan_attribute_3: "For the time being, endurance en par with an Adventurer. Our Level Editor is super preliminary and frustrating to use. You have been warned!" # artisan_join_desc: "Use the Level Editor in these steps, give or take:" # artisan_join_step1: "Read the documentation." # artisan_join_step2: "Create a new level and explore existing levels." # artisan_join_step3: "Find us in our public HipChat room for help." # artisan_join_step4: "Post your levels on the forum for feedback." # more_about_artisan: "Learn More About Becoming an Artisan" # artisan_subscribe_desc: "Get emails on level editor updates and announcements." # adventurer_summary: "Let us be clear about your role: you are the tank. You are going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class is for you." # adventurer_introduction: "Let's be clear about your role: you are the tank. You're going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class might be for you." # adventurer_attribute_1: "A thirst for learning. You want to learn how to code and we want to teach you how to code. You'll probably be doing most of the teaching in this case, though." # adventurer_attribute_2: "Charismatic. Be gentle but articulate about what needs improving, and offer suggestions on how to improve." # adventurer_join_pref: "Either get together with (or recruit!) an Artisan and work with them, or check the box below to receive emails when there are new levels to test. We'll also be posting about levels to review on our networks like" # adventurer_forum_url: "our forum" # adventurer_join_suf: "so if you prefer to be notified those ways, sign up there!" # more_about_adventurer: "Learn More About Becoming an Adventurer" # adventurer_subscribe_desc: "Get emails when there are new levels to test." # scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the " # scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you." # scribe_introduction_pref: "CodeCombat isn't just going to be a bunch of levels. It will also include a resource for knowledge, a wiki of programming concepts that levels can hook into. That way rather than each Artisan having to describe in detail what a comparison operator is, they can simply link their level to the Article describing them that is already written for the player's edification. Something along the lines of what the " # scribe_introduction_url_mozilla: "Mozilla Developer Network" # scribe_introduction_suf: " has built. If your idea of fun is articulating the concepts of programming in Markdown form, then this class might be for you." # scribe_attribute_1: "Skill in words is pretty much all you need. Not only grammar and spelling, but able to convey complicated ideas to others." # contact_us_url: "Contact us" # scribe_join_description: "tell us a little about yourself, your experience with programming and what sort of things you'd like to write about. We'll go from there!" # more_about_scribe: "Learn More About Becoming a Scribe" # scribe_subscribe_desc: "Get emails about article writing announcements." # diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you." # diplomat_introduction_pref: "So, if there's one thing we learned from the " # diplomat_launch_url: "launch in October" # diplomat_introduction_suf: "it's that there is sizeable interest in CodeCombat in other countries! We're building a corps of translators eager to turn one set of words into another set of words to get CodeCombat as accessible across the world as possible. If you like getting sneak peeks at upcoming content and getting these levels to your fellow nationals ASAP, then this class might be for you." # diplomat_attribute_1: "Fluency in English and the language you would like to translate to. When conveying complicated ideas, it's important to have a strong grasp in both!" # diplomat_i18n_page_prefix: "You can start translating our levels by going to our" # diplomat_i18n_page: "translations page" # diplomat_i18n_page_suffix: ", or our interface and website on GitHub." # diplomat_join_pref_github: "Find your language locale file " # diplomat_github_url: "on GitHub" # diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!" # more_about_diplomat: "Learn More About Becoming a Diplomat" # diplomat_subscribe_desc: "Get emails about i18n developments and levels to translate." # ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you." # ambassador_introduction: "This is a community we're building, and you are the connections. We've got Olark chats, emails, and social networks with lots of people to talk with and help get acquainted with the game and learn from. If you want to help people get involved and have fun, and get a good feel of the pulse of CodeCombat and where we're going, then this class might be for you." # ambassador_attribute_1: "Communication skills. Be able to identify the problems players are having and help them solve them. Also, keep the rest of us informed about what players are saying, what they like and don't like and want more of!" # ambassador_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll go from there!" # ambassador_join_note_strong: "Note" # ambassador_join_note_desc: "One of our top priorities is to build multiplayer where players having difficulty solving levels can summon higher level wizards to help them. This will be a great way for ambassadors to do their thing. We'll keep you posted!" # more_about_ambassador: "Learn More About Becoming an Ambassador" # ambassador_subscribe_desc: "Get emails on support updates and multiplayer developments." # changes_auto_save: "Changes are saved automatically when you toggle checkboxes." # diligent_scribes: "Our Diligent Scribes:" # powerful_archmages: "Our Powerful Archmages:" # creative_artisans: "Our Creative Artisans:" # brave_adventurers: "Our Brave Adventurers:" # translating_diplomats: "Our Translating Diplomats:" # helpful_ambassadors: "Our Helpful Ambassadors:" ladder: please_login: "Por favor inicia sesión antes de jugar una partida de escalera." my_matches: "Mis Partidas" simulate: "Simular" simulation_explanation: "¡Simulando tus juegos puedes mejorar tu posición más rápido!" simulate_games: "¡Simular Juegos!" simulate_all: "REINICIAR Y SIMULAR JUEGOS" games_simulated_by: "Juegos simulados por ti:" games_simulated_for: "Juegos simulados para ti:" games_simulated: "Juegos simulados" games_played: "Juegos jugados" ratio: "Proporción" leaderboard: "Posiciones" battle_as: "Combate como " summary_your: "Tus " summary_matches: "Partidas - " summary_wins: " Ganadas, " summary_losses: " Perdidas" rank_no_code: "Sin Código Nuevo para Clasificar" rank_my_game: "¡Clasifica Mi Juego!" rank_submitting: "Enviando..." rank_submitted: "Enviado para Clasificación" rank_failed: "Fallo al Clasificar" rank_being_ranked: "Juego Siendo Clasificado" # rank_last_submitted: "submitted " # help_simulate: "Help simulate games?" code_being_simulated: "Tu nuevo código está siendo simulado por otros jugadores para clasificación. Esto se refrescará a medida que vengan nuevas partidas." no_ranked_matches_pre: "Sin partidas clasificadas para el " no_ranked_matches_post: " equipo! Juega en contra de algunos competidores y luego vuelve aquí para ver tu juego clasificado." choose_opponent: "Escoge un Oponente" # select_your_language: "Select your language!" tutorial_play: "Juega el Tutorial" tutorial_recommended: "Recomendado si nunca has jugado antes" tutorial_skip: "Saltar Tutorial" tutorial_not_sure: "¿No estás seguro de que sucede?" tutorial_play_first: "Juega el Tutorial primero." simple_ai: "IA Simple" warmup: "Calentamiento" # friends_playing: "Friends Playing" # log_in_for_friends: "Log in to play with your friends!" # social_connect_blurb: "Connect and play against your friends!" # invite_friends_to_battle: "Invite your friends to join you in battle!" # fight: "Fight!" # watch_victory: "Watch your victory" # defeat_the: "Defeat the" # tournament_ends: "Tournament ends" # tournament_ended: "Tournament ended" # tournament_rules: "Tournament Rules" # tournament_blurb: "Write code, collect gold, build armies, crush foes, win prizes, and upgrade your career in our $40,000 Greed tournament! Check out the details" # tournament_blurb_criss_cross: "Win bids, construct paths, outwit opponents, grab gems, and upgrade your career in our Criss-Cross tournament! Check out the details" # tournament_blurb_blog: "on our blog" # rules: "Rules" # winners: "Winners" # user: # stats: "Stats" # singleplayer_title: "Singleplayer Levels" # multiplayer_title: "Multiplayer Levels" # achievements_title: "Achievements" # last_played: "Last Played" # status: "Status" # status_completed: "Completed" # status_unfinished: "Unfinished" # no_singleplayer: "No Singleplayer games played yet." # no_multiplayer: "No Multiplayer games played yet." # no_achievements: "No Achievements earned yet." # favorite_prefix: "Favorite language is " # favorite_postfix: "." # achievements: # last_earned: "Last Earned" # amount_achieved: "Amount" # achievement: "Achievement" # category_contributor: "Contributor" # category_ladder: "Ladder" # category_level: "Level" # category_miscellaneous: "Miscellaneous" # category_levels: "Levels" # category_undefined: "Uncategorized" # current_xp_prefix: "" # current_xp_postfix: " in total" # new_xp_prefix: "" # new_xp_postfix: " earned" # left_xp_prefix: "" # left_xp_infix: " until level " # left_xp_postfix: "" # account: # recently_played: "Recently Played" # no_recent_games: "No games played during the past two weeks." # payments: "Payments" # service_apple: "Apple" # service_web: "Web" # paid_on: "Paid On" # service: "Service" # price: "Price" # gems: "Gems" # status_subscribed: "You're currently subscribed at $9.99 USD/mo. Thanks for your support!" # status_unsubscribed_active: "You're not subscribed and won't be billed, but your account is still active for now." # status_unsubscribed: "Get access to new levels, heroes, items, and bonus gems with a CodeCombat subscription!" loading_error: could_not_load: "Error cargando del servidor" connection_failure: "Fallo de conexión." unauthorized: "Necesitas acceder. ¿Tienes desabilitadas las cookies?" forbidden: "No tienes los permisos." not_found: "No encontrado." not_allowed: "Método no permitido." timeout: "Expiró el tiempo del servidor." conflict: "Conflicto de recurso." bad_input: "Mala entrada." server_error: "Error de servidor." unknown: "Error desconocido." resources: # sessions: "Sessions" your_sessions: "Tus sesiones" level: "Nivel" social_network_apis: "APIs de Redes Sociales" facebook_status: "Estado de Facebook" facebook_friends: "Amigos de Facebook" facebook_friend_sessions: "Sesiones de Amigos de Facebook" gplus_friends: "Amigos de G+" gplus_friend_sessions: "Sesiones de Amigos de G+" leaderboard: "Clasificación" user_schema: "Esquema de Usuario" user_profile: "Perfil de Usuario" patches: "Parches" # patched_model: "Source Document" model: "Modelo" # system: "System" # systems: "Systems" # component: "Component" # components: "Components" # thang: "Thang" # thangs: "Thangs" # level_session: "Your Session" # opponent_session: "Opponent Session" # article: "Article" # user_names: "PI:NAME:<NAME>END_PI" # thang_names: "PI:NAME:<NAME>END_PI Names" # files: "Files" # top_simulators: "Top Simulators" # source_document: "Source Document" # document: "Document" # sprite_sheet: "Sprite Sheet" # employers: "Employers" # candidates: "Candidates" # candidate_sessions: "Candidate Sessions" # user_remark: "User Remark" # user_remarks: "User Remarks" # versions: "Versions" # items: "Items" # heroes: "Heroes" # wizard: "Wizard" # achievement: "Achievement" # clas: "CLAs" # play_counts: "Play Counts" # feedback: "Feedback" # delta: # added: "Added" # modified: "Modified" # deleted: "Deleted" # moved_index: "Moved Index" # text_diff: "Text Diff" # merge_conflict_with: "MERGE CONFLICT WITH" # no_changes: "No Changes" # guide: # temp: "Temp" multiplayer: multiplayer_title: "Configuración de Multijugador" # We'll be changing this around significantly soon. Until then, it's not important to translate. # multiplayer_toggle: "Enable multiplayer" # multiplayer_toggle_description: "Allow others to join your game." multiplayer_link_description: "Da este enlace a cualquiera para que se te una." multiplayer_hint_label: "Consejo:" multiplayer_hint: " Cliquea el enlace para seleccionar todo, luego presiona ⌘-C o Ctrl-C para copiar el enlace." multiplayer_coming_soon: "¡Más características de multijugador por venir!" # multiplayer_sign_in_leaderboard: "Sign in or create an account and get your solution on the leaderboard." # legal: # page_title: "Legal" # opensource_intro: "CodeCombat is completely open source." # opensource_description_prefix: "Check out " # github_url: "our GitHub" # opensource_description_center: "and help out if you like! CodeCombat is built on dozens of open source projects, and we love them. See " # archmage_wiki_url: "our Archmage wiki" # opensource_description_suffix: "for a list of the software that makes this game possible." # practices_title: "Respectful Best Practices" # practices_description: "These are our promises to you, the player, in slightly less legalese." # privacy_title: "Privacy" # privacy_description: "We will not sell any of your personal information." # security_title: "Security" # security_description: "We strive to keep your personal information safe. As an open source project, our site is freely open to anyone to review and improve our security systems." # email_title: "Email" # email_description_prefix: "We will not inundate you with spam. Through" # email_settings_url: "your email settings" # email_description_suffix: "or through links in the emails we send, you can change your preferences and easily unsubscribe at any time." # cost_title: "Cost" # cost_description: "CodeCombat is free to play in the dungeon campaign, with a $9.99 USD/mo subscription for access to later campaigns and 3500 bonus gems per month. You can cancel with a click, and we offer a 100% money-back guarantee." # copyrights_title: "Copyrights and Licenses" # contributor_title: "Contributor License Agreement" # contributor_description_prefix: "All contributions, both on the site and on our GitHub repository, are subject to our" # cla_url: "CLA" # contributor_description_suffix: "to which you should agree before contributing." # code_title: "Code - MIT" # code_description_prefix: "All code owned by CodeCombat or hosted on codecombat.com, both in the GitHub repository or in the codecombat.com database, is licensed under the" # mit_license_url: "MIT license" # code_description_suffix: "This includes all code in Systems and Components that are made available by CodeCombat for the purpose of creating levels." # art_title: "Art/Music - Creative Commons " # art_description_prefix: "All common content is available under the" # cc_license_url: "Creative Commons Attribution 4.0 International License" # art_description_suffix: "Common content is anything made generally available by CodeCombat for the purpose of creating Levels. This includes:" # art_music: "Music" # art_sound: "Sound" # art_artwork: "Artwork" # art_sprites: "Sprites" # art_other: "Any and all other non-code creative works that are made available when creating Levels." # art_access: "Currently there is no universal, easy system for fetching these assets. In general, fetch them from the URLs as used by the site, contact us for assistance, or help us in extending the site to make these assets more easily accessible." # art_paragraph_1: "For attribution, please name and link to codecombat.com near where the source is used or where appropriate for the medium. For example:" # use_list_1: "If used in a movie or another game, include codecombat.com in the credits." # use_list_2: "If used on a website, include a link near the usage, for example underneath an image, or in a general attributions page where you might also mention other Creative Commons works and open source software being used on the site. Something that's already clearly referencing CodeCombat, such as a blog post mentioning CodeCombat, does not need some separate attribution." # art_paragraph_2: "If the content being used is created not by CodeCombat but instead by a user of codecombat.com, attribute them instead, and follow attribution directions provided in that resource's description if there are any." # rights_title: "Rights Reserved" # rights_desc: "All rights are reserved for Levels themselves. This includes" # rights_scripts: "Scripts" # rights_unit: "Unit configuration" # rights_description: "Description" # rights_writings: "Writings" # rights_media: "Media (sounds, music) and any other creative content made specifically for that Level and not made generally available when creating Levels." # rights_clarification: "To clarify, anything that is made available in the Level Editor for the purpose of making levels is under CC, whereas the content created with the Level Editor or uploaded in the course of creation of Levels is not." # nutshell_title: "In a Nutshell" # nutshell_description: "Any resources we provide in the Level Editor are free to use as you like for creating Levels. But we reserve the right to restrict distribution of the Levels themselves (that are created on codecombat.com) so that they may be charged for in the future, if that's what ends up happening." # canonical: "The English version of this document is the definitive, canonical version. If there are any discrepencies between translations, the English document takes precedence." # ladder_prizes: # title: "Tournament Prizes" # This section was for an old tournament and doesn't need new translations now. # blurb_1: "These prizes will be awarded according to" # blurb_2: "the tournament rules" # blurb_3: "to the top human and ogre players." # blurb_4: "Two teams means double the prizes!" # blurb_5: "(There will be two first place winners, two second-place winners, etc.)" # rank: "Rank" # prizes: "Prizes" # total_value: "Total Value" # in_cash: "in cash" # custom_wizard: "Custom CodeCombat Wizard" # custom_avatar: "Custom CodeCombat avatar" # heap: "for six months of \"Startup\" access" # credits: "credits" # one_month_coupon: "coupon: choose either Rails or HTML" # one_month_discount: "discount, 30% off: choose either Rails or HTML" # license: "license" # oreilly: "ebook of your choice" wizard_settings: title: "Configuración del mago" customize_avatar: "Personaliza tu avatar" active: "Activo" color: "Color" group: "Grupo" clothes: "Ropa" trim: "Recortar" cloud: "Nube" team: "Equipo" spell: "Hechizo" boots: "Botas" hue: "Matiz" saturation: "Saturación" lightness: "Brillo" account_profile: settings: "Configuración" # We are not actively recruiting right now, so there's no need to add new translations for this section. edit_profile: "Editar Perfil" done_editing: "Terminar Edición" profile_for_prefix: "Perfil para " profile_for_suffix: "" featured: "Soportado" not_featured: "No Soportado" looking_for: "Buscando:" last_updated: "Última Actualización:" contact: "Contacto" active: "En busca de entrevistas ahora mismo" inactive: "No busco entrevistas por ahora" complete: "completado" next: "Siguiente" next_city: "¿Ciudad?" next_country: "selecciona tu país" next_name: "¿Nombre?" next_short_description: "escribe una breve descripción." next_long_description: "describe a que posción aspiras." next_skills: "nombra al menos cinco de tus cualidades." next_work: "detalla tu historial laboral." next_education: "realiza un recuento de tus méritos academicos." next_projects: "exhibe un máximo de tres proyectos en los que hayas participado." next_links: "añade cualquier enlace personal o social" next_photo: "añade una foto profesional (opcional)." next_active: "etiquetate como abierto a ofertas, para aparecer en las busquedas." example_blog: "Blog" example_personal_site: "Sitio Personal" links_header: "Enlaces Personale" links_blurb: "Añade enlaces a cualquier otro sitio o perfil que desees destacar, como tu GitHub, LinkedIn, o blog." links_name: "Nombre del enlace" links_name_help: "¿A que estas enlazando?" links_link_blurb: "URL del enlace" basics_header: "Actualizar información básica" basics_active: "Abierto a ofertas" basics_active_help: "¿Quieres ofertas para entrevistarte ahora mismo?" basics_job_title: "Posición Laboral deseada" basics_job_title_help: "¿Qué posición laboral estas buscando?" basics_city: "Ciudad" basics_city_help: "Ciudad en la que deseas trabajar (o en la que vives ahora)." basics_country: "País" basics_country_help: "País en el que deseas trabajar (o en el que vives ahora)." basics_visa: "Estatus laboral en EEUU" basics_visa_help: "¿Te encuentras autorizado para trabajar en los EEUU, o necesitas un patrocinador de visa? (Si vives en Canada o australia, selecciona autorizado.)" basics_looking_for: "Buscando" basics_looking_for_full_time: "Tiempo completo" basics_looking_for_part_time: "Tiempo parcial" basics_looking_for_remote: "A distacia" basics_looking_for_contracting: "Contratación" basics_looking_for_internship: "Pasantía" basics_looking_for_help: "¿Qué tipo de posición estas buscando como desarrollador?" name_header: "Escribe tu nombre" name_anonymous: "PI:NAME:<NAME>END_PI" name_help: "El nombre que los empleadores verán, por ejemplo 'PI:NAME:<NAME>END_PI Power'." short_description_header: "Descríbete en pocas palabras" short_description_blurb: "Añade un lema, para que un empleador pueda conocerte mejor facilmente." short_description: "Lema" short_description_help: "¿Quién eres, y que estas buscando? 140 caractéres máximo." skills_header: "Cualidades" skills_help: "Etiqueta tus cualidades más relevantes como desarrollador, en orden de competencia." long_description_header: "Describe tu posición laboral deseada" long_description_blurb: "Dile a los empleadores lo genial que eres, y que rol estas buscando." long_description: "Auto Descripción" long_description_help: "Describete a ti mismo para tus potenciales empleadores. Mantenlo corto y ve al grano. Te recomendamos destacar la posición laboral de mayor interes para ti. Un enfoque reduccionista, de buen gusto, es bienvenido; 600 caracteres mmáximo." work_experience: "Experiencia de Trabajo" work_header: "Detalla tu historial laboral" work_years: "Años de Experiencia" work_years_help: "Cuántos años de experiencia profesional (pagos) desarrollando software tienes?" work_blurb: "Realiza una lista con lo que consideres es tu experiencia laboral relevante, comenzando por la más reciente." work_employer: "Empleador" work_employer_help: "Nombre de tu empleador." work_role: "Nombre de la posición laboral" work_role_help: "¿Cuál era tu posición laboral o rol?" work_duration: "Duración" work_duration_help: "¿Cuál fue la duración de esa experiencia?" work_description: "Descripción" work_description_help: "¿Qué actividades realizabas allí? (140 caracteres; opcional)" education: "Educación" education_header: "Realiza un recuento de tus méritos academicos" education_blurb: "Escribe un recuento de tus méritos academicos." education_school: "Escuela" education_school_help: "Nombre de tu escuela." education_degree: "Título" education_degree_help: "¿Cuál fue tu título y área de estudio" education_duration: "Fechas" education_duration_help: "¿Cuándo?" education_description: "Descripción" education_description_help: "Destaca cualquier cosa acerca de esta experiencia educacional. (140 caracteres; opcional)" our_notes: "Nuestras Notas" remarks: "Observaciones" projects: "Proyectos" projects_header: "Añade 3 proyectos" projects_header_2: "Proyectos (Top 3)" projects_blurb: "Destaca tus proyectos para sorprender a los empleadores." project_name: "Nombre del Proyecto" project_name_help: "¿Cómo se llamaba el proyecto?" project_description: "Descripción" project_description_help: "Describe el proyecto brevemente.." project_picture: "Foto" project_picture_help: "Sube una imagen de 230x115px (o mayor) mostrando el proyecto" project_link: "Enlace" project_link_help: "Enlace al proyecto." player_code: "Código de Jugador" employers: # deprecation_warning_title: "Sorry, CodeCombat is not recruiting right now." # deprecation_warning: "We are focusing on beginner levels instead of finding expert developers for the time being." hire_developers_not_credentials: "Contrata desarrolladores, no credenciales." # We are not actively recruiting right now, so there's no need to add new translations for the rest of this section. get_started: "Comenzar" already_screened: "Ya hemos realizado un monitoreo técnico de todos los candidatos" filter_further: ",pero también puedes hacer un filtrado mas específico:" filter_visa: "Visa" filter_visa_yes: "Autorizado para los EEUU" filter_visa_no: "No autorizado" filter_education_top: "Escuela de elite" filter_education_other: "Otro" filter_role_web_developer: "Desarrollador Web" filter_role_software_developer: "Desarrollador de Software" filter_role_mobile_developer: "Desarrollador Móvil" filter_experience: "Experiencia" filter_experience_senior: "Senior" filter_experience_junior: "Junior" filter_experience_recent_grad: "Grado académico reciente" filter_experience_student: "Estudiante Universitario" filter_results: "resultados" start_hiring: "Comenzar a contratar." reasons: "Tres razones por las cuales deberías contratar a traves de nosotros:" everyone_looking: "Todos aquí estan en busqueda de una oportunidad laboral." everyone_looking_blurb: "Olvidate del 20% de respuestas promedio obtenidas via LinkedIn InMail. Todas las personas listadas en este sitio quieren encontrar su próxima posición laboral y responderan a tu solicitud para concretar una introducción." weeding: "Relajate; ya hemos desmalezado por ti." weeding_blurb: "Todo jugador listado ha sido monitoreado en lo que a su habilidad técnica se refiere. También llevamos a cabo monitoreos telefónicos a los candidatos seleccionados y dejamos notas en sus perfiles para ahorrarte tiempo." pass_screen: "Ell@s superaran tu monitoreo técnico." pass_screen_blurb: "Revisa el código de cada jugador antes de ponerte en contacto. Uno de nuestros empleadores se encontro con una proporción 5 veces mayor de nuestros desarrolladores superando su monitoreo técnico al compararlo con contrataciones realizadas en Hacker News." make_hiring_easier: "Has mi contratación mas simple, por favor." what: "Que es CodeCombat?" what_blurb: "CodeCombat es un juego multijugador de programación para navegadores. Los jugadores escriben un código para medirse en batalla contra otros desarrolladores. Nuestros jugadores cuentan con experiencia en los principales lenguajes técnicos." cost: "¿Cuánto cobramos?" cost_blurb: "Cobramos un 15% del primer salario anual y ofrecemos una garantía de devolución del 100% del dinero por 90 días. No cobramos por candidatos que actualmente se encuentren siendo entrevistados de forma activa por tu compañia." candidate_name: "PI:NAME:<NAME>END_PI" candidate_location: "Ubicación" candidate_looking_for: "Buscando" candidate_role: "Rol" candidate_top_skills: "Mejores Habilidades" candidate_years_experience: "Años de Exp" candidate_last_updated: "Última Actualización" candidate_who: "Quién" featured_developers: "Desarrolladores Destacados" other_developers: "Otros Desarrolladores" inactive_developers: "Desarrolladores Inactivos" admin: # av_espionage: "Espionage" # Really not important to translate /admin controls. # av_espionage_placeholder: "Email or username" # av_usersearch: "User Search" # av_usersearch_placeholder: "Email, username, name, whatever" # av_usersearch_search: "Search" av_title: "Vistas de Admin" av_entities_sub_title: "Entidades" av_entities_users_url: "Usuarios" av_entities_active_instances_url: "Instancias Activas" # av_entities_employer_list_url: "Employer List" # av_entities_candidates_list_url: "Candidate List" # av_entities_user_code_problems_list_url: "User Code Problems List" av_other_sub_title: "Otro" av_other_debug_base_url: "Base (para depurar base.jade)" u_title: "Lista de Usuarios" # ucp_title: "User Code Problems" lg_title: "Últimos Juegos" clas: "CLAs"
[ { "context": "###\n * javascript 打包\n * @author jackie Lin <dashi_lin @163.com>\n###\n\n'use strict'\nthrough2 =", "end": 42, "score": 0.9996557831764221, "start": 32, "tag": "NAME", "value": "jackie Lin" }, { "context": "###\n * javascript 打包\n * @author jackie Lin <dashi_lin @163.com>\n###\n\n'use strict'\nthrough2 = require 'through2'\n", "end": 62, "score": 0.9970793724060059, "start": 44, "tag": "EMAIL", "value": "dashi_lin @163.com" } ]
pack.coffee
JackieLin/gis
0
### * javascript 打包 * @author jackie Lin <dashi_lin @163.com> ### 'use strict' through2 = require 'through2' FS = require "q-io/fs" path = require 'path' gutil = require 'gulp-util' _ = require 'lodash' config = {} ### * 设置配置 ### exports.setConfig = (projectConfig) -> config = projectConfig ### * 将对应目录的文件进行合并 ### exports.combineFile = (filterList=[])-> through2.obj (file, enc, callback) -> srcPath = file.path files = [] self = @ # console.log srcPath FS.stat srcPath .then (stat)-> throw new Error '%s is not directory', srcPath if stat.isDirectory() is false FS.list srcPath .then (list) -> # console.log list # 过滤出 js 文件 list.filter (item) -> # path.extname(item) is '.js' and path.join(srcPath, item) not in filterList and item.indexOf('.') isnt 0 path.extname(item) is '.js' and item.indexOf('.') isnt 0 .then (list) -> # console.log list hasIndex = false task = [] # console.log list list.forEach (v) -> # require index hasIndex = v if v.indexOf(config.index or 'index.js') >= 0 task.push FS.read(path.join(srcPath, v)) if v.indexOf(config.index or 'index.js') < 0 files.push path.join(srcPath, v) if v.indexOf(config.index or 'index.js') < 0 return # console.log hasIndex task.push FS.read(path.join(srcPath, hasIndex)) if hasIndex files.push path.join(srcPath, hasIndex) if hasIndex task .spread -> args = Array.prototype.slice.call arguments excludeFiles = [] # 过滤掉排除文件信息 excludeFiles = files.map (v, k)-> if v? and v in filterList [tmp] = args.splice(k, 1) data = key: path.relative srcPath, v value: tmp return data excludeFiles = excludeFiles.filter (v)-> v? # console.log args source = args.join(';') name = _.chain srcPath.split(path.sep) .initial().last() name = name + '.all.js' # console.log name file.contents = new Buffer source file.path = path.join srcPath, '../', name # console.log file.path self.push file excludeFiles.forEach (v) -> # console.log v.key self.push new gutil.File cwd : file.cwd path : v.key contents: new Buffer v.value # console.log file.path callback() .fail (err)-> callback err, file
190006
### * javascript 打包 * @author <NAME> <<EMAIL>> ### 'use strict' through2 = require 'through2' FS = require "q-io/fs" path = require 'path' gutil = require 'gulp-util' _ = require 'lodash' config = {} ### * 设置配置 ### exports.setConfig = (projectConfig) -> config = projectConfig ### * 将对应目录的文件进行合并 ### exports.combineFile = (filterList=[])-> through2.obj (file, enc, callback) -> srcPath = file.path files = [] self = @ # console.log srcPath FS.stat srcPath .then (stat)-> throw new Error '%s is not directory', srcPath if stat.isDirectory() is false FS.list srcPath .then (list) -> # console.log list # 过滤出 js 文件 list.filter (item) -> # path.extname(item) is '.js' and path.join(srcPath, item) not in filterList and item.indexOf('.') isnt 0 path.extname(item) is '.js' and item.indexOf('.') isnt 0 .then (list) -> # console.log list hasIndex = false task = [] # console.log list list.forEach (v) -> # require index hasIndex = v if v.indexOf(config.index or 'index.js') >= 0 task.push FS.read(path.join(srcPath, v)) if v.indexOf(config.index or 'index.js') < 0 files.push path.join(srcPath, v) if v.indexOf(config.index or 'index.js') < 0 return # console.log hasIndex task.push FS.read(path.join(srcPath, hasIndex)) if hasIndex files.push path.join(srcPath, hasIndex) if hasIndex task .spread -> args = Array.prototype.slice.call arguments excludeFiles = [] # 过滤掉排除文件信息 excludeFiles = files.map (v, k)-> if v? and v in filterList [tmp] = args.splice(k, 1) data = key: path.relative srcPath, v value: tmp return data excludeFiles = excludeFiles.filter (v)-> v? # console.log args source = args.join(';') name = _.chain srcPath.split(path.sep) .initial().last() name = name + '.all.js' # console.log name file.contents = new Buffer source file.path = path.join srcPath, '../', name # console.log file.path self.push file excludeFiles.forEach (v) -> # console.log v.key self.push new gutil.File cwd : file.cwd path : v.key contents: new Buffer v.value # console.log file.path callback() .fail (err)-> callback err, file
true
### * javascript 打包 * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### 'use strict' through2 = require 'through2' FS = require "q-io/fs" path = require 'path' gutil = require 'gulp-util' _ = require 'lodash' config = {} ### * 设置配置 ### exports.setConfig = (projectConfig) -> config = projectConfig ### * 将对应目录的文件进行合并 ### exports.combineFile = (filterList=[])-> through2.obj (file, enc, callback) -> srcPath = file.path files = [] self = @ # console.log srcPath FS.stat srcPath .then (stat)-> throw new Error '%s is not directory', srcPath if stat.isDirectory() is false FS.list srcPath .then (list) -> # console.log list # 过滤出 js 文件 list.filter (item) -> # path.extname(item) is '.js' and path.join(srcPath, item) not in filterList and item.indexOf('.') isnt 0 path.extname(item) is '.js' and item.indexOf('.') isnt 0 .then (list) -> # console.log list hasIndex = false task = [] # console.log list list.forEach (v) -> # require index hasIndex = v if v.indexOf(config.index or 'index.js') >= 0 task.push FS.read(path.join(srcPath, v)) if v.indexOf(config.index or 'index.js') < 0 files.push path.join(srcPath, v) if v.indexOf(config.index or 'index.js') < 0 return # console.log hasIndex task.push FS.read(path.join(srcPath, hasIndex)) if hasIndex files.push path.join(srcPath, hasIndex) if hasIndex task .spread -> args = Array.prototype.slice.call arguments excludeFiles = [] # 过滤掉排除文件信息 excludeFiles = files.map (v, k)-> if v? and v in filterList [tmp] = args.splice(k, 1) data = key: path.relative srcPath, v value: tmp return data excludeFiles = excludeFiles.filter (v)-> v? # console.log args source = args.join(';') name = _.chain srcPath.split(path.sep) .initial().last() name = name + '.all.js' # console.log name file.contents = new Buffer source file.path = path.join srcPath, '../', name # console.log file.path self.push file excludeFiles.forEach (v) -> # console.log v.key self.push new gutil.File cwd : file.cwd path : v.key contents: new Buffer v.value # console.log file.path callback() .fail (err)-> callback err, file
[ { "context": "eventDefault()\n @btnDisable()\n username = @$username.val()\n password = @$password.val()\n if @$re", "end": 724, "score": 0.9315829873085022, "start": 716, "tag": "USERNAME", "value": "username" }, { "context": "\n username = @$username.val()\n password = @$password.val()\n if @$remember.prop('checked')\n rem", "end": 756, "score": 0.9229033589363098, "start": 748, "tag": "PASSWORD", "value": "password" }, { "context": "\n # 发送信息\n login.send\n \"username\": username\n \"password\": password\n \"remember\": ", "end": 1199, "score": 0.9926815629005432, "start": 1191, "tag": "USERNAME", "value": "username" }, { "context": "d\n \"username\": username\n \"password\": password\n \"remember\": remember\n else\n $.pub", "end": 1228, "score": 0.9982574582099915, "start": 1220, "tag": "PASSWORD", "value": "password" } ]
NodeSite/NodeSite/static/coffee/login.coffee
creamidea/Mushroom
1
class Login # alert 'ice' constructor: (uri) -> @$login = $login = $('#login') @$username = $login.find('input[name=username]') @$password = $login.find('input[name=password]') @$remember = $login.find('input[name=remember]') @$btnLogin = $btnLogin = $login.find('button[type="submit"]') @loginURI = uri || '/login/' # 单击事件处理 $login.submit $.proxy(@handler, this) show: -> $login = @$login $login.show() hide: -> $login = @$login $login.hide() btnDisable: -> @$btnLogin.html('登录中...').attr('disabled','disabled') btnEnable: -> @$btnLogin.html('登录').removeAttr('disabled') handler: (e) -> e.preventDefault() @btnDisable() username = @$username.val() password = @$password.val() if @$remember.prop('checked') remember = true else remember = false loginURI = @loginURI if username and password # alert "#{username}: #{[password]}: #{remember}" login = new Post loginURI, (data) => if data.code is "-1" @btnEnable() else $.publish "#login", [data] , () => @btnEnable() # 发送信息 login.send "username": username "password": password "remember": remember else $.publish "#echo/", [{code: -1, definition: 'Error, who are you?'}] @btnEnable()
48105
class Login # alert 'ice' constructor: (uri) -> @$login = $login = $('#login') @$username = $login.find('input[name=username]') @$password = $login.find('input[name=password]') @$remember = $login.find('input[name=remember]') @$btnLogin = $btnLogin = $login.find('button[type="submit"]') @loginURI = uri || '/login/' # 单击事件处理 $login.submit $.proxy(@handler, this) show: -> $login = @$login $login.show() hide: -> $login = @$login $login.hide() btnDisable: -> @$btnLogin.html('登录中...').attr('disabled','disabled') btnEnable: -> @$btnLogin.html('登录').removeAttr('disabled') handler: (e) -> e.preventDefault() @btnDisable() username = @$username.val() password = @$<PASSWORD>.val() if @$remember.prop('checked') remember = true else remember = false loginURI = @loginURI if username and password # alert "#{username}: #{[password]}: #{remember}" login = new Post loginURI, (data) => if data.code is "-1" @btnEnable() else $.publish "#login", [data] , () => @btnEnable() # 发送信息 login.send "username": username "password": <PASSWORD> "remember": remember else $.publish "#echo/", [{code: -1, definition: 'Error, who are you?'}] @btnEnable()
true
class Login # alert 'ice' constructor: (uri) -> @$login = $login = $('#login') @$username = $login.find('input[name=username]') @$password = $login.find('input[name=password]') @$remember = $login.find('input[name=remember]') @$btnLogin = $btnLogin = $login.find('button[type="submit"]') @loginURI = uri || '/login/' # 单击事件处理 $login.submit $.proxy(@handler, this) show: -> $login = @$login $login.show() hide: -> $login = @$login $login.hide() btnDisable: -> @$btnLogin.html('登录中...').attr('disabled','disabled') btnEnable: -> @$btnLogin.html('登录').removeAttr('disabled') handler: (e) -> e.preventDefault() @btnDisable() username = @$username.val() password = @$PI:PASSWORD:<PASSWORD>END_PI.val() if @$remember.prop('checked') remember = true else remember = false loginURI = @loginURI if username and password # alert "#{username}: #{[password]}: #{remember}" login = new Post loginURI, (data) => if data.code is "-1" @btnEnable() else $.publish "#login", [data] , () => @btnEnable() # 发送信息 login.send "username": username "password": PI:PASSWORD:<PASSWORD>END_PI "remember": remember else $.publish "#echo/", [{code: -1, definition: 'Error, who are you?'}] @btnEnable()
[ { "context": "ollaborators = [\n id: \"35\"\n full_name: \"Aaron Baker\"\n info: \"testroles2, collaborator\"\n ]\n\n ", "end": 500, "score": 0.9998461008071899, "start": 489, "tag": "NAME", "value": "Aaron Baker" } ]
test/javascripts/integration/super_ad_hoc_test.js.coffee
johan--/tahi
1
module 'Integration: Super AdHoc Card', teardown: -> ETahi.reset() setup: -> setupApp integration: true ef = ETahi.Factory records = ETahi.Setups.paperWithTask('Task' id: 1 title: "Super Ad-Hoc" ) ETahi.Test = {} ETahi.Test.currentPaper = records[0] paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat([fakeUser])) paperResponse = paperPayload.toJSON() collaborators = [ id: "35" full_name: "Aaron Baker" info: "testroles2, collaborator" ] server.respondWith 'GET', "/dashboards", [ 200, {"Content-Type": "application/json"}, JSON.stringify {dashboards: []} ] server.respondWith 'GET', "/papers/#{ETahi.Test.currentPaper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperResponse ] server.respondWith 'PUT', /\/tasks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] server.respondWith 'GET', "/filtered_users/collaborators/#{ETahi.Test.currentPaper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify collaborators ] server.respondWith 'GET', /\/filtered_users\/non_participants\/\d+\/\w+/, [ 200, {"Content-Type": "application/json"}, JSON.stringify [] ] test "Changing the title on an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click 'h1.inline-edit .glyphicon-pencil' fillIn '.large-edit input[name=title]', 'Shazam!' click '.large-edit .button--green:contains("Save")' andThen -> ok exists find 'h1.inline-edit:contains("Shazam!")' test "Adding a text block to an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--text' andThen -> Em.$('.inline-edit-form div[contenteditable]') .html("New contenteditable, yahoo!") .trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' andThen -> assertText('.inline-edit', 'yahoo') click '.inline-edit-body-part .glyphicon-trash' andThen -> assertText('.inline-edit-body-part', 'Are you sure?') click '.inline-edit-body-part .delete-button' andThen -> assertNoText('.inline-edit', 'yahoo') test "Adding and removing a checkbox item to an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--list' andThen -> ok exists find '.inline-edit-form .item-remove' Em.$('.inline-edit-form label[contenteditable]') .html("Here is a checkbox list item") .trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' andThen -> assertText('.inline-edit', 'checkbox list item') ok exists find '.inline-edit input[type=checkbox]' click '.inline-edit-body-part .glyphicon-trash' andThen -> assertText('.inline-edit-body-part', 'Are you sure?') click '.inline-edit-body-part .delete-button' andThen -> assertNoText('.inline-edit', 'checkbox list item') test "Adding an email block to an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--email' fillIn '.inline-edit-form input[placeholder="Enter a subject"]', "Deep subject" andThen -> Em.$('.inline-edit-form div[contenteditable]').html("Awesome email body!").trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' andThen -> assertText('.inline-edit .item-subject', 'Deep') assertText('.inline-edit .item-text', 'Awesome') test "User can send an email from an adhoc card", -> server.respondWith 'PUT', /\/tasks\/\d+\/send_message/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--email' fillIn '.inline-edit-form input[placeholder="Enter a subject"]', "Deep subject" andThen -> Em.$('.inline-edit-form div[contenteditable]').html("Awesome email body!").trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' click '.task-body .email-send-participants' click('.send-email-action') andThen -> ok find('.bodypart-last-sent').length, 'The sent at time should appear' ok find('.bodypart-email-sent-overlay').length, 'The sent confirmation should appear' ok _.findWhere(server.requests, {method: "PUT", url: "/tasks/1/send_message"}), "It posts to the server"
202367
module 'Integration: Super AdHoc Card', teardown: -> ETahi.reset() setup: -> setupApp integration: true ef = ETahi.Factory records = ETahi.Setups.paperWithTask('Task' id: 1 title: "Super Ad-Hoc" ) ETahi.Test = {} ETahi.Test.currentPaper = records[0] paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat([fakeUser])) paperResponse = paperPayload.toJSON() collaborators = [ id: "35" full_name: "<NAME>" info: "testroles2, collaborator" ] server.respondWith 'GET', "/dashboards", [ 200, {"Content-Type": "application/json"}, JSON.stringify {dashboards: []} ] server.respondWith 'GET', "/papers/#{ETahi.Test.currentPaper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperResponse ] server.respondWith 'PUT', /\/tasks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] server.respondWith 'GET', "/filtered_users/collaborators/#{ETahi.Test.currentPaper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify collaborators ] server.respondWith 'GET', /\/filtered_users\/non_participants\/\d+\/\w+/, [ 200, {"Content-Type": "application/json"}, JSON.stringify [] ] test "Changing the title on an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click 'h1.inline-edit .glyphicon-pencil' fillIn '.large-edit input[name=title]', 'Shazam!' click '.large-edit .button--green:contains("Save")' andThen -> ok exists find 'h1.inline-edit:contains("Shazam!")' test "Adding a text block to an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--text' andThen -> Em.$('.inline-edit-form div[contenteditable]') .html("New contenteditable, yahoo!") .trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' andThen -> assertText('.inline-edit', 'yahoo') click '.inline-edit-body-part .glyphicon-trash' andThen -> assertText('.inline-edit-body-part', 'Are you sure?') click '.inline-edit-body-part .delete-button' andThen -> assertNoText('.inline-edit', 'yahoo') test "Adding and removing a checkbox item to an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--list' andThen -> ok exists find '.inline-edit-form .item-remove' Em.$('.inline-edit-form label[contenteditable]') .html("Here is a checkbox list item") .trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' andThen -> assertText('.inline-edit', 'checkbox list item') ok exists find '.inline-edit input[type=checkbox]' click '.inline-edit-body-part .glyphicon-trash' andThen -> assertText('.inline-edit-body-part', 'Are you sure?') click '.inline-edit-body-part .delete-button' andThen -> assertNoText('.inline-edit', 'checkbox list item') test "Adding an email block to an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--email' fillIn '.inline-edit-form input[placeholder="Enter a subject"]', "Deep subject" andThen -> Em.$('.inline-edit-form div[contenteditable]').html("Awesome email body!").trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' andThen -> assertText('.inline-edit .item-subject', 'Deep') assertText('.inline-edit .item-text', 'Awesome') test "User can send an email from an adhoc card", -> server.respondWith 'PUT', /\/tasks\/\d+\/send_message/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--email' fillIn '.inline-edit-form input[placeholder="Enter a subject"]', "Deep subject" andThen -> Em.$('.inline-edit-form div[contenteditable]').html("Awesome email body!").trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' click '.task-body .email-send-participants' click('.send-email-action') andThen -> ok find('.bodypart-last-sent').length, 'The sent at time should appear' ok find('.bodypart-email-sent-overlay').length, 'The sent confirmation should appear' ok _.findWhere(server.requests, {method: "PUT", url: "/tasks/1/send_message"}), "It posts to the server"
true
module 'Integration: Super AdHoc Card', teardown: -> ETahi.reset() setup: -> setupApp integration: true ef = ETahi.Factory records = ETahi.Setups.paperWithTask('Task' id: 1 title: "Super Ad-Hoc" ) ETahi.Test = {} ETahi.Test.currentPaper = records[0] paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat([fakeUser])) paperResponse = paperPayload.toJSON() collaborators = [ id: "35" full_name: "PI:NAME:<NAME>END_PI" info: "testroles2, collaborator" ] server.respondWith 'GET', "/dashboards", [ 200, {"Content-Type": "application/json"}, JSON.stringify {dashboards: []} ] server.respondWith 'GET', "/papers/#{ETahi.Test.currentPaper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperResponse ] server.respondWith 'PUT', /\/tasks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] server.respondWith 'GET', "/filtered_users/collaborators/#{ETahi.Test.currentPaper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify collaborators ] server.respondWith 'GET', /\/filtered_users\/non_participants\/\d+\/\w+/, [ 200, {"Content-Type": "application/json"}, JSON.stringify [] ] test "Changing the title on an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click 'h1.inline-edit .glyphicon-pencil' fillIn '.large-edit input[name=title]', 'Shazam!' click '.large-edit .button--green:contains("Save")' andThen -> ok exists find 'h1.inline-edit:contains("Shazam!")' test "Adding a text block to an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--text' andThen -> Em.$('.inline-edit-form div[contenteditable]') .html("New contenteditable, yahoo!") .trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' andThen -> assertText('.inline-edit', 'yahoo') click '.inline-edit-body-part .glyphicon-trash' andThen -> assertText('.inline-edit-body-part', 'Are you sure?') click '.inline-edit-body-part .delete-button' andThen -> assertNoText('.inline-edit', 'yahoo') test "Adding and removing a checkbox item to an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--list' andThen -> ok exists find '.inline-edit-form .item-remove' Em.$('.inline-edit-form label[contenteditable]') .html("Here is a checkbox list item") .trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' andThen -> assertText('.inline-edit', 'checkbox list item') ok exists find '.inline-edit input[type=checkbox]' click '.inline-edit-body-part .glyphicon-trash' andThen -> assertText('.inline-edit-body-part', 'Are you sure?') click '.inline-edit-body-part .delete-button' andThen -> assertNoText('.inline-edit', 'checkbox list item') test "Adding an email block to an AdHoc Task", -> visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--email' fillIn '.inline-edit-form input[placeholder="Enter a subject"]', "Deep subject" andThen -> Em.$('.inline-edit-form div[contenteditable]').html("Awesome email body!").trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' andThen -> assertText('.inline-edit .item-subject', 'Deep') assertText('.inline-edit .item-text', 'Awesome') test "User can send an email from an adhoc card", -> server.respondWith 'PUT', /\/tasks\/\d+\/send_message/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] visit "/papers/#{ETahi.Test.currentPaper.id}/tasks/1" click '.adhoc-content-toolbar .glyphicon-plus' click '.adhoc-content-toolbar .adhoc-toolbar-item--email' fillIn '.inline-edit-form input[placeholder="Enter a subject"]', "Deep subject" andThen -> Em.$('.inline-edit-form div[contenteditable]').html("Awesome email body!").trigger('keyup') click '.task-body .inline-edit-body-part .button--green:contains("Save")' click '.task-body .email-send-participants' click('.send-email-action') andThen -> ok find('.bodypart-last-sent').length, 'The sent at time should appear' ok find('.bodypart-email-sent-overlay').length, 'The sent confirmation should appear' ok _.findWhere(server.requests, {method: "PUT", url: "/tasks/1/send_message"}), "It posts to the server"
[ { "context": "tClient = new CanadaPostClient\n username: 'oh canada'\n password: 'zamboni'\n\n\n describe \"delivere", "end": 505, "score": 0.651942789554596, "start": 499, "tag": "USERNAME", "value": "canada" }, { "context": "ient\n username: 'oh canada'\n password: 'zamboni'\n\n\n describe \"delivered package\", ->\n\n _packa", "end": 531, "score": 0.999119222164154, "start": 524, "tag": "PASSWORD", "value": "zamboni" } ]
test/canada_post.coffee
launchd-baemon/rebu-track
82
fs = require 'fs' assert = require 'assert' should = require('chai').should() expect = require('chai').expect bond = require 'bondjs' {CanadaPostClient} = require '../lib/canada_post' {ShipperClient} = require '../lib/shipper' {Builder, Parser} = require 'xml2js' describe "canada post client", -> _canpostClient = null _xmlParser = new Parser() _xmlHeader = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' before -> _canpostClient = new CanadaPostClient username: 'oh canada' password: 'zamboni' describe "delivered package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_delivered.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delivered", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELIVERED it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of T3Z3J7", -> expect(_package.destination).to.equal 'T3Z3J7' it "has 7 activities", -> expect(_package.activities).to.have.length 7 it "has an eta of Sep 23", -> expect(_package.eta).to.deep.equal new Date '2015-09-23T23:59:59Z' it "has first activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2015-09-23T11:59:59.000Z' expect(act.details).to.equal 'Item successfully delivered' expect(act.location).to.equal 'Calgary, AB' it "has last activity with timestamp, location and details", -> act = _package.activities[6] expect(act.timestamp).to.deep.equal new Date '2015-09-21T13:49:14.000Z' expect(act.details).to.equal 'Electronic information submitted by shipper' expect(act.location).to.equal 'Richmond, BC' describe "en-route package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_en_route.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of en-route", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.EN_ROUTE it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of L4J8A2", -> expect(_package.destination).to.equal 'L4J8A2' it "has 4 activities", -> expect(_package.activities).to.have.length 4 it "has an eta of Oct 01", -> expect(_package.eta).to.deep.equal new Date '2015-10-01T23:59:59Z' it "has first activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2015-10-01T06:04:27.000Z' expect(act.details).to.equal 'Item processed' expect(act.location).to.equal 'Richmond Hill, ON' it "has last activity with timestamp, location and details", -> act = _package.activities[3] expect(act.timestamp).to.deep.equal new Date '2015-09-30T18:34:49.000Z' expect(act.details).to.equal 'Item processed' expect(act.location).to.equal 'Mississauga, ON' describe "shipping package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_shipping.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of shipping", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.SHIPPING it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of T3H5S3", -> expect(_package.destination).to.equal 'T3H5S3' it "has 1 activity", -> expect(_package.activities).to.have.length 1 it "has activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2015-09-30T16:56:50.000Z' expect(act.details).to.equal 'Electronic information submitted by shipper' expect(act.location).to.equal 'Saskatoon, SK' describe "another delivered package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_delivered2.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delivered", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELIVERED describe "delayed package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_delayed.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delayed", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELAYED describe "en-route package with a 'departed' activity", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_departed.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of en-route", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.EN_ROUTE it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of X1A0A1", -> expect(_package.destination).to.equal 'X1A0A1' it "has an eta of Mar 14", -> expect(_package.eta).to.deep.equal new Date '2016-03-14T23:59:59Z'
86739
fs = require 'fs' assert = require 'assert' should = require('chai').should() expect = require('chai').expect bond = require 'bondjs' {CanadaPostClient} = require '../lib/canada_post' {ShipperClient} = require '../lib/shipper' {Builder, Parser} = require 'xml2js' describe "canada post client", -> _canpostClient = null _xmlParser = new Parser() _xmlHeader = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' before -> _canpostClient = new CanadaPostClient username: 'oh canada' password: '<PASSWORD>' describe "delivered package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_delivered.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delivered", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELIVERED it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of T3Z3J7", -> expect(_package.destination).to.equal 'T3Z3J7' it "has 7 activities", -> expect(_package.activities).to.have.length 7 it "has an eta of Sep 23", -> expect(_package.eta).to.deep.equal new Date '2015-09-23T23:59:59Z' it "has first activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2015-09-23T11:59:59.000Z' expect(act.details).to.equal 'Item successfully delivered' expect(act.location).to.equal 'Calgary, AB' it "has last activity with timestamp, location and details", -> act = _package.activities[6] expect(act.timestamp).to.deep.equal new Date '2015-09-21T13:49:14.000Z' expect(act.details).to.equal 'Electronic information submitted by shipper' expect(act.location).to.equal 'Richmond, BC' describe "en-route package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_en_route.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of en-route", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.EN_ROUTE it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of L4J8A2", -> expect(_package.destination).to.equal 'L4J8A2' it "has 4 activities", -> expect(_package.activities).to.have.length 4 it "has an eta of Oct 01", -> expect(_package.eta).to.deep.equal new Date '2015-10-01T23:59:59Z' it "has first activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2015-10-01T06:04:27.000Z' expect(act.details).to.equal 'Item processed' expect(act.location).to.equal 'Richmond Hill, ON' it "has last activity with timestamp, location and details", -> act = _package.activities[3] expect(act.timestamp).to.deep.equal new Date '2015-09-30T18:34:49.000Z' expect(act.details).to.equal 'Item processed' expect(act.location).to.equal 'Mississauga, ON' describe "shipping package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_shipping.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of shipping", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.SHIPPING it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of T3H5S3", -> expect(_package.destination).to.equal 'T3H5S3' it "has 1 activity", -> expect(_package.activities).to.have.length 1 it "has activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2015-09-30T16:56:50.000Z' expect(act.details).to.equal 'Electronic information submitted by shipper' expect(act.location).to.equal 'Saskatoon, SK' describe "another delivered package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_delivered2.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delivered", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELIVERED describe "delayed package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_delayed.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delayed", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELAYED describe "en-route package with a 'departed' activity", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_departed.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of en-route", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.EN_ROUTE it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of X1A0A1", -> expect(_package.destination).to.equal 'X1A0A1' it "has an eta of Mar 14", -> expect(_package.eta).to.deep.equal new Date '2016-03-14T23:59:59Z'
true
fs = require 'fs' assert = require 'assert' should = require('chai').should() expect = require('chai').expect bond = require 'bondjs' {CanadaPostClient} = require '../lib/canada_post' {ShipperClient} = require '../lib/shipper' {Builder, Parser} = require 'xml2js' describe "canada post client", -> _canpostClient = null _xmlParser = new Parser() _xmlHeader = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' before -> _canpostClient = new CanadaPostClient username: 'oh canada' password: 'PI:PASSWORD:<PASSWORD>END_PI' describe "delivered package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_delivered.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delivered", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELIVERED it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of T3Z3J7", -> expect(_package.destination).to.equal 'T3Z3J7' it "has 7 activities", -> expect(_package.activities).to.have.length 7 it "has an eta of Sep 23", -> expect(_package.eta).to.deep.equal new Date '2015-09-23T23:59:59Z' it "has first activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2015-09-23T11:59:59.000Z' expect(act.details).to.equal 'Item successfully delivered' expect(act.location).to.equal 'Calgary, AB' it "has last activity with timestamp, location and details", -> act = _package.activities[6] expect(act.timestamp).to.deep.equal new Date '2015-09-21T13:49:14.000Z' expect(act.details).to.equal 'Electronic information submitted by shipper' expect(act.location).to.equal 'Richmond, BC' describe "en-route package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_en_route.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of en-route", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.EN_ROUTE it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of L4J8A2", -> expect(_package.destination).to.equal 'L4J8A2' it "has 4 activities", -> expect(_package.activities).to.have.length 4 it "has an eta of Oct 01", -> expect(_package.eta).to.deep.equal new Date '2015-10-01T23:59:59Z' it "has first activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2015-10-01T06:04:27.000Z' expect(act.details).to.equal 'Item processed' expect(act.location).to.equal 'Richmond Hill, ON' it "has last activity with timestamp, location and details", -> act = _package.activities[3] expect(act.timestamp).to.deep.equal new Date '2015-09-30T18:34:49.000Z' expect(act.details).to.equal 'Item processed' expect(act.location).to.equal 'Mississauga, ON' describe "shipping package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_shipping.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of shipping", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.SHIPPING it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of T3H5S3", -> expect(_package.destination).to.equal 'T3H5S3' it "has 1 activity", -> expect(_package.activities).to.have.length 1 it "has activity with timestamp, location and details", -> act = _package.activities[0] expect(act.timestamp).to.deep.equal new Date '2015-09-30T16:56:50.000Z' expect(act.details).to.equal 'Electronic information submitted by shipper' expect(act.location).to.equal 'Saskatoon, SK' describe "another delivered package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_delivered2.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delivered", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELIVERED describe "delayed package", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_delayed.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of delayed", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.DELAYED describe "en-route package with a 'departed' activity", -> _package = null before (done) -> fs.readFile 'test/stub_data/canada_post_departed.xml', 'utf8', (err, xmlDoc) -> _canpostClient.presentResponse xmlDoc, 'trk', (err, resp) -> should.not.exist(err) _package = resp done() it "has a status of en-route", -> expect(_package.status).to.equal ShipperClient.STATUS_TYPES.EN_ROUTE it "has a service type of Expedited Parcels", -> expect(_package.service).to.equal 'Expedited Parcels' it "has a destination of X1A0A1", -> expect(_package.destination).to.equal 'X1A0A1' it "has an eta of Mar 14", -> expect(_package.eta).to.deep.equal new Date '2016-03-14T23:59:59Z'
[ { "context": "e:\n label: 'Username (temporary)'\n id: 'instructor_username'\n value: ''\n \n wizard_start_date:\n ", "end": 743, "score": 0.9991706609725952, "start": 724, "tag": "USERNAME", "value": "instructor_username" }, { "context": "hing_else:\n type: 'link'\n href: 'mailto:contact@wikiedu.org'\n id: 'something_else'\n selected: false", "end": 1935, "score": 0.9999201893806458, "start": 1916, "tag": "EMAIL", "value": "contact@wikiedu.org" }, { "context": "s through: <a style='color:#505a7f;' href='mailto:contact@wikiedu.org'>contact@wikiedu.org</a>.\"\n\n## Start of input opt", "end": 2397, "score": 0.9999310374259949, "start": 2378, "tag": "EMAIL", "value": "contact@wikiedu.org" }, { "context": "color:#505a7f;' href='mailto:contact@wikiedu.org'>contact@wikiedu.org</a>.\"\n\n## Start of input options for the research", "end": 2418, "score": 0.999930202960968, "start": 2399, "tag": "EMAIL", "value": "contact@wikiedu.org" } ]
source/javascripts/data/WizardStepInputs.coffee
WikiEducationFoundation/WikiEduWizard
1
WizardStepInputs = intro: teacher: type: 'text' label: 'Instructor name' id: 'teacher' value: '' required: true course_name: type: 'text' label: 'Course name' id: 'course_name' value: '' required: true school: type: 'text' label: 'University' id: 'school' value: '' required: true subject: type: 'text' label: 'Subject' id: 'subject' value: '' required: true students: type: 'text' label: 'Approximate number of students' id: 'students' value: '' required: true instructor_username: label: 'Username (temporary)' id: 'instructor_username' value: '' wizard_start_date: isDate: true month: '' day: '' year: '' value: '' required: true wizard_end_date: isDate: true month: '' day: '' year: '' value: '' required: true # Assignment selection options assignment_selection: researchwrite: type: 'checkbox' id: 'researchwrite' selected: false label: 'Create or expand an article' exclusive: true hasCourseInfo: true required: true translation: type: 'checkbox' id: 'translation' selected: false label: 'Translate an article' exclusive: false hasCourseInfo: true disabled: false multimedia: type: 'checkbox' id: 'multimedia' selected: false label: 'Add images & multimedia' exclusive: false hasCourseInfo: true disabled: false copyedit: type: 'checkbox' id: 'copyedit' selected: false label: 'Copyedit articles' exclusive: false hasCourseInfo: true disabled: false something_else: type: 'link' href: 'mailto:contact@wikiedu.org' id: 'something_else' selected: false label: 'A different assignment? Get in touch here.' exclusive: false hasCourseInfo: false tipInfo: title: '' content: "Have another idea for incorporating Wikipedia into your class? We've found that these assignments work well, but they aren't the only way to do it. Get in touch, and we can talk things through: <a style='color:#505a7f;' href='mailto:contact@wikiedu.org'>contact@wikiedu.org</a>." ## Start of input options for the researchwrite path learning_essentials: training_graded: type: 'radioBox' id: 'training_graded' selected: false label: 'Completion of training will be graded' exclusive: false required: true training_not_graded: type: 'radioBox' id: 'training_not_graded' selected: false label: 'Completion of training will not be graded' exclusive: false required: true getting_started: critique_article: type: 'checkbox' id: 'critique_article' selected: true label: 'Critique an article' exclusive: false required: true add_to_article: type: 'checkbox' id: 'add_to_article' selected: true label: 'Add to an article' exclusive: false required: true copy_edit_article: type: 'checkbox' id: 'copy_edit_article' selected: false label: 'Copyedit an article' exclusive: false required: true illustrate_article: type: 'checkbox' id: 'illustrate_article' selected: false label: 'Illustrate an article' exclusive: false required: true choosing_articles: prepare_list: type: 'radioBox' id: 'prepare_list' selected: false label: 'Instructor prepares a list' exclusive: false hasSubChoice: true required: true students_explore: type: 'radioBox' id: 'students_explore' selected: false label: 'Students find articles' exclusive: false hasSubChoice: true required: true request_help: type: 'checkbox' id: 'request_help' selected: false label: 'Would you like help selecting or evaulating article choices?' exclusive: false required: true ignoreValidation: true conditional_label: prepare_list: "Would you like help selecting articles?" students_explore: "Would you like help evaluating student choices?" tricky_topics: yes_definitely: type: 'radioBox' id: 'yes_definitely' selected: false label: 'Yes. We will work on medicine or psychology articles.' exclusive: false required: true maybe: type: 'radioBox' id: 'maybe' selected: false label: 'Maybe. Students might choose a medicine or psychology topic.' exclusive: false required: true definitely_not: type: 'radioBox' id: 'definitely_not' selected: false label: 'No. No one will work on medicine or psychology topics.' exclusive: false required: true research_planning: create_outline: type: 'radioBox' id: 'create_outline' selected: false label: 'Traditional outline' exclusive: false required: true tipInfo: title: "Traditional outline" content: "For each article, the students create an outline that reflects the improvements they plan to make, and then post it to the article's talk page. This is a relatively easy way to get started." write_lead: type: 'radioBox' id: 'write_lead' selected: false required: true label: 'Wikipedia lead section' exclusive: false tipInfo: title: "Wikipedia lead section" content: "<p>For each article, the students create a well-balanced summary of its future state in the form of a Wikipedia lead section. The ideal lead section exemplifies Wikipedia's summary style of writing: it begins with a single sentence that defines the topic and places it in context, and then — in one to four paragraphs, depending on the article's size — it offers a concise summary of topic. A good lead section should reflect the main topics and balance of coverage over the whole article.</p> <p>Outlining an article this way is a more challenging assignment — and will require more work to evaluate and provide feedback for. However, it can be more effective for teaching the process of research, writing, and revision. Students will return to this lead section as they go, to guide their writing and to revise it to reflect their improved understanding of the topic as their research progresses. They will tackle Wikipedia's encyclopedic style early on, and their outline efforts will be an integral part of their final work.</p>" drafts_mainspace: work_live: type: 'radioBox' id: 'work_live' selected: false label: 'Work live from the start' exclusive: false required: true sandbox: type: 'radioBox' id: 'sandbox' selected: false label: 'Draft early work in sandboxes' exclusive: false required: true peer_feedback: peer_reviews: type: 'radioGroup' id: 'peer_reviews' label: '' value: 'two' selected: 1 overviewLabel: 'Two peer review' options: [ { id: 0 name: 'peer_reviews' label: '1' value: 'one' selected: false overviewLabel: 'One peer review' } { id: 1 name: 'peer_reviews' label: '2' value: 'two' selected: true overviewLabel: 'Two peer review' } { id: 2 name: 'peer_reviews' label: '3' value: 'three' selected: false overviewLabel: 'Three peer review' } { id: 3 name: 'peer_reviews' label: '4' value: 'four' selected: false overviewLabel: 'Four peer review' } { id: 4 name: 'peer_reviews' label: '5' value: 'five' selected: false overviewLabel: 'Five peer review' } ] supplementary_assignments: class_blog: type: 'checkbox' id: 'class_blog' selected: false required: false label: 'Class blog or discussion' exclusive: false tipInfo: title: 'Class blog or class discussion' content: 'Students keep a running blog about their experiences. Giving them prompts every week or two, such as “To what extent are the editors on Wikipedia a self-selecting group and why?” will help them think about the larger issues surrounding this online encyclopedia community. It will also give you material both on the wiki and off the wiki to grade. If you have time in class, these discussions can be particularly constructive in person.' class_presentation: type: 'checkbox' id: 'class_presentation' selected: false required: false label: 'In-class presentations' exclusive: false tipInfo: title: 'In-class presentation of Wikipedia work' content: "Each student or group prepares a short presentation for the class, explaining what they worked on, what went well and what didn't, and what they learned. These presentations can make excellent fodder for class discussions to reinforce your course's learning goals." reflective_essay: type: 'checkbox' id: 'reflective_essay' selected: false required: false label: 'Reflective essay' exclusive: false tipInfo: title: 'Reflective essay' content: "Ask students to write a short reflective essay on their experiences using Wikipedia. This works well for both short and long Wikipedia projects. An interesting iteration of this is to have students write a short version of the essay before they begin editing Wikipedia, outlining their expectations, and then have them reflect on whether or not they met those expectations during the assignment." portfolio: type: 'checkbox' id: 'portfolio' selected: false required: false label: 'Wikipedia portfolio' exclusive: false tipInfo: title: 'Wikipedia portfolio' content: "Students organize their Wikipedia work into a portfolio, including a narrative of the contributions they made — and how they were received, and possibly changed, by other Wikipedians — and links to their key edits. Composing this portfolio will help students think more deeply about their Wikipedia experiences, and also provides a lens through which to understand — and grade — their work." original_paper: type: 'checkbox' id: 'original_paper' selected: false required: false label: 'Original analytical paper' exclusive: false tipInfo: title: 'Original analytical paper' content: "In courses that emphasize traditional research skills and the development of original ideas through a term paper, Wikipedia's policy of \"no original research\" may be too restrictive. Many instructors pair Wikipedia writing with a complementary analytical paper; students’ Wikipedia articles serve as a literature review, and the students go on to develop their own ideas and arguments in the offline analytical paper." dyk: dyk: type: 'checkbox' id: 'dyk' selected: false required: false label: 'Did You Know?' exclusive: false ga: ga: type: 'checkbox' id: 'ga' selected: false required: false label: 'Good Article nominations' exclusive: false ## Start of input options for the translate path translation_essentials: translation_training_graded: type: 'radioBox' id: 'translation_training_graded' selected: false label: 'Completion of training will be graded' exclusive: false required: true translation_training_not_graded: type: 'radioBox' id: 'translation_training_not_graded' selected: false label: 'Completion of training will not be graded' exclusive: false required: true translation_choosing_articles: prepare_list: type: 'radioBox' id: 'prepare_list' selected: false label: 'Instructor prepares a list' exclusive: false hasSubChoice: true required: true students_explore: type: 'radioBox' id: 'students_explore' selected: false label: 'Students find articles' exclusive: false hasSubChoice: true required: true request_help: type: 'checkbox' id: 'request_help' selected: false label: 'Would you like help selecting or evaulating article choices?' exclusive: false required: true ignoreValidation: true conditional_label: prepare_list: "Would you like help selecting articles?" students_explore: "Would you like help evaluating student choices?" translation_media_literacy: fact_checking: type: 'checkbox' id: 'fact_checking' selected: false required: false label: 'Fact-checking assignment' exclusive: false # grading_multimedia: # complete_multimedia: # type: 'percent' # label: 'Add images & multimedia' # id: 'complete_multimedia' # value: 50 # renderInOutput: true # contingentUpon: [] # grading_copyedit: # complete_copyedit: # type: 'percent' # label: 'Copyedit articles' # id: 'omplete_copyedit' # value: 50 # renderInOutput: true # contingentUpon: [] ## Start of grading configuration grading: # Research and write an article grading researchwrite: complete_training: type: 'percent' label: 'Completion of Wikipedia training' id: 'complete_training' value: 5 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [ 'training_graded' ] getting_started: type: 'percent' label: 'Early Wikipedia exercises' id: 'getting_started' value: 15 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] outline_quality: type: 'percent' id: 'outline_quality' label: 'Quality of bibliography and outline' value: 10 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] peer_reviews: id: 'peer_reviews' type: 'percent' label: 'Peer reviews and collaboration with classmates' value: 10 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] contribution_quality: type: 'percent' id: 'contribution_quality' label: 'Quality of your main Wikipedia contributions' value: 50 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] supplementary_assignments: type: 'percent' id: 'supplementary_assignments' label: 'Supplementary assignments' value: 10 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [ 'class_blog' 'class_presentation' 'reflective_essay' 'portfolio' 'original_paper' ] # Translation assignment grading translation: complete_translation_training: type: 'percent' label: 'Was the training completed?' id: 'complete_translation_training' value: 5 renderInOutput: true pathwayId: 'translation' contingentUpon: [ 'translation_training_graded' ] translation_accuracy: type: 'percent' label: 'Is the translation accurate?' id: 'translation_accuracy' value: 25 renderInOutput: true pathwayId: 'translation' contingentUpon: [ ] translation_language: type: 'percent' label: 'Does the article use natural vocabulary?' id: 'translation_language' value: 25 renderInOutput: true pathwayId: 'translation' contingentUpon: [ ] translation_consistency: type: 'percent' label: "Is the article's style consistent?" id: 'translation_consistency' value: 15 renderInOutput: true pathwayId: 'translation' contingentUpon: [ ] translation_documentation: type: 'percent' label: "Are the original article's sources well-documented?" id: 'translation_documentation' value: 15 renderInOutput: true pathwayId: 'translation' contingentUpon: [ 'fact_checking' ] translation_revisions: type: 'percent' label: 'Does the article adopt new, quality sources?' id: 'translation_revisions' value: 15 renderInOutput: true pathwayId: 'translation' contingentUpon: [ 'fact_checking' ] # Copyedit grading copyedit: copyedit: type: 'percent' label: 'Copyedit articles' id: 'copyedit' value: 100 renderInOutput: true pathwayId: 'copyedit' contingentUpon: [ ] # Add multimedia grading multimedia: multimedia: type: 'percent' label: 'Add images & multimedia' id: 'multimedia' value: 100 renderInOutput: true pathwayId: 'multimedia' contingentUpon: [ ] grading_selection: label: 'Grading based on:' id: 'grading_selection' value: '' renderInOutput: false options: percent: label: 'Percentage' value: 'percent' selected: true points: label: 'Points' value: 'points' selected: false overview: learning_essentials: type: 'edit' label: 'Learning Wiki essentials' id: 'learning_essentials' value: '' getting_started: type: 'edit' label: 'Getting started with editing' id: 'getting_started' value: '' choosing_articles: type: 'edit' label: 'Choosing articles' id: 'choosing_articles' value: '' research_planning: type: 'edit' label: 'Research and planning' id: 'research_planning' value: '' drafts_mainspace: type: 'edit' label: 'Drafts and mainspace' id: 'drafts_mainspace' value: '' peer_feedback: type: 'edit' label: 'Peer Feedback' id: 'peer_feedback' value: '' supplementary_assignments: type: 'edit' label: 'Supplementary assignments' id: 'supplementary_assignments' value: '' wizard_start_date: month: '' day: '' year: '' wizard_end_date: month: '' day: '' year: '' course_details: description: '' term_start_date: '' term_end_date: '' start_date: '' start_weekof_date: '' end_weekof_date: '' end_date: '' weekdays_selected: [false,false,false,false,false,false,false] length_in_weeks: 16 assignments: [] module.exports = WizardStepInputs
146488
WizardStepInputs = intro: teacher: type: 'text' label: 'Instructor name' id: 'teacher' value: '' required: true course_name: type: 'text' label: 'Course name' id: 'course_name' value: '' required: true school: type: 'text' label: 'University' id: 'school' value: '' required: true subject: type: 'text' label: 'Subject' id: 'subject' value: '' required: true students: type: 'text' label: 'Approximate number of students' id: 'students' value: '' required: true instructor_username: label: 'Username (temporary)' id: 'instructor_username' value: '' wizard_start_date: isDate: true month: '' day: '' year: '' value: '' required: true wizard_end_date: isDate: true month: '' day: '' year: '' value: '' required: true # Assignment selection options assignment_selection: researchwrite: type: 'checkbox' id: 'researchwrite' selected: false label: 'Create or expand an article' exclusive: true hasCourseInfo: true required: true translation: type: 'checkbox' id: 'translation' selected: false label: 'Translate an article' exclusive: false hasCourseInfo: true disabled: false multimedia: type: 'checkbox' id: 'multimedia' selected: false label: 'Add images & multimedia' exclusive: false hasCourseInfo: true disabled: false copyedit: type: 'checkbox' id: 'copyedit' selected: false label: 'Copyedit articles' exclusive: false hasCourseInfo: true disabled: false something_else: type: 'link' href: 'mailto:<EMAIL>' id: 'something_else' selected: false label: 'A different assignment? Get in touch here.' exclusive: false hasCourseInfo: false tipInfo: title: '' content: "Have another idea for incorporating Wikipedia into your class? We've found that these assignments work well, but they aren't the only way to do it. Get in touch, and we can talk things through: <a style='color:#505a7f;' href='mailto:<EMAIL>'><EMAIL></a>." ## Start of input options for the researchwrite path learning_essentials: training_graded: type: 'radioBox' id: 'training_graded' selected: false label: 'Completion of training will be graded' exclusive: false required: true training_not_graded: type: 'radioBox' id: 'training_not_graded' selected: false label: 'Completion of training will not be graded' exclusive: false required: true getting_started: critique_article: type: 'checkbox' id: 'critique_article' selected: true label: 'Critique an article' exclusive: false required: true add_to_article: type: 'checkbox' id: 'add_to_article' selected: true label: 'Add to an article' exclusive: false required: true copy_edit_article: type: 'checkbox' id: 'copy_edit_article' selected: false label: 'Copyedit an article' exclusive: false required: true illustrate_article: type: 'checkbox' id: 'illustrate_article' selected: false label: 'Illustrate an article' exclusive: false required: true choosing_articles: prepare_list: type: 'radioBox' id: 'prepare_list' selected: false label: 'Instructor prepares a list' exclusive: false hasSubChoice: true required: true students_explore: type: 'radioBox' id: 'students_explore' selected: false label: 'Students find articles' exclusive: false hasSubChoice: true required: true request_help: type: 'checkbox' id: 'request_help' selected: false label: 'Would you like help selecting or evaulating article choices?' exclusive: false required: true ignoreValidation: true conditional_label: prepare_list: "Would you like help selecting articles?" students_explore: "Would you like help evaluating student choices?" tricky_topics: yes_definitely: type: 'radioBox' id: 'yes_definitely' selected: false label: 'Yes. We will work on medicine or psychology articles.' exclusive: false required: true maybe: type: 'radioBox' id: 'maybe' selected: false label: 'Maybe. Students might choose a medicine or psychology topic.' exclusive: false required: true definitely_not: type: 'radioBox' id: 'definitely_not' selected: false label: 'No. No one will work on medicine or psychology topics.' exclusive: false required: true research_planning: create_outline: type: 'radioBox' id: 'create_outline' selected: false label: 'Traditional outline' exclusive: false required: true tipInfo: title: "Traditional outline" content: "For each article, the students create an outline that reflects the improvements they plan to make, and then post it to the article's talk page. This is a relatively easy way to get started." write_lead: type: 'radioBox' id: 'write_lead' selected: false required: true label: 'Wikipedia lead section' exclusive: false tipInfo: title: "Wikipedia lead section" content: "<p>For each article, the students create a well-balanced summary of its future state in the form of a Wikipedia lead section. The ideal lead section exemplifies Wikipedia's summary style of writing: it begins with a single sentence that defines the topic and places it in context, and then — in one to four paragraphs, depending on the article's size — it offers a concise summary of topic. A good lead section should reflect the main topics and balance of coverage over the whole article.</p> <p>Outlining an article this way is a more challenging assignment — and will require more work to evaluate and provide feedback for. However, it can be more effective for teaching the process of research, writing, and revision. Students will return to this lead section as they go, to guide their writing and to revise it to reflect their improved understanding of the topic as their research progresses. They will tackle Wikipedia's encyclopedic style early on, and their outline efforts will be an integral part of their final work.</p>" drafts_mainspace: work_live: type: 'radioBox' id: 'work_live' selected: false label: 'Work live from the start' exclusive: false required: true sandbox: type: 'radioBox' id: 'sandbox' selected: false label: 'Draft early work in sandboxes' exclusive: false required: true peer_feedback: peer_reviews: type: 'radioGroup' id: 'peer_reviews' label: '' value: 'two' selected: 1 overviewLabel: 'Two peer review' options: [ { id: 0 name: 'peer_reviews' label: '1' value: 'one' selected: false overviewLabel: 'One peer review' } { id: 1 name: 'peer_reviews' label: '2' value: 'two' selected: true overviewLabel: 'Two peer review' } { id: 2 name: 'peer_reviews' label: '3' value: 'three' selected: false overviewLabel: 'Three peer review' } { id: 3 name: 'peer_reviews' label: '4' value: 'four' selected: false overviewLabel: 'Four peer review' } { id: 4 name: 'peer_reviews' label: '5' value: 'five' selected: false overviewLabel: 'Five peer review' } ] supplementary_assignments: class_blog: type: 'checkbox' id: 'class_blog' selected: false required: false label: 'Class blog or discussion' exclusive: false tipInfo: title: 'Class blog or class discussion' content: 'Students keep a running blog about their experiences. Giving them prompts every week or two, such as “To what extent are the editors on Wikipedia a self-selecting group and why?” will help them think about the larger issues surrounding this online encyclopedia community. It will also give you material both on the wiki and off the wiki to grade. If you have time in class, these discussions can be particularly constructive in person.' class_presentation: type: 'checkbox' id: 'class_presentation' selected: false required: false label: 'In-class presentations' exclusive: false tipInfo: title: 'In-class presentation of Wikipedia work' content: "Each student or group prepares a short presentation for the class, explaining what they worked on, what went well and what didn't, and what they learned. These presentations can make excellent fodder for class discussions to reinforce your course's learning goals." reflective_essay: type: 'checkbox' id: 'reflective_essay' selected: false required: false label: 'Reflective essay' exclusive: false tipInfo: title: 'Reflective essay' content: "Ask students to write a short reflective essay on their experiences using Wikipedia. This works well for both short and long Wikipedia projects. An interesting iteration of this is to have students write a short version of the essay before they begin editing Wikipedia, outlining their expectations, and then have them reflect on whether or not they met those expectations during the assignment." portfolio: type: 'checkbox' id: 'portfolio' selected: false required: false label: 'Wikipedia portfolio' exclusive: false tipInfo: title: 'Wikipedia portfolio' content: "Students organize their Wikipedia work into a portfolio, including a narrative of the contributions they made — and how they were received, and possibly changed, by other Wikipedians — and links to their key edits. Composing this portfolio will help students think more deeply about their Wikipedia experiences, and also provides a lens through which to understand — and grade — their work." original_paper: type: 'checkbox' id: 'original_paper' selected: false required: false label: 'Original analytical paper' exclusive: false tipInfo: title: 'Original analytical paper' content: "In courses that emphasize traditional research skills and the development of original ideas through a term paper, Wikipedia's policy of \"no original research\" may be too restrictive. Many instructors pair Wikipedia writing with a complementary analytical paper; students’ Wikipedia articles serve as a literature review, and the students go on to develop their own ideas and arguments in the offline analytical paper." dyk: dyk: type: 'checkbox' id: 'dyk' selected: false required: false label: 'Did You Know?' exclusive: false ga: ga: type: 'checkbox' id: 'ga' selected: false required: false label: 'Good Article nominations' exclusive: false ## Start of input options for the translate path translation_essentials: translation_training_graded: type: 'radioBox' id: 'translation_training_graded' selected: false label: 'Completion of training will be graded' exclusive: false required: true translation_training_not_graded: type: 'radioBox' id: 'translation_training_not_graded' selected: false label: 'Completion of training will not be graded' exclusive: false required: true translation_choosing_articles: prepare_list: type: 'radioBox' id: 'prepare_list' selected: false label: 'Instructor prepares a list' exclusive: false hasSubChoice: true required: true students_explore: type: 'radioBox' id: 'students_explore' selected: false label: 'Students find articles' exclusive: false hasSubChoice: true required: true request_help: type: 'checkbox' id: 'request_help' selected: false label: 'Would you like help selecting or evaulating article choices?' exclusive: false required: true ignoreValidation: true conditional_label: prepare_list: "Would you like help selecting articles?" students_explore: "Would you like help evaluating student choices?" translation_media_literacy: fact_checking: type: 'checkbox' id: 'fact_checking' selected: false required: false label: 'Fact-checking assignment' exclusive: false # grading_multimedia: # complete_multimedia: # type: 'percent' # label: 'Add images & multimedia' # id: 'complete_multimedia' # value: 50 # renderInOutput: true # contingentUpon: [] # grading_copyedit: # complete_copyedit: # type: 'percent' # label: 'Copyedit articles' # id: 'omplete_copyedit' # value: 50 # renderInOutput: true # contingentUpon: [] ## Start of grading configuration grading: # Research and write an article grading researchwrite: complete_training: type: 'percent' label: 'Completion of Wikipedia training' id: 'complete_training' value: 5 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [ 'training_graded' ] getting_started: type: 'percent' label: 'Early Wikipedia exercises' id: 'getting_started' value: 15 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] outline_quality: type: 'percent' id: 'outline_quality' label: 'Quality of bibliography and outline' value: 10 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] peer_reviews: id: 'peer_reviews' type: 'percent' label: 'Peer reviews and collaboration with classmates' value: 10 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] contribution_quality: type: 'percent' id: 'contribution_quality' label: 'Quality of your main Wikipedia contributions' value: 50 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] supplementary_assignments: type: 'percent' id: 'supplementary_assignments' label: 'Supplementary assignments' value: 10 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [ 'class_blog' 'class_presentation' 'reflective_essay' 'portfolio' 'original_paper' ] # Translation assignment grading translation: complete_translation_training: type: 'percent' label: 'Was the training completed?' id: 'complete_translation_training' value: 5 renderInOutput: true pathwayId: 'translation' contingentUpon: [ 'translation_training_graded' ] translation_accuracy: type: 'percent' label: 'Is the translation accurate?' id: 'translation_accuracy' value: 25 renderInOutput: true pathwayId: 'translation' contingentUpon: [ ] translation_language: type: 'percent' label: 'Does the article use natural vocabulary?' id: 'translation_language' value: 25 renderInOutput: true pathwayId: 'translation' contingentUpon: [ ] translation_consistency: type: 'percent' label: "Is the article's style consistent?" id: 'translation_consistency' value: 15 renderInOutput: true pathwayId: 'translation' contingentUpon: [ ] translation_documentation: type: 'percent' label: "Are the original article's sources well-documented?" id: 'translation_documentation' value: 15 renderInOutput: true pathwayId: 'translation' contingentUpon: [ 'fact_checking' ] translation_revisions: type: 'percent' label: 'Does the article adopt new, quality sources?' id: 'translation_revisions' value: 15 renderInOutput: true pathwayId: 'translation' contingentUpon: [ 'fact_checking' ] # Copyedit grading copyedit: copyedit: type: 'percent' label: 'Copyedit articles' id: 'copyedit' value: 100 renderInOutput: true pathwayId: 'copyedit' contingentUpon: [ ] # Add multimedia grading multimedia: multimedia: type: 'percent' label: 'Add images & multimedia' id: 'multimedia' value: 100 renderInOutput: true pathwayId: 'multimedia' contingentUpon: [ ] grading_selection: label: 'Grading based on:' id: 'grading_selection' value: '' renderInOutput: false options: percent: label: 'Percentage' value: 'percent' selected: true points: label: 'Points' value: 'points' selected: false overview: learning_essentials: type: 'edit' label: 'Learning Wiki essentials' id: 'learning_essentials' value: '' getting_started: type: 'edit' label: 'Getting started with editing' id: 'getting_started' value: '' choosing_articles: type: 'edit' label: 'Choosing articles' id: 'choosing_articles' value: '' research_planning: type: 'edit' label: 'Research and planning' id: 'research_planning' value: '' drafts_mainspace: type: 'edit' label: 'Drafts and mainspace' id: 'drafts_mainspace' value: '' peer_feedback: type: 'edit' label: 'Peer Feedback' id: 'peer_feedback' value: '' supplementary_assignments: type: 'edit' label: 'Supplementary assignments' id: 'supplementary_assignments' value: '' wizard_start_date: month: '' day: '' year: '' wizard_end_date: month: '' day: '' year: '' course_details: description: '' term_start_date: '' term_end_date: '' start_date: '' start_weekof_date: '' end_weekof_date: '' end_date: '' weekdays_selected: [false,false,false,false,false,false,false] length_in_weeks: 16 assignments: [] module.exports = WizardStepInputs
true
WizardStepInputs = intro: teacher: type: 'text' label: 'Instructor name' id: 'teacher' value: '' required: true course_name: type: 'text' label: 'Course name' id: 'course_name' value: '' required: true school: type: 'text' label: 'University' id: 'school' value: '' required: true subject: type: 'text' label: 'Subject' id: 'subject' value: '' required: true students: type: 'text' label: 'Approximate number of students' id: 'students' value: '' required: true instructor_username: label: 'Username (temporary)' id: 'instructor_username' value: '' wizard_start_date: isDate: true month: '' day: '' year: '' value: '' required: true wizard_end_date: isDate: true month: '' day: '' year: '' value: '' required: true # Assignment selection options assignment_selection: researchwrite: type: 'checkbox' id: 'researchwrite' selected: false label: 'Create or expand an article' exclusive: true hasCourseInfo: true required: true translation: type: 'checkbox' id: 'translation' selected: false label: 'Translate an article' exclusive: false hasCourseInfo: true disabled: false multimedia: type: 'checkbox' id: 'multimedia' selected: false label: 'Add images & multimedia' exclusive: false hasCourseInfo: true disabled: false copyedit: type: 'checkbox' id: 'copyedit' selected: false label: 'Copyedit articles' exclusive: false hasCourseInfo: true disabled: false something_else: type: 'link' href: 'mailto:PI:EMAIL:<EMAIL>END_PI' id: 'something_else' selected: false label: 'A different assignment? Get in touch here.' exclusive: false hasCourseInfo: false tipInfo: title: '' content: "Have another idea for incorporating Wikipedia into your class? We've found that these assignments work well, but they aren't the only way to do it. Get in touch, and we can talk things through: <a style='color:#505a7f;' href='mailto:PI:EMAIL:<EMAIL>END_PI'>PI:EMAIL:<EMAIL>END_PI</a>." ## Start of input options for the researchwrite path learning_essentials: training_graded: type: 'radioBox' id: 'training_graded' selected: false label: 'Completion of training will be graded' exclusive: false required: true training_not_graded: type: 'radioBox' id: 'training_not_graded' selected: false label: 'Completion of training will not be graded' exclusive: false required: true getting_started: critique_article: type: 'checkbox' id: 'critique_article' selected: true label: 'Critique an article' exclusive: false required: true add_to_article: type: 'checkbox' id: 'add_to_article' selected: true label: 'Add to an article' exclusive: false required: true copy_edit_article: type: 'checkbox' id: 'copy_edit_article' selected: false label: 'Copyedit an article' exclusive: false required: true illustrate_article: type: 'checkbox' id: 'illustrate_article' selected: false label: 'Illustrate an article' exclusive: false required: true choosing_articles: prepare_list: type: 'radioBox' id: 'prepare_list' selected: false label: 'Instructor prepares a list' exclusive: false hasSubChoice: true required: true students_explore: type: 'radioBox' id: 'students_explore' selected: false label: 'Students find articles' exclusive: false hasSubChoice: true required: true request_help: type: 'checkbox' id: 'request_help' selected: false label: 'Would you like help selecting or evaulating article choices?' exclusive: false required: true ignoreValidation: true conditional_label: prepare_list: "Would you like help selecting articles?" students_explore: "Would you like help evaluating student choices?" tricky_topics: yes_definitely: type: 'radioBox' id: 'yes_definitely' selected: false label: 'Yes. We will work on medicine or psychology articles.' exclusive: false required: true maybe: type: 'radioBox' id: 'maybe' selected: false label: 'Maybe. Students might choose a medicine or psychology topic.' exclusive: false required: true definitely_not: type: 'radioBox' id: 'definitely_not' selected: false label: 'No. No one will work on medicine or psychology topics.' exclusive: false required: true research_planning: create_outline: type: 'radioBox' id: 'create_outline' selected: false label: 'Traditional outline' exclusive: false required: true tipInfo: title: "Traditional outline" content: "For each article, the students create an outline that reflects the improvements they plan to make, and then post it to the article's talk page. This is a relatively easy way to get started." write_lead: type: 'radioBox' id: 'write_lead' selected: false required: true label: 'Wikipedia lead section' exclusive: false tipInfo: title: "Wikipedia lead section" content: "<p>For each article, the students create a well-balanced summary of its future state in the form of a Wikipedia lead section. The ideal lead section exemplifies Wikipedia's summary style of writing: it begins with a single sentence that defines the topic and places it in context, and then — in one to four paragraphs, depending on the article's size — it offers a concise summary of topic. A good lead section should reflect the main topics and balance of coverage over the whole article.</p> <p>Outlining an article this way is a more challenging assignment — and will require more work to evaluate and provide feedback for. However, it can be more effective for teaching the process of research, writing, and revision. Students will return to this lead section as they go, to guide their writing and to revise it to reflect their improved understanding of the topic as their research progresses. They will tackle Wikipedia's encyclopedic style early on, and their outline efforts will be an integral part of their final work.</p>" drafts_mainspace: work_live: type: 'radioBox' id: 'work_live' selected: false label: 'Work live from the start' exclusive: false required: true sandbox: type: 'radioBox' id: 'sandbox' selected: false label: 'Draft early work in sandboxes' exclusive: false required: true peer_feedback: peer_reviews: type: 'radioGroup' id: 'peer_reviews' label: '' value: 'two' selected: 1 overviewLabel: 'Two peer review' options: [ { id: 0 name: 'peer_reviews' label: '1' value: 'one' selected: false overviewLabel: 'One peer review' } { id: 1 name: 'peer_reviews' label: '2' value: 'two' selected: true overviewLabel: 'Two peer review' } { id: 2 name: 'peer_reviews' label: '3' value: 'three' selected: false overviewLabel: 'Three peer review' } { id: 3 name: 'peer_reviews' label: '4' value: 'four' selected: false overviewLabel: 'Four peer review' } { id: 4 name: 'peer_reviews' label: '5' value: 'five' selected: false overviewLabel: 'Five peer review' } ] supplementary_assignments: class_blog: type: 'checkbox' id: 'class_blog' selected: false required: false label: 'Class blog or discussion' exclusive: false tipInfo: title: 'Class blog or class discussion' content: 'Students keep a running blog about their experiences. Giving them prompts every week or two, such as “To what extent are the editors on Wikipedia a self-selecting group and why?” will help them think about the larger issues surrounding this online encyclopedia community. It will also give you material both on the wiki and off the wiki to grade. If you have time in class, these discussions can be particularly constructive in person.' class_presentation: type: 'checkbox' id: 'class_presentation' selected: false required: false label: 'In-class presentations' exclusive: false tipInfo: title: 'In-class presentation of Wikipedia work' content: "Each student or group prepares a short presentation for the class, explaining what they worked on, what went well and what didn't, and what they learned. These presentations can make excellent fodder for class discussions to reinforce your course's learning goals." reflective_essay: type: 'checkbox' id: 'reflective_essay' selected: false required: false label: 'Reflective essay' exclusive: false tipInfo: title: 'Reflective essay' content: "Ask students to write a short reflective essay on their experiences using Wikipedia. This works well for both short and long Wikipedia projects. An interesting iteration of this is to have students write a short version of the essay before they begin editing Wikipedia, outlining their expectations, and then have them reflect on whether or not they met those expectations during the assignment." portfolio: type: 'checkbox' id: 'portfolio' selected: false required: false label: 'Wikipedia portfolio' exclusive: false tipInfo: title: 'Wikipedia portfolio' content: "Students organize their Wikipedia work into a portfolio, including a narrative of the contributions they made — and how they were received, and possibly changed, by other Wikipedians — and links to their key edits. Composing this portfolio will help students think more deeply about their Wikipedia experiences, and also provides a lens through which to understand — and grade — their work." original_paper: type: 'checkbox' id: 'original_paper' selected: false required: false label: 'Original analytical paper' exclusive: false tipInfo: title: 'Original analytical paper' content: "In courses that emphasize traditional research skills and the development of original ideas through a term paper, Wikipedia's policy of \"no original research\" may be too restrictive. Many instructors pair Wikipedia writing with a complementary analytical paper; students’ Wikipedia articles serve as a literature review, and the students go on to develop their own ideas and arguments in the offline analytical paper." dyk: dyk: type: 'checkbox' id: 'dyk' selected: false required: false label: 'Did You Know?' exclusive: false ga: ga: type: 'checkbox' id: 'ga' selected: false required: false label: 'Good Article nominations' exclusive: false ## Start of input options for the translate path translation_essentials: translation_training_graded: type: 'radioBox' id: 'translation_training_graded' selected: false label: 'Completion of training will be graded' exclusive: false required: true translation_training_not_graded: type: 'radioBox' id: 'translation_training_not_graded' selected: false label: 'Completion of training will not be graded' exclusive: false required: true translation_choosing_articles: prepare_list: type: 'radioBox' id: 'prepare_list' selected: false label: 'Instructor prepares a list' exclusive: false hasSubChoice: true required: true students_explore: type: 'radioBox' id: 'students_explore' selected: false label: 'Students find articles' exclusive: false hasSubChoice: true required: true request_help: type: 'checkbox' id: 'request_help' selected: false label: 'Would you like help selecting or evaulating article choices?' exclusive: false required: true ignoreValidation: true conditional_label: prepare_list: "Would you like help selecting articles?" students_explore: "Would you like help evaluating student choices?" translation_media_literacy: fact_checking: type: 'checkbox' id: 'fact_checking' selected: false required: false label: 'Fact-checking assignment' exclusive: false # grading_multimedia: # complete_multimedia: # type: 'percent' # label: 'Add images & multimedia' # id: 'complete_multimedia' # value: 50 # renderInOutput: true # contingentUpon: [] # grading_copyedit: # complete_copyedit: # type: 'percent' # label: 'Copyedit articles' # id: 'omplete_copyedit' # value: 50 # renderInOutput: true # contingentUpon: [] ## Start of grading configuration grading: # Research and write an article grading researchwrite: complete_training: type: 'percent' label: 'Completion of Wikipedia training' id: 'complete_training' value: 5 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [ 'training_graded' ] getting_started: type: 'percent' label: 'Early Wikipedia exercises' id: 'getting_started' value: 15 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] outline_quality: type: 'percent' id: 'outline_quality' label: 'Quality of bibliography and outline' value: 10 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] peer_reviews: id: 'peer_reviews' type: 'percent' label: 'Peer reviews and collaboration with classmates' value: 10 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] contribution_quality: type: 'percent' id: 'contribution_quality' label: 'Quality of your main Wikipedia contributions' value: 50 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [] supplementary_assignments: type: 'percent' id: 'supplementary_assignments' label: 'Supplementary assignments' value: 10 renderInOutput: true pathwayId: 'researchwrite' contingentUpon: [ 'class_blog' 'class_presentation' 'reflective_essay' 'portfolio' 'original_paper' ] # Translation assignment grading translation: complete_translation_training: type: 'percent' label: 'Was the training completed?' id: 'complete_translation_training' value: 5 renderInOutput: true pathwayId: 'translation' contingentUpon: [ 'translation_training_graded' ] translation_accuracy: type: 'percent' label: 'Is the translation accurate?' id: 'translation_accuracy' value: 25 renderInOutput: true pathwayId: 'translation' contingentUpon: [ ] translation_language: type: 'percent' label: 'Does the article use natural vocabulary?' id: 'translation_language' value: 25 renderInOutput: true pathwayId: 'translation' contingentUpon: [ ] translation_consistency: type: 'percent' label: "Is the article's style consistent?" id: 'translation_consistency' value: 15 renderInOutput: true pathwayId: 'translation' contingentUpon: [ ] translation_documentation: type: 'percent' label: "Are the original article's sources well-documented?" id: 'translation_documentation' value: 15 renderInOutput: true pathwayId: 'translation' contingentUpon: [ 'fact_checking' ] translation_revisions: type: 'percent' label: 'Does the article adopt new, quality sources?' id: 'translation_revisions' value: 15 renderInOutput: true pathwayId: 'translation' contingentUpon: [ 'fact_checking' ] # Copyedit grading copyedit: copyedit: type: 'percent' label: 'Copyedit articles' id: 'copyedit' value: 100 renderInOutput: true pathwayId: 'copyedit' contingentUpon: [ ] # Add multimedia grading multimedia: multimedia: type: 'percent' label: 'Add images & multimedia' id: 'multimedia' value: 100 renderInOutput: true pathwayId: 'multimedia' contingentUpon: [ ] grading_selection: label: 'Grading based on:' id: 'grading_selection' value: '' renderInOutput: false options: percent: label: 'Percentage' value: 'percent' selected: true points: label: 'Points' value: 'points' selected: false overview: learning_essentials: type: 'edit' label: 'Learning Wiki essentials' id: 'learning_essentials' value: '' getting_started: type: 'edit' label: 'Getting started with editing' id: 'getting_started' value: '' choosing_articles: type: 'edit' label: 'Choosing articles' id: 'choosing_articles' value: '' research_planning: type: 'edit' label: 'Research and planning' id: 'research_planning' value: '' drafts_mainspace: type: 'edit' label: 'Drafts and mainspace' id: 'drafts_mainspace' value: '' peer_feedback: type: 'edit' label: 'Peer Feedback' id: 'peer_feedback' value: '' supplementary_assignments: type: 'edit' label: 'Supplementary assignments' id: 'supplementary_assignments' value: '' wizard_start_date: month: '' day: '' year: '' wizard_end_date: month: '' day: '' year: '' course_details: description: '' term_start_date: '' term_end_date: '' start_date: '' start_weekof_date: '' end_weekof_date: '' end_date: '' weekdays_selected: [false,false,false,false,false,false,false] length_in_weeks: 16 assignments: [] module.exports = WizardStepInputs
[ { "context": " : \"(555) 123-4567\"\n \"contact person\": \"JOHN DOE\"\n \"title\" : \"WWW Widgets Associati", "end": 354, "score": 0.9998860359191895, "start": 346, "tag": "NAME", "value": "JOHN DOE" }, { "context": "Profile.aspx?applid=9\"\n \"email\" : \"somebody@github.com\"\n \"description\" : \"The WWW Widgets Assoc", "end": 651, "score": 0.9996665120124817, "start": 632, "tag": "EMAIL", "value": "somebody@github.com" }, { "context": "be.true()\n it \"should export email field\", -> /somebody@github\\.com/.test(@csv).should.be.true()\n it \"should expor", "end": 1713, "score": 0.950519323348999, "start": 1693, "tag": "EMAIL", "value": "somebody@github\\.com" }, { "context": "\n it \"should export contact person field\", -> /JOHN DOE/.test(@csv).should.be.true()\n it \"should expor", "end": 1800, "score": 0.9996823668479919, "start": 1792, "tag": "NAME", "value": "JOHN DOE" }, { "context": "ld\", -> /The WWW Widgets Association\\.\\.\\./.test(@csv).should.be.true()\n", "end": 2249, "score": 0.576114296913147, "start": 2246, "tag": "USERNAME", "value": "csv" } ]
test/issue-13.coffee
rodolforios/json-csv
3
jsoncsv = require '../index' should = require "should" describe.skip "Issue 13", -> describe "When exporting fields containing literal periods as opposed to object separators", -> before (done) -> @items = [{ "website url" : "http ://www.somewhere.com" "phone no." : "(555) 123-4567" "contact person": "JOHN DOE" "title" : "WWW Widgets Association Inc." "service area" : "KANSAS CITY" "address" : "123 MAIN ST KANSAS CITY, MO 64145" "hcr_data_url" : "https://github.com/LocalHousingOrgLists/Profile.aspx?applid=9" "email" : "somebody@github.com" "description" : "The WWW Widgets Association..." }] @options = [ {name: 'title', label: 'org name'} {name: 'website url', label: 'website'} {name: 'email', label: 'email'} {name: 'phone no.', label: 'phone'} {name: 'contact person', label: 'contact person'} {name: 'service area', label: 'service area'} {name: 'address', label: 'address'} {name: 'hcr_data_url', label: 'hcr url'} {name: 'description', label: 'description'} ] jsoncsv.csvBuffered @items, {fields: @options}, (err, csv) => @csv = csv @err = err done() it "should export correct header row", -> /^org name,website,email,phone,contact person,service area,address,hcr url,description\r\n/.test(@csv).should.be.true() it "should export phone field", -> /\(555\) 123-4567/.test(@csv).should.be.true() it "should export title field", -> /WWW Widgets Association Inc\./.test(@csv).should.be.true() it "should export email field", -> /somebody@github\.com/.test(@csv).should.be.true() it "should export contact person field", -> /JOHN DOE/.test(@csv).should.be.true() it "should export service area field", -> /KANSAS CITY/.test(@csv).should.be.true() it "should export address field", -> /123 MAIN ST KANSAS CITY, MO 64145/.test(@csv).should.be.true() it "should export hcr field", -> /https:\/\/github\.com\/LocalHousingOrgLists\/Profile\.aspx\?applid=9/.test(@csv).should.be.true() it "should export description field", -> /The WWW Widgets Association\.\.\./.test(@csv).should.be.true()
150377
jsoncsv = require '../index' should = require "should" describe.skip "Issue 13", -> describe "When exporting fields containing literal periods as opposed to object separators", -> before (done) -> @items = [{ "website url" : "http ://www.somewhere.com" "phone no." : "(555) 123-4567" "contact person": "<NAME>" "title" : "WWW Widgets Association Inc." "service area" : "KANSAS CITY" "address" : "123 MAIN ST KANSAS CITY, MO 64145" "hcr_data_url" : "https://github.com/LocalHousingOrgLists/Profile.aspx?applid=9" "email" : "<EMAIL>" "description" : "The WWW Widgets Association..." }] @options = [ {name: 'title', label: 'org name'} {name: 'website url', label: 'website'} {name: 'email', label: 'email'} {name: 'phone no.', label: 'phone'} {name: 'contact person', label: 'contact person'} {name: 'service area', label: 'service area'} {name: 'address', label: 'address'} {name: 'hcr_data_url', label: 'hcr url'} {name: 'description', label: 'description'} ] jsoncsv.csvBuffered @items, {fields: @options}, (err, csv) => @csv = csv @err = err done() it "should export correct header row", -> /^org name,website,email,phone,contact person,service area,address,hcr url,description\r\n/.test(@csv).should.be.true() it "should export phone field", -> /\(555\) 123-4567/.test(@csv).should.be.true() it "should export title field", -> /WWW Widgets Association Inc\./.test(@csv).should.be.true() it "should export email field", -> /<EMAIL>/.test(@csv).should.be.true() it "should export contact person field", -> /<NAME>/.test(@csv).should.be.true() it "should export service area field", -> /KANSAS CITY/.test(@csv).should.be.true() it "should export address field", -> /123 MAIN ST KANSAS CITY, MO 64145/.test(@csv).should.be.true() it "should export hcr field", -> /https:\/\/github\.com\/LocalHousingOrgLists\/Profile\.aspx\?applid=9/.test(@csv).should.be.true() it "should export description field", -> /The WWW Widgets Association\.\.\./.test(@csv).should.be.true()
true
jsoncsv = require '../index' should = require "should" describe.skip "Issue 13", -> describe "When exporting fields containing literal periods as opposed to object separators", -> before (done) -> @items = [{ "website url" : "http ://www.somewhere.com" "phone no." : "(555) 123-4567" "contact person": "PI:NAME:<NAME>END_PI" "title" : "WWW Widgets Association Inc." "service area" : "KANSAS CITY" "address" : "123 MAIN ST KANSAS CITY, MO 64145" "hcr_data_url" : "https://github.com/LocalHousingOrgLists/Profile.aspx?applid=9" "email" : "PI:EMAIL:<EMAIL>END_PI" "description" : "The WWW Widgets Association..." }] @options = [ {name: 'title', label: 'org name'} {name: 'website url', label: 'website'} {name: 'email', label: 'email'} {name: 'phone no.', label: 'phone'} {name: 'contact person', label: 'contact person'} {name: 'service area', label: 'service area'} {name: 'address', label: 'address'} {name: 'hcr_data_url', label: 'hcr url'} {name: 'description', label: 'description'} ] jsoncsv.csvBuffered @items, {fields: @options}, (err, csv) => @csv = csv @err = err done() it "should export correct header row", -> /^org name,website,email,phone,contact person,service area,address,hcr url,description\r\n/.test(@csv).should.be.true() it "should export phone field", -> /\(555\) 123-4567/.test(@csv).should.be.true() it "should export title field", -> /WWW Widgets Association Inc\./.test(@csv).should.be.true() it "should export email field", -> /PI:EMAIL:<EMAIL>END_PI/.test(@csv).should.be.true() it "should export contact person field", -> /PI:NAME:<NAME>END_PI/.test(@csv).should.be.true() it "should export service area field", -> /KANSAS CITY/.test(@csv).should.be.true() it "should export address field", -> /123 MAIN ST KANSAS CITY, MO 64145/.test(@csv).should.be.true() it "should export hcr field", -> /https:\/\/github\.com\/LocalHousingOrgLists\/Profile\.aspx\?applid=9/.test(@csv).should.be.true() it "should export description field", -> /The WWW Widgets Association\.\.\./.test(@csv).should.be.true()
[ { "context": "ocessor\n\nasp = new ASP {}\nbundle = null\nuserid = 'maxtaco@keybase.io'\nmaster_passphrase = Buffer.from 'so long and tha", "end": 465, "score": 0.9999043345451355, "start": 447, "tag": "EMAIL", "value": "maxtaco@keybase.io" }, { "context": "taco@keybase.io'\nmaster_passphrase = Buffer.from 'so long and thanks for all the fish', \"utf8\"\ntsenc = null\nopenpgp_pass = null\npgp_pri", "end": 535, "score": 0.9873390793800354, "start": 500, "tag": "PASSWORD", "value": "so long and thanks for all the fish" }, { "context": "rr\n T.no_error err\n unless err?\n passphrase = openpgp_pass\n await bundle.export_pgp_private { passphrase,", "end": 1724, "score": 0.9931017756462097, "start": 1712, "tag": "PASSWORD", "value": "openpgp_pass" }, { "context": "2 has a private half but is locked\"\n bad_pass = \"a\" + openpgp_pass\n await b2.unlock_pgp { passphrase : bad_pass }, ", "end": 2853, "score": 0.9566888809204102, "start": 2836, "tag": "PASSWORD", "value": "a\" + openpgp_pass" }, { "context": "bad password\"\n await b2.unlock_pgp { passphrase : openpgp_pass }, defer err\n T.no_error err\n T.assert (not b2.", "end": 3045, "score": 0.8670800924301147, "start": 3033, "tag": "PASSWORD", "value": "openpgp_pass" }, { "context": "_flags\n expire_in = 100\n args = {\n userid: \"<test@example.org>\"\n primary :\n algo: ecc.EDDSA\n flags", "end": 4853, "score": 0.9999091029167175, "start": 4837, "tag": "EMAIL", "value": "test@example.org" }, { "context": ".key_flags\n args = {\n userid: 'keymanager.iced test'\n primary: { flags: F.sign_data | F.certify_ke", "end": 6126, "score": 0.6422681212425232, "start": 6122, "tag": "USERNAME", "value": "test" } ]
test/files/keymanager.iced
samkenxstream/kbpgp
464
kbpgp = require '../../' {kb,KeyManager} = kbpgp {bufferify,ASP} = require '../../lib/util' {make_esc} = require 'iced-error' util = require 'util' {box} = require '../../lib/keybase/encode' {Encryptor} = require 'triplesec' {base91} = require '../../lib/basex' example_keys = (require '../data/keys.iced').keys C = require '../../lib/const' ecc = require '../../lib/ecc/main' {Message} = kbpgp.processor asp = new ASP {} bundle = null userid = 'maxtaco@keybase.io' master_passphrase = Buffer.from 'so long and thanks for all the fish', "utf8" tsenc = null openpgp_pass = null pgp_private = null b2 = null b3 = null compare_keys = (T, k1, k2, what) -> T.equal k1.ekid().toString('hex'), k2.ekid().toString('hex'), "#{what} keys match" compare_bundles = (T, b1, b2) -> compare_keys T, b1.primary, b2.primary, "primary" compare_keys T, b1.subkeys[0], b2. subkeys[0], "subkeys[0]" sanity_check = (T, bundle, cb) -> await bundle.primary.key.sanity_check defer err T.no_error err await bundle.subkeys[0].key.sanity_check defer err T.no_error err cb() exports.step1_generate = (T,cb) -> await KeyManager.generate { asp, nbits : 1024, nsubs : 1, userid }, defer err, tmp bundle = tmp T.no_error err await sanity_check T, bundle, defer err cb() exports.step2_salt_triplesec = (T, cb) -> tsenc = new Encryptor { key : master_passphrase, version : 3 } len = 12 await tsenc.resalt { extra_keymaterial : len}, defer err, keys T.no_error err openpgp_pass = base91.encode keys.extra[0...len] T.waypoint "new OpenPGP password: #{openpgp_pass}" cb() exports.step3_export_pgp_private = (T,cb) -> await bundle.sign { asp }, defer err T.no_error err unless err? passphrase = openpgp_pass await bundle.export_pgp_private { passphrase, asp }, defer err, msg T.no_error err unless err? T.waypoint "Generated new PGP Private key: #{msg.split(/\n/)[0...2].join(' ')}" pgp_private = msg cb() exports.step4_import_pgp_public = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : pgp_private, asp, userid}, defer err, tmp b2 = tmp T.no_error err unless err? compare_bundles T, bundle, b2 cb() exports.step4a_test_failed_private_merge = (T,cb) -> await bundle.export_pgp_public {}, defer err, pub await KeyManager.import_from_armored_pgp { raw : pub }, defer err, b3 T.no_error err await b3.merge_pgp_private { raw : pub }, defer err T.assert err?, "error came back" T.assert (err.toString().indexOf("no private key material found after merge") > 0), "the right error message" cb() exports.step5_merge_pgp_private = (T,cb) -> await b2.merge_pgp_private { raw : pgp_private, asp }, defer err T.no_error err T.assert b2.has_pgp_private(), "b2 has a private half" T.assert b2.is_pgp_locked(), "b2 has a private half but is locked" bad_pass = "a" + openpgp_pass await b2.unlock_pgp { passphrase : bad_pass }, defer err T.assert err?, "we should have gotten an error when opening with a bad password" await b2.unlock_pgp { passphrase : openpgp_pass }, defer err T.no_error err T.assert (not b2.is_pgp_locked()), "unlocked b2 successfully" await sanity_check T, b2, defer err cb() exports.step6_export_p3skb_private = (T,cb) -> await bundle.export_private_to_server { tsenc, asp }, defer err, p3skb T.no_error err await KeyManager.import_from_p3skb { raw : p3skb, asp }, defer err, tmp T.no_error err b3 = tmp T.assert b3.has_p3skb_private(), "b3 has keybase private part" T.assert b3.is_p3skb_locked(), "b3 is still locked" bad_pass = Buffer.concat [ master_passphrase, (Buffer.from "yo")] bad_tsenc = new Encryptor { key : bad_pass, version : 3 } await b3.unlock_p3skb { tsenc : bad_tsenc, asp }, defer err T.assert b3.is_p3skb_locked(), "b3 is still locked" T.assert err?, "failed to decrypt w/ bad passphrase" await b3.unlock_p3skb { tsenc, asp }, defer err T.no_error err T.assert (not b3.is_p3skb_locked()), "b3 is unlocked" await sanity_check T, b3, defer err compare_bundles T, bundle, b3 T.no_error err cb() exports.pgp_full_hash = (T,cb) -> now = Math.floor(new Date(2015, 9, 10)/1000) opts = { now } await KeyManager.import_from_armored_pgp { armored : example_keys.portwood, opts }, defer err, km T.no_error err await km.pgp_full_hash {}, defer err, hash T.no_error err T.assert hash == "5c31f2642b01d6beaf836999dafb54db59295a27a1e6e75665edc8db22691d90", "full hash doesn't match" cb() exports.pgp_full_hash_nacl = (T,cb) -> km = null await kb.KeyManager.generate {}, T.esc(defer(km), cb) await km.pgp_full_hash {}, T.esc(defer(res), cb) T.assert not res?, "null value back" cb() exports.change_key_and_reexport = (T, cb) -> esc = make_esc cb, "change_key_and_reexport" km = null F = C.openpgp.key_flags expire_in = 100 args = { userid: "<test@example.org>" primary : algo: ecc.EDDSA flags : F.certify_keys | F.sign_data | F.auth expire_in : expire_in subkeys : [ { flags : F.encrypt_storage | F.encrypt_comm expire_in : 0 algo : ecc.ECDH curve_name : 'Curve25519' } ] } await KeyManager.generate args, esc defer km await km.sign {}, esc defer() await km.export_public {}, esc defer armored await KeyManager.import_from_armored_pgp { armored }, esc defer() # Extend expiration, resign, re-export, and try to import again. km.clear_pgp_internal_sigs() km.pgp.primary.lifespan.expire_in = 200 km.pgp.subkeys[0].lifespan.expire_in = 100 await km.sign {}, esc defer() await km.export_public { regen : true }, T.esc(defer(armored), cb) await KeyManager.import_from_armored_pgp { armored }, esc defer km2 T.assert km2.primary._pgp.get_expire_time().expire_in is 200, "got correct expiration on primary" T.assert km2.subkeys[0]._pgp.get_expire_time().expire_in is 100, "got correct expiration on subkey" cb null {Signature, EmbeddedSignature} = require '../../lib/openpgp/packet/signature' exports.generate_key_default_hash = (T, cb) -> esc = make_esc cb F = C.openpgp.key_flags args = { userid: 'keymanager.iced test' primary: { flags: F.sign_data | F.certify_keys, algo : ecc.EDDSA } subkeys: [ { flags: F.sign_data, algo : ecc.ECDSA } { flags: F.encrypt_storage | F.encrypt_conn, algo : ecc.ECDH, curve_name: 'NIST P-384' } ] } await KeyManager.generate args, esc defer km await km.sign {}, esc defer() await km.export_public {}, esc defer armored # Expect default hash to be SHA512 hasher = kbpgp.hash.SHA512 # Decode armored key, make sure the hasher is correct in # all signatures and embedded signatures. [err,msg] = kbpgp.armor.decode armored T.no_error err processor = new Message {} await processor.parse_and_inflate msg.body, esc defer() for pkt in processor.packets when pkt instanceof Signature T.equal pkt.hasher.klass, hasher.klass T.equal pkt.hasher.algname, hasher.algname T.equal pkt.hasher.type, hasher.type for subpkt in (pkt.unhashed_subpackets ? []) when subpkt instanceof EmbeddedSignature {sig} = subpkt T.equal sig.hasher.klass, hasher.klass T.equal sig.hasher.algname, hasher.algname T.equal sig.hasher.type, hasher.type cb null exports.sign_key_with_hasher = (T, cb) -> esc = make_esc cb F = C.openpgp.key_flags args = { userid: 'keymanager.iced test' primary: { flags: F.sign_data | F.certify_keys, algo : ecc.EDDSA } subkeys: [ { flags: F.sign_data, algo : ecc.ECDSA } { flags: F.encrypt_storage | F.encrypt_conn, algo : ecc.ECDH, curve_name: 'NIST P-384' } ] } hasher = kbpgp.hash.SHA1 await KeyManager.generate args, esc defer km # Set hasher to SHA1 in primary key and subkeys. for key in [km.primary].concat(km.subkeys) key = km.pgp.key(key) T.assert key.hasher is null key.hasher = hasher # Signing should use SHA1 for self signature and subkey # signatures (as well as primary sigs from subkeys). await km.sign {}, esc defer() await km.export_public {}, esc defer armored # Decode armored key, make sure the hasher is correct in # all signatures and embedded signatures. [err,msg] = kbpgp.armor.decode armored T.no_error err processor = new Message {} await processor.parse_and_inflate msg.body, esc defer() for pkt in processor.packets when pkt instanceof Signature T.equal pkt.hasher.klass, hasher.klass T.equal pkt.hasher.algname, hasher.algname T.equal pkt.hasher.type, hasher.type for subpkt in (pkt.unhashed_subpackets ? []) when subpkt instanceof EmbeddedSignature {sig} = subpkt T.equal sig.hasher.klass, hasher.klass T.equal sig.hasher.algname, hasher.algname T.equal sig.hasher.type, hasher.type assert_pgp_hash = (hasher) -> if hasher.algname is 'SHA1' T.assert hasher.klass is kbpgp.hash.SHA1.klass T.equal hasher.type, 2 new Error("signatures using SHA1 are not allowed") await KeyManager.import_from_armored_pgp { armored, opts: { assert_pgp_hash } }, defer err, km, warnings T.assert err?.message.indexOf("no valid primary key") >= 0 T.assert not km? warns = warnings?.warnings() ? [] T.equal warns.length, 3 for v,i in [1,3,5] T.assert warns[i].match(new RegExp("^Signature failure in packet #{v}")) T.assert warns[i].indexOf("signatures using SHA1 are not allowed") >= 0 cb null
130251
kbpgp = require '../../' {kb,KeyManager} = kbpgp {bufferify,ASP} = require '../../lib/util' {make_esc} = require 'iced-error' util = require 'util' {box} = require '../../lib/keybase/encode' {Encryptor} = require 'triplesec' {base91} = require '../../lib/basex' example_keys = (require '../data/keys.iced').keys C = require '../../lib/const' ecc = require '../../lib/ecc/main' {Message} = kbpgp.processor asp = new ASP {} bundle = null userid = '<EMAIL>' master_passphrase = Buffer.from '<PASSWORD>', "utf8" tsenc = null openpgp_pass = null pgp_private = null b2 = null b3 = null compare_keys = (T, k1, k2, what) -> T.equal k1.ekid().toString('hex'), k2.ekid().toString('hex'), "#{what} keys match" compare_bundles = (T, b1, b2) -> compare_keys T, b1.primary, b2.primary, "primary" compare_keys T, b1.subkeys[0], b2. subkeys[0], "subkeys[0]" sanity_check = (T, bundle, cb) -> await bundle.primary.key.sanity_check defer err T.no_error err await bundle.subkeys[0].key.sanity_check defer err T.no_error err cb() exports.step1_generate = (T,cb) -> await KeyManager.generate { asp, nbits : 1024, nsubs : 1, userid }, defer err, tmp bundle = tmp T.no_error err await sanity_check T, bundle, defer err cb() exports.step2_salt_triplesec = (T, cb) -> tsenc = new Encryptor { key : master_passphrase, version : 3 } len = 12 await tsenc.resalt { extra_keymaterial : len}, defer err, keys T.no_error err openpgp_pass = base91.encode keys.extra[0...len] T.waypoint "new OpenPGP password: #{openpgp_pass}" cb() exports.step3_export_pgp_private = (T,cb) -> await bundle.sign { asp }, defer err T.no_error err unless err? passphrase = <PASSWORD> await bundle.export_pgp_private { passphrase, asp }, defer err, msg T.no_error err unless err? T.waypoint "Generated new PGP Private key: #{msg.split(/\n/)[0...2].join(' ')}" pgp_private = msg cb() exports.step4_import_pgp_public = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : pgp_private, asp, userid}, defer err, tmp b2 = tmp T.no_error err unless err? compare_bundles T, bundle, b2 cb() exports.step4a_test_failed_private_merge = (T,cb) -> await bundle.export_pgp_public {}, defer err, pub await KeyManager.import_from_armored_pgp { raw : pub }, defer err, b3 T.no_error err await b3.merge_pgp_private { raw : pub }, defer err T.assert err?, "error came back" T.assert (err.toString().indexOf("no private key material found after merge") > 0), "the right error message" cb() exports.step5_merge_pgp_private = (T,cb) -> await b2.merge_pgp_private { raw : pgp_private, asp }, defer err T.no_error err T.assert b2.has_pgp_private(), "b2 has a private half" T.assert b2.is_pgp_locked(), "b2 has a private half but is locked" bad_pass = "<PASSWORD> await b2.unlock_pgp { passphrase : bad_pass }, defer err T.assert err?, "we should have gotten an error when opening with a bad password" await b2.unlock_pgp { passphrase : <PASSWORD> }, defer err T.no_error err T.assert (not b2.is_pgp_locked()), "unlocked b2 successfully" await sanity_check T, b2, defer err cb() exports.step6_export_p3skb_private = (T,cb) -> await bundle.export_private_to_server { tsenc, asp }, defer err, p3skb T.no_error err await KeyManager.import_from_p3skb { raw : p3skb, asp }, defer err, tmp T.no_error err b3 = tmp T.assert b3.has_p3skb_private(), "b3 has keybase private part" T.assert b3.is_p3skb_locked(), "b3 is still locked" bad_pass = Buffer.concat [ master_passphrase, (Buffer.from "yo")] bad_tsenc = new Encryptor { key : bad_pass, version : 3 } await b3.unlock_p3skb { tsenc : bad_tsenc, asp }, defer err T.assert b3.is_p3skb_locked(), "b3 is still locked" T.assert err?, "failed to decrypt w/ bad passphrase" await b3.unlock_p3skb { tsenc, asp }, defer err T.no_error err T.assert (not b3.is_p3skb_locked()), "b3 is unlocked" await sanity_check T, b3, defer err compare_bundles T, bundle, b3 T.no_error err cb() exports.pgp_full_hash = (T,cb) -> now = Math.floor(new Date(2015, 9, 10)/1000) opts = { now } await KeyManager.import_from_armored_pgp { armored : example_keys.portwood, opts }, defer err, km T.no_error err await km.pgp_full_hash {}, defer err, hash T.no_error err T.assert hash == "5c31f2642b01d6beaf836999dafb54db59295a27a1e6e75665edc8db22691d90", "full hash doesn't match" cb() exports.pgp_full_hash_nacl = (T,cb) -> km = null await kb.KeyManager.generate {}, T.esc(defer(km), cb) await km.pgp_full_hash {}, T.esc(defer(res), cb) T.assert not res?, "null value back" cb() exports.change_key_and_reexport = (T, cb) -> esc = make_esc cb, "change_key_and_reexport" km = null F = C.openpgp.key_flags expire_in = 100 args = { userid: "<<EMAIL>>" primary : algo: ecc.EDDSA flags : F.certify_keys | F.sign_data | F.auth expire_in : expire_in subkeys : [ { flags : F.encrypt_storage | F.encrypt_comm expire_in : 0 algo : ecc.ECDH curve_name : 'Curve25519' } ] } await KeyManager.generate args, esc defer km await km.sign {}, esc defer() await km.export_public {}, esc defer armored await KeyManager.import_from_armored_pgp { armored }, esc defer() # Extend expiration, resign, re-export, and try to import again. km.clear_pgp_internal_sigs() km.pgp.primary.lifespan.expire_in = 200 km.pgp.subkeys[0].lifespan.expire_in = 100 await km.sign {}, esc defer() await km.export_public { regen : true }, T.esc(defer(armored), cb) await KeyManager.import_from_armored_pgp { armored }, esc defer km2 T.assert km2.primary._pgp.get_expire_time().expire_in is 200, "got correct expiration on primary" T.assert km2.subkeys[0]._pgp.get_expire_time().expire_in is 100, "got correct expiration on subkey" cb null {Signature, EmbeddedSignature} = require '../../lib/openpgp/packet/signature' exports.generate_key_default_hash = (T, cb) -> esc = make_esc cb F = C.openpgp.key_flags args = { userid: 'keymanager.iced test' primary: { flags: F.sign_data | F.certify_keys, algo : ecc.EDDSA } subkeys: [ { flags: F.sign_data, algo : ecc.ECDSA } { flags: F.encrypt_storage | F.encrypt_conn, algo : ecc.ECDH, curve_name: 'NIST P-384' } ] } await KeyManager.generate args, esc defer km await km.sign {}, esc defer() await km.export_public {}, esc defer armored # Expect default hash to be SHA512 hasher = kbpgp.hash.SHA512 # Decode armored key, make sure the hasher is correct in # all signatures and embedded signatures. [err,msg] = kbpgp.armor.decode armored T.no_error err processor = new Message {} await processor.parse_and_inflate msg.body, esc defer() for pkt in processor.packets when pkt instanceof Signature T.equal pkt.hasher.klass, hasher.klass T.equal pkt.hasher.algname, hasher.algname T.equal pkt.hasher.type, hasher.type for subpkt in (pkt.unhashed_subpackets ? []) when subpkt instanceof EmbeddedSignature {sig} = subpkt T.equal sig.hasher.klass, hasher.klass T.equal sig.hasher.algname, hasher.algname T.equal sig.hasher.type, hasher.type cb null exports.sign_key_with_hasher = (T, cb) -> esc = make_esc cb F = C.openpgp.key_flags args = { userid: 'keymanager.iced test' primary: { flags: F.sign_data | F.certify_keys, algo : ecc.EDDSA } subkeys: [ { flags: F.sign_data, algo : ecc.ECDSA } { flags: F.encrypt_storage | F.encrypt_conn, algo : ecc.ECDH, curve_name: 'NIST P-384' } ] } hasher = kbpgp.hash.SHA1 await KeyManager.generate args, esc defer km # Set hasher to SHA1 in primary key and subkeys. for key in [km.primary].concat(km.subkeys) key = km.pgp.key(key) T.assert key.hasher is null key.hasher = hasher # Signing should use SHA1 for self signature and subkey # signatures (as well as primary sigs from subkeys). await km.sign {}, esc defer() await km.export_public {}, esc defer armored # Decode armored key, make sure the hasher is correct in # all signatures and embedded signatures. [err,msg] = kbpgp.armor.decode armored T.no_error err processor = new Message {} await processor.parse_and_inflate msg.body, esc defer() for pkt in processor.packets when pkt instanceof Signature T.equal pkt.hasher.klass, hasher.klass T.equal pkt.hasher.algname, hasher.algname T.equal pkt.hasher.type, hasher.type for subpkt in (pkt.unhashed_subpackets ? []) when subpkt instanceof EmbeddedSignature {sig} = subpkt T.equal sig.hasher.klass, hasher.klass T.equal sig.hasher.algname, hasher.algname T.equal sig.hasher.type, hasher.type assert_pgp_hash = (hasher) -> if hasher.algname is 'SHA1' T.assert hasher.klass is kbpgp.hash.SHA1.klass T.equal hasher.type, 2 new Error("signatures using SHA1 are not allowed") await KeyManager.import_from_armored_pgp { armored, opts: { assert_pgp_hash } }, defer err, km, warnings T.assert err?.message.indexOf("no valid primary key") >= 0 T.assert not km? warns = warnings?.warnings() ? [] T.equal warns.length, 3 for v,i in [1,3,5] T.assert warns[i].match(new RegExp("^Signature failure in packet #{v}")) T.assert warns[i].indexOf("signatures using SHA1 are not allowed") >= 0 cb null
true
kbpgp = require '../../' {kb,KeyManager} = kbpgp {bufferify,ASP} = require '../../lib/util' {make_esc} = require 'iced-error' util = require 'util' {box} = require '../../lib/keybase/encode' {Encryptor} = require 'triplesec' {base91} = require '../../lib/basex' example_keys = (require '../data/keys.iced').keys C = require '../../lib/const' ecc = require '../../lib/ecc/main' {Message} = kbpgp.processor asp = new ASP {} bundle = null userid = 'PI:EMAIL:<EMAIL>END_PI' master_passphrase = Buffer.from 'PI:PASSWORD:<PASSWORD>END_PI', "utf8" tsenc = null openpgp_pass = null pgp_private = null b2 = null b3 = null compare_keys = (T, k1, k2, what) -> T.equal k1.ekid().toString('hex'), k2.ekid().toString('hex'), "#{what} keys match" compare_bundles = (T, b1, b2) -> compare_keys T, b1.primary, b2.primary, "primary" compare_keys T, b1.subkeys[0], b2. subkeys[0], "subkeys[0]" sanity_check = (T, bundle, cb) -> await bundle.primary.key.sanity_check defer err T.no_error err await bundle.subkeys[0].key.sanity_check defer err T.no_error err cb() exports.step1_generate = (T,cb) -> await KeyManager.generate { asp, nbits : 1024, nsubs : 1, userid }, defer err, tmp bundle = tmp T.no_error err await sanity_check T, bundle, defer err cb() exports.step2_salt_triplesec = (T, cb) -> tsenc = new Encryptor { key : master_passphrase, version : 3 } len = 12 await tsenc.resalt { extra_keymaterial : len}, defer err, keys T.no_error err openpgp_pass = base91.encode keys.extra[0...len] T.waypoint "new OpenPGP password: #{openpgp_pass}" cb() exports.step3_export_pgp_private = (T,cb) -> await bundle.sign { asp }, defer err T.no_error err unless err? passphrase = PI:PASSWORD:<PASSWORD>END_PI await bundle.export_pgp_private { passphrase, asp }, defer err, msg T.no_error err unless err? T.waypoint "Generated new PGP Private key: #{msg.split(/\n/)[0...2].join(' ')}" pgp_private = msg cb() exports.step4_import_pgp_public = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : pgp_private, asp, userid}, defer err, tmp b2 = tmp T.no_error err unless err? compare_bundles T, bundle, b2 cb() exports.step4a_test_failed_private_merge = (T,cb) -> await bundle.export_pgp_public {}, defer err, pub await KeyManager.import_from_armored_pgp { raw : pub }, defer err, b3 T.no_error err await b3.merge_pgp_private { raw : pub }, defer err T.assert err?, "error came back" T.assert (err.toString().indexOf("no private key material found after merge") > 0), "the right error message" cb() exports.step5_merge_pgp_private = (T,cb) -> await b2.merge_pgp_private { raw : pgp_private, asp }, defer err T.no_error err T.assert b2.has_pgp_private(), "b2 has a private half" T.assert b2.is_pgp_locked(), "b2 has a private half but is locked" bad_pass = "PI:PASSWORD:<PASSWORD>END_PI await b2.unlock_pgp { passphrase : bad_pass }, defer err T.assert err?, "we should have gotten an error when opening with a bad password" await b2.unlock_pgp { passphrase : PI:PASSWORD:<PASSWORD>END_PI }, defer err T.no_error err T.assert (not b2.is_pgp_locked()), "unlocked b2 successfully" await sanity_check T, b2, defer err cb() exports.step6_export_p3skb_private = (T,cb) -> await bundle.export_private_to_server { tsenc, asp }, defer err, p3skb T.no_error err await KeyManager.import_from_p3skb { raw : p3skb, asp }, defer err, tmp T.no_error err b3 = tmp T.assert b3.has_p3skb_private(), "b3 has keybase private part" T.assert b3.is_p3skb_locked(), "b3 is still locked" bad_pass = Buffer.concat [ master_passphrase, (Buffer.from "yo")] bad_tsenc = new Encryptor { key : bad_pass, version : 3 } await b3.unlock_p3skb { tsenc : bad_tsenc, asp }, defer err T.assert b3.is_p3skb_locked(), "b3 is still locked" T.assert err?, "failed to decrypt w/ bad passphrase" await b3.unlock_p3skb { tsenc, asp }, defer err T.no_error err T.assert (not b3.is_p3skb_locked()), "b3 is unlocked" await sanity_check T, b3, defer err compare_bundles T, bundle, b3 T.no_error err cb() exports.pgp_full_hash = (T,cb) -> now = Math.floor(new Date(2015, 9, 10)/1000) opts = { now } await KeyManager.import_from_armored_pgp { armored : example_keys.portwood, opts }, defer err, km T.no_error err await km.pgp_full_hash {}, defer err, hash T.no_error err T.assert hash == "5c31f2642b01d6beaf836999dafb54db59295a27a1e6e75665edc8db22691d90", "full hash doesn't match" cb() exports.pgp_full_hash_nacl = (T,cb) -> km = null await kb.KeyManager.generate {}, T.esc(defer(km), cb) await km.pgp_full_hash {}, T.esc(defer(res), cb) T.assert not res?, "null value back" cb() exports.change_key_and_reexport = (T, cb) -> esc = make_esc cb, "change_key_and_reexport" km = null F = C.openpgp.key_flags expire_in = 100 args = { userid: "<PI:EMAIL:<EMAIL>END_PI>" primary : algo: ecc.EDDSA flags : F.certify_keys | F.sign_data | F.auth expire_in : expire_in subkeys : [ { flags : F.encrypt_storage | F.encrypt_comm expire_in : 0 algo : ecc.ECDH curve_name : 'Curve25519' } ] } await KeyManager.generate args, esc defer km await km.sign {}, esc defer() await km.export_public {}, esc defer armored await KeyManager.import_from_armored_pgp { armored }, esc defer() # Extend expiration, resign, re-export, and try to import again. km.clear_pgp_internal_sigs() km.pgp.primary.lifespan.expire_in = 200 km.pgp.subkeys[0].lifespan.expire_in = 100 await km.sign {}, esc defer() await km.export_public { regen : true }, T.esc(defer(armored), cb) await KeyManager.import_from_armored_pgp { armored }, esc defer km2 T.assert km2.primary._pgp.get_expire_time().expire_in is 200, "got correct expiration on primary" T.assert km2.subkeys[0]._pgp.get_expire_time().expire_in is 100, "got correct expiration on subkey" cb null {Signature, EmbeddedSignature} = require '../../lib/openpgp/packet/signature' exports.generate_key_default_hash = (T, cb) -> esc = make_esc cb F = C.openpgp.key_flags args = { userid: 'keymanager.iced test' primary: { flags: F.sign_data | F.certify_keys, algo : ecc.EDDSA } subkeys: [ { flags: F.sign_data, algo : ecc.ECDSA } { flags: F.encrypt_storage | F.encrypt_conn, algo : ecc.ECDH, curve_name: 'NIST P-384' } ] } await KeyManager.generate args, esc defer km await km.sign {}, esc defer() await km.export_public {}, esc defer armored # Expect default hash to be SHA512 hasher = kbpgp.hash.SHA512 # Decode armored key, make sure the hasher is correct in # all signatures and embedded signatures. [err,msg] = kbpgp.armor.decode armored T.no_error err processor = new Message {} await processor.parse_and_inflate msg.body, esc defer() for pkt in processor.packets when pkt instanceof Signature T.equal pkt.hasher.klass, hasher.klass T.equal pkt.hasher.algname, hasher.algname T.equal pkt.hasher.type, hasher.type for subpkt in (pkt.unhashed_subpackets ? []) when subpkt instanceof EmbeddedSignature {sig} = subpkt T.equal sig.hasher.klass, hasher.klass T.equal sig.hasher.algname, hasher.algname T.equal sig.hasher.type, hasher.type cb null exports.sign_key_with_hasher = (T, cb) -> esc = make_esc cb F = C.openpgp.key_flags args = { userid: 'keymanager.iced test' primary: { flags: F.sign_data | F.certify_keys, algo : ecc.EDDSA } subkeys: [ { flags: F.sign_data, algo : ecc.ECDSA } { flags: F.encrypt_storage | F.encrypt_conn, algo : ecc.ECDH, curve_name: 'NIST P-384' } ] } hasher = kbpgp.hash.SHA1 await KeyManager.generate args, esc defer km # Set hasher to SHA1 in primary key and subkeys. for key in [km.primary].concat(km.subkeys) key = km.pgp.key(key) T.assert key.hasher is null key.hasher = hasher # Signing should use SHA1 for self signature and subkey # signatures (as well as primary sigs from subkeys). await km.sign {}, esc defer() await km.export_public {}, esc defer armored # Decode armored key, make sure the hasher is correct in # all signatures and embedded signatures. [err,msg] = kbpgp.armor.decode armored T.no_error err processor = new Message {} await processor.parse_and_inflate msg.body, esc defer() for pkt in processor.packets when pkt instanceof Signature T.equal pkt.hasher.klass, hasher.klass T.equal pkt.hasher.algname, hasher.algname T.equal pkt.hasher.type, hasher.type for subpkt in (pkt.unhashed_subpackets ? []) when subpkt instanceof EmbeddedSignature {sig} = subpkt T.equal sig.hasher.klass, hasher.klass T.equal sig.hasher.algname, hasher.algname T.equal sig.hasher.type, hasher.type assert_pgp_hash = (hasher) -> if hasher.algname is 'SHA1' T.assert hasher.klass is kbpgp.hash.SHA1.klass T.equal hasher.type, 2 new Error("signatures using SHA1 are not allowed") await KeyManager.import_from_armored_pgp { armored, opts: { assert_pgp_hash } }, defer err, km, warnings T.assert err?.message.indexOf("no valid primary key") >= 0 T.assert not km? warns = warnings?.warnings() ? [] T.equal warns.length, 3 for v,i in [1,3,5] T.assert warns[i].match(new RegExp("^Signature failure in packet #{v}")) T.assert warns[i].indexOf("signatures using SHA1 are not allowed") >= 0 cb null
[ { "context": "# @fileoverview Tests for global-require\n# @author Jamund Ferguson\n###\n\n'use strict'\n\n#-----------------------------", "end": 71, "score": 0.9998663663864136, "start": 56, "tag": "NAME", "value": "Jamund Ferguson" } ]
src/tests/rules/global-require.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for global-require # @author Jamund Ferguson ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/global-require' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' valid = [ "x = require('y')" "if (x) then x.require('y')" "x; x = require('y')" ''' x = 1 y = require('y') ''' ''' x = require('y') y = require('y') z = require('z') ''' "x = require('y').foo" "require('y').foo()" "require('y')" ''' x = -> x() if x > y doSomething() x = require('y').foo ''' "logger = require(if DEBUG then 'dev-logger' else 'logger')" "logger = if DEBUG then require('dev-logger') else require('logger')" "localScopedRequire = (require) -> require('y')" ''' someFunc = require './someFunc' someFunc (require) -> 'bananas' ''' ] message = 'Unexpected require().' type = 'CallExpression' invalid = [ # block statements code: ''' if process.env.NODE_ENV is 'DEVELOPMENT' require('debug') ''' errors: [ { line: 2 column: 3 message type } ] , code: ''' x = null if (y) x = require('debug') ''' errors: [ { line: 3 column: 7 message type } ] , code: ''' x = null if y x = require('debug').baz ''' errors: [ { line: 3 column: 7 message type } ] , code: "x = -> require('y')" errors: [ { line: 1 column: 8 message type } ] , code: ''' try require('x') catch e console.log e ''' errors: [ { line: 2 column: 3 message type } ] , # non-block statements code: 'getModule = (x) => require(x)' errors: [ { line: 1 column: 20 message type } ] , code: "x = ((x) => require(x))('weird')" errors: [ { line: 1 column: 13 message type } ] , code: ''' switch x when '1' require('1') ''' errors: [ { line: 3 column: 5 message type } ] ] ruleTester.run 'global-require', rule, { valid invalid }
70844
###* # @fileoverview Tests for global-require # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/global-require' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' valid = [ "x = require('y')" "if (x) then x.require('y')" "x; x = require('y')" ''' x = 1 y = require('y') ''' ''' x = require('y') y = require('y') z = require('z') ''' "x = require('y').foo" "require('y').foo()" "require('y')" ''' x = -> x() if x > y doSomething() x = require('y').foo ''' "logger = require(if DEBUG then 'dev-logger' else 'logger')" "logger = if DEBUG then require('dev-logger') else require('logger')" "localScopedRequire = (require) -> require('y')" ''' someFunc = require './someFunc' someFunc (require) -> 'bananas' ''' ] message = 'Unexpected require().' type = 'CallExpression' invalid = [ # block statements code: ''' if process.env.NODE_ENV is 'DEVELOPMENT' require('debug') ''' errors: [ { line: 2 column: 3 message type } ] , code: ''' x = null if (y) x = require('debug') ''' errors: [ { line: 3 column: 7 message type } ] , code: ''' x = null if y x = require('debug').baz ''' errors: [ { line: 3 column: 7 message type } ] , code: "x = -> require('y')" errors: [ { line: 1 column: 8 message type } ] , code: ''' try require('x') catch e console.log e ''' errors: [ { line: 2 column: 3 message type } ] , # non-block statements code: 'getModule = (x) => require(x)' errors: [ { line: 1 column: 20 message type } ] , code: "x = ((x) => require(x))('weird')" errors: [ { line: 1 column: 13 message type } ] , code: ''' switch x when '1' require('1') ''' errors: [ { line: 3 column: 5 message type } ] ] ruleTester.run 'global-require', rule, { valid invalid }
true
###* # @fileoverview Tests for global-require # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/global-require' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' valid = [ "x = require('y')" "if (x) then x.require('y')" "x; x = require('y')" ''' x = 1 y = require('y') ''' ''' x = require('y') y = require('y') z = require('z') ''' "x = require('y').foo" "require('y').foo()" "require('y')" ''' x = -> x() if x > y doSomething() x = require('y').foo ''' "logger = require(if DEBUG then 'dev-logger' else 'logger')" "logger = if DEBUG then require('dev-logger') else require('logger')" "localScopedRequire = (require) -> require('y')" ''' someFunc = require './someFunc' someFunc (require) -> 'bananas' ''' ] message = 'Unexpected require().' type = 'CallExpression' invalid = [ # block statements code: ''' if process.env.NODE_ENV is 'DEVELOPMENT' require('debug') ''' errors: [ { line: 2 column: 3 message type } ] , code: ''' x = null if (y) x = require('debug') ''' errors: [ { line: 3 column: 7 message type } ] , code: ''' x = null if y x = require('debug').baz ''' errors: [ { line: 3 column: 7 message type } ] , code: "x = -> require('y')" errors: [ { line: 1 column: 8 message type } ] , code: ''' try require('x') catch e console.log e ''' errors: [ { line: 2 column: 3 message type } ] , # non-block statements code: 'getModule = (x) => require(x)' errors: [ { line: 1 column: 20 message type } ] , code: "x = ((x) => require(x))('weird')" errors: [ { line: 1 column: 13 message type } ] , code: ''' switch x when '1' require('1') ''' errors: [ { line: 3 column: 5 message type } ] ] ruleTester.run 'global-require', rule, { valid invalid }
[ { "context": "le: 'test'\n inspired: no\n users: [\n {email: 'house@gmail.com', name: 'house'}\n {email: 'cuddy@gmail.com', n", "end": 219, "score": 0.9999223947525024, "start": 204, "tag": "EMAIL", "value": "house@gmail.com" }, { "context": "\n users: [\n {email: 'house@gmail.com', name: 'house'}\n {email: 'cuddy@gmail.com', name: 'cuddy'}\n ", "end": 234, "score": 0.7401115298271179, "start": 229, "tag": "USERNAME", "value": "house" }, { "context": "l: 'house@gmail.com', name: 'house'}\n {email: 'cuddy@gmail.com', name: 'cuddy'}\n {email: 'wilson@gmail.com', ", "end": 265, "score": 0.9999280571937561, "start": 250, "tag": "EMAIL", "value": "cuddy@gmail.com" }, { "context": "e: 'house'}\n {email: 'cuddy@gmail.com', name: 'cuddy'}\n {email: 'wilson@gmail.com', name: 'wilson'}", "end": 280, "score": 0.8277727365493774, "start": 275, "tag": "NAME", "value": "cuddy" }, { "context": "l: 'cuddy@gmail.com', name: 'cuddy'}\n {email: 'wilson@gmail.com', name: 'wilson'}\n ]\n\ncoffeekup_template = ->\n ", "end": 312, "score": 0.9999285340309143, "start": 296, "tag": "EMAIL", "value": "wilson@gmail.com" }, { "context": ": 'cuddy'}\n {email: 'wilson@gmail.com', name: 'wilson'}\n ]\n\ncoffeekup_template = ->\n doctype 5\n html", "end": 328, "score": 0.9954839944839478, "start": 322, "tag": "NAME", "value": "wilson" } ]
wro4j-examples/wro4j-demo/src/main/webapp/static/coffee/benchmark.coffee
changcheng/wro4j
1
coffeekup = require './src/coffeekup' jade = require 'jade' ejs = require 'ejs' eco = require 'eco' haml = require 'haml' log = console.log data = title: 'test' inspired: no users: [ {email: 'house@gmail.com', name: 'house'} {email: 'cuddy@gmail.com', name: 'cuddy'} {email: 'wilson@gmail.com', name: 'wilson'} ] coffeekup_template = -> doctype 5 html lang: 'en', -> head -> meta charset: 'utf-8' title @title style ''' body {font-family: "sans-serif"} section, header {display: block} ''' body -> section -> header -> h1 @title if @inspired p 'Create a witty example' else p 'Go meta' ul -> for user in @users li user.name li -> a href: "mailto:#{user.email}", -> user.email coffeekup_string_template = """ doctype 5 html lang: 'en', -> head -> meta charset: 'utf-8' title @title style ''' body {font-family: "sans-serif"} section, header {display: block} ''' body -> section -> header -> h1 @title if @inspired p 'Create a witty example' else p 'Go meta' ul -> for user in @users li user.name li -> a href: "mailto:\#{user.email}", -> user.email """ coffeekup_compiled_template = coffeekup.compile coffeekup_template jade_template = ''' !!! 5 html(lang="en") head meta(charset="utf-8") title= title style | body {font-family: "sans-serif"} | section, header {display: block} body section header h1= title - if (inspired) p Create a witty example - else p Go meta ul - each user in users li= user.name li a(href="mailto:"+user.email)= user.email ''' jade_compiled_template = jade.compile jade_template ejs_template = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><%= title %></title> <style> body {font-family: "sans-serif"} section, header {display: block} </style> </head> <body> <section> <header> <h1><%= title %></h1> </header> <% if (inspired) { %> <p>Create a witty example</p> <% } else { %> <p>Go meta</p> <% } %> <ul> <% for (user in users) { %> <li><%= user.name %></li> <li><a href="mailto:<%= user.email %>"><%= user.email %></a></li> <% } %> </ul> </section> </body> </html> ''' eco_template = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><%= @title %></title> <style> body {font-family: "sans-serif"} section, header {display: block} </style> </head> <body> <section> <header> <h1><%= @title %></h1> </header> <% if @inspired: %> <p>Create a witty example</p> <% else: %> <p>Go meta</p> <% end %> <ul> <% for user in @users: %> <li><%= user.name %></li> <li><a href="mailto:<%= user.email %>"><%= user.email %></a></li> <% end %> </ul> </section> </body> </html> ''' haml_template = ''' !!! 5 %html{lang: "en"} %head %meta{charset: "utf-8"} %title= title :css body {font-family: "sans-serif"} section, header {display: block} %body %section %header %h1= title :if inspired %p Create a witty example :if !inspired %p Go meta %ul :each user in users %li= user.name %li %a{href: "mailto:#{user.email}"}= user.email ''' haml_template_compiled = haml(haml_template) benchmark = (title, code) -> start = new Date for i in [1..5000] code() log "#{title}: #{new Date - start} ms" @run = -> benchmark 'CoffeeKup (precompiled)', -> coffeekup_compiled_template data benchmark 'Jade (precompiled)', -> jade_compiled_template data benchmark 'haml-js (precompiled)', -> haml_template_compiled data benchmark 'Eco', -> eco.render eco_template, data console.log '\n' benchmark 'CoffeeKup (function, cache on)', -> coffeekup.render coffeekup_template, data, cache: on benchmark 'CoffeeKup (string, cache on)', -> coffeekup.render coffeekup_string_template, data, cache: on benchmark 'Jade (cache on)', -> jade.render jade_template, locals: data, cache: on, filename: 'test' benchmark 'ejs (cache on)', -> ejs.render ejs_template, locals: data, cache: on, filename: 'test' console.log '\n' benchmark 'CoffeeKup (function, cache off)', -> coffeekup.render coffeekup_template, data benchmark 'CoffeeKup (string, cache off)', -> coffeekup.render coffeekup_string_template, data, cache: off benchmark 'Jade (cache off)', -> jade.render jade_template, locals: data benchmark 'haml-js', -> haml.render haml_template, locals: data benchmark 'ejs (cache off)', -> ejs.render ejs_template, locals: data
222066
coffeekup = require './src/coffeekup' jade = require 'jade' ejs = require 'ejs' eco = require 'eco' haml = require 'haml' log = console.log data = title: 'test' inspired: no users: [ {email: '<EMAIL>', name: 'house'} {email: '<EMAIL>', name: '<NAME>'} {email: '<EMAIL>', name: '<NAME>'} ] coffeekup_template = -> doctype 5 html lang: 'en', -> head -> meta charset: 'utf-8' title @title style ''' body {font-family: "sans-serif"} section, header {display: block} ''' body -> section -> header -> h1 @title if @inspired p 'Create a witty example' else p 'Go meta' ul -> for user in @users li user.name li -> a href: "mailto:#{user.email}", -> user.email coffeekup_string_template = """ doctype 5 html lang: 'en', -> head -> meta charset: 'utf-8' title @title style ''' body {font-family: "sans-serif"} section, header {display: block} ''' body -> section -> header -> h1 @title if @inspired p 'Create a witty example' else p 'Go meta' ul -> for user in @users li user.name li -> a href: "mailto:\#{user.email}", -> user.email """ coffeekup_compiled_template = coffeekup.compile coffeekup_template jade_template = ''' !!! 5 html(lang="en") head meta(charset="utf-8") title= title style | body {font-family: "sans-serif"} | section, header {display: block} body section header h1= title - if (inspired) p Create a witty example - else p Go meta ul - each user in users li= user.name li a(href="mailto:"+user.email)= user.email ''' jade_compiled_template = jade.compile jade_template ejs_template = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><%= title %></title> <style> body {font-family: "sans-serif"} section, header {display: block} </style> </head> <body> <section> <header> <h1><%= title %></h1> </header> <% if (inspired) { %> <p>Create a witty example</p> <% } else { %> <p>Go meta</p> <% } %> <ul> <% for (user in users) { %> <li><%= user.name %></li> <li><a href="mailto:<%= user.email %>"><%= user.email %></a></li> <% } %> </ul> </section> </body> </html> ''' eco_template = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><%= @title %></title> <style> body {font-family: "sans-serif"} section, header {display: block} </style> </head> <body> <section> <header> <h1><%= @title %></h1> </header> <% if @inspired: %> <p>Create a witty example</p> <% else: %> <p>Go meta</p> <% end %> <ul> <% for user in @users: %> <li><%= user.name %></li> <li><a href="mailto:<%= user.email %>"><%= user.email %></a></li> <% end %> </ul> </section> </body> </html> ''' haml_template = ''' !!! 5 %html{lang: "en"} %head %meta{charset: "utf-8"} %title= title :css body {font-family: "sans-serif"} section, header {display: block} %body %section %header %h1= title :if inspired %p Create a witty example :if !inspired %p Go meta %ul :each user in users %li= user.name %li %a{href: "mailto:#{user.email}"}= user.email ''' haml_template_compiled = haml(haml_template) benchmark = (title, code) -> start = new Date for i in [1..5000] code() log "#{title}: #{new Date - start} ms" @run = -> benchmark 'CoffeeKup (precompiled)', -> coffeekup_compiled_template data benchmark 'Jade (precompiled)', -> jade_compiled_template data benchmark 'haml-js (precompiled)', -> haml_template_compiled data benchmark 'Eco', -> eco.render eco_template, data console.log '\n' benchmark 'CoffeeKup (function, cache on)', -> coffeekup.render coffeekup_template, data, cache: on benchmark 'CoffeeKup (string, cache on)', -> coffeekup.render coffeekup_string_template, data, cache: on benchmark 'Jade (cache on)', -> jade.render jade_template, locals: data, cache: on, filename: 'test' benchmark 'ejs (cache on)', -> ejs.render ejs_template, locals: data, cache: on, filename: 'test' console.log '\n' benchmark 'CoffeeKup (function, cache off)', -> coffeekup.render coffeekup_template, data benchmark 'CoffeeKup (string, cache off)', -> coffeekup.render coffeekup_string_template, data, cache: off benchmark 'Jade (cache off)', -> jade.render jade_template, locals: data benchmark 'haml-js', -> haml.render haml_template, locals: data benchmark 'ejs (cache off)', -> ejs.render ejs_template, locals: data
true
coffeekup = require './src/coffeekup' jade = require 'jade' ejs = require 'ejs' eco = require 'eco' haml = require 'haml' log = console.log data = title: 'test' inspired: no users: [ {email: 'PI:EMAIL:<EMAIL>END_PI', name: 'house'} {email: 'PI:EMAIL:<EMAIL>END_PI', name: 'PI:NAME:<NAME>END_PI'} {email: 'PI:EMAIL:<EMAIL>END_PI', name: 'PI:NAME:<NAME>END_PI'} ] coffeekup_template = -> doctype 5 html lang: 'en', -> head -> meta charset: 'utf-8' title @title style ''' body {font-family: "sans-serif"} section, header {display: block} ''' body -> section -> header -> h1 @title if @inspired p 'Create a witty example' else p 'Go meta' ul -> for user in @users li user.name li -> a href: "mailto:#{user.email}", -> user.email coffeekup_string_template = """ doctype 5 html lang: 'en', -> head -> meta charset: 'utf-8' title @title style ''' body {font-family: "sans-serif"} section, header {display: block} ''' body -> section -> header -> h1 @title if @inspired p 'Create a witty example' else p 'Go meta' ul -> for user in @users li user.name li -> a href: "mailto:\#{user.email}", -> user.email """ coffeekup_compiled_template = coffeekup.compile coffeekup_template jade_template = ''' !!! 5 html(lang="en") head meta(charset="utf-8") title= title style | body {font-family: "sans-serif"} | section, header {display: block} body section header h1= title - if (inspired) p Create a witty example - else p Go meta ul - each user in users li= user.name li a(href="mailto:"+user.email)= user.email ''' jade_compiled_template = jade.compile jade_template ejs_template = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><%= title %></title> <style> body {font-family: "sans-serif"} section, header {display: block} </style> </head> <body> <section> <header> <h1><%= title %></h1> </header> <% if (inspired) { %> <p>Create a witty example</p> <% } else { %> <p>Go meta</p> <% } %> <ul> <% for (user in users) { %> <li><%= user.name %></li> <li><a href="mailto:<%= user.email %>"><%= user.email %></a></li> <% } %> </ul> </section> </body> </html> ''' eco_template = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><%= @title %></title> <style> body {font-family: "sans-serif"} section, header {display: block} </style> </head> <body> <section> <header> <h1><%= @title %></h1> </header> <% if @inspired: %> <p>Create a witty example</p> <% else: %> <p>Go meta</p> <% end %> <ul> <% for user in @users: %> <li><%= user.name %></li> <li><a href="mailto:<%= user.email %>"><%= user.email %></a></li> <% end %> </ul> </section> </body> </html> ''' haml_template = ''' !!! 5 %html{lang: "en"} %head %meta{charset: "utf-8"} %title= title :css body {font-family: "sans-serif"} section, header {display: block} %body %section %header %h1= title :if inspired %p Create a witty example :if !inspired %p Go meta %ul :each user in users %li= user.name %li %a{href: "mailto:#{user.email}"}= user.email ''' haml_template_compiled = haml(haml_template) benchmark = (title, code) -> start = new Date for i in [1..5000] code() log "#{title}: #{new Date - start} ms" @run = -> benchmark 'CoffeeKup (precompiled)', -> coffeekup_compiled_template data benchmark 'Jade (precompiled)', -> jade_compiled_template data benchmark 'haml-js (precompiled)', -> haml_template_compiled data benchmark 'Eco', -> eco.render eco_template, data console.log '\n' benchmark 'CoffeeKup (function, cache on)', -> coffeekup.render coffeekup_template, data, cache: on benchmark 'CoffeeKup (string, cache on)', -> coffeekup.render coffeekup_string_template, data, cache: on benchmark 'Jade (cache on)', -> jade.render jade_template, locals: data, cache: on, filename: 'test' benchmark 'ejs (cache on)', -> ejs.render ejs_template, locals: data, cache: on, filename: 'test' console.log '\n' benchmark 'CoffeeKup (function, cache off)', -> coffeekup.render coffeekup_template, data benchmark 'CoffeeKup (string, cache off)', -> coffeekup.render coffeekup_string_template, data, cache: off benchmark 'Jade (cache off)', -> jade.render jade_template, locals: data benchmark 'haml-js', -> haml.render haml_template, locals: data benchmark 'ejs (cache off)', -> ejs.render ejs_template, locals: data
[ { "context": "est 'nested for .. of .. loops', (cb) ->\n x =\n christian:\n age: 36\n last: \"rudder\"\n max:\n ", "end": 6467, "score": 0.9364180564880371, "start": 6458, "tag": "NAME", "value": "christian" }, { "context": "\n x =\n christian:\n age: 36\n last: \"rudder\"\n max:\n age: 34\n last: \"krohn\"\n\n to", "end": 6502, "score": 0.6828187108039856, "start": 6497, "tag": "NAME", "value": "udder" }, { "context": "ast: \"rudder\"\n max:\n age: 34\n last: \"krohn\"\n\n tot = 0\n for first, info of x\n tot += inf", "end": 6545, "score": 0.7438488602638245, "start": 6540, "tag": "NAME", "value": "krohn" }, { "context": "i is 3, {})\n\natest 'more for + when (Issue #38 via @boris-petrov)', (cb) ->\n x = 'x'\n bar = { b : 1 }\n for o in", "end": 8767, "score": 0.968071460723877, "start": 8754, "tag": "USERNAME", "value": "@boris-petrov" }, { "context": "is 10, {})\n\natest 'negative strides (Issue #86 via @davidbau)', (cb) ->\n last_1 = last_2 = -1\n tot_1 = tot_2", "end": 9099, "score": 0.996139407157898, "start": 9090, "tag": "USERNAME", "value": "@davidbau" }, { "context": " 2 and c.z is 3, {}\n\n# tests bug #146 (github.com/maxtaco/coffee-script/issues/146)\natest 'deferral variabl", "end": 11801, "score": 0.9996638298034668, "start": 11794, "tag": "USERNAME", "value": "maxtaco" }, { "context": " true, {}\n\natest 'loops with defers (Issue #89 via @davidbau)', (cb) ->\n arr = []\n for x in [0..3] by 2\n ", "end": 13466, "score": 0.9923181533813477, "start": 13457, "tag": "USERNAME", "value": "@davidbau" }, { "context": "ctor : (@name) ->\n a : (cb) ->\n m = \"Hello #{@name}\"\n await delay defer()\n zzz = () ->", "end": 23776, "score": 0.4413466453552246, "start": 23776, "tag": "NAME", "value": "" } ]
test/iced.coffee
zapu/iced-coffee-script-v3
1
delay = (cb, i) -> i = i || 3 setTimeout cb, i atest "cb scoping", (cb) -> # Common pattern used in iced programming - ensure # scoping rules here do not change for any reason. foo = (cb) -> await delay defer() cb false, {} # to be ignored - we should call foo's func cb, not outer func cb await foo defer() cb true, {} atest "nested of/in loop", (cb) -> counter = 0 bar = () -> if counter++ > 100 throw new Error "infinite loop found" for a,b of { foo : 1 } for v, i in [0,1] await delay defer() bar() cb true, {} atest "basic iced waiting", (cb) -> i = 1 await delay defer() i++ cb(i is 2, {}) glfoo = (i, cb) -> await delay(defer(), i) cb(i) atest "basic iced waiting", (cb) -> i = 1 await delay defer() i++ cb(i is 2, {}) atest "basic iced trigger values", (cb) -> i = 10 await glfoo(i, defer j) cb(i is j, {}) atest "basic iced set structs", (cb) -> field = "yo" i = 10 obj = { cat : { dog : 0 } } await glfoo(i, defer obj.cat[field]) field = "bar" # change the field to make sure that we captured "yo" cb(obj.cat.yo is i, {}) multi = (cb, arr) -> await delay defer() cb.apply(null, arr) atest "defer splats", (cb) -> v = [ 1, 2, 3, 4] obj = { x : 0 } await multi(defer(obj.x, out...), v) out.unshift obj.x ok = true for i in [0..v.length-1] ok = false if v[i] != out[i] cb(ok, {}) atest "continue / break test" , (cb) -> tot = 0 for i in [0..100] await delay defer() continue if i is 3 tot += i break if i is 10 cb(tot is 52, {}) atest "for k,v of obj testing", (cb) -> obj = { the : "quick", brown : "fox", jumped : "over" } s = "" for k,v of obj await delay defer() s += k + " " + v + " " cb( s is "the quick brown fox jumped over ", {} ) atest "for k,v in arr testing", (cb) -> obj = [ "the", "quick", "brown" ] s = "" for v,i in obj await delay defer() s += v + " " + i + " " cb( s is "the 0 quick 1 brown 2 ", {} ) atest "switch --- github issue #55", (cb) -> await delay defer() switch "blah" when "a" await delay defer() when "b" await delay defer() cb( true, {} ) atest "switch-a-roos", (cb) -> res = 0 for i in [0..4] await delay defer() switch i when 0 then res += 1 when 1 await delay defer() res += 20 when 2 await delay defer() if false res += 100000 else await delay defer() res += 300 else res += i*1000 res += 10000 if i is 2 cb( res is 17321, {} ) atest "parallel awaits with classes", (cb) -> class MyClass constructor: -> @val = 0 increment: (wait, i, cb) -> await setTimeout(defer(),wait) @val += i await setTimeout(defer(),wait) @val += i cb() getVal: -> @val obj = new MyClass() await obj.increment 10, 1, defer() obj.increment 20, 2, defer() obj.increment 30, 4, defer() v = obj.getVal() cb(v is 14, {}) atest "loop construct", (cb) -> i = 0 loop await delay defer() i += 1 await delay defer() break if i is 10 await delay defer() cb(i is 10, {}) test "`this` points to object instance in methods with await", -> class MyClass huh: (cb) -> ok @a is 'a' await delay defer() cb() o = new MyClass o.a = 'a' o.huh(->) atest "AT variable works in an await (1)", (cb) -> class MyClass constructor : -> @flag = false chill : (cb) -> await delay defer() cb() run : (cb) -> await @chill defer() @flag = true cb() getFlag : -> @flag o = new MyClass await o.run defer() cb(o.getFlag(), {}) atest "test nested serial/parallel", (cb) -> slots = [] await for i in [0..10] ( (j, cb) -> await delay defer(), 5 * Math.random() await delay defer(), 4 * Math.random() slots[j] = true cb() )(i, defer()) ok = true for i in [0..10] ok = false unless slots[i] cb(ok, {}) atest "test scoping", (cb) -> class MyClass constructor : -> @val = 0 run : (cb) -> @val++ await delay defer() @val++ await class Inner chill : (cb) -> await delay defer() @val = 0 cb() i = new Inner i.chill defer() @val++ await delay defer() @val++ await ( (cb) -> class Inner chill : (cb) -> await delay defer() @val = 0 cb() i = new Inner await i.chill defer() cb() )(defer()) ++@val cb(@val) getVal : -> @val o = new MyClass await o.run defer(v) cb(v is 5, {}) atest "AT variable works in an await (2)", (cb) -> class MyClass constructor : -> @val = 0 inc : -> @val++ chill : (cb) -> await delay defer() cb() run : (cb) -> await @chill defer() for i in [0..9] await @chill defer() @inc() cb() getVal : -> @val o = new MyClass await o.run defer() cb(o.getVal() is 10, {}) atest "fat arrow versus iced", (cb) -> class Foo constructor : -> @bindings = {} addHandler : (key,cb) -> @bindings[key] = cb useHandler : (key, args...) -> @bindings[key](args...) delay : (cb) -> await delay defer() cb() addHandlers : -> @addHandler "sleep1", (cb) => await delay defer() await @delay defer() cb(true) @addHandler "sleep2", (cb) => await @delay defer() await delay defer() cb(true) ok1 = ok2 = false f = new Foo() f.addHandlers() await f.useHandler "sleep1", defer(ok1) await f.useHandler "sleep2", defer(ok2) cb(ok1 and ok2, {}) atest "nested loops", (cb) -> val = 0 for i in [0..9] await delay(defer(),1) for j in [0..9] await delay(defer(),1) val++ cb(val is 100, {}) atest "until", (cb) -> i = 10 out = 0 until i is 0 await delay defer() out += i-- cb(out is 55, {}) atest 'super with no args', (cb) -> class P constructor: -> @x = 10 class A extends P constructor : -> super foo : (cb) -> await delay defer() cb() a = new A await a.foo defer() cb(a.x is 10, {}) atest 'nested for .. of .. loops', (cb) -> x = christian: age: 36 last: "rudder" max: age: 34 last: "krohn" tot = 0 for first, info of x tot += info.age for k,v of info await delay defer() tot++ cb(tot is 74, {}) atest "for + guards", (cb) -> v = [] for i in [0..10] when i % 2 is 0 await delay defer() v.push i cb(v[3] is 6, {}) atest "while + guards", (cb) -> i = 0 v = [] while (x = i++) < 10 when x % 2 is 0 await delay defer() v.push x cb(v[3] is 6, {}) atest "nested loops + inner break", (cb) -> i = 0 while i < 10 await delay defer() j = 0 while j < 10 if j == 5 break j++ i++ res = j*i cb(res is 50, {}) atest "defer and object assignment", (cb) -> baz = (cb) -> await delay defer() cb { a : 1, b : 2, c : 3} out = [] await for i in [0..2] switch i when 0 then baz defer { c : out[i] } when 1 then baz defer { b : out[i] } when 2 then baz defer { a : out[i] } cb( out[0] is 3 and out[1] is 2 and out[2] is 1, {} ) atest 'defer + arguments', (cb) -> bar = (i, cb) -> await delay defer() arguments[1](arguments[0]) await bar 10, defer x eq x, 10 cb true, {} atest 'defer + arguments 2', (cb) -> x = null foo = (a,b,c,cb) -> x = arguments[1] await delay defer() cb null await foo 1, 2, 3, defer() eq x, 2 cb x, {} atest 'defer + arguments 3', (cb) -> x = null foo = (a,b,c,cb) -> @x = arguments[1] await delay defer() cb null obj = {} await foo.call obj, 1, 2, 3, defer() eq obj.x, 2 cb true, {} test 'arguments array without await', -> code = CoffeeScript.compile "fun = -> console.log(arguments)" eq code.indexOf("_arguments"), -1 atest 'for in by + await', (cb) -> res = [] for i in [0..10] by 3 await delay defer() res.push i cb(res.length is 4 and res[3] is 9, {}) atest 'super after await', (cb) -> class A constructor : -> @_i = 0 foo : (cb) -> await delay defer() @_i += 1 cb() class B extends A constructor : -> super foo : (cb) -> await delay defer() await delay defer() @_i += 2 super cb b = new B() await b.foo defer() cb(b._i is 3, {}) atest 'more for + when (Issue #38 via @boris-petrov)', (cb) -> x = 'x' bar = { b : 1 } for o in [ { p : 'a' }, { p : 'b' } ] when bar[o.p]? await delay defer() x = o.p cb(x is 'b', {}) atest 'for + ...', (cb) -> x = 0 inc = () -> x++ for i in [0...10] await delay defer(), 0 inc() cb(x is 10, {}) atest 'negative strides (Issue #86 via @davidbau)', (cb) -> last_1 = last_2 = -1 tot_1 = tot_2 = 0 for i in [4..1] await delay defer(), 0 last_1 = i tot_1 += i for i in [4...1] await delay defer(), 0 last_2 = i tot_2 += i cb ((last_1 is 1) and (tot_1 is 10) and (last_2 is 2) and (tot_2 is 9)), {} atest "positive strides", (cb) -> total1 = 0 last1 = -1 for i in [1..5] await delay defer(), 0 total1 += i last1 = i total2 = 0 last2 = -1 for i in [1...5] await delay defer(), 0 total2 += i last2 = i cb ((total1 is 15) and (last1 is 5) and (total2 is 10) and (last2 is 4)), {} atest "positive strides with expression", (cb) -> count = 6 total1 = 0 last1 = -1 for i in [1..count-1] await delay defer(), 0 total1 += i last1 = i total2 = 0 last2 = -1 for i in [1...count] await delay defer(), 0 total2 += i last2 = i cb ((total1 is 15) and (last1 is 5) and (total2 is 15) and (last2 is 5)), {} atest "negative strides with expression", (cb) -> count = 6 total1 = 0 last1 = -1 for i in [count-1..1] await delay defer(), 0 total1 += i last1 = i total2 = 0 last2 = -1 for i in [count...1] await delay defer(), 0 total2 += i last2 = i cb ((total1 is 15) and (last1 is 1) and (total2 is 20) and (last2 is 2)), {} atest "loop without looping variable", (cb) -> count = 6 total1 = 0 for [1..count] await delay defer(), 0 total1 += 1 total2 = 0 for i in [count..1] await delay defer(), 0 total2 += 1 cb ((total1 is 6) and (total2 is 6)), {} atest "destructuring assignment in defer", (cb) -> j = (cb) -> await delay defer(), 0 cb { z : 33 } await j defer { z } cb(z is 33, {}) atest 'defer + class member assignments', (cb) -> myfn = (cb) -> await delay defer() cb 3, { y : 4, z : 5} class MyClass2 f : (cb) -> await myfn defer @x, { @y , z } cb z c = new MyClass2() await c.f defer z cb(c.x is 3 and c.y is 4 and z is 5, {}) atest 'defer + class member assignments 2', (cb) -> foo = (cb) -> await delay defer() cb null, 1, 2, 3 class Bar b : (cb) -> await delay defer() await foo defer err, @x, @y, @z cb null c = new Bar() await c.b defer() cb c.x is 1 and c.y is 2 and c.z is 3, {} atest 'defer + class member assignments 3', (cb) -> foo = (cb) -> await delay defer() cb null, 1, 2, 3 class Bar b : (cb) -> await delay defer() bfoo = (cb) => await foo defer err, @x, @y, @z cb null await bfoo defer() cb null c = new Bar() await c.b defer() cb c.x is 1 and c.y is 2 and c.z is 3, {} # tests bug #146 (github.com/maxtaco/coffee-script/issues/146) atest 'deferral variable with same name as a parameter in outer scope', (cb) -> val = 0 g = (cb) -> cb(2) f = (x) -> (-> val = x await g defer(x) )() f 1 cb(val is 1, {}) atest 'funcname with double quotes is safely emitted', (cb) -> v = 0 b = {} f = -> v++ b["xyz"] = -> await f defer() do b["xyz"] cb(v is 1, {}) atest 'consistent behavior of ranges with and without await', (cb) -> arr1 = [] arr2 = [] for x in [3..0] await delay defer() arr1.push x for x in [3..0] arr2.push x arrayEq arr1, arr2 arr1 = [] arr2 = [] for x in [3..0] by -1 await delay defer() arr1.push x for x in [3..0] by -1 arr2.push x arrayEq arr1, arr2 for x in [3...0] by 1 await delay defer() throw new Error 'Should never enter this loop' for x in [3...0] by 1 throw new Error 'Should never enter this loop' for x in [3..0] by 1 await delay defer() throw new Error 'Should never enter this loop' for x in [3..0] by 1 throw new Error 'Should never enter this loop' for x in [0..3] by -1 throw new Error 'Should never enter this loop' await delay defer() for x in [0..3] by -1 throw new Error 'Should never enter this loop' arr1 = [] arr2 = [] for x in [3..0] by -2 ok x <= 3 await delay defer() arr1.push x for x in [3..0] by -2 arr2.push x arrayEq arr1, arr2 arr1 = [] arr2 = [] for x in [0..3] by 2 await delay defer() arr1.push x for x in [0..3] by 2 arr2.push x arrayEq arr1, arr2 cb true, {} atest 'loops with defers (Issue #89 via @davidbau)', (cb) -> arr = [] for x in [0..3] by 2 await delay defer() arr.push x arrayEq [0, 2], arr arr = [] for x in ['a', 'b', 'c'] await delay defer() arr.push x arrayEq arr, ['a', 'b', 'c'] arr = [] for x in ['a', 'b', 'c'] by 1 await delay defer() arr.push x arrayEq arr, ['a', 'b', 'c'] arr = [] for x in ['d', 'e', 'f', 'g'] by 2 await delay defer() arr.push x arrayEq arr, [ 'd', 'f' ] arr = [] for x in ['a', 'b', 'c'] by -1 await delay defer() arr.push x arrayEq arr, ['c', 'b', 'a'] arr = [] step = -2 for x in ['a', 'b', 'c'] by step await delay defer() arr.push x arrayEq arr, ['c', 'a'] cb true, {} atest "nested loops with negative steps", (cb) -> v1 = [] for i in [10...0] by -1 for j in [10...i] by -1 await delay defer() v1.push (i*1000)+j v2 = [] for i in [10...0] by -1 for j in [10...i] by -1 v2.push (i*1000)+j arrayEq v1, v2 cb true, {} atest 'loop with function as step', (cb) -> makeFunc = -> calld = false return -> if calld throw Error 'step function called twice' calld = true return 1 # Basically, func should be called only once and its result should # be used as step. func = makeFunc() arr = [] for x in [1,2,3] by func() arr.push x arrayEq [1,2,3], arr func = makeFunc() arr = [] for x in [1,2,3] by func() await delay defer() arr.push x arrayEq [1,2,3], arr func = makeFunc() arr = [] for x in [1..3] by func() arr.push x arrayEq [1,2,3], arr func = makeFunc() arr = [] for x in [1..3] by func() await delay defer() arr.push x arrayEq [1,2,3], arr cb true, {} atest '_arguments clash', (cb) -> func = (cb, test) -> _arguments = [1,2,3] await delay defer(), 1 cb(arguments[1]) await func defer(res), 'test' cb res == 'test', {} atest 'can return immediately from awaited func', (cb) -> func = (cb) -> cb() await func defer() cb true, {} atest 'using defer in other contexts', (cb) -> a = defer: -> cb true, {} await delay defer() a.defer() atest 'await race condition with immediate defer (issue #175)', (test_cb) -> foo = (cb) -> cb() bar = (cb) -> # The bug here was that after both "defer()" calls, Deferrals # counter should be 2, so it knows it has to wait for two # callbacks. But because foo calls cb immediately, Deferalls is # considered completed before it reaches second defer() call. await foo defer() delay defer() await delay defer() cb() await bar defer() test_cb true, {} atest 'await race condition pesky conditions (issue #175)', (test_cb) -> foo = (cb) -> cb() # Because just checking for child node count is not enough await if 1 == 1 foo defer() delay defer() test_cb true, {} atest 'await potential race condition but not really', (test_cb) -> await if test_cb == 'this is not even a string' delay defer() delay defer() test_cb true, {} atest 'awaits that do not really wait for anything', (test_cb) -> await if test_cb == 'this is not even a string' delay defer() delay defer() await if test_cb == 'this is not even a string' delay defer() test_cb true, {} # helper to assert that a string should fail compilation cantCompile = (code) -> throws -> CoffeeScript.compile code atest "await expression assertions 1", (cb) -> cantCompile ''' x = if true await foo defer bar bar else 10 ''' cantCompile ''' foo if true await foo defer bar bar else 10 ''' cantCompile ''' if (if true await foo defer bar bar) then 10 else 20 ''' cantCompile ''' while ( await foo defer bar bar ) say_ho() ''' cantCompile ''' for i in ( await foo defer bar bar) go_nuts() ''' cantCompile ''' switch ( await foo defer bar 10 ) when 10 then 11 else 20 ''' cb true, {} atest "autocb is illegal", (cb) -> cantCompile ''' func = (autocb) -> ''' cb true, {} # Nasty evals! But we can't sandbox those, we expect the evaluated # string to call our cb function. atest "can run toplevel await", (cb) -> eval CoffeeScript.compile ''' await delay defer() cb true, {} ''', { bare: true } atest "can run toplevel await 2", (cb) -> eval CoffeeScript.compile ''' acc = 0 for i in [0..5] await delay defer() acc += 1 cb acc == 6, {} ''', { bare: true } test "top level awaits are wrapped", -> js = CoffeeScript.compile ''' await delay defer() cb true, {} ''', { bare: true } eq js.trim().indexOf("(function() {"), 0 atest "eval iced", (test_cb) -> global.cb = -> delete global.cb test_cb true, {} result = CoffeeScript.eval """ await setTimeout defer(), 1 cb() """, { runtime: 'inline' } if vm = require? 'vm' atest "eval sandbox iced", (test_cb) -> createContext = vm.Script.createContext ? vm.createContext sandbox = createContext() sandbox.delay = delay sandbox.cb = -> test_cb true, {} result = CoffeeScript.eval """ await delay defer() cb() """, { runtime: 'inline', sandbox } atest "iced coffee all the way down", (cb) -> js = CoffeeScript.compile """ await delay defer() js_inside = CoffeeScript.compile 'await delay defer()\\ncb true, {}', { runtime: 'inline' } eval js_inside """, { bare: true, runtime: 'inline' } eval js test "helpers.strToJavascript and back", -> str_to_js = CoffeeScript.helpers.strToJavascript # We use this to "encode" JavaScript files so naturally this test # should try to encode some JavaScript code snippet. test_string = str_to_js.toString() javascript_literal = str_to_js test_string eval "var back_to_string = #{javascript_literal};" eq back_to_string, test_string # Tests if we are emitting 'traces' correctly and if runtime uses # them to generate proper errors. wrap_error = (test_cb, predicate) -> real_warn = console.error console.error = (msg) -> console.error = real_warn if predicate(msg) test_cb true, {} else console.log 'Unexpected overused deferral msg:', msg test_cb false, {} atest "overused deferral error message", (test_cb) -> # "<anonymous>" because the call which triggers overused deferral orginates # from `(test_cb) ->` func - this one that the comment is in. wrap_error test_cb, (msg) -> msg.indexOf('test/iced.coffee:') != -1 and msg.indexOf('<anonymous>') != -1 foo = (cb) -> cb(); cb() await foo defer() atest "overused deferral error message 2", (test_cb) -> wrap_error test_cb, (msg) -> msg.indexOf('test/iced.coffee:') != -1 and msg.indexOf('A::b') != -1 class A b : () -> foo = (cb) -> cb(); cb() await foo defer() new A().b() atest "overused deferral error message 3", (test_cb) -> wrap_error test_cb, (msg) -> msg.indexOf('test/iced.coffee:') != -1 and msg.indexOf('anon_func') != -1 anon_func = -> foo = (cb) -> cb(); cb() await foo defer() anon_func() atest "await in try block", (test_cb) -> foo_a = () -> throw new Error "test error" foo_b = (cb) -> throw new Error "unexpected error - reached foo_b" glob_err = null foo = (f, g, cb) -> try f() await g defer x catch err glob_err = err cb(2) await foo foo_a, foo_b, defer ret eq ret, 2, "foo came back with right value" ok glob_err instanceof Error, "error caught" eq glob_err?.message, "test error", "caught right error" test_cb true, null atest "await in try block 2", (test_cb) -> error_func = (cb) -> throw new Error "error_func error" glob_err = null foo = (cb) -> try await error_func defer x catch err glob_err = err cb 1 await foo defer ret eq ret, 1, "foo came back with right value" ok glob_err instanceof Error, "error was caught" eq glob_err?.message, "error_func error", "it was the right error" test_cb true, null test "await expression errors", -> # forgetting `,` between `err` and `result` makes it a function # call, which is invalid iced slot. make sure the error mentions # that. code = "await foo defer err result" throws (-> CoffeeScript.compile code), /function call cannot be a slot/ test "builtin version literal", -> ver = __builtin_iced_version eq ver, "iced3" eq __builtin_iced_version, "iced3" test "builtin unassignable", -> cantCompile "__builtin_iced_version = 1" atest "non-builtin assignable", (cb) -> eval CoffeeScript.compile """ __builtin_iced_version_x = 1 cb true, {} """, { bare : true } test "non-existing builtin fallback", -> # Methods to check for version built-in. Pretend __builtin_iced_version_x is # another built-in that some future iced version will support. try ver1 = __builtin_iced_version_x catch then ver1 = "unknown" eq ver1, "unknown" try ver2 = __builtin_iced_version catch then ver2 = "unknown" eq ver2, "iced3" ver3 = __builtin_iced_version ? "unknown" eq ver3, "iced3" ver4 = __builtin_iced_version_x ? "unknown" eq ver4, "unknown" obj = { version : __builtin_iced_version ? "unknown" } eq obj.version, "iced3" obj2 = { version : __builtin_iced_version_x ? "unknown" } eq obj2.version, "unknown" atest 'async function and this-binding 1', (cb) -> a = (cb) -> await delay defer() @x = 5 cb null obj = {} await a.call(obj, defer()) cb obj.x is 5, {} atest 'async function and this-binding 2', (cb) -> obj = {} a = (cb) -> b = (cb) => await delay defer() ok @ is obj cb null await b defer() # passing another `this` using `call` should not do anything # because b is bound. await b.call {}, defer() cb null await a.call(obj, defer()) cb true, {} atest 'async function and this-binding 3', (cb) -> obj1 = {} obj2 = {} a = (cb) -> ok @ is obj1 b = (cb) -> await delay defer() ok @ is obj2 cb null ok @ is obj1 await b.call obj2, defer() ok @ is obj1 cb null await a.call obj1, defer() cb true, {} atest 'this-binding in string interpolations', (cb) -> class A constructor : (@name) -> a : (cb) -> m = "Hello #{@name}" await delay defer() zzz = () -> ok no cb m obj = new A("world") await obj.a defer msg cb msg is "Hello world", {} atest 'this-binding in class method', (cb) -> class A constructor : () -> @test = 0 foo : (cb) -> bar = (cb) => await delay defer() @test++ cb null await bar defer() await bar.call {}, defer() cb null obj = new A() await obj.foo defer() cb obj.test is 2, {} # test "caller name compatibility", () -> # main_sync = () -> # foo = () -> # caller = foo.caller?.name # eq caller, "main_sync" # x = foo() # main_sync() # atest "(async) caller name compatibility", (cb) -> # main_async = (cb) -> # main_async.name2 = 'main_async' # foo = () -> # caller = foo.caller?.name2 # eq caller.caller, "main_async" # x = foo() # await delay defer() # cb true, {} # main_async cb
210396
delay = (cb, i) -> i = i || 3 setTimeout cb, i atest "cb scoping", (cb) -> # Common pattern used in iced programming - ensure # scoping rules here do not change for any reason. foo = (cb) -> await delay defer() cb false, {} # to be ignored - we should call foo's func cb, not outer func cb await foo defer() cb true, {} atest "nested of/in loop", (cb) -> counter = 0 bar = () -> if counter++ > 100 throw new Error "infinite loop found" for a,b of { foo : 1 } for v, i in [0,1] await delay defer() bar() cb true, {} atest "basic iced waiting", (cb) -> i = 1 await delay defer() i++ cb(i is 2, {}) glfoo = (i, cb) -> await delay(defer(), i) cb(i) atest "basic iced waiting", (cb) -> i = 1 await delay defer() i++ cb(i is 2, {}) atest "basic iced trigger values", (cb) -> i = 10 await glfoo(i, defer j) cb(i is j, {}) atest "basic iced set structs", (cb) -> field = "yo" i = 10 obj = { cat : { dog : 0 } } await glfoo(i, defer obj.cat[field]) field = "bar" # change the field to make sure that we captured "yo" cb(obj.cat.yo is i, {}) multi = (cb, arr) -> await delay defer() cb.apply(null, arr) atest "defer splats", (cb) -> v = [ 1, 2, 3, 4] obj = { x : 0 } await multi(defer(obj.x, out...), v) out.unshift obj.x ok = true for i in [0..v.length-1] ok = false if v[i] != out[i] cb(ok, {}) atest "continue / break test" , (cb) -> tot = 0 for i in [0..100] await delay defer() continue if i is 3 tot += i break if i is 10 cb(tot is 52, {}) atest "for k,v of obj testing", (cb) -> obj = { the : "quick", brown : "fox", jumped : "over" } s = "" for k,v of obj await delay defer() s += k + " " + v + " " cb( s is "the quick brown fox jumped over ", {} ) atest "for k,v in arr testing", (cb) -> obj = [ "the", "quick", "brown" ] s = "" for v,i in obj await delay defer() s += v + " " + i + " " cb( s is "the 0 quick 1 brown 2 ", {} ) atest "switch --- github issue #55", (cb) -> await delay defer() switch "blah" when "a" await delay defer() when "b" await delay defer() cb( true, {} ) atest "switch-a-roos", (cb) -> res = 0 for i in [0..4] await delay defer() switch i when 0 then res += 1 when 1 await delay defer() res += 20 when 2 await delay defer() if false res += 100000 else await delay defer() res += 300 else res += i*1000 res += 10000 if i is 2 cb( res is 17321, {} ) atest "parallel awaits with classes", (cb) -> class MyClass constructor: -> @val = 0 increment: (wait, i, cb) -> await setTimeout(defer(),wait) @val += i await setTimeout(defer(),wait) @val += i cb() getVal: -> @val obj = new MyClass() await obj.increment 10, 1, defer() obj.increment 20, 2, defer() obj.increment 30, 4, defer() v = obj.getVal() cb(v is 14, {}) atest "loop construct", (cb) -> i = 0 loop await delay defer() i += 1 await delay defer() break if i is 10 await delay defer() cb(i is 10, {}) test "`this` points to object instance in methods with await", -> class MyClass huh: (cb) -> ok @a is 'a' await delay defer() cb() o = new MyClass o.a = 'a' o.huh(->) atest "AT variable works in an await (1)", (cb) -> class MyClass constructor : -> @flag = false chill : (cb) -> await delay defer() cb() run : (cb) -> await @chill defer() @flag = true cb() getFlag : -> @flag o = new MyClass await o.run defer() cb(o.getFlag(), {}) atest "test nested serial/parallel", (cb) -> slots = [] await for i in [0..10] ( (j, cb) -> await delay defer(), 5 * Math.random() await delay defer(), 4 * Math.random() slots[j] = true cb() )(i, defer()) ok = true for i in [0..10] ok = false unless slots[i] cb(ok, {}) atest "test scoping", (cb) -> class MyClass constructor : -> @val = 0 run : (cb) -> @val++ await delay defer() @val++ await class Inner chill : (cb) -> await delay defer() @val = 0 cb() i = new Inner i.chill defer() @val++ await delay defer() @val++ await ( (cb) -> class Inner chill : (cb) -> await delay defer() @val = 0 cb() i = new Inner await i.chill defer() cb() )(defer()) ++@val cb(@val) getVal : -> @val o = new MyClass await o.run defer(v) cb(v is 5, {}) atest "AT variable works in an await (2)", (cb) -> class MyClass constructor : -> @val = 0 inc : -> @val++ chill : (cb) -> await delay defer() cb() run : (cb) -> await @chill defer() for i in [0..9] await @chill defer() @inc() cb() getVal : -> @val o = new MyClass await o.run defer() cb(o.getVal() is 10, {}) atest "fat arrow versus iced", (cb) -> class Foo constructor : -> @bindings = {} addHandler : (key,cb) -> @bindings[key] = cb useHandler : (key, args...) -> @bindings[key](args...) delay : (cb) -> await delay defer() cb() addHandlers : -> @addHandler "sleep1", (cb) => await delay defer() await @delay defer() cb(true) @addHandler "sleep2", (cb) => await @delay defer() await delay defer() cb(true) ok1 = ok2 = false f = new Foo() f.addHandlers() await f.useHandler "sleep1", defer(ok1) await f.useHandler "sleep2", defer(ok2) cb(ok1 and ok2, {}) atest "nested loops", (cb) -> val = 0 for i in [0..9] await delay(defer(),1) for j in [0..9] await delay(defer(),1) val++ cb(val is 100, {}) atest "until", (cb) -> i = 10 out = 0 until i is 0 await delay defer() out += i-- cb(out is 55, {}) atest 'super with no args', (cb) -> class P constructor: -> @x = 10 class A extends P constructor : -> super foo : (cb) -> await delay defer() cb() a = new A await a.foo defer() cb(a.x is 10, {}) atest 'nested for .. of .. loops', (cb) -> x = <NAME>: age: 36 last: "r<NAME>" max: age: 34 last: "<NAME>" tot = 0 for first, info of x tot += info.age for k,v of info await delay defer() tot++ cb(tot is 74, {}) atest "for + guards", (cb) -> v = [] for i in [0..10] when i % 2 is 0 await delay defer() v.push i cb(v[3] is 6, {}) atest "while + guards", (cb) -> i = 0 v = [] while (x = i++) < 10 when x % 2 is 0 await delay defer() v.push x cb(v[3] is 6, {}) atest "nested loops + inner break", (cb) -> i = 0 while i < 10 await delay defer() j = 0 while j < 10 if j == 5 break j++ i++ res = j*i cb(res is 50, {}) atest "defer and object assignment", (cb) -> baz = (cb) -> await delay defer() cb { a : 1, b : 2, c : 3} out = [] await for i in [0..2] switch i when 0 then baz defer { c : out[i] } when 1 then baz defer { b : out[i] } when 2 then baz defer { a : out[i] } cb( out[0] is 3 and out[1] is 2 and out[2] is 1, {} ) atest 'defer + arguments', (cb) -> bar = (i, cb) -> await delay defer() arguments[1](arguments[0]) await bar 10, defer x eq x, 10 cb true, {} atest 'defer + arguments 2', (cb) -> x = null foo = (a,b,c,cb) -> x = arguments[1] await delay defer() cb null await foo 1, 2, 3, defer() eq x, 2 cb x, {} atest 'defer + arguments 3', (cb) -> x = null foo = (a,b,c,cb) -> @x = arguments[1] await delay defer() cb null obj = {} await foo.call obj, 1, 2, 3, defer() eq obj.x, 2 cb true, {} test 'arguments array without await', -> code = CoffeeScript.compile "fun = -> console.log(arguments)" eq code.indexOf("_arguments"), -1 atest 'for in by + await', (cb) -> res = [] for i in [0..10] by 3 await delay defer() res.push i cb(res.length is 4 and res[3] is 9, {}) atest 'super after await', (cb) -> class A constructor : -> @_i = 0 foo : (cb) -> await delay defer() @_i += 1 cb() class B extends A constructor : -> super foo : (cb) -> await delay defer() await delay defer() @_i += 2 super cb b = new B() await b.foo defer() cb(b._i is 3, {}) atest 'more for + when (Issue #38 via @boris-petrov)', (cb) -> x = 'x' bar = { b : 1 } for o in [ { p : 'a' }, { p : 'b' } ] when bar[o.p]? await delay defer() x = o.p cb(x is 'b', {}) atest 'for + ...', (cb) -> x = 0 inc = () -> x++ for i in [0...10] await delay defer(), 0 inc() cb(x is 10, {}) atest 'negative strides (Issue #86 via @davidbau)', (cb) -> last_1 = last_2 = -1 tot_1 = tot_2 = 0 for i in [4..1] await delay defer(), 0 last_1 = i tot_1 += i for i in [4...1] await delay defer(), 0 last_2 = i tot_2 += i cb ((last_1 is 1) and (tot_1 is 10) and (last_2 is 2) and (tot_2 is 9)), {} atest "positive strides", (cb) -> total1 = 0 last1 = -1 for i in [1..5] await delay defer(), 0 total1 += i last1 = i total2 = 0 last2 = -1 for i in [1...5] await delay defer(), 0 total2 += i last2 = i cb ((total1 is 15) and (last1 is 5) and (total2 is 10) and (last2 is 4)), {} atest "positive strides with expression", (cb) -> count = 6 total1 = 0 last1 = -1 for i in [1..count-1] await delay defer(), 0 total1 += i last1 = i total2 = 0 last2 = -1 for i in [1...count] await delay defer(), 0 total2 += i last2 = i cb ((total1 is 15) and (last1 is 5) and (total2 is 15) and (last2 is 5)), {} atest "negative strides with expression", (cb) -> count = 6 total1 = 0 last1 = -1 for i in [count-1..1] await delay defer(), 0 total1 += i last1 = i total2 = 0 last2 = -1 for i in [count...1] await delay defer(), 0 total2 += i last2 = i cb ((total1 is 15) and (last1 is 1) and (total2 is 20) and (last2 is 2)), {} atest "loop without looping variable", (cb) -> count = 6 total1 = 0 for [1..count] await delay defer(), 0 total1 += 1 total2 = 0 for i in [count..1] await delay defer(), 0 total2 += 1 cb ((total1 is 6) and (total2 is 6)), {} atest "destructuring assignment in defer", (cb) -> j = (cb) -> await delay defer(), 0 cb { z : 33 } await j defer { z } cb(z is 33, {}) atest 'defer + class member assignments', (cb) -> myfn = (cb) -> await delay defer() cb 3, { y : 4, z : 5} class MyClass2 f : (cb) -> await myfn defer @x, { @y , z } cb z c = new MyClass2() await c.f defer z cb(c.x is 3 and c.y is 4 and z is 5, {}) atest 'defer + class member assignments 2', (cb) -> foo = (cb) -> await delay defer() cb null, 1, 2, 3 class Bar b : (cb) -> await delay defer() await foo defer err, @x, @y, @z cb null c = new Bar() await c.b defer() cb c.x is 1 and c.y is 2 and c.z is 3, {} atest 'defer + class member assignments 3', (cb) -> foo = (cb) -> await delay defer() cb null, 1, 2, 3 class Bar b : (cb) -> await delay defer() bfoo = (cb) => await foo defer err, @x, @y, @z cb null await bfoo defer() cb null c = new Bar() await c.b defer() cb c.x is 1 and c.y is 2 and c.z is 3, {} # tests bug #146 (github.com/maxtaco/coffee-script/issues/146) atest 'deferral variable with same name as a parameter in outer scope', (cb) -> val = 0 g = (cb) -> cb(2) f = (x) -> (-> val = x await g defer(x) )() f 1 cb(val is 1, {}) atest 'funcname with double quotes is safely emitted', (cb) -> v = 0 b = {} f = -> v++ b["xyz"] = -> await f defer() do b["xyz"] cb(v is 1, {}) atest 'consistent behavior of ranges with and without await', (cb) -> arr1 = [] arr2 = [] for x in [3..0] await delay defer() arr1.push x for x in [3..0] arr2.push x arrayEq arr1, arr2 arr1 = [] arr2 = [] for x in [3..0] by -1 await delay defer() arr1.push x for x in [3..0] by -1 arr2.push x arrayEq arr1, arr2 for x in [3...0] by 1 await delay defer() throw new Error 'Should never enter this loop' for x in [3...0] by 1 throw new Error 'Should never enter this loop' for x in [3..0] by 1 await delay defer() throw new Error 'Should never enter this loop' for x in [3..0] by 1 throw new Error 'Should never enter this loop' for x in [0..3] by -1 throw new Error 'Should never enter this loop' await delay defer() for x in [0..3] by -1 throw new Error 'Should never enter this loop' arr1 = [] arr2 = [] for x in [3..0] by -2 ok x <= 3 await delay defer() arr1.push x for x in [3..0] by -2 arr2.push x arrayEq arr1, arr2 arr1 = [] arr2 = [] for x in [0..3] by 2 await delay defer() arr1.push x for x in [0..3] by 2 arr2.push x arrayEq arr1, arr2 cb true, {} atest 'loops with defers (Issue #89 via @davidbau)', (cb) -> arr = [] for x in [0..3] by 2 await delay defer() arr.push x arrayEq [0, 2], arr arr = [] for x in ['a', 'b', 'c'] await delay defer() arr.push x arrayEq arr, ['a', 'b', 'c'] arr = [] for x in ['a', 'b', 'c'] by 1 await delay defer() arr.push x arrayEq arr, ['a', 'b', 'c'] arr = [] for x in ['d', 'e', 'f', 'g'] by 2 await delay defer() arr.push x arrayEq arr, [ 'd', 'f' ] arr = [] for x in ['a', 'b', 'c'] by -1 await delay defer() arr.push x arrayEq arr, ['c', 'b', 'a'] arr = [] step = -2 for x in ['a', 'b', 'c'] by step await delay defer() arr.push x arrayEq arr, ['c', 'a'] cb true, {} atest "nested loops with negative steps", (cb) -> v1 = [] for i in [10...0] by -1 for j in [10...i] by -1 await delay defer() v1.push (i*1000)+j v2 = [] for i in [10...0] by -1 for j in [10...i] by -1 v2.push (i*1000)+j arrayEq v1, v2 cb true, {} atest 'loop with function as step', (cb) -> makeFunc = -> calld = false return -> if calld throw Error 'step function called twice' calld = true return 1 # Basically, func should be called only once and its result should # be used as step. func = makeFunc() arr = [] for x in [1,2,3] by func() arr.push x arrayEq [1,2,3], arr func = makeFunc() arr = [] for x in [1,2,3] by func() await delay defer() arr.push x arrayEq [1,2,3], arr func = makeFunc() arr = [] for x in [1..3] by func() arr.push x arrayEq [1,2,3], arr func = makeFunc() arr = [] for x in [1..3] by func() await delay defer() arr.push x arrayEq [1,2,3], arr cb true, {} atest '_arguments clash', (cb) -> func = (cb, test) -> _arguments = [1,2,3] await delay defer(), 1 cb(arguments[1]) await func defer(res), 'test' cb res == 'test', {} atest 'can return immediately from awaited func', (cb) -> func = (cb) -> cb() await func defer() cb true, {} atest 'using defer in other contexts', (cb) -> a = defer: -> cb true, {} await delay defer() a.defer() atest 'await race condition with immediate defer (issue #175)', (test_cb) -> foo = (cb) -> cb() bar = (cb) -> # The bug here was that after both "defer()" calls, Deferrals # counter should be 2, so it knows it has to wait for two # callbacks. But because foo calls cb immediately, Deferalls is # considered completed before it reaches second defer() call. await foo defer() delay defer() await delay defer() cb() await bar defer() test_cb true, {} atest 'await race condition pesky conditions (issue #175)', (test_cb) -> foo = (cb) -> cb() # Because just checking for child node count is not enough await if 1 == 1 foo defer() delay defer() test_cb true, {} atest 'await potential race condition but not really', (test_cb) -> await if test_cb == 'this is not even a string' delay defer() delay defer() test_cb true, {} atest 'awaits that do not really wait for anything', (test_cb) -> await if test_cb == 'this is not even a string' delay defer() delay defer() await if test_cb == 'this is not even a string' delay defer() test_cb true, {} # helper to assert that a string should fail compilation cantCompile = (code) -> throws -> CoffeeScript.compile code atest "await expression assertions 1", (cb) -> cantCompile ''' x = if true await foo defer bar bar else 10 ''' cantCompile ''' foo if true await foo defer bar bar else 10 ''' cantCompile ''' if (if true await foo defer bar bar) then 10 else 20 ''' cantCompile ''' while ( await foo defer bar bar ) say_ho() ''' cantCompile ''' for i in ( await foo defer bar bar) go_nuts() ''' cantCompile ''' switch ( await foo defer bar 10 ) when 10 then 11 else 20 ''' cb true, {} atest "autocb is illegal", (cb) -> cantCompile ''' func = (autocb) -> ''' cb true, {} # Nasty evals! But we can't sandbox those, we expect the evaluated # string to call our cb function. atest "can run toplevel await", (cb) -> eval CoffeeScript.compile ''' await delay defer() cb true, {} ''', { bare: true } atest "can run toplevel await 2", (cb) -> eval CoffeeScript.compile ''' acc = 0 for i in [0..5] await delay defer() acc += 1 cb acc == 6, {} ''', { bare: true } test "top level awaits are wrapped", -> js = CoffeeScript.compile ''' await delay defer() cb true, {} ''', { bare: true } eq js.trim().indexOf("(function() {"), 0 atest "eval iced", (test_cb) -> global.cb = -> delete global.cb test_cb true, {} result = CoffeeScript.eval """ await setTimeout defer(), 1 cb() """, { runtime: 'inline' } if vm = require? 'vm' atest "eval sandbox iced", (test_cb) -> createContext = vm.Script.createContext ? vm.createContext sandbox = createContext() sandbox.delay = delay sandbox.cb = -> test_cb true, {} result = CoffeeScript.eval """ await delay defer() cb() """, { runtime: 'inline', sandbox } atest "iced coffee all the way down", (cb) -> js = CoffeeScript.compile """ await delay defer() js_inside = CoffeeScript.compile 'await delay defer()\\ncb true, {}', { runtime: 'inline' } eval js_inside """, { bare: true, runtime: 'inline' } eval js test "helpers.strToJavascript and back", -> str_to_js = CoffeeScript.helpers.strToJavascript # We use this to "encode" JavaScript files so naturally this test # should try to encode some JavaScript code snippet. test_string = str_to_js.toString() javascript_literal = str_to_js test_string eval "var back_to_string = #{javascript_literal};" eq back_to_string, test_string # Tests if we are emitting 'traces' correctly and if runtime uses # them to generate proper errors. wrap_error = (test_cb, predicate) -> real_warn = console.error console.error = (msg) -> console.error = real_warn if predicate(msg) test_cb true, {} else console.log 'Unexpected overused deferral msg:', msg test_cb false, {} atest "overused deferral error message", (test_cb) -> # "<anonymous>" because the call which triggers overused deferral orginates # from `(test_cb) ->` func - this one that the comment is in. wrap_error test_cb, (msg) -> msg.indexOf('test/iced.coffee:') != -1 and msg.indexOf('<anonymous>') != -1 foo = (cb) -> cb(); cb() await foo defer() atest "overused deferral error message 2", (test_cb) -> wrap_error test_cb, (msg) -> msg.indexOf('test/iced.coffee:') != -1 and msg.indexOf('A::b') != -1 class A b : () -> foo = (cb) -> cb(); cb() await foo defer() new A().b() atest "overused deferral error message 3", (test_cb) -> wrap_error test_cb, (msg) -> msg.indexOf('test/iced.coffee:') != -1 and msg.indexOf('anon_func') != -1 anon_func = -> foo = (cb) -> cb(); cb() await foo defer() anon_func() atest "await in try block", (test_cb) -> foo_a = () -> throw new Error "test error" foo_b = (cb) -> throw new Error "unexpected error - reached foo_b" glob_err = null foo = (f, g, cb) -> try f() await g defer x catch err glob_err = err cb(2) await foo foo_a, foo_b, defer ret eq ret, 2, "foo came back with right value" ok glob_err instanceof Error, "error caught" eq glob_err?.message, "test error", "caught right error" test_cb true, null atest "await in try block 2", (test_cb) -> error_func = (cb) -> throw new Error "error_func error" glob_err = null foo = (cb) -> try await error_func defer x catch err glob_err = err cb 1 await foo defer ret eq ret, 1, "foo came back with right value" ok glob_err instanceof Error, "error was caught" eq glob_err?.message, "error_func error", "it was the right error" test_cb true, null test "await expression errors", -> # forgetting `,` between `err` and `result` makes it a function # call, which is invalid iced slot. make sure the error mentions # that. code = "await foo defer err result" throws (-> CoffeeScript.compile code), /function call cannot be a slot/ test "builtin version literal", -> ver = __builtin_iced_version eq ver, "iced3" eq __builtin_iced_version, "iced3" test "builtin unassignable", -> cantCompile "__builtin_iced_version = 1" atest "non-builtin assignable", (cb) -> eval CoffeeScript.compile """ __builtin_iced_version_x = 1 cb true, {} """, { bare : true } test "non-existing builtin fallback", -> # Methods to check for version built-in. Pretend __builtin_iced_version_x is # another built-in that some future iced version will support. try ver1 = __builtin_iced_version_x catch then ver1 = "unknown" eq ver1, "unknown" try ver2 = __builtin_iced_version catch then ver2 = "unknown" eq ver2, "iced3" ver3 = __builtin_iced_version ? "unknown" eq ver3, "iced3" ver4 = __builtin_iced_version_x ? "unknown" eq ver4, "unknown" obj = { version : __builtin_iced_version ? "unknown" } eq obj.version, "iced3" obj2 = { version : __builtin_iced_version_x ? "unknown" } eq obj2.version, "unknown" atest 'async function and this-binding 1', (cb) -> a = (cb) -> await delay defer() @x = 5 cb null obj = {} await a.call(obj, defer()) cb obj.x is 5, {} atest 'async function and this-binding 2', (cb) -> obj = {} a = (cb) -> b = (cb) => await delay defer() ok @ is obj cb null await b defer() # passing another `this` using `call` should not do anything # because b is bound. await b.call {}, defer() cb null await a.call(obj, defer()) cb true, {} atest 'async function and this-binding 3', (cb) -> obj1 = {} obj2 = {} a = (cb) -> ok @ is obj1 b = (cb) -> await delay defer() ok @ is obj2 cb null ok @ is obj1 await b.call obj2, defer() ok @ is obj1 cb null await a.call obj1, defer() cb true, {} atest 'this-binding in string interpolations', (cb) -> class A constructor : (@name) -> a : (cb) -> m = "Hello<NAME> #{@name}" await delay defer() zzz = () -> ok no cb m obj = new A("world") await obj.a defer msg cb msg is "Hello world", {} atest 'this-binding in class method', (cb) -> class A constructor : () -> @test = 0 foo : (cb) -> bar = (cb) => await delay defer() @test++ cb null await bar defer() await bar.call {}, defer() cb null obj = new A() await obj.foo defer() cb obj.test is 2, {} # test "caller name compatibility", () -> # main_sync = () -> # foo = () -> # caller = foo.caller?.name # eq caller, "main_sync" # x = foo() # main_sync() # atest "(async) caller name compatibility", (cb) -> # main_async = (cb) -> # main_async.name2 = 'main_async' # foo = () -> # caller = foo.caller?.name2 # eq caller.caller, "main_async" # x = foo() # await delay defer() # cb true, {} # main_async cb
true
delay = (cb, i) -> i = i || 3 setTimeout cb, i atest "cb scoping", (cb) -> # Common pattern used in iced programming - ensure # scoping rules here do not change for any reason. foo = (cb) -> await delay defer() cb false, {} # to be ignored - we should call foo's func cb, not outer func cb await foo defer() cb true, {} atest "nested of/in loop", (cb) -> counter = 0 bar = () -> if counter++ > 100 throw new Error "infinite loop found" for a,b of { foo : 1 } for v, i in [0,1] await delay defer() bar() cb true, {} atest "basic iced waiting", (cb) -> i = 1 await delay defer() i++ cb(i is 2, {}) glfoo = (i, cb) -> await delay(defer(), i) cb(i) atest "basic iced waiting", (cb) -> i = 1 await delay defer() i++ cb(i is 2, {}) atest "basic iced trigger values", (cb) -> i = 10 await glfoo(i, defer j) cb(i is j, {}) atest "basic iced set structs", (cb) -> field = "yo" i = 10 obj = { cat : { dog : 0 } } await glfoo(i, defer obj.cat[field]) field = "bar" # change the field to make sure that we captured "yo" cb(obj.cat.yo is i, {}) multi = (cb, arr) -> await delay defer() cb.apply(null, arr) atest "defer splats", (cb) -> v = [ 1, 2, 3, 4] obj = { x : 0 } await multi(defer(obj.x, out...), v) out.unshift obj.x ok = true for i in [0..v.length-1] ok = false if v[i] != out[i] cb(ok, {}) atest "continue / break test" , (cb) -> tot = 0 for i in [0..100] await delay defer() continue if i is 3 tot += i break if i is 10 cb(tot is 52, {}) atest "for k,v of obj testing", (cb) -> obj = { the : "quick", brown : "fox", jumped : "over" } s = "" for k,v of obj await delay defer() s += k + " " + v + " " cb( s is "the quick brown fox jumped over ", {} ) atest "for k,v in arr testing", (cb) -> obj = [ "the", "quick", "brown" ] s = "" for v,i in obj await delay defer() s += v + " " + i + " " cb( s is "the 0 quick 1 brown 2 ", {} ) atest "switch --- github issue #55", (cb) -> await delay defer() switch "blah" when "a" await delay defer() when "b" await delay defer() cb( true, {} ) atest "switch-a-roos", (cb) -> res = 0 for i in [0..4] await delay defer() switch i when 0 then res += 1 when 1 await delay defer() res += 20 when 2 await delay defer() if false res += 100000 else await delay defer() res += 300 else res += i*1000 res += 10000 if i is 2 cb( res is 17321, {} ) atest "parallel awaits with classes", (cb) -> class MyClass constructor: -> @val = 0 increment: (wait, i, cb) -> await setTimeout(defer(),wait) @val += i await setTimeout(defer(),wait) @val += i cb() getVal: -> @val obj = new MyClass() await obj.increment 10, 1, defer() obj.increment 20, 2, defer() obj.increment 30, 4, defer() v = obj.getVal() cb(v is 14, {}) atest "loop construct", (cb) -> i = 0 loop await delay defer() i += 1 await delay defer() break if i is 10 await delay defer() cb(i is 10, {}) test "`this` points to object instance in methods with await", -> class MyClass huh: (cb) -> ok @a is 'a' await delay defer() cb() o = new MyClass o.a = 'a' o.huh(->) atest "AT variable works in an await (1)", (cb) -> class MyClass constructor : -> @flag = false chill : (cb) -> await delay defer() cb() run : (cb) -> await @chill defer() @flag = true cb() getFlag : -> @flag o = new MyClass await o.run defer() cb(o.getFlag(), {}) atest "test nested serial/parallel", (cb) -> slots = [] await for i in [0..10] ( (j, cb) -> await delay defer(), 5 * Math.random() await delay defer(), 4 * Math.random() slots[j] = true cb() )(i, defer()) ok = true for i in [0..10] ok = false unless slots[i] cb(ok, {}) atest "test scoping", (cb) -> class MyClass constructor : -> @val = 0 run : (cb) -> @val++ await delay defer() @val++ await class Inner chill : (cb) -> await delay defer() @val = 0 cb() i = new Inner i.chill defer() @val++ await delay defer() @val++ await ( (cb) -> class Inner chill : (cb) -> await delay defer() @val = 0 cb() i = new Inner await i.chill defer() cb() )(defer()) ++@val cb(@val) getVal : -> @val o = new MyClass await o.run defer(v) cb(v is 5, {}) atest "AT variable works in an await (2)", (cb) -> class MyClass constructor : -> @val = 0 inc : -> @val++ chill : (cb) -> await delay defer() cb() run : (cb) -> await @chill defer() for i in [0..9] await @chill defer() @inc() cb() getVal : -> @val o = new MyClass await o.run defer() cb(o.getVal() is 10, {}) atest "fat arrow versus iced", (cb) -> class Foo constructor : -> @bindings = {} addHandler : (key,cb) -> @bindings[key] = cb useHandler : (key, args...) -> @bindings[key](args...) delay : (cb) -> await delay defer() cb() addHandlers : -> @addHandler "sleep1", (cb) => await delay defer() await @delay defer() cb(true) @addHandler "sleep2", (cb) => await @delay defer() await delay defer() cb(true) ok1 = ok2 = false f = new Foo() f.addHandlers() await f.useHandler "sleep1", defer(ok1) await f.useHandler "sleep2", defer(ok2) cb(ok1 and ok2, {}) atest "nested loops", (cb) -> val = 0 for i in [0..9] await delay(defer(),1) for j in [0..9] await delay(defer(),1) val++ cb(val is 100, {}) atest "until", (cb) -> i = 10 out = 0 until i is 0 await delay defer() out += i-- cb(out is 55, {}) atest 'super with no args', (cb) -> class P constructor: -> @x = 10 class A extends P constructor : -> super foo : (cb) -> await delay defer() cb() a = new A await a.foo defer() cb(a.x is 10, {}) atest 'nested for .. of .. loops', (cb) -> x = PI:NAME:<NAME>END_PI: age: 36 last: "rPI:NAME:<NAME>END_PI" max: age: 34 last: "PI:NAME:<NAME>END_PI" tot = 0 for first, info of x tot += info.age for k,v of info await delay defer() tot++ cb(tot is 74, {}) atest "for + guards", (cb) -> v = [] for i in [0..10] when i % 2 is 0 await delay defer() v.push i cb(v[3] is 6, {}) atest "while + guards", (cb) -> i = 0 v = [] while (x = i++) < 10 when x % 2 is 0 await delay defer() v.push x cb(v[3] is 6, {}) atest "nested loops + inner break", (cb) -> i = 0 while i < 10 await delay defer() j = 0 while j < 10 if j == 5 break j++ i++ res = j*i cb(res is 50, {}) atest "defer and object assignment", (cb) -> baz = (cb) -> await delay defer() cb { a : 1, b : 2, c : 3} out = [] await for i in [0..2] switch i when 0 then baz defer { c : out[i] } when 1 then baz defer { b : out[i] } when 2 then baz defer { a : out[i] } cb( out[0] is 3 and out[1] is 2 and out[2] is 1, {} ) atest 'defer + arguments', (cb) -> bar = (i, cb) -> await delay defer() arguments[1](arguments[0]) await bar 10, defer x eq x, 10 cb true, {} atest 'defer + arguments 2', (cb) -> x = null foo = (a,b,c,cb) -> x = arguments[1] await delay defer() cb null await foo 1, 2, 3, defer() eq x, 2 cb x, {} atest 'defer + arguments 3', (cb) -> x = null foo = (a,b,c,cb) -> @x = arguments[1] await delay defer() cb null obj = {} await foo.call obj, 1, 2, 3, defer() eq obj.x, 2 cb true, {} test 'arguments array without await', -> code = CoffeeScript.compile "fun = -> console.log(arguments)" eq code.indexOf("_arguments"), -1 atest 'for in by + await', (cb) -> res = [] for i in [0..10] by 3 await delay defer() res.push i cb(res.length is 4 and res[3] is 9, {}) atest 'super after await', (cb) -> class A constructor : -> @_i = 0 foo : (cb) -> await delay defer() @_i += 1 cb() class B extends A constructor : -> super foo : (cb) -> await delay defer() await delay defer() @_i += 2 super cb b = new B() await b.foo defer() cb(b._i is 3, {}) atest 'more for + when (Issue #38 via @boris-petrov)', (cb) -> x = 'x' bar = { b : 1 } for o in [ { p : 'a' }, { p : 'b' } ] when bar[o.p]? await delay defer() x = o.p cb(x is 'b', {}) atest 'for + ...', (cb) -> x = 0 inc = () -> x++ for i in [0...10] await delay defer(), 0 inc() cb(x is 10, {}) atest 'negative strides (Issue #86 via @davidbau)', (cb) -> last_1 = last_2 = -1 tot_1 = tot_2 = 0 for i in [4..1] await delay defer(), 0 last_1 = i tot_1 += i for i in [4...1] await delay defer(), 0 last_2 = i tot_2 += i cb ((last_1 is 1) and (tot_1 is 10) and (last_2 is 2) and (tot_2 is 9)), {} atest "positive strides", (cb) -> total1 = 0 last1 = -1 for i in [1..5] await delay defer(), 0 total1 += i last1 = i total2 = 0 last2 = -1 for i in [1...5] await delay defer(), 0 total2 += i last2 = i cb ((total1 is 15) and (last1 is 5) and (total2 is 10) and (last2 is 4)), {} atest "positive strides with expression", (cb) -> count = 6 total1 = 0 last1 = -1 for i in [1..count-1] await delay defer(), 0 total1 += i last1 = i total2 = 0 last2 = -1 for i in [1...count] await delay defer(), 0 total2 += i last2 = i cb ((total1 is 15) and (last1 is 5) and (total2 is 15) and (last2 is 5)), {} atest "negative strides with expression", (cb) -> count = 6 total1 = 0 last1 = -1 for i in [count-1..1] await delay defer(), 0 total1 += i last1 = i total2 = 0 last2 = -1 for i in [count...1] await delay defer(), 0 total2 += i last2 = i cb ((total1 is 15) and (last1 is 1) and (total2 is 20) and (last2 is 2)), {} atest "loop without looping variable", (cb) -> count = 6 total1 = 0 for [1..count] await delay defer(), 0 total1 += 1 total2 = 0 for i in [count..1] await delay defer(), 0 total2 += 1 cb ((total1 is 6) and (total2 is 6)), {} atest "destructuring assignment in defer", (cb) -> j = (cb) -> await delay defer(), 0 cb { z : 33 } await j defer { z } cb(z is 33, {}) atest 'defer + class member assignments', (cb) -> myfn = (cb) -> await delay defer() cb 3, { y : 4, z : 5} class MyClass2 f : (cb) -> await myfn defer @x, { @y , z } cb z c = new MyClass2() await c.f defer z cb(c.x is 3 and c.y is 4 and z is 5, {}) atest 'defer + class member assignments 2', (cb) -> foo = (cb) -> await delay defer() cb null, 1, 2, 3 class Bar b : (cb) -> await delay defer() await foo defer err, @x, @y, @z cb null c = new Bar() await c.b defer() cb c.x is 1 and c.y is 2 and c.z is 3, {} atest 'defer + class member assignments 3', (cb) -> foo = (cb) -> await delay defer() cb null, 1, 2, 3 class Bar b : (cb) -> await delay defer() bfoo = (cb) => await foo defer err, @x, @y, @z cb null await bfoo defer() cb null c = new Bar() await c.b defer() cb c.x is 1 and c.y is 2 and c.z is 3, {} # tests bug #146 (github.com/maxtaco/coffee-script/issues/146) atest 'deferral variable with same name as a parameter in outer scope', (cb) -> val = 0 g = (cb) -> cb(2) f = (x) -> (-> val = x await g defer(x) )() f 1 cb(val is 1, {}) atest 'funcname with double quotes is safely emitted', (cb) -> v = 0 b = {} f = -> v++ b["xyz"] = -> await f defer() do b["xyz"] cb(v is 1, {}) atest 'consistent behavior of ranges with and without await', (cb) -> arr1 = [] arr2 = [] for x in [3..0] await delay defer() arr1.push x for x in [3..0] arr2.push x arrayEq arr1, arr2 arr1 = [] arr2 = [] for x in [3..0] by -1 await delay defer() arr1.push x for x in [3..0] by -1 arr2.push x arrayEq arr1, arr2 for x in [3...0] by 1 await delay defer() throw new Error 'Should never enter this loop' for x in [3...0] by 1 throw new Error 'Should never enter this loop' for x in [3..0] by 1 await delay defer() throw new Error 'Should never enter this loop' for x in [3..0] by 1 throw new Error 'Should never enter this loop' for x in [0..3] by -1 throw new Error 'Should never enter this loop' await delay defer() for x in [0..3] by -1 throw new Error 'Should never enter this loop' arr1 = [] arr2 = [] for x in [3..0] by -2 ok x <= 3 await delay defer() arr1.push x for x in [3..0] by -2 arr2.push x arrayEq arr1, arr2 arr1 = [] arr2 = [] for x in [0..3] by 2 await delay defer() arr1.push x for x in [0..3] by 2 arr2.push x arrayEq arr1, arr2 cb true, {} atest 'loops with defers (Issue #89 via @davidbau)', (cb) -> arr = [] for x in [0..3] by 2 await delay defer() arr.push x arrayEq [0, 2], arr arr = [] for x in ['a', 'b', 'c'] await delay defer() arr.push x arrayEq arr, ['a', 'b', 'c'] arr = [] for x in ['a', 'b', 'c'] by 1 await delay defer() arr.push x arrayEq arr, ['a', 'b', 'c'] arr = [] for x in ['d', 'e', 'f', 'g'] by 2 await delay defer() arr.push x arrayEq arr, [ 'd', 'f' ] arr = [] for x in ['a', 'b', 'c'] by -1 await delay defer() arr.push x arrayEq arr, ['c', 'b', 'a'] arr = [] step = -2 for x in ['a', 'b', 'c'] by step await delay defer() arr.push x arrayEq arr, ['c', 'a'] cb true, {} atest "nested loops with negative steps", (cb) -> v1 = [] for i in [10...0] by -1 for j in [10...i] by -1 await delay defer() v1.push (i*1000)+j v2 = [] for i in [10...0] by -1 for j in [10...i] by -1 v2.push (i*1000)+j arrayEq v1, v2 cb true, {} atest 'loop with function as step', (cb) -> makeFunc = -> calld = false return -> if calld throw Error 'step function called twice' calld = true return 1 # Basically, func should be called only once and its result should # be used as step. func = makeFunc() arr = [] for x in [1,2,3] by func() arr.push x arrayEq [1,2,3], arr func = makeFunc() arr = [] for x in [1,2,3] by func() await delay defer() arr.push x arrayEq [1,2,3], arr func = makeFunc() arr = [] for x in [1..3] by func() arr.push x arrayEq [1,2,3], arr func = makeFunc() arr = [] for x in [1..3] by func() await delay defer() arr.push x arrayEq [1,2,3], arr cb true, {} atest '_arguments clash', (cb) -> func = (cb, test) -> _arguments = [1,2,3] await delay defer(), 1 cb(arguments[1]) await func defer(res), 'test' cb res == 'test', {} atest 'can return immediately from awaited func', (cb) -> func = (cb) -> cb() await func defer() cb true, {} atest 'using defer in other contexts', (cb) -> a = defer: -> cb true, {} await delay defer() a.defer() atest 'await race condition with immediate defer (issue #175)', (test_cb) -> foo = (cb) -> cb() bar = (cb) -> # The bug here was that after both "defer()" calls, Deferrals # counter should be 2, so it knows it has to wait for two # callbacks. But because foo calls cb immediately, Deferalls is # considered completed before it reaches second defer() call. await foo defer() delay defer() await delay defer() cb() await bar defer() test_cb true, {} atest 'await race condition pesky conditions (issue #175)', (test_cb) -> foo = (cb) -> cb() # Because just checking for child node count is not enough await if 1 == 1 foo defer() delay defer() test_cb true, {} atest 'await potential race condition but not really', (test_cb) -> await if test_cb == 'this is not even a string' delay defer() delay defer() test_cb true, {} atest 'awaits that do not really wait for anything', (test_cb) -> await if test_cb == 'this is not even a string' delay defer() delay defer() await if test_cb == 'this is not even a string' delay defer() test_cb true, {} # helper to assert that a string should fail compilation cantCompile = (code) -> throws -> CoffeeScript.compile code atest "await expression assertions 1", (cb) -> cantCompile ''' x = if true await foo defer bar bar else 10 ''' cantCompile ''' foo if true await foo defer bar bar else 10 ''' cantCompile ''' if (if true await foo defer bar bar) then 10 else 20 ''' cantCompile ''' while ( await foo defer bar bar ) say_ho() ''' cantCompile ''' for i in ( await foo defer bar bar) go_nuts() ''' cantCompile ''' switch ( await foo defer bar 10 ) when 10 then 11 else 20 ''' cb true, {} atest "autocb is illegal", (cb) -> cantCompile ''' func = (autocb) -> ''' cb true, {} # Nasty evals! But we can't sandbox those, we expect the evaluated # string to call our cb function. atest "can run toplevel await", (cb) -> eval CoffeeScript.compile ''' await delay defer() cb true, {} ''', { bare: true } atest "can run toplevel await 2", (cb) -> eval CoffeeScript.compile ''' acc = 0 for i in [0..5] await delay defer() acc += 1 cb acc == 6, {} ''', { bare: true } test "top level awaits are wrapped", -> js = CoffeeScript.compile ''' await delay defer() cb true, {} ''', { bare: true } eq js.trim().indexOf("(function() {"), 0 atest "eval iced", (test_cb) -> global.cb = -> delete global.cb test_cb true, {} result = CoffeeScript.eval """ await setTimeout defer(), 1 cb() """, { runtime: 'inline' } if vm = require? 'vm' atest "eval sandbox iced", (test_cb) -> createContext = vm.Script.createContext ? vm.createContext sandbox = createContext() sandbox.delay = delay sandbox.cb = -> test_cb true, {} result = CoffeeScript.eval """ await delay defer() cb() """, { runtime: 'inline', sandbox } atest "iced coffee all the way down", (cb) -> js = CoffeeScript.compile """ await delay defer() js_inside = CoffeeScript.compile 'await delay defer()\\ncb true, {}', { runtime: 'inline' } eval js_inside """, { bare: true, runtime: 'inline' } eval js test "helpers.strToJavascript and back", -> str_to_js = CoffeeScript.helpers.strToJavascript # We use this to "encode" JavaScript files so naturally this test # should try to encode some JavaScript code snippet. test_string = str_to_js.toString() javascript_literal = str_to_js test_string eval "var back_to_string = #{javascript_literal};" eq back_to_string, test_string # Tests if we are emitting 'traces' correctly and if runtime uses # them to generate proper errors. wrap_error = (test_cb, predicate) -> real_warn = console.error console.error = (msg) -> console.error = real_warn if predicate(msg) test_cb true, {} else console.log 'Unexpected overused deferral msg:', msg test_cb false, {} atest "overused deferral error message", (test_cb) -> # "<anonymous>" because the call which triggers overused deferral orginates # from `(test_cb) ->` func - this one that the comment is in. wrap_error test_cb, (msg) -> msg.indexOf('test/iced.coffee:') != -1 and msg.indexOf('<anonymous>') != -1 foo = (cb) -> cb(); cb() await foo defer() atest "overused deferral error message 2", (test_cb) -> wrap_error test_cb, (msg) -> msg.indexOf('test/iced.coffee:') != -1 and msg.indexOf('A::b') != -1 class A b : () -> foo = (cb) -> cb(); cb() await foo defer() new A().b() atest "overused deferral error message 3", (test_cb) -> wrap_error test_cb, (msg) -> msg.indexOf('test/iced.coffee:') != -1 and msg.indexOf('anon_func') != -1 anon_func = -> foo = (cb) -> cb(); cb() await foo defer() anon_func() atest "await in try block", (test_cb) -> foo_a = () -> throw new Error "test error" foo_b = (cb) -> throw new Error "unexpected error - reached foo_b" glob_err = null foo = (f, g, cb) -> try f() await g defer x catch err glob_err = err cb(2) await foo foo_a, foo_b, defer ret eq ret, 2, "foo came back with right value" ok glob_err instanceof Error, "error caught" eq glob_err?.message, "test error", "caught right error" test_cb true, null atest "await in try block 2", (test_cb) -> error_func = (cb) -> throw new Error "error_func error" glob_err = null foo = (cb) -> try await error_func defer x catch err glob_err = err cb 1 await foo defer ret eq ret, 1, "foo came back with right value" ok glob_err instanceof Error, "error was caught" eq glob_err?.message, "error_func error", "it was the right error" test_cb true, null test "await expression errors", -> # forgetting `,` between `err` and `result` makes it a function # call, which is invalid iced slot. make sure the error mentions # that. code = "await foo defer err result" throws (-> CoffeeScript.compile code), /function call cannot be a slot/ test "builtin version literal", -> ver = __builtin_iced_version eq ver, "iced3" eq __builtin_iced_version, "iced3" test "builtin unassignable", -> cantCompile "__builtin_iced_version = 1" atest "non-builtin assignable", (cb) -> eval CoffeeScript.compile """ __builtin_iced_version_x = 1 cb true, {} """, { bare : true } test "non-existing builtin fallback", -> # Methods to check for version built-in. Pretend __builtin_iced_version_x is # another built-in that some future iced version will support. try ver1 = __builtin_iced_version_x catch then ver1 = "unknown" eq ver1, "unknown" try ver2 = __builtin_iced_version catch then ver2 = "unknown" eq ver2, "iced3" ver3 = __builtin_iced_version ? "unknown" eq ver3, "iced3" ver4 = __builtin_iced_version_x ? "unknown" eq ver4, "unknown" obj = { version : __builtin_iced_version ? "unknown" } eq obj.version, "iced3" obj2 = { version : __builtin_iced_version_x ? "unknown" } eq obj2.version, "unknown" atest 'async function and this-binding 1', (cb) -> a = (cb) -> await delay defer() @x = 5 cb null obj = {} await a.call(obj, defer()) cb obj.x is 5, {} atest 'async function and this-binding 2', (cb) -> obj = {} a = (cb) -> b = (cb) => await delay defer() ok @ is obj cb null await b defer() # passing another `this` using `call` should not do anything # because b is bound. await b.call {}, defer() cb null await a.call(obj, defer()) cb true, {} atest 'async function and this-binding 3', (cb) -> obj1 = {} obj2 = {} a = (cb) -> ok @ is obj1 b = (cb) -> await delay defer() ok @ is obj2 cb null ok @ is obj1 await b.call obj2, defer() ok @ is obj1 cb null await a.call obj1, defer() cb true, {} atest 'this-binding in string interpolations', (cb) -> class A constructor : (@name) -> a : (cb) -> m = "HelloPI:NAME:<NAME>END_PI #{@name}" await delay defer() zzz = () -> ok no cb m obj = new A("world") await obj.a defer msg cb msg is "Hello world", {} atest 'this-binding in class method', (cb) -> class A constructor : () -> @test = 0 foo : (cb) -> bar = (cb) => await delay defer() @test++ cb null await bar defer() await bar.call {}, defer() cb null obj = new A() await obj.foo defer() cb obj.test is 2, {} # test "caller name compatibility", () -> # main_sync = () -> # foo = () -> # caller = foo.caller?.name # eq caller, "main_sync" # x = foo() # main_sync() # atest "(async) caller name compatibility", (cb) -> # main_async = (cb) -> # main_async.name2 = 'main_async' # foo = () -> # caller = foo.caller?.name2 # eq caller.caller, "main_async" # x = foo() # await delay defer() # cb true, {} # main_async cb
[ { "context": " \":\" + String app.config.port\n\nvalidEmail = \"matthieu.stone@gmail.com\"\ninvalidEmail = \"nol\"\n\nvalidPassword = \"vali", "end": 728, "score": 0.9999203085899353, "start": 704, "tag": "EMAIL", "value": "matthieu.stone@gmail.com" }, { "context": ".com\"\ninvalidEmail = \"nol\"\n\nvalidPassword = \"validPathword23!\"\ninvalidPassword = \"foo\"\n\nuser = null", "end": 789, "score": 0.9991334080696106, "start": 774, "tag": "PASSWORD", "value": "validPathword23" }, { "context": "assword = \"validPathword23!\"\ninvalidPassword = \"foo\"\n\nuser = null\nconfirmationCode = nu", "end": 814, "score": 0.9992414116859436, "start": 811, "tag": "PASSWORD", "value": "foo" }, { "context": "up\"\n json: true\n body: {user: {password: validPassword }}\n\n request.post opts, (err, response, body) ", "end": 1557, "score": 0.9984579086303711, "start": 1544, "tag": "PASSWORD", "value": "validPassword" }, { "context": " body: { user: { email: invalidEmail, password: validPassword }}\n\n request.post opts, (err, response, body) ", "end": 2324, "score": 0.9952603578567505, "start": 2311, "tag": "PASSWORD", "value": "validPassword" }, { "context": " body: { user: { email: validEmail, password: validPassword }}\n\n request.post opts, (err, response, body) ", "end": 2726, "score": 0.9985934495925903, "start": 2713, "tag": "PASSWORD", "value": "validPassword" }, { "context": "n: true\n body: { user: { email: \"\", password: validPassword }}\n\n request.post opts, (err, response, body) ", "end": 4472, "score": 0.9993438124656677, "start": 4459, "tag": "PASSWORD", "value": "validPassword" }, { "context": " body: { user: { email: invalidEmail, password: validPassword }}\n\n request.post opts, (err, response, body) ", "end": 4862, "score": 0.9993463754653931, "start": 4849, "tag": "PASSWORD", "value": "validPassword" }, { "context": " body: { user: { email: validEmail, password: invalidPassword }}\n\n request.post opts, (err, response, body) ", "end": 5255, "score": 0.99932461977005, "start": 5240, "tag": "PASSWORD", "value": "invalidPassword" }, { "context": " body: { user: { email: validEmail, password: validPassword }}\n\n request.post opts, (err, response, body) ", "end": 5692, "score": 0.9989829063415527, "start": 5679, "tag": "PASSWORD", "value": "validPassword" }, { "context": " opts =\n url: appEndPoint + \"/reset-password/asdfasdf\"\n json: true\n\n request.get opts, (err, re", "end": 9260, "score": 0.9918663501739502, "start": 9252, "tag": "PASSWORD", "value": "asdfasdf" } ]
test/working-tests/user-create-login.test.coffee
mattstone/StarterApp-Server
0
should = require('chai').should() config = require '../config/config.test.coffee' request = require 'request' # Start Setup App app = {} app.config = require '../config/config.test.coffee' app.helpers = require '../lib/helpers.coffee' app.mongoose = require 'mongoose' app.mongoose.promise = global.Promise app.mongoose.connect app.config.mongodb.uri, { useNewUrlParser: true } # load Redis RedisManager = require '../lib/RedisManager' app.r = new RedisManager app # load models app.models = app.helpers.loadModels app # End Setup App appEndPoint = app.config.appEndPoint + ":" + String app.config.port apiEndPoint = app.config.apiEndPoint + ":" + String app.config.port validEmail = "matthieu.stone@gmail.com" invalidEmail = "nol" validPassword = "validPathword23!" invalidPassword = "foo" user = null confirmationCode = null describe 'User Create Login', () -> before (done) -> this.timeout = 30000 done() after (done) -> this.timeout = 30000 app.mongoose.connection.db.dropDatabase (err) -> done() it 'should not create user with no details', (done) -> opts = url: appEndPoint + "/signup" json: true request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not create user without email', (done) -> opts = url: appEndPoint + "/signup" json: true body: {user: {password: validPassword }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not create user without password', (done) -> opts = url: appEndPoint + "/signup" json: true body: { user: { email: validEmail }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not create user with invalid email', (done) -> opts = url: appEndPoint + "/signup" json: true body: { user: { email: invalidEmail, password: validPassword }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should create user with valid email and password', (done) -> opts = url: appEndPoint + "/signup" json: true body: { user: { email: validEmail, password: validPassword }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.user.should.be.an 'object' user = body.user user.email.should.equal validEmail user.createdAt.should.not.be.empty user.updatedAt.should.not.be.empty done() it 'should have salt and hash in user database record', () -> query = { email: validEmail } app.models.User.findOne query .then( (data) -> data.email.should.equal validEmail data.confirmed.should.equal false data.salt.should.not.be.empty data.hash.should.not.be.empty user = data ) .catch( (err) -> should.not.exist err ) it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal 1 data[0].emailToSend.should.equal 1 data[0].users.length.should.equal 1 String(data[0].users[0]).should.equal String(user.id) data[0].from.should.equal app.config.email.marketing data[0].custom.should.be.an 'object' data[0].custom.confirmationCode.should.be.a 'string' confirmationCode = data[0].custom.confirmationCode app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> should.not.exist err ) it 'should take some to let the QEmail delete finish', (done) -> for i in [0 .. 100000000] x = 1 done() it 'should not login with empty email', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: "", password: validPassword }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not login with invalid email', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: invalidEmail, password: validPassword }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not login with invalid password', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: validEmail, password: invalidPassword }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should get confirmation error when attempting to login with valid password and email', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: validEmail, password: validPassword }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not confirm user email address without a confirmation code', (done) -> opts = url: appEndPoint + '/confirm/' json: true request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal(404) done() it 'should not confirm user email address with invalid confirmation code', (done) -> opts = url: appEndPoint + "/confirm/" + "invalidConfirmationCode" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.error.should.be.a 'string' done() it 'should not request a new confirmation code with an invalid email address', (done) -> opts = url: appEndPoint + "/resend-confirmation-code/asdfasdf" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.error.should.be.a 'string' done() it 'should request a new confirmation code with a valid email address', (done) -> opts = url: appEndPoint + "/resend-confirmation-code/" + validEmail + "?test=true", json: true request.get opts, (err, response, body) -> response.statusCode.should.equal 200 body.should.be.an 'object' body.success.should.equal 'OK' done() it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal 1 data[0].emailToSend.should.equal 1 data[0].users.length.should.equal 1 String(data[0].users[0]).should.equal String(user.id) data[0].from.should.equal app.config.email.marketing data[0].custom.should.be.an 'object' data[0].custom.confirmationCode.should.be.a 'string' confirmationCode = data[0].custom.confirmationCode app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> should.not.exist err ) it 'should take some to let the QEmail delete finish', (done) -> for i in [0 .. 1000000000] x = 1 done() it 'should confirm user email address', (done) -> opts = url: appEndPoint + "/confirm/" + confirmationCode json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.user.should.be.an 'object' done() it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal 1 data[0].emailToSend.should.equal 5 data[0].users.length.should.equal 1 String(data[0].users[0]).should.equal String(user.id) data[0].from.should.equal app.config.email.marketing app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> console.log "Am I happening: 1" console.log err ) it 'should take some to let the QEmail delete finish', (done) -> for i in [0 .. 1000000000] x = 1 done() it 'should not send password reset email code with an invalid email address', (done) -> opts = url: appEndPoint + "/reset-password/asdfasdf" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.error.should.be.a 'string' done() it 'should send password reset email code with a valid email address', (done) -> opts = url: appEndPoint + "/reset-password/" + validEmail json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' should.not.exist body.error body.success.should.equal 'OK' done() it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal(1); data[0].emailToSend.should.equal(3); data[0].users.length.should.equal(1); String(data[0].users[0]).should.equal(String(user.id)); data[0].from.should.equal(app.config.email.marketing); app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> console.log "Am I happening: 2" console.log err # should.not.exist err ) # it 'should take some to let the QEmail delete finish', (done) -> # for i in [0 .. 10000000] # x = 1 # done() it 'should logout', (done) -> opts = url: appEndPoint + "/logout" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.a 'string' done() ###
123896
should = require('chai').should() config = require '../config/config.test.coffee' request = require 'request' # Start Setup App app = {} app.config = require '../config/config.test.coffee' app.helpers = require '../lib/helpers.coffee' app.mongoose = require 'mongoose' app.mongoose.promise = global.Promise app.mongoose.connect app.config.mongodb.uri, { useNewUrlParser: true } # load Redis RedisManager = require '../lib/RedisManager' app.r = new RedisManager app # load models app.models = app.helpers.loadModels app # End Setup App appEndPoint = app.config.appEndPoint + ":" + String app.config.port apiEndPoint = app.config.apiEndPoint + ":" + String app.config.port validEmail = "<EMAIL>" invalidEmail = "nol" validPassword = "<PASSWORD>!" invalidPassword = "<PASSWORD>" user = null confirmationCode = null describe 'User Create Login', () -> before (done) -> this.timeout = 30000 done() after (done) -> this.timeout = 30000 app.mongoose.connection.db.dropDatabase (err) -> done() it 'should not create user with no details', (done) -> opts = url: appEndPoint + "/signup" json: true request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not create user without email', (done) -> opts = url: appEndPoint + "/signup" json: true body: {user: {password: <PASSWORD> }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not create user without password', (done) -> opts = url: appEndPoint + "/signup" json: true body: { user: { email: validEmail }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not create user with invalid email', (done) -> opts = url: appEndPoint + "/signup" json: true body: { user: { email: invalidEmail, password: <PASSWORD> }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should create user with valid email and password', (done) -> opts = url: appEndPoint + "/signup" json: true body: { user: { email: validEmail, password: <PASSWORD> }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.user.should.be.an 'object' user = body.user user.email.should.equal validEmail user.createdAt.should.not.be.empty user.updatedAt.should.not.be.empty done() it 'should have salt and hash in user database record', () -> query = { email: validEmail } app.models.User.findOne query .then( (data) -> data.email.should.equal validEmail data.confirmed.should.equal false data.salt.should.not.be.empty data.hash.should.not.be.empty user = data ) .catch( (err) -> should.not.exist err ) it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal 1 data[0].emailToSend.should.equal 1 data[0].users.length.should.equal 1 String(data[0].users[0]).should.equal String(user.id) data[0].from.should.equal app.config.email.marketing data[0].custom.should.be.an 'object' data[0].custom.confirmationCode.should.be.a 'string' confirmationCode = data[0].custom.confirmationCode app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> should.not.exist err ) it 'should take some to let the QEmail delete finish', (done) -> for i in [0 .. 100000000] x = 1 done() it 'should not login with empty email', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: "", password: <PASSWORD> }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not login with invalid email', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: invalidEmail, password: <PASSWORD> }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not login with invalid password', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: validEmail, password: <PASSWORD> }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should get confirmation error when attempting to login with valid password and email', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: validEmail, password: <PASSWORD> }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not confirm user email address without a confirmation code', (done) -> opts = url: appEndPoint + '/confirm/' json: true request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal(404) done() it 'should not confirm user email address with invalid confirmation code', (done) -> opts = url: appEndPoint + "/confirm/" + "invalidConfirmationCode" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.error.should.be.a 'string' done() it 'should not request a new confirmation code with an invalid email address', (done) -> opts = url: appEndPoint + "/resend-confirmation-code/asdfasdf" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.error.should.be.a 'string' done() it 'should request a new confirmation code with a valid email address', (done) -> opts = url: appEndPoint + "/resend-confirmation-code/" + validEmail + "?test=true", json: true request.get opts, (err, response, body) -> response.statusCode.should.equal 200 body.should.be.an 'object' body.success.should.equal 'OK' done() it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal 1 data[0].emailToSend.should.equal 1 data[0].users.length.should.equal 1 String(data[0].users[0]).should.equal String(user.id) data[0].from.should.equal app.config.email.marketing data[0].custom.should.be.an 'object' data[0].custom.confirmationCode.should.be.a 'string' confirmationCode = data[0].custom.confirmationCode app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> should.not.exist err ) it 'should take some to let the QEmail delete finish', (done) -> for i in [0 .. 1000000000] x = 1 done() it 'should confirm user email address', (done) -> opts = url: appEndPoint + "/confirm/" + confirmationCode json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.user.should.be.an 'object' done() it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal 1 data[0].emailToSend.should.equal 5 data[0].users.length.should.equal 1 String(data[0].users[0]).should.equal String(user.id) data[0].from.should.equal app.config.email.marketing app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> console.log "Am I happening: 1" console.log err ) it 'should take some to let the QEmail delete finish', (done) -> for i in [0 .. 1000000000] x = 1 done() it 'should not send password reset email code with an invalid email address', (done) -> opts = url: appEndPoint + "/reset-password/<PASSWORD>" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.error.should.be.a 'string' done() it 'should send password reset email code with a valid email address', (done) -> opts = url: appEndPoint + "/reset-password/" + validEmail json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' should.not.exist body.error body.success.should.equal 'OK' done() it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal(1); data[0].emailToSend.should.equal(3); data[0].users.length.should.equal(1); String(data[0].users[0]).should.equal(String(user.id)); data[0].from.should.equal(app.config.email.marketing); app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> console.log "Am I happening: 2" console.log err # should.not.exist err ) # it 'should take some to let the QEmail delete finish', (done) -> # for i in [0 .. 10000000] # x = 1 # done() it 'should logout', (done) -> opts = url: appEndPoint + "/logout" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.a 'string' done() ###
true
should = require('chai').should() config = require '../config/config.test.coffee' request = require 'request' # Start Setup App app = {} app.config = require '../config/config.test.coffee' app.helpers = require '../lib/helpers.coffee' app.mongoose = require 'mongoose' app.mongoose.promise = global.Promise app.mongoose.connect app.config.mongodb.uri, { useNewUrlParser: true } # load Redis RedisManager = require '../lib/RedisManager' app.r = new RedisManager app # load models app.models = app.helpers.loadModels app # End Setup App appEndPoint = app.config.appEndPoint + ":" + String app.config.port apiEndPoint = app.config.apiEndPoint + ":" + String app.config.port validEmail = "PI:EMAIL:<EMAIL>END_PI" invalidEmail = "nol" validPassword = "PI:PASSWORD:<PASSWORD>END_PI!" invalidPassword = "PI:PASSWORD:<PASSWORD>END_PI" user = null confirmationCode = null describe 'User Create Login', () -> before (done) -> this.timeout = 30000 done() after (done) -> this.timeout = 30000 app.mongoose.connection.db.dropDatabase (err) -> done() it 'should not create user with no details', (done) -> opts = url: appEndPoint + "/signup" json: true request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not create user without email', (done) -> opts = url: appEndPoint + "/signup" json: true body: {user: {password: PI:PASSWORD:<PASSWORD>END_PI }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not create user without password', (done) -> opts = url: appEndPoint + "/signup" json: true body: { user: { email: validEmail }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not create user with invalid email', (done) -> opts = url: appEndPoint + "/signup" json: true body: { user: { email: invalidEmail, password: PI:PASSWORD:<PASSWORD>END_PI }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should create user with valid email and password', (done) -> opts = url: appEndPoint + "/signup" json: true body: { user: { email: validEmail, password: PI:PASSWORD:<PASSWORD>END_PI }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.user.should.be.an 'object' user = body.user user.email.should.equal validEmail user.createdAt.should.not.be.empty user.updatedAt.should.not.be.empty done() it 'should have salt and hash in user database record', () -> query = { email: validEmail } app.models.User.findOne query .then( (data) -> data.email.should.equal validEmail data.confirmed.should.equal false data.salt.should.not.be.empty data.hash.should.not.be.empty user = data ) .catch( (err) -> should.not.exist err ) it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal 1 data[0].emailToSend.should.equal 1 data[0].users.length.should.equal 1 String(data[0].users[0]).should.equal String(user.id) data[0].from.should.equal app.config.email.marketing data[0].custom.should.be.an 'object' data[0].custom.confirmationCode.should.be.a 'string' confirmationCode = data[0].custom.confirmationCode app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> should.not.exist err ) it 'should take some to let the QEmail delete finish', (done) -> for i in [0 .. 100000000] x = 1 done() it 'should not login with empty email', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: "", password: PI:PASSWORD:<PASSWORD>END_PI }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not login with invalid email', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: invalidEmail, password: PI:PASSWORD:<PASSWORD>END_PI }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not login with invalid password', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: validEmail, password: PI:PASSWORD:<PASSWORD>END_PI }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should get confirmation error when attempting to login with valid password and email', (done) -> opts = url: appEndPoint + "/login" json: true body: { user: { email: validEmail, password: PI:PASSWORD:<PASSWORD>END_PI }} request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' body.error.should.be.a 'string' done() it 'should not confirm user email address without a confirmation code', (done) -> opts = url: appEndPoint + '/confirm/' json: true request.post opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal(404) done() it 'should not confirm user email address with invalid confirmation code', (done) -> opts = url: appEndPoint + "/confirm/" + "invalidConfirmationCode" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.error.should.be.a 'string' done() it 'should not request a new confirmation code with an invalid email address', (done) -> opts = url: appEndPoint + "/resend-confirmation-code/asdfasdf" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.error.should.be.a 'string' done() it 'should request a new confirmation code with a valid email address', (done) -> opts = url: appEndPoint + "/resend-confirmation-code/" + validEmail + "?test=true", json: true request.get opts, (err, response, body) -> response.statusCode.should.equal 200 body.should.be.an 'object' body.success.should.equal 'OK' done() it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal 1 data[0].emailToSend.should.equal 1 data[0].users.length.should.equal 1 String(data[0].users[0]).should.equal String(user.id) data[0].from.should.equal app.config.email.marketing data[0].custom.should.be.an 'object' data[0].custom.confirmationCode.should.be.a 'string' confirmationCode = data[0].custom.confirmationCode app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> should.not.exist err ) it 'should take some to let the QEmail delete finish', (done) -> for i in [0 .. 1000000000] x = 1 done() it 'should confirm user email address', (done) -> opts = url: appEndPoint + "/confirm/" + confirmationCode json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.user.should.be.an 'object' done() it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal 1 data[0].emailToSend.should.equal 5 data[0].users.length.should.equal 1 String(data[0].users[0]).should.equal String(user.id) data[0].from.should.equal app.config.email.marketing app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> console.log "Am I happening: 1" console.log err ) it 'should take some to let the QEmail delete finish', (done) -> for i in [0 .. 1000000000] x = 1 done() it 'should not send password reset email code with an invalid email address', (done) -> opts = url: appEndPoint + "/reset-password/PI:PASSWORD:<PASSWORD>END_PI" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.error.should.be.a 'string' done() it 'should send password reset email code with a valid email address', (done) -> opts = url: appEndPoint + "/reset-password/" + validEmail json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.an 'object' should.not.exist body.error body.success.should.equal 'OK' done() it 'should have one QEmail Record', () -> app.models.QEmail.find() .then( (data) -> console.log "" data.length.should.equal(1); data[0].emailToSend.should.equal(3); data[0].users.length.should.equal(1); String(data[0].users[0]).should.equal(String(user.id)); data[0].from.should.equal(app.config.email.marketing); app.models.QEmail.deleteMany {}, (err, data) -> should.not.exist err data.ok.should.equal 1 data.n.should.equal 1 ) .catch( (err) -> console.log "Am I happening: 2" console.log err # should.not.exist err ) # it 'should take some to let the QEmail delete finish', (done) -> # for i in [0 .. 10000000] # x = 1 # done() it 'should logout', (done) -> opts = url: appEndPoint + "/logout" json: true request.get opts, (err, response, body) -> should.not.exist err response.statusCode.should.equal 200 body.should.be.a 'string' done() ###
[ { "context": "<li class=\"item click20\" data-id=\"3\" data-key=\"anyone\">Tre<span class=\"tags\">bully,zombopuppy</span></l", "end": 9225, "score": 0.7801569104194641, "start": 9222, "tag": "KEY", "value": "one" } ]
test/components/list/nested_list_test.coffee
pieces-js/pieces-list
0
'use strict' h = require 'pieces-list/test/helpers' utils = pi.utils Nod = pi.Nod describe "List.NestedSelect", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="selectable nested_select(klass:'pi-list')" data-pid="test" style="position:relative"> <ul class="list"> <li class="pi item pi-list click1" data-component="list" data-group-id="1" data-id="10" data-plugins="selectable"> <span class="click1">Click1</span> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item click2" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item click20" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </li> <li class="pi item pi-list" data-component="list" data-group-id="2" data-key="a" data-id="11" data-plugins="selectable"> <span>Click2</span> <ul class="list"> <li class="item click3" data-key="a" data-id="4">A</li> <li class="item click30" data-id="5">B</li> <li class="item" data-id="6">C</li> </ul> </li> <li class="pi item"> <span>Nested sublist</span> <div class="pi pi-list click10" data-component="list" pid="list" data-group-id="3" data-id="12" data-plugins="selectable sortable searchable"> <span>Click3</span> <ul class="list"> <li class="item" data-id="7">1</li> <li class="item click4" data-id="8" data-key="a">2</li> <li class="item" data-id="9" data-key="a">3</li> </ul> </div> </li> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove() describe "selected/selected_item", -> it "select one upper level item", (done)-> list.on 'selected', (event) => expect(list.selected()[0].record.group_id).to.eq 1 expect(event.data[0].record.group_id).to.eq 1 done() h.clickElement test_div.find('.click1').node it "select one lower level item", (done)-> list.on 'selected', (event) => expect(list.selected()[0].record.id).to.eq 2 expect(event.data[0].record.id).to.eq 2 done() h.clickElement test_div.find('.click2').node it "select_all", (done)-> list.on 'selected', (event) => expect(list.selected()).to.have.length 12 expect(event.data[1].record.id).to.eq 1 done() list.select_all() describe "events", -> beforeEach -> list.items[1].selectable.type 'check' describe "selection_cleared", -> it "don't send nested selection_cleared", (done)-> list.select_item list.items[0] list.items[1].select_item list.items[1].items[0] list.on 'selection_cleared', (event) => done("should not send nested event!") h.clickElement test_div.find('.click3').node utils.after 200, done it "selection_cleared if all cleared", (done)-> list.items[1].select_item list.items[1].items[0] list.on 'selection_cleared', (event) => done() h.clickElement test_div.find('.click3').node describe "selected", -> it "selected event with all selected items", (done)-> list.select_item list.items[0] list.items[1].select_item list.items[1].items[1] list.on 'selected', (e) => expect(e.data).to.have.length 3 done() h.clickElement test_div.find('.click3').node describe "update", -> it "update events from nested lists", (done)-> list.on 'update', (e) => expect(e.data.type).to.eq 'item_added' expect(e.data.item.record.id).to.eq 10 done() list.items[2].list.add_item pi.Nod.create('''<li class="item" data-id="10">10</li>''') describe "where", -> it "find items within nested lists and host list", -> expect(list.where(record: {key: 'a'})).to.have.length 4 describe "select and deselect item", -> it "select and deselect items", (done) -> list.on 'selected', (e) => expect(e.data[0].record.id).to.eq 7 done() list.select_item(list.where(record: {id: 7})[0]) describe "selected records", -> it "select records", -> list.select_item list.items[0] list.items[1].select_item list.items[1].items[0] list.items[2].list.select_item list.items[2].list.items[2] expect(list.selected_records().map((rec) -> rec.id)).to.eql [10, 4, 9] it "return one selected record", -> list.select_item list.items[0] expect(list.selected_record().id).to.eq 10 list.clear_selection() list.items[1].select_item list.items[1].items[0] expect(list.selected_record().id).to.eq 4 describe "selection types", -> it "radio", -> h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 4 it "inner as radio and outer as check", -> list.selectable.type 'check' h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 5 it "inner as check and outer as radio", -> item.selectable?.type('check') for item in list.items list.items[2].list.selectable.type 'check' h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 6 it "check", -> list.selectable.type 'check' item.selectable?.type('check') for item in list.items list.items[2].list.selectable.type 'check' h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 7 it "nested_select_type is radio", -> list.selectable.type 'check radio' item.selectable?.type('check radio') for item in list.items list.items[2].list.selectable.type 'check radio' list.nested_select.type 'radio' h.clickElement test_div.find('.click1').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 0 describe "List.NestedSelect (but not Selectable)", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="nested_select(klass:'pi-list')" data-pid="test" style="position:relative"> <ul class="list"> <li class="pi item pi-list click1" data-component="list" data-group-id="1" data-id="10" data-plugins="selectable"> <span class="click1">Click1</span> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item click2" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item click20" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </li> <li class="pi item pi-list" data-component="list" data-group-id="2" data-id="11" data-plugins="selectable(type:'check')"> <span>Click2</span> <ul class="list"> <li class="item click3" data-id="4">A</li> <li class="item click30" data-id="5">B</li> <li class="item" data-id="6">C</li> </ul> </li> <li class="pi item pi-list click10" data-component="list" data-group-id="3" data-id="12" data-plugins="selectable"> <span>Click3</span> <ul class="list"> <li class="item" data-id="7">1</li> <li class="item click4" data-id="8">2</li> <li class="item" data-id="9">3</li> </ul> </li> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove() describe "selected and selected_item", -> it "don't select one upper level item", -> spy_fun = sinon.spy() list.on 'selected', spy_fun h.clickElement test_div.find('.click1').node expect(spy_fun.callCount).to.eq 0 it "select all", (done)-> list.on 'selected', (event) => expect(list.selected()).to.have.length 9 expect(event.data[1].record.id).to.eq 2 done() list.select_all() describe "selection cleared", -> it "selection_cleared if all cleared", (done)-> list.items[1].select_item list.items[1].items[0] list.on 'selection_cleared', (event) => done() h.clickElement test_div.find('.click3').node describe "List.NestedSelect (several nested lists within one item)", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="nested_select(klass:'pi-list')" data-pid="test" style="position:relative"> <ul class="list"> <li class="pi item pi-list click1" data-component="list" data-group-id="1" data-id="10" data-plugins="selectable"> <span class="click1">Click1</span> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item click2" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item click20" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </li> <div class="pi item"> <li class="pi pi-list" data-group-id="2" data-component="list" data-id="11" data-plugins="selectable(type:'check')"> <span>Click2</span> <ul class="list"> <li class="item click3" data-id="4">A</li> <li class="item click30" data-id="5">B</li> <li class="item" data-id="6">C</li> </ul> </li> <li class="pi pi-list click10" data-component="list" data-group-id="3" data-id="12" data-plugins="selectable(type:'check')"> <span>Click3</span> <ul class="list"> <li class="item" data-id="7">1</li> <li class="item click4" data-id="8">2</li> <li class="item" data-id="9">3</li> </ul> </li> </div> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove() describe "selected and selected_item", -> it "select item", -> spy_fun = sinon.spy() list.on 'selected', spy_fun h.clickElement $('.click4').node expect(list.selected()).to.have.length 1 expect(spy_fun.callCount).to.eq 1 it "select all", -> list.on 'selected', (spy_fun = sinon.spy()) list.select_all() expect(spy_fun.callCount).to.eq 1 expect(list.selected()).to.have.length 9 expect(list.selected()[8].record.id).to.eq 9 describe "selection cleared", -> it "send nested selection cleared if all cleared", -> h.clickElement $('.click4').node sublist = $('.click10') expect(list.selected()).to.have.length 1 expect(sublist.selected()).to.have.length 1 list.on 'selection_cleared', (spy_fun = sinon.spy()) h.clickElement $('.click4').node expect(sublist.selected()).to.have.length 0 expect(list.selected()).to.have.length 0 expect(spy_fun.callCount).to.eq 1
60837
'use strict' h = require 'pieces-list/test/helpers' utils = pi.utils Nod = pi.Nod describe "List.NestedSelect", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="selectable nested_select(klass:'pi-list')" data-pid="test" style="position:relative"> <ul class="list"> <li class="pi item pi-list click1" data-component="list" data-group-id="1" data-id="10" data-plugins="selectable"> <span class="click1">Click1</span> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item click2" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item click20" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </li> <li class="pi item pi-list" data-component="list" data-group-id="2" data-key="a" data-id="11" data-plugins="selectable"> <span>Click2</span> <ul class="list"> <li class="item click3" data-key="a" data-id="4">A</li> <li class="item click30" data-id="5">B</li> <li class="item" data-id="6">C</li> </ul> </li> <li class="pi item"> <span>Nested sublist</span> <div class="pi pi-list click10" data-component="list" pid="list" data-group-id="3" data-id="12" data-plugins="selectable sortable searchable"> <span>Click3</span> <ul class="list"> <li class="item" data-id="7">1</li> <li class="item click4" data-id="8" data-key="a">2</li> <li class="item" data-id="9" data-key="a">3</li> </ul> </div> </li> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove() describe "selected/selected_item", -> it "select one upper level item", (done)-> list.on 'selected', (event) => expect(list.selected()[0].record.group_id).to.eq 1 expect(event.data[0].record.group_id).to.eq 1 done() h.clickElement test_div.find('.click1').node it "select one lower level item", (done)-> list.on 'selected', (event) => expect(list.selected()[0].record.id).to.eq 2 expect(event.data[0].record.id).to.eq 2 done() h.clickElement test_div.find('.click2').node it "select_all", (done)-> list.on 'selected', (event) => expect(list.selected()).to.have.length 12 expect(event.data[1].record.id).to.eq 1 done() list.select_all() describe "events", -> beforeEach -> list.items[1].selectable.type 'check' describe "selection_cleared", -> it "don't send nested selection_cleared", (done)-> list.select_item list.items[0] list.items[1].select_item list.items[1].items[0] list.on 'selection_cleared', (event) => done("should not send nested event!") h.clickElement test_div.find('.click3').node utils.after 200, done it "selection_cleared if all cleared", (done)-> list.items[1].select_item list.items[1].items[0] list.on 'selection_cleared', (event) => done() h.clickElement test_div.find('.click3').node describe "selected", -> it "selected event with all selected items", (done)-> list.select_item list.items[0] list.items[1].select_item list.items[1].items[1] list.on 'selected', (e) => expect(e.data).to.have.length 3 done() h.clickElement test_div.find('.click3').node describe "update", -> it "update events from nested lists", (done)-> list.on 'update', (e) => expect(e.data.type).to.eq 'item_added' expect(e.data.item.record.id).to.eq 10 done() list.items[2].list.add_item pi.Nod.create('''<li class="item" data-id="10">10</li>''') describe "where", -> it "find items within nested lists and host list", -> expect(list.where(record: {key: 'a'})).to.have.length 4 describe "select and deselect item", -> it "select and deselect items", (done) -> list.on 'selected', (e) => expect(e.data[0].record.id).to.eq 7 done() list.select_item(list.where(record: {id: 7})[0]) describe "selected records", -> it "select records", -> list.select_item list.items[0] list.items[1].select_item list.items[1].items[0] list.items[2].list.select_item list.items[2].list.items[2] expect(list.selected_records().map((rec) -> rec.id)).to.eql [10, 4, 9] it "return one selected record", -> list.select_item list.items[0] expect(list.selected_record().id).to.eq 10 list.clear_selection() list.items[1].select_item list.items[1].items[0] expect(list.selected_record().id).to.eq 4 describe "selection types", -> it "radio", -> h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 4 it "inner as radio and outer as check", -> list.selectable.type 'check' h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 5 it "inner as check and outer as radio", -> item.selectable?.type('check') for item in list.items list.items[2].list.selectable.type 'check' h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 6 it "check", -> list.selectable.type 'check' item.selectable?.type('check') for item in list.items list.items[2].list.selectable.type 'check' h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 7 it "nested_select_type is radio", -> list.selectable.type 'check radio' item.selectable?.type('check radio') for item in list.items list.items[2].list.selectable.type 'check radio' list.nested_select.type 'radio' h.clickElement test_div.find('.click1').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 0 describe "List.NestedSelect (but not Selectable)", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="nested_select(klass:'pi-list')" data-pid="test" style="position:relative"> <ul class="list"> <li class="pi item pi-list click1" data-component="list" data-group-id="1" data-id="10" data-plugins="selectable"> <span class="click1">Click1</span> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item click2" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item click20" data-id="3" data-key="any<KEY>">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </li> <li class="pi item pi-list" data-component="list" data-group-id="2" data-id="11" data-plugins="selectable(type:'check')"> <span>Click2</span> <ul class="list"> <li class="item click3" data-id="4">A</li> <li class="item click30" data-id="5">B</li> <li class="item" data-id="6">C</li> </ul> </li> <li class="pi item pi-list click10" data-component="list" data-group-id="3" data-id="12" data-plugins="selectable"> <span>Click3</span> <ul class="list"> <li class="item" data-id="7">1</li> <li class="item click4" data-id="8">2</li> <li class="item" data-id="9">3</li> </ul> </li> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove() describe "selected and selected_item", -> it "don't select one upper level item", -> spy_fun = sinon.spy() list.on 'selected', spy_fun h.clickElement test_div.find('.click1').node expect(spy_fun.callCount).to.eq 0 it "select all", (done)-> list.on 'selected', (event) => expect(list.selected()).to.have.length 9 expect(event.data[1].record.id).to.eq 2 done() list.select_all() describe "selection cleared", -> it "selection_cleared if all cleared", (done)-> list.items[1].select_item list.items[1].items[0] list.on 'selection_cleared', (event) => done() h.clickElement test_div.find('.click3').node describe "List.NestedSelect (several nested lists within one item)", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="nested_select(klass:'pi-list')" data-pid="test" style="position:relative"> <ul class="list"> <li class="pi item pi-list click1" data-component="list" data-group-id="1" data-id="10" data-plugins="selectable"> <span class="click1">Click1</span> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item click2" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item click20" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </li> <div class="pi item"> <li class="pi pi-list" data-group-id="2" data-component="list" data-id="11" data-plugins="selectable(type:'check')"> <span>Click2</span> <ul class="list"> <li class="item click3" data-id="4">A</li> <li class="item click30" data-id="5">B</li> <li class="item" data-id="6">C</li> </ul> </li> <li class="pi pi-list click10" data-component="list" data-group-id="3" data-id="12" data-plugins="selectable(type:'check')"> <span>Click3</span> <ul class="list"> <li class="item" data-id="7">1</li> <li class="item click4" data-id="8">2</li> <li class="item" data-id="9">3</li> </ul> </li> </div> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove() describe "selected and selected_item", -> it "select item", -> spy_fun = sinon.spy() list.on 'selected', spy_fun h.clickElement $('.click4').node expect(list.selected()).to.have.length 1 expect(spy_fun.callCount).to.eq 1 it "select all", -> list.on 'selected', (spy_fun = sinon.spy()) list.select_all() expect(spy_fun.callCount).to.eq 1 expect(list.selected()).to.have.length 9 expect(list.selected()[8].record.id).to.eq 9 describe "selection cleared", -> it "send nested selection cleared if all cleared", -> h.clickElement $('.click4').node sublist = $('.click10') expect(list.selected()).to.have.length 1 expect(sublist.selected()).to.have.length 1 list.on 'selection_cleared', (spy_fun = sinon.spy()) h.clickElement $('.click4').node expect(sublist.selected()).to.have.length 0 expect(list.selected()).to.have.length 0 expect(spy_fun.callCount).to.eq 1
true
'use strict' h = require 'pieces-list/test/helpers' utils = pi.utils Nod = pi.Nod describe "List.NestedSelect", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="selectable nested_select(klass:'pi-list')" data-pid="test" style="position:relative"> <ul class="list"> <li class="pi item pi-list click1" data-component="list" data-group-id="1" data-id="10" data-plugins="selectable"> <span class="click1">Click1</span> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item click2" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item click20" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </li> <li class="pi item pi-list" data-component="list" data-group-id="2" data-key="a" data-id="11" data-plugins="selectable"> <span>Click2</span> <ul class="list"> <li class="item click3" data-key="a" data-id="4">A</li> <li class="item click30" data-id="5">B</li> <li class="item" data-id="6">C</li> </ul> </li> <li class="pi item"> <span>Nested sublist</span> <div class="pi pi-list click10" data-component="list" pid="list" data-group-id="3" data-id="12" data-plugins="selectable sortable searchable"> <span>Click3</span> <ul class="list"> <li class="item" data-id="7">1</li> <li class="item click4" data-id="8" data-key="a">2</li> <li class="item" data-id="9" data-key="a">3</li> </ul> </div> </li> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove() describe "selected/selected_item", -> it "select one upper level item", (done)-> list.on 'selected', (event) => expect(list.selected()[0].record.group_id).to.eq 1 expect(event.data[0].record.group_id).to.eq 1 done() h.clickElement test_div.find('.click1').node it "select one lower level item", (done)-> list.on 'selected', (event) => expect(list.selected()[0].record.id).to.eq 2 expect(event.data[0].record.id).to.eq 2 done() h.clickElement test_div.find('.click2').node it "select_all", (done)-> list.on 'selected', (event) => expect(list.selected()).to.have.length 12 expect(event.data[1].record.id).to.eq 1 done() list.select_all() describe "events", -> beforeEach -> list.items[1].selectable.type 'check' describe "selection_cleared", -> it "don't send nested selection_cleared", (done)-> list.select_item list.items[0] list.items[1].select_item list.items[1].items[0] list.on 'selection_cleared', (event) => done("should not send nested event!") h.clickElement test_div.find('.click3').node utils.after 200, done it "selection_cleared if all cleared", (done)-> list.items[1].select_item list.items[1].items[0] list.on 'selection_cleared', (event) => done() h.clickElement test_div.find('.click3').node describe "selected", -> it "selected event with all selected items", (done)-> list.select_item list.items[0] list.items[1].select_item list.items[1].items[1] list.on 'selected', (e) => expect(e.data).to.have.length 3 done() h.clickElement test_div.find('.click3').node describe "update", -> it "update events from nested lists", (done)-> list.on 'update', (e) => expect(e.data.type).to.eq 'item_added' expect(e.data.item.record.id).to.eq 10 done() list.items[2].list.add_item pi.Nod.create('''<li class="item" data-id="10">10</li>''') describe "where", -> it "find items within nested lists and host list", -> expect(list.where(record: {key: 'a'})).to.have.length 4 describe "select and deselect item", -> it "select and deselect items", (done) -> list.on 'selected', (e) => expect(e.data[0].record.id).to.eq 7 done() list.select_item(list.where(record: {id: 7})[0]) describe "selected records", -> it "select records", -> list.select_item list.items[0] list.items[1].select_item list.items[1].items[0] list.items[2].list.select_item list.items[2].list.items[2] expect(list.selected_records().map((rec) -> rec.id)).to.eql [10, 4, 9] it "return one selected record", -> list.select_item list.items[0] expect(list.selected_record().id).to.eq 10 list.clear_selection() list.items[1].select_item list.items[1].items[0] expect(list.selected_record().id).to.eq 4 describe "selection types", -> it "radio", -> h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 4 it "inner as radio and outer as check", -> list.selectable.type 'check' h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 5 it "inner as check and outer as radio", -> item.selectable?.type('check') for item in list.items list.items[2].list.selectable.type 'check' h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 6 it "check", -> list.selectable.type 'check' item.selectable?.type('check') for item in list.items list.items[2].list.selectable.type 'check' h.clickElement test_div.find('.click1').node h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 7 it "nested_select_type is radio", -> list.selectable.type 'check radio' item.selectable?.type('check radio') for item in list.items list.items[2].list.selectable.type 'check radio' list.nested_select.type 'radio' h.clickElement test_div.find('.click1').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click2').node h.clickElement test_div.find('.click10').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click3').node h.clickElement test_div.find('.click20').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click30').node h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 1 h.clickElement test_div.find('.click4').node expect(list.selected_size()).to.eq 0 describe "List.NestedSelect (but not Selectable)", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="nested_select(klass:'pi-list')" data-pid="test" style="position:relative"> <ul class="list"> <li class="pi item pi-list click1" data-component="list" data-group-id="1" data-id="10" data-plugins="selectable"> <span class="click1">Click1</span> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item click2" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item click20" data-id="3" data-key="anyPI:KEY:<KEY>END_PI">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </li> <li class="pi item pi-list" data-component="list" data-group-id="2" data-id="11" data-plugins="selectable(type:'check')"> <span>Click2</span> <ul class="list"> <li class="item click3" data-id="4">A</li> <li class="item click30" data-id="5">B</li> <li class="item" data-id="6">C</li> </ul> </li> <li class="pi item pi-list click10" data-component="list" data-group-id="3" data-id="12" data-plugins="selectable"> <span>Click3</span> <ul class="list"> <li class="item" data-id="7">1</li> <li class="item click4" data-id="8">2</li> <li class="item" data-id="9">3</li> </ul> </li> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove() describe "selected and selected_item", -> it "don't select one upper level item", -> spy_fun = sinon.spy() list.on 'selected', spy_fun h.clickElement test_div.find('.click1').node expect(spy_fun.callCount).to.eq 0 it "select all", (done)-> list.on 'selected', (event) => expect(list.selected()).to.have.length 9 expect(event.data[1].record.id).to.eq 2 done() list.select_all() describe "selection cleared", -> it "selection_cleared if all cleared", (done)-> list.items[1].select_item list.items[1].items[0] list.on 'selection_cleared', (event) => done() h.clickElement test_div.find('.click3').node describe "List.NestedSelect (several nested lists within one item)", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="nested_select(klass:'pi-list')" data-pid="test" style="position:relative"> <ul class="list"> <li class="pi item pi-list click1" data-component="list" data-group-id="1" data-id="10" data-plugins="selectable"> <span class="click1">Click1</span> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item click2" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item click20" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </li> <div class="pi item"> <li class="pi pi-list" data-group-id="2" data-component="list" data-id="11" data-plugins="selectable(type:'check')"> <span>Click2</span> <ul class="list"> <li class="item click3" data-id="4">A</li> <li class="item click30" data-id="5">B</li> <li class="item" data-id="6">C</li> </ul> </li> <li class="pi pi-list click10" data-component="list" data-group-id="3" data-id="12" data-plugins="selectable(type:'check')"> <span>Click3</span> <ul class="list"> <li class="item" data-id="7">1</li> <li class="item click4" data-id="8">2</li> <li class="item" data-id="9">3</li> </ul> </li> </div> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove() describe "selected and selected_item", -> it "select item", -> spy_fun = sinon.spy() list.on 'selected', spy_fun h.clickElement $('.click4').node expect(list.selected()).to.have.length 1 expect(spy_fun.callCount).to.eq 1 it "select all", -> list.on 'selected', (spy_fun = sinon.spy()) list.select_all() expect(spy_fun.callCount).to.eq 1 expect(list.selected()).to.have.length 9 expect(list.selected()[8].record.id).to.eq 9 describe "selection cleared", -> it "send nested selection cleared if all cleared", -> h.clickElement $('.click4').node sublist = $('.click10') expect(list.selected()).to.have.length 1 expect(sublist.selected()).to.have.length 1 list.on 'selection_cleared', (spy_fun = sinon.spy()) h.clickElement $('.click4').node expect(sublist.selected()).to.have.length 0 expect(list.selected()).to.have.length 0 expect(spy_fun.callCount).to.eq 1
[ { "context": "path\n id: @token.getID()\n token: @token.get()\n\n @termView = new TerminalView(@term, null, ", "end": 6205, "score": 0.5788967609405518, "start": 6202, "tag": "KEY", "value": "get" } ]
lib/commit-live.coffee
commit-live-admin/dev-greyatom-ide
5
localStorage = require './local-storage' {CompositeDisposable, Notification} = require 'atom' Terminal = require './terminal' TerminalView = require './views/terminal' StatusView = require './views/status' {EventEmitter} = require 'events' Updater = require './updater' ProjectSearch = require './project-search' bus = require('./event-bus')() Notifier = require './notifier' atomHelper = require './atom-helper' startInstance = require './instance' auth = require './auth' loginWithGithub = require('./auth').loginWithGithub remote = require 'remote' BrowserWindow = remote.BrowserWindow localStorage = require './local-storage' {$} = require 'atom-space-pen-views' {name} = require '../package.json' toolBar = null; module.exports = token: require('./token') activate: (state) -> @checkForV1WindowsInstall() @subscriptions = new CompositeDisposable @subscribeToLogin() # atom.config.set('tool-bar.visible', false) atom.project.commitLiveIde = activateIde: => @activateIDE(state) @authenticateUser() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:test-task': () => @testTask() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:submit-task': () => @submitTask() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:execute-task': () => @executeTask() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:toggle-dashboard': () => @showDashboard() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:login-with-github': () => loginWithGithub() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:connect-to-project': () => atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:hide') atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live:change-project-title') atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live:refill-tasks') preReqPopup = new Notification("info", "Fetching Prerequisites...", {dismissable: true}) atom.notifications.addNotification(preReqPopup) auth().then => preReqPopup.dismiss() setTimeout => @studentServer = JSON.parse(localStorage.get('commit-live:user-info')).servers.student serverStatus = JSON.parse(localStorage.get('commit-live:user-info')).serverStatus if serverStatus == 2 spinUpPopup = new Notification("info", "Spining up your server...", {dismissable: true}) atom.notifications.addNotification(spinUpPopup) startInstance().then => spinUpPopup.dismiss() atom.notifications.addSuccess 'Your server is ready now!' setTimeout => @studentServer = JSON.parse(localStorage.get('commit-live:user-info')).servers.student @waitAndConnectToServer() , 0 .catch => spinUpPopup.dismiss() @showSessionExpired() @logout() else if atom.project and atom.project.remoteftp if atom.project.remoteftp.isConnected() @showCodingScreen() else atom.project.remoteftp.connectToStudentFTP() , 0 .catch => preReqPopup.dismiss() @showSessionExpired() @logout() @projectSearch = new ProjectSearch() @activateUpdater() showDashboard: () -> dashboardView = $('.commit-live-settings-view') if !dashboardView.length atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:show-dashboard') if atom.project.remoteftp.isConnected() atom.project['remoteftp-main'].treeView.detach() @termView.panel.hide() showCodingScreen: () -> atom.project['remoteftp-main'].treeView.attach() @termView.panel.show() lastProject = JSON.parse(localStorage.get('commit-live:last-opened-project')) if lastProject @termView?.openLab(lastProject.id) showSessionExpired: () -> sessionExpiredNotify = new Notification("info", "Commit Live IDE: Please Login Again", { dismissable: false, description: 'Your session has expired!' }); atom.notifications.addNotification(sessionExpiredNotify) waitAndConnectToServer: () -> waitTime = 10 # seconds launchPopup = null launchPopup = new Notification("info", "Launching our services...", {dismissable: true}) atom.notifications.addNotification(launchPopup) setTimeout -> launchPopup.dismiss() if atom.project and atom.project.remoteftp atom.project.remoteftp.connectToStudentFTP() , 1000 * waitTime authenticateUser: () -> authPopup = new Notification("info", "Commit Live IDE: Authenticating...", {dismissable: true}) atom.notifications.addNotification(authPopup) @waitForAuth = auth().then => authPopup.dismiss() setTimeout -> atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:show-dashboard') atom.notifications.addSuccess 'Commit Live IDE: You have successfully logged in.' , 0 .catch => authPopup.dismiss() atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:show-login') activateIDE: (state) -> @isTerminalWindow = (localStorage.get('popoutTerminal') == 'true') if @isTerminalWindow window.resizeTo(750, 500) localStorage.delete('popoutTerminal') @isRestartAfterUpdate = (localStorage.get('restartingForUpdate') == 'true') if @isRestartAfterUpdate Updater.didRestartAfterUpdate() localStorage.delete('restartingForUpdate') @activateTerminal() @activateStatusView(state) @activateEventHandlers() @activateSubscriptions() @activateNotifier() # @termView.sendClear() activateTerminal: -> @term = new Terminal host: @studentServer.host port: @studentServer.port path: @studentServer.terminal_path id: @token.getID() token: @token.get() @termView = new TerminalView(@term, null, @isTerminalWindow) @termView.toggle() activateStatusView: (state) -> @statusView = new StatusView state, @term, {@isTerminalWindow} @addStatusBar(item: @statusView, priority: 5000) bus.on 'terminal:popin', () => @statusView.onTerminalPopIn() @termView.showAndFocus() @statusView.on 'terminal:popout', => @termView.toggle() activateEventHandlers: -> atomHelper.trackFocusedWindow() # listen for commit-live:open event from other render processes (url handler) bus.on 'commit-live:open', (lab) => console.log "inside bus.on " , lab.slug @termView.openLab(lab.slug) atom.getCurrentWindow().focus() # tidy up when the window closes atom.getCurrentWindow().on 'close', => @cleanup() if @isTerminalWindow bus.emit('terminal:popin', Date.now()) activateSubscriptions: -> @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:open': (e) => @termView?.openLab(e.detail.path) 'commit-live:toggle-terminal': () => @termView?.toggle() 'commit-live:toggle-focus': => @termView?.toggleFocus() 'commit-live:focus': => @termView?.fullFocus() 'commit-live:toggle:debugger': => @term.toggleDebugger() 'commit-live:reset': => @term.reset() # 'application:update-ile': -> (new Updater).checkForUpdate() atom.config.onDidChange "#{name}.notifier", ({newValue}) => if newValue then @activateNotifier() else @notifier.deactivate() openPath = localStorage.get('commitLiveOpenLabOnActivation') if openPath localStorage.delete('commitLiveOpenLabOnActivation') @termView.openLab(openPath) activateNotifier: -> if atom.config.get("#{name}.notifier") @notifier = new Notifier(@token.get()) @notifier.activate() activateUpdater: -> if !@isRestartAfterUpdate Updater.checkForUpdate() deactivate: -> localStorage.delete('disableTreeView') localStorage.delete('terminalOut') @termView = null @statusView = null @subscriptions.dispose() @projectSearch.destroy() subscribeToLogin: -> @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:log-in-out': => @logInOrOut() cleanup: -> atomHelper.cleanup() testTask: -> @termView.showAndFocus() blob = localStorage.get('commit-live:current-track') if blob {titleSlug, titleSlugTestCase} = JSON.parse(blob) path = atom.project.remoteftp.getPathForTrack(titleSlug) command = "cd #{path} \r clear \rclive test #{titleSlugTestCase}" @termView.executeCommand(command) submitTask: -> @termView.showAndFocus() blob = localStorage.get('commit-live:current-track') if blob {titleSlug, titleSlugTestCase} = JSON.parse(blob) path = atom.project.remoteftp.getPathForTrack(titleSlug) command = "cd #{path} \r clear \rclive submit #{titleSlugTestCase}" @termView.executeCommand(command) executeTask: -> @termView.showAndFocus() blob = localStorage.get('commit-live:current-track') if blob {titleSlug, testCase} = JSON.parse(blob) path = atom.project.remoteftp.getPathForTrack(titleSlug) command = "cd #{path} \r clear \rpython #{testCase}/build.py" @termView.executeCommand(command) consumeStatusBar: (statusBar) -> @addStatusBar = statusBar.addRightTile logInOrOut: -> if @token.get()? @logout() else atomHelper.resetPackage() logout: -> localStorage.delete('commit-live:user-info') localStorage.delete('commit-live:last-opened-project') @token.unset() @token.unsetID() atom.restartApplication() checkForV1WindowsInstall: -> require('./windows')
201180
localStorage = require './local-storage' {CompositeDisposable, Notification} = require 'atom' Terminal = require './terminal' TerminalView = require './views/terminal' StatusView = require './views/status' {EventEmitter} = require 'events' Updater = require './updater' ProjectSearch = require './project-search' bus = require('./event-bus')() Notifier = require './notifier' atomHelper = require './atom-helper' startInstance = require './instance' auth = require './auth' loginWithGithub = require('./auth').loginWithGithub remote = require 'remote' BrowserWindow = remote.BrowserWindow localStorage = require './local-storage' {$} = require 'atom-space-pen-views' {name} = require '../package.json' toolBar = null; module.exports = token: require('./token') activate: (state) -> @checkForV1WindowsInstall() @subscriptions = new CompositeDisposable @subscribeToLogin() # atom.config.set('tool-bar.visible', false) atom.project.commitLiveIde = activateIde: => @activateIDE(state) @authenticateUser() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:test-task': () => @testTask() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:submit-task': () => @submitTask() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:execute-task': () => @executeTask() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:toggle-dashboard': () => @showDashboard() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:login-with-github': () => loginWithGithub() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:connect-to-project': () => atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:hide') atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live:change-project-title') atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live:refill-tasks') preReqPopup = new Notification("info", "Fetching Prerequisites...", {dismissable: true}) atom.notifications.addNotification(preReqPopup) auth().then => preReqPopup.dismiss() setTimeout => @studentServer = JSON.parse(localStorage.get('commit-live:user-info')).servers.student serverStatus = JSON.parse(localStorage.get('commit-live:user-info')).serverStatus if serverStatus == 2 spinUpPopup = new Notification("info", "Spining up your server...", {dismissable: true}) atom.notifications.addNotification(spinUpPopup) startInstance().then => spinUpPopup.dismiss() atom.notifications.addSuccess 'Your server is ready now!' setTimeout => @studentServer = JSON.parse(localStorage.get('commit-live:user-info')).servers.student @waitAndConnectToServer() , 0 .catch => spinUpPopup.dismiss() @showSessionExpired() @logout() else if atom.project and atom.project.remoteftp if atom.project.remoteftp.isConnected() @showCodingScreen() else atom.project.remoteftp.connectToStudentFTP() , 0 .catch => preReqPopup.dismiss() @showSessionExpired() @logout() @projectSearch = new ProjectSearch() @activateUpdater() showDashboard: () -> dashboardView = $('.commit-live-settings-view') if !dashboardView.length atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:show-dashboard') if atom.project.remoteftp.isConnected() atom.project['remoteftp-main'].treeView.detach() @termView.panel.hide() showCodingScreen: () -> atom.project['remoteftp-main'].treeView.attach() @termView.panel.show() lastProject = JSON.parse(localStorage.get('commit-live:last-opened-project')) if lastProject @termView?.openLab(lastProject.id) showSessionExpired: () -> sessionExpiredNotify = new Notification("info", "Commit Live IDE: Please Login Again", { dismissable: false, description: 'Your session has expired!' }); atom.notifications.addNotification(sessionExpiredNotify) waitAndConnectToServer: () -> waitTime = 10 # seconds launchPopup = null launchPopup = new Notification("info", "Launching our services...", {dismissable: true}) atom.notifications.addNotification(launchPopup) setTimeout -> launchPopup.dismiss() if atom.project and atom.project.remoteftp atom.project.remoteftp.connectToStudentFTP() , 1000 * waitTime authenticateUser: () -> authPopup = new Notification("info", "Commit Live IDE: Authenticating...", {dismissable: true}) atom.notifications.addNotification(authPopup) @waitForAuth = auth().then => authPopup.dismiss() setTimeout -> atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:show-dashboard') atom.notifications.addSuccess 'Commit Live IDE: You have successfully logged in.' , 0 .catch => authPopup.dismiss() atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:show-login') activateIDE: (state) -> @isTerminalWindow = (localStorage.get('popoutTerminal') == 'true') if @isTerminalWindow window.resizeTo(750, 500) localStorage.delete('popoutTerminal') @isRestartAfterUpdate = (localStorage.get('restartingForUpdate') == 'true') if @isRestartAfterUpdate Updater.didRestartAfterUpdate() localStorage.delete('restartingForUpdate') @activateTerminal() @activateStatusView(state) @activateEventHandlers() @activateSubscriptions() @activateNotifier() # @termView.sendClear() activateTerminal: -> @term = new Terminal host: @studentServer.host port: @studentServer.port path: @studentServer.terminal_path id: @token.getID() token: @token.<KEY>() @termView = new TerminalView(@term, null, @isTerminalWindow) @termView.toggle() activateStatusView: (state) -> @statusView = new StatusView state, @term, {@isTerminalWindow} @addStatusBar(item: @statusView, priority: 5000) bus.on 'terminal:popin', () => @statusView.onTerminalPopIn() @termView.showAndFocus() @statusView.on 'terminal:popout', => @termView.toggle() activateEventHandlers: -> atomHelper.trackFocusedWindow() # listen for commit-live:open event from other render processes (url handler) bus.on 'commit-live:open', (lab) => console.log "inside bus.on " , lab.slug @termView.openLab(lab.slug) atom.getCurrentWindow().focus() # tidy up when the window closes atom.getCurrentWindow().on 'close', => @cleanup() if @isTerminalWindow bus.emit('terminal:popin', Date.now()) activateSubscriptions: -> @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:open': (e) => @termView?.openLab(e.detail.path) 'commit-live:toggle-terminal': () => @termView?.toggle() 'commit-live:toggle-focus': => @termView?.toggleFocus() 'commit-live:focus': => @termView?.fullFocus() 'commit-live:toggle:debugger': => @term.toggleDebugger() 'commit-live:reset': => @term.reset() # 'application:update-ile': -> (new Updater).checkForUpdate() atom.config.onDidChange "#{name}.notifier", ({newValue}) => if newValue then @activateNotifier() else @notifier.deactivate() openPath = localStorage.get('commitLiveOpenLabOnActivation') if openPath localStorage.delete('commitLiveOpenLabOnActivation') @termView.openLab(openPath) activateNotifier: -> if atom.config.get("#{name}.notifier") @notifier = new Notifier(@token.get()) @notifier.activate() activateUpdater: -> if !@isRestartAfterUpdate Updater.checkForUpdate() deactivate: -> localStorage.delete('disableTreeView') localStorage.delete('terminalOut') @termView = null @statusView = null @subscriptions.dispose() @projectSearch.destroy() subscribeToLogin: -> @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:log-in-out': => @logInOrOut() cleanup: -> atomHelper.cleanup() testTask: -> @termView.showAndFocus() blob = localStorage.get('commit-live:current-track') if blob {titleSlug, titleSlugTestCase} = JSON.parse(blob) path = atom.project.remoteftp.getPathForTrack(titleSlug) command = "cd #{path} \r clear \rclive test #{titleSlugTestCase}" @termView.executeCommand(command) submitTask: -> @termView.showAndFocus() blob = localStorage.get('commit-live:current-track') if blob {titleSlug, titleSlugTestCase} = JSON.parse(blob) path = atom.project.remoteftp.getPathForTrack(titleSlug) command = "cd #{path} \r clear \rclive submit #{titleSlugTestCase}" @termView.executeCommand(command) executeTask: -> @termView.showAndFocus() blob = localStorage.get('commit-live:current-track') if blob {titleSlug, testCase} = JSON.parse(blob) path = atom.project.remoteftp.getPathForTrack(titleSlug) command = "cd #{path} \r clear \rpython #{testCase}/build.py" @termView.executeCommand(command) consumeStatusBar: (statusBar) -> @addStatusBar = statusBar.addRightTile logInOrOut: -> if @token.get()? @logout() else atomHelper.resetPackage() logout: -> localStorage.delete('commit-live:user-info') localStorage.delete('commit-live:last-opened-project') @token.unset() @token.unsetID() atom.restartApplication() checkForV1WindowsInstall: -> require('./windows')
true
localStorage = require './local-storage' {CompositeDisposable, Notification} = require 'atom' Terminal = require './terminal' TerminalView = require './views/terminal' StatusView = require './views/status' {EventEmitter} = require 'events' Updater = require './updater' ProjectSearch = require './project-search' bus = require('./event-bus')() Notifier = require './notifier' atomHelper = require './atom-helper' startInstance = require './instance' auth = require './auth' loginWithGithub = require('./auth').loginWithGithub remote = require 'remote' BrowserWindow = remote.BrowserWindow localStorage = require './local-storage' {$} = require 'atom-space-pen-views' {name} = require '../package.json' toolBar = null; module.exports = token: require('./token') activate: (state) -> @checkForV1WindowsInstall() @subscriptions = new CompositeDisposable @subscribeToLogin() # atom.config.set('tool-bar.visible', false) atom.project.commitLiveIde = activateIde: => @activateIDE(state) @authenticateUser() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:test-task': () => @testTask() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:submit-task': () => @submitTask() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:execute-task': () => @executeTask() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:toggle-dashboard': () => @showDashboard() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:login-with-github': () => loginWithGithub() @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:connect-to-project': () => atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:hide') atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live:change-project-title') atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live:refill-tasks') preReqPopup = new Notification("info", "Fetching Prerequisites...", {dismissable: true}) atom.notifications.addNotification(preReqPopup) auth().then => preReqPopup.dismiss() setTimeout => @studentServer = JSON.parse(localStorage.get('commit-live:user-info')).servers.student serverStatus = JSON.parse(localStorage.get('commit-live:user-info')).serverStatus if serverStatus == 2 spinUpPopup = new Notification("info", "Spining up your server...", {dismissable: true}) atom.notifications.addNotification(spinUpPopup) startInstance().then => spinUpPopup.dismiss() atom.notifications.addSuccess 'Your server is ready now!' setTimeout => @studentServer = JSON.parse(localStorage.get('commit-live:user-info')).servers.student @waitAndConnectToServer() , 0 .catch => spinUpPopup.dismiss() @showSessionExpired() @logout() else if atom.project and atom.project.remoteftp if atom.project.remoteftp.isConnected() @showCodingScreen() else atom.project.remoteftp.connectToStudentFTP() , 0 .catch => preReqPopup.dismiss() @showSessionExpired() @logout() @projectSearch = new ProjectSearch() @activateUpdater() showDashboard: () -> dashboardView = $('.commit-live-settings-view') if !dashboardView.length atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:show-dashboard') if atom.project.remoteftp.isConnected() atom.project['remoteftp-main'].treeView.detach() @termView.panel.hide() showCodingScreen: () -> atom.project['remoteftp-main'].treeView.attach() @termView.panel.show() lastProject = JSON.parse(localStorage.get('commit-live:last-opened-project')) if lastProject @termView?.openLab(lastProject.id) showSessionExpired: () -> sessionExpiredNotify = new Notification("info", "Commit Live IDE: Please Login Again", { dismissable: false, description: 'Your session has expired!' }); atom.notifications.addNotification(sessionExpiredNotify) waitAndConnectToServer: () -> waitTime = 10 # seconds launchPopup = null launchPopup = new Notification("info", "Launching our services...", {dismissable: true}) atom.notifications.addNotification(launchPopup) setTimeout -> launchPopup.dismiss() if atom.project and atom.project.remoteftp atom.project.remoteftp.connectToStudentFTP() , 1000 * waitTime authenticateUser: () -> authPopup = new Notification("info", "Commit Live IDE: Authenticating...", {dismissable: true}) atom.notifications.addNotification(authPopup) @waitForAuth = auth().then => authPopup.dismiss() setTimeout -> atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:show-dashboard') atom.notifications.addSuccess 'Commit Live IDE: You have successfully logged in.' , 0 .catch => authPopup.dismiss() atom.commands.dispatch(atom.views.getView(atom.workspace), 'commit-live-welcome:show-login') activateIDE: (state) -> @isTerminalWindow = (localStorage.get('popoutTerminal') == 'true') if @isTerminalWindow window.resizeTo(750, 500) localStorage.delete('popoutTerminal') @isRestartAfterUpdate = (localStorage.get('restartingForUpdate') == 'true') if @isRestartAfterUpdate Updater.didRestartAfterUpdate() localStorage.delete('restartingForUpdate') @activateTerminal() @activateStatusView(state) @activateEventHandlers() @activateSubscriptions() @activateNotifier() # @termView.sendClear() activateTerminal: -> @term = new Terminal host: @studentServer.host port: @studentServer.port path: @studentServer.terminal_path id: @token.getID() token: @token.PI:KEY:<KEY>END_PI() @termView = new TerminalView(@term, null, @isTerminalWindow) @termView.toggle() activateStatusView: (state) -> @statusView = new StatusView state, @term, {@isTerminalWindow} @addStatusBar(item: @statusView, priority: 5000) bus.on 'terminal:popin', () => @statusView.onTerminalPopIn() @termView.showAndFocus() @statusView.on 'terminal:popout', => @termView.toggle() activateEventHandlers: -> atomHelper.trackFocusedWindow() # listen for commit-live:open event from other render processes (url handler) bus.on 'commit-live:open', (lab) => console.log "inside bus.on " , lab.slug @termView.openLab(lab.slug) atom.getCurrentWindow().focus() # tidy up when the window closes atom.getCurrentWindow().on 'close', => @cleanup() if @isTerminalWindow bus.emit('terminal:popin', Date.now()) activateSubscriptions: -> @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:open': (e) => @termView?.openLab(e.detail.path) 'commit-live:toggle-terminal': () => @termView?.toggle() 'commit-live:toggle-focus': => @termView?.toggleFocus() 'commit-live:focus': => @termView?.fullFocus() 'commit-live:toggle:debugger': => @term.toggleDebugger() 'commit-live:reset': => @term.reset() # 'application:update-ile': -> (new Updater).checkForUpdate() atom.config.onDidChange "#{name}.notifier", ({newValue}) => if newValue then @activateNotifier() else @notifier.deactivate() openPath = localStorage.get('commitLiveOpenLabOnActivation') if openPath localStorage.delete('commitLiveOpenLabOnActivation') @termView.openLab(openPath) activateNotifier: -> if atom.config.get("#{name}.notifier") @notifier = new Notifier(@token.get()) @notifier.activate() activateUpdater: -> if !@isRestartAfterUpdate Updater.checkForUpdate() deactivate: -> localStorage.delete('disableTreeView') localStorage.delete('terminalOut') @termView = null @statusView = null @subscriptions.dispose() @projectSearch.destroy() subscribeToLogin: -> @subscriptions.add atom.commands.add 'atom-workspace', 'commit-live:log-in-out': => @logInOrOut() cleanup: -> atomHelper.cleanup() testTask: -> @termView.showAndFocus() blob = localStorage.get('commit-live:current-track') if blob {titleSlug, titleSlugTestCase} = JSON.parse(blob) path = atom.project.remoteftp.getPathForTrack(titleSlug) command = "cd #{path} \r clear \rclive test #{titleSlugTestCase}" @termView.executeCommand(command) submitTask: -> @termView.showAndFocus() blob = localStorage.get('commit-live:current-track') if blob {titleSlug, titleSlugTestCase} = JSON.parse(blob) path = atom.project.remoteftp.getPathForTrack(titleSlug) command = "cd #{path} \r clear \rclive submit #{titleSlugTestCase}" @termView.executeCommand(command) executeTask: -> @termView.showAndFocus() blob = localStorage.get('commit-live:current-track') if blob {titleSlug, testCase} = JSON.parse(blob) path = atom.project.remoteftp.getPathForTrack(titleSlug) command = "cd #{path} \r clear \rpython #{testCase}/build.py" @termView.executeCommand(command) consumeStatusBar: (statusBar) -> @addStatusBar = statusBar.addRightTile logInOrOut: -> if @token.get()? @logout() else atomHelper.resetPackage() logout: -> localStorage.delete('commit-live:user-info') localStorage.delete('commit-live:last-opened-project') @token.unset() @token.unsetID() atom.restartApplication() checkForV1WindowsInstall: -> require('./windows')
[ { "context": "ontroller.create()\n#myArray.content.pushObjects([\"Jack\", \"Cassandra\", \"Raj\"])\n\n#window.myArray2 = Ember.", "end": 1231, "score": 0.9971268773078918, "start": 1227, "tag": "NAME", "value": "Jack" }, { "context": "r.create()\n#myArray.content.pushObjects([\"Jack\", \"Cassandra\", \"Raj\"])\n\n#window.myArray2 = Ember.SortedArrayCo", "end": 1244, "score": 0.984147310256958, "start": 1235, "tag": "NAME", "value": "Cassandra" }, { "context": "yArray.content.pushObjects([\"Jack\", \"Cassandra\", \"Raj\"])\n\n#window.myArray2 = Ember.SortedArrayControlle", "end": 1251, "score": 0.9950133562088013, "start": 1248, "tag": "NAME", "value": "Raj" }, { "context": "rder: \"reverse\"})\n#myArray2.content.pushObjects([\"Jack\", \"Cassandra\", \"Raj\"])\n#\n#window.myArray3 = Ember", "end": 1370, "score": 0.9949895739555359, "start": 1366, "tag": "NAME", "value": "Jack" }, { "context": "everse\"})\n#myArray2.content.pushObjects([\"Jack\", \"Cassandra\", \"Raj\"])\n#\n#window.myArray3 = Ember.SortedArrayC", "end": 1383, "score": 0.9721680879592896, "start": 1374, "tag": "NAME", "value": "Cassandra" }, { "context": "Array2.content.pushObjects([\"Jack\", \"Cassandra\", \"Raj\"])\n#\n#window.myArray3 = Ember.SortedArrayControll", "end": 1390, "score": 0.9935567378997803, "start": 1387, "tag": "NAME", "value": "Raj" }, { "context": "Order: \"random\"})\n#myArray3.content.pushObjects([\"Jack\", \"Cassandra\", \"Raj\"])\n", "end": 1509, "score": 0.9939490556716919, "start": 1505, "tag": "NAME", "value": "Jack" }, { "context": "random\"})\n#myArray3.content.pushObjects([\"Jack\", \"Cassandra\", \"Raj\"])\n", "end": 1522, "score": 0.9414827227592468, "start": 1513, "tag": "NAME", "value": "Cassandra" }, { "context": "Array3.content.pushObjects([\"Jack\", \"Cassandra\", \"Raj\"])\n", "end": 1529, "score": 0.9848476648330688, "start": 1526, "tag": "NAME", "value": "Raj" } ]
app/assets/javascripts/sorted-array.js.coffee
StoneCypher/coderwall
1
Ember.SortedArrayController = Ember.ArrayController.extend( sortOrder: "normal" sortFunction: null inputCollectionName: "content" outputCollectionName: "content" maxCollectionSize: -1 init: -> @set(@inputCollectionName, []) @addObserver(@inputCollectionName + '.@each', -> @elementAdded()) @addObserver(@outputCollectionName + '.@each', -> @trimArray()) elementAdded: (-> context = @ content = @get(@inputCollectionName) if @sortOrder == "normal" if @sortFunction? then content.sort((a, b)-> context.sortFunction(a, b)) else content.sort() else if @sortOrder == "reverse" if @sortFunction? then content.sort((a, b)-> context.sortFunction(b, a)) else content.reverse() else if @sortOrder == "random" content.sort((a, b)-> 0.5 - Math.random("deadbeef")) @set(@outputCollectionName, content) ) trimArray: (-> content = @get(@outputCollectionName) @set(@outputCollectionName, content.slice(0, @maxCollectionSize - 1))if (@maxCollectionSize > 0) and (content.length > @maxCollectionSize) ) ) #window.myArray = Ember.SortedArrayController.create() #myArray.content.pushObjects(["Jack", "Cassandra", "Raj"]) #window.myArray2 = Ember.SortedArrayController.create({sortOrder: "reverse"}) #myArray2.content.pushObjects(["Jack", "Cassandra", "Raj"]) # #window.myArray3 = Ember.SortedArrayController.create({sortOrder: "random"}) #myArray3.content.pushObjects(["Jack", "Cassandra", "Raj"])
52055
Ember.SortedArrayController = Ember.ArrayController.extend( sortOrder: "normal" sortFunction: null inputCollectionName: "content" outputCollectionName: "content" maxCollectionSize: -1 init: -> @set(@inputCollectionName, []) @addObserver(@inputCollectionName + '.@each', -> @elementAdded()) @addObserver(@outputCollectionName + '.@each', -> @trimArray()) elementAdded: (-> context = @ content = @get(@inputCollectionName) if @sortOrder == "normal" if @sortFunction? then content.sort((a, b)-> context.sortFunction(a, b)) else content.sort() else if @sortOrder == "reverse" if @sortFunction? then content.sort((a, b)-> context.sortFunction(b, a)) else content.reverse() else if @sortOrder == "random" content.sort((a, b)-> 0.5 - Math.random("deadbeef")) @set(@outputCollectionName, content) ) trimArray: (-> content = @get(@outputCollectionName) @set(@outputCollectionName, content.slice(0, @maxCollectionSize - 1))if (@maxCollectionSize > 0) and (content.length > @maxCollectionSize) ) ) #window.myArray = Ember.SortedArrayController.create() #myArray.content.pushObjects(["<NAME>", "<NAME>", "<NAME>"]) #window.myArray2 = Ember.SortedArrayController.create({sortOrder: "reverse"}) #myArray2.content.pushObjects(["<NAME>", "<NAME>", "<NAME>"]) # #window.myArray3 = Ember.SortedArrayController.create({sortOrder: "random"}) #myArray3.content.pushObjects(["<NAME>", "<NAME>", "<NAME>"])
true
Ember.SortedArrayController = Ember.ArrayController.extend( sortOrder: "normal" sortFunction: null inputCollectionName: "content" outputCollectionName: "content" maxCollectionSize: -1 init: -> @set(@inputCollectionName, []) @addObserver(@inputCollectionName + '.@each', -> @elementAdded()) @addObserver(@outputCollectionName + '.@each', -> @trimArray()) elementAdded: (-> context = @ content = @get(@inputCollectionName) if @sortOrder == "normal" if @sortFunction? then content.sort((a, b)-> context.sortFunction(a, b)) else content.sort() else if @sortOrder == "reverse" if @sortFunction? then content.sort((a, b)-> context.sortFunction(b, a)) else content.reverse() else if @sortOrder == "random" content.sort((a, b)-> 0.5 - Math.random("deadbeef")) @set(@outputCollectionName, content) ) trimArray: (-> content = @get(@outputCollectionName) @set(@outputCollectionName, content.slice(0, @maxCollectionSize - 1))if (@maxCollectionSize > 0) and (content.length > @maxCollectionSize) ) ) #window.myArray = Ember.SortedArrayController.create() #myArray.content.pushObjects(["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]) #window.myArray2 = Ember.SortedArrayController.create({sortOrder: "reverse"}) #myArray2.content.pushObjects(["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]) # #window.myArray3 = Ember.SortedArrayController.create({sortOrder: "random"}) #myArray3.content.pushObjects(["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"])
[ { "context": " ->\n x = 0x40000000\n \n # Put in an eval to foil Crankshaft.\n eval \"\"\n i = 0\n\n while i < 1000000\n asser", "end": 2162, "score": 0.9997960925102234, "start": 2152, "tag": "NAME", "value": "Crankshaft" } ]
deps/v8/test/mjsunit/bit-not.coffee
lxe/io.coffee
0
# Copyright 2009 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. testBitNot = (x, name) -> # The VM constant folds so we use that to check the result. expected = eval("~(" + x + ")") actual = ~x assertEquals expected, actual, "x: " + name # Test the path where we can overwrite the result. Use - # to avoid concatenating strings. expected = eval("~(" + x + " - 0.01)") actual = ~(x - 0.01) assertEquals expected, actual, "x - 0.01: " + name return # Try to test that we can deal with allocation failures in # the fast path and just use the slow path instead. TryToGC = -> x = 0x40000000 # Put in an eval to foil Crankshaft. eval "" i = 0 while i < 1000000 assertEquals ~0x40000000, ~x i++ return testBitNot 0, 0 testBitNot 1, 1 testBitNot -1, 1 testBitNot 100, 100 testBitNot 0x40000000, "0x40000000" testBitNot 0x7fffffff, "0x7fffffff" testBitNot 0x80000000, "0x80000000" testBitNot 2.2, 2.2 testBitNot -2.3, -2.3 testBitNot Infinity, "Infinity" testBitNot NaN, "NaN" testBitNot -Infinity, "-Infinity" testBitNot 0x40000000 + 0.12345, "float1" testBitNot 0x40000000 - 0.12345, "float2" testBitNot 0x7fffffff + 0.12345, "float3" testBitNot 0x7fffffff - 0.12345, "float4" testBitNot 0x80000000 + 0.12345, "float5" testBitNot 0x80000000 - 0.12345, "float6" testBitNot "0", "string0" testBitNot "2.3", "string2.3" testBitNot "-9.4", "string-9.4" TryToGC()
109043
# Copyright 2009 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. testBitNot = (x, name) -> # The VM constant folds so we use that to check the result. expected = eval("~(" + x + ")") actual = ~x assertEquals expected, actual, "x: " + name # Test the path where we can overwrite the result. Use - # to avoid concatenating strings. expected = eval("~(" + x + " - 0.01)") actual = ~(x - 0.01) assertEquals expected, actual, "x - 0.01: " + name return # Try to test that we can deal with allocation failures in # the fast path and just use the slow path instead. TryToGC = -> x = 0x40000000 # Put in an eval to foil <NAME>. eval "" i = 0 while i < 1000000 assertEquals ~0x40000000, ~x i++ return testBitNot 0, 0 testBitNot 1, 1 testBitNot -1, 1 testBitNot 100, 100 testBitNot 0x40000000, "0x40000000" testBitNot 0x7fffffff, "0x7fffffff" testBitNot 0x80000000, "0x80000000" testBitNot 2.2, 2.2 testBitNot -2.3, -2.3 testBitNot Infinity, "Infinity" testBitNot NaN, "NaN" testBitNot -Infinity, "-Infinity" testBitNot 0x40000000 + 0.12345, "float1" testBitNot 0x40000000 - 0.12345, "float2" testBitNot 0x7fffffff + 0.12345, "float3" testBitNot 0x7fffffff - 0.12345, "float4" testBitNot 0x80000000 + 0.12345, "float5" testBitNot 0x80000000 - 0.12345, "float6" testBitNot "0", "string0" testBitNot "2.3", "string2.3" testBitNot "-9.4", "string-9.4" TryToGC()
true
# Copyright 2009 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. testBitNot = (x, name) -> # The VM constant folds so we use that to check the result. expected = eval("~(" + x + ")") actual = ~x assertEquals expected, actual, "x: " + name # Test the path where we can overwrite the result. Use - # to avoid concatenating strings. expected = eval("~(" + x + " - 0.01)") actual = ~(x - 0.01) assertEquals expected, actual, "x - 0.01: " + name return # Try to test that we can deal with allocation failures in # the fast path and just use the slow path instead. TryToGC = -> x = 0x40000000 # Put in an eval to foil PI:NAME:<NAME>END_PI. eval "" i = 0 while i < 1000000 assertEquals ~0x40000000, ~x i++ return testBitNot 0, 0 testBitNot 1, 1 testBitNot -1, 1 testBitNot 100, 100 testBitNot 0x40000000, "0x40000000" testBitNot 0x7fffffff, "0x7fffffff" testBitNot 0x80000000, "0x80000000" testBitNot 2.2, 2.2 testBitNot -2.3, -2.3 testBitNot Infinity, "Infinity" testBitNot NaN, "NaN" testBitNot -Infinity, "-Infinity" testBitNot 0x40000000 + 0.12345, "float1" testBitNot 0x40000000 - 0.12345, "float2" testBitNot 0x7fffffff + 0.12345, "float3" testBitNot 0x7fffffff - 0.12345, "float4" testBitNot 0x80000000 + 0.12345, "float5" testBitNot 0x80000000 - 0.12345, "float6" testBitNot "0", "string0" testBitNot "2.3", "string2.3" testBitNot "-9.4", "string-9.4" TryToGC()
[ { "context": ".com/'\n\ndescribe 'Balena SDK', ->\n\n\tvalidKeys = ['auth', 'models', 'logs', 'settings', 'version']\n\n\tdescribe 'factory function', ->\n\n\t\tdes", "end": 289, "score": 0.9624083042144775, "start": 251, "tag": "KEY", "value": "auth', 'models', 'logs', 'settings', '" } ]
tests/integration/balena.spec.coffee
josecoelho/balena-sdk
1
m = require('mochainon') packageJSON = require('../../package.json') { balena, getSdk, sdkOpts, givenLoggedInUser } = require('./setup') DIFFERENT_TEST_SERVER_URL = 'https://www.non-balena-api-domain.com/' describe 'Balena SDK', -> validKeys = ['auth', 'models', 'logs', 'settings', 'version'] describe 'factory function', -> describe 'given no opts', -> it 'should return an object with valid keys', -> mockBalena = getSdk() m.chai.expect(mockBalena).to.include.keys(validKeys) describe 'given empty opts', -> it 'should return an object with valid keys', -> mockBalena = getSdk({}) m.chai.expect(mockBalena).to.include.keys(validKeys) describe 'given opts', -> it 'should return an object with valid keys', -> mockBalena = getSdk(sdkOpts) m.chai.expect(mockBalena).to.include.keys(validKeys) describe 'version', -> it 'should match the package.json version', -> mockBalena = getSdk() m.chai.expect(mockBalena).to.have.property('version', packageJSON.version) it 'should expose a balena-pine instance', -> m.chai.expect(balena.pine).to.exist it 'should expose an balena-errors instance', -> m.chai.expect(balena.errors).to.exist describe 'interception Hooks', -> originalInterceptors = null before -> originalInterceptors = balena.interceptors.slice() balena.interceptors = originalInterceptors.slice() afterEach -> # register this afterEach first, so that we # are able to clear the mock interceptor, before # all other requests that might happen in afterEach balena.interceptors = originalInterceptors.slice() givenLoggedInUser(beforeEach) ignoreWhoamiCalls = (fn) -> (arg) -> if /\/user\/v1\/whoami/.test(arg.url) return arg return fn(arg) it "should update if the array is set directly (not only if it's mutated)", -> interceptor = m.sinon.mock().returnsArg(0) balena.interceptors = [ { request: ignoreWhoamiCalls(interceptor) } ] balena.models.application.getAll().then -> m.chai.expect(interceptor.called).to.equal true, 'Interceptor set directly should have its request hook called' describe 'for request', -> it 'should be able to intercept requests', -> requestInterceptor = m.sinon.mock().returnsArg(0) balena.interceptors.push request: requestInterceptor promise = balena.models.application.getAll() promise.then -> m.chai.expect(requestInterceptor.called).to.equal true, 'Interceptor request hook should be called' describe 'for requestError', -> it 'should intercept request errors from other interceptors', -> requestInterceptor = m.sinon.mock().throws(new Error('rejected')) requestErrorInterceptor = m.sinon.mock().throws(new Error('replacement error')) balena.interceptors.push request: requestInterceptor balena.interceptors.push requestError: requestErrorInterceptor promise = balena.models.application.getAll() m.chai.expect(promise).to.be.rejectedWith('replacement error') .then -> m.chai.expect(requestErrorInterceptor.called).to.equal true, 'Interceptor requestError hook should be called' describe 'for response', -> it 'should be able to intercept responses', -> responseInterceptor = m.sinon.mock().returnsArg(0) balena.interceptors.push response: responseInterceptor promise = balena.models.application.getAll() promise.then -> m.chai.expect(responseInterceptor.called).to.equal true, 'Interceptor response hook should be called' describe 'for responseError', -> it 'should be able to intercept error responses', -> called = false balena.interceptors.push responseError: (err) -> called = true throw err promise = balena.models.device.restartApplication(999999) m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(called).to.equal true, 'responseError should be called when request fails' describe 'version header', -> getVersionHeaderResponseInterceptor = -> responseInterceptor = (response) -> responseInterceptor.callCount++ m.chai.expect(response.request.headers) .to.have.property('X-Balena-Client', "#{packageJSON.name}/#{packageJSON.version}") return response responseInterceptor.callCount = 0 return responseInterceptor getVersionHeaderResponseErrorInterceptor = -> responseInterceptor = (err) -> responseInterceptor.callCount++ m.chai.expect(err.requestOptions.headers) .to.not.have.property('X-Balena-Client') throw err responseInterceptor.callCount = 0 return responseInterceptor describe 'model requests', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.models.application.getAll() promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'pine requests', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.pine.get({ resource: 'application' }) promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'plain requests', -> describe 'with a relative url & without a baseUrl', -> it 'should not include the version header', -> responseInterceptor = getVersionHeaderResponseErrorInterceptor() balena.interceptors.push responseError: responseInterceptor promise = balena.request.send method: 'GET' url: '/v5/application' m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'with a baseUrl option', -> describe 'to the API', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.request.send method: 'GET' url: '/v5/application' baseUrl: sdkOpts.apiUrl promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'to a differnet server', -> it 'should not include the version header', -> responseInterceptor = getVersionHeaderResponseErrorInterceptor() balena.interceptors.push responseError: responseInterceptor promise = balena.request.send method: 'GET' url: '/v5/application' baseUrl: DIFFERENT_TEST_SERVER_URL m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'with a complete url option', -> describe 'to the API', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.request.send method: 'GET' url: "#{sdkOpts.apiUrl}/v5/application" promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'to a differnet server', -> it 'should not include the version header', -> responseInterceptor = getVersionHeaderResponseErrorInterceptor() balena.interceptors.push responseError: responseInterceptor promise = balena.request.send method: 'GET' url: "#{DIFFERENT_TEST_SERVER_URL}/v5/application" m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'getSdk.setSharedOptions()', -> it 'should set a global containing shared options', -> root = if window? then window else global opts = foo: 'bar' getSdk.setSharedOptions(opts) m.chai.expect(root['BALENA_SDK_SHARED_OPTIONS']).to.equal(opts) describe 'getSdk.fromSharedOptions()', -> it 'should return an object with valid keys', -> mockBalena = getSdk.fromSharedOptions() m.chai.expect(mockBalena).to.include.keys(validKeys)
207671
m = require('mochainon') packageJSON = require('../../package.json') { balena, getSdk, sdkOpts, givenLoggedInUser } = require('./setup') DIFFERENT_TEST_SERVER_URL = 'https://www.non-balena-api-domain.com/' describe 'Balena SDK', -> validKeys = ['<KEY>version'] describe 'factory function', -> describe 'given no opts', -> it 'should return an object with valid keys', -> mockBalena = getSdk() m.chai.expect(mockBalena).to.include.keys(validKeys) describe 'given empty opts', -> it 'should return an object with valid keys', -> mockBalena = getSdk({}) m.chai.expect(mockBalena).to.include.keys(validKeys) describe 'given opts', -> it 'should return an object with valid keys', -> mockBalena = getSdk(sdkOpts) m.chai.expect(mockBalena).to.include.keys(validKeys) describe 'version', -> it 'should match the package.json version', -> mockBalena = getSdk() m.chai.expect(mockBalena).to.have.property('version', packageJSON.version) it 'should expose a balena-pine instance', -> m.chai.expect(balena.pine).to.exist it 'should expose an balena-errors instance', -> m.chai.expect(balena.errors).to.exist describe 'interception Hooks', -> originalInterceptors = null before -> originalInterceptors = balena.interceptors.slice() balena.interceptors = originalInterceptors.slice() afterEach -> # register this afterEach first, so that we # are able to clear the mock interceptor, before # all other requests that might happen in afterEach balena.interceptors = originalInterceptors.slice() givenLoggedInUser(beforeEach) ignoreWhoamiCalls = (fn) -> (arg) -> if /\/user\/v1\/whoami/.test(arg.url) return arg return fn(arg) it "should update if the array is set directly (not only if it's mutated)", -> interceptor = m.sinon.mock().returnsArg(0) balena.interceptors = [ { request: ignoreWhoamiCalls(interceptor) } ] balena.models.application.getAll().then -> m.chai.expect(interceptor.called).to.equal true, 'Interceptor set directly should have its request hook called' describe 'for request', -> it 'should be able to intercept requests', -> requestInterceptor = m.sinon.mock().returnsArg(0) balena.interceptors.push request: requestInterceptor promise = balena.models.application.getAll() promise.then -> m.chai.expect(requestInterceptor.called).to.equal true, 'Interceptor request hook should be called' describe 'for requestError', -> it 'should intercept request errors from other interceptors', -> requestInterceptor = m.sinon.mock().throws(new Error('rejected')) requestErrorInterceptor = m.sinon.mock().throws(new Error('replacement error')) balena.interceptors.push request: requestInterceptor balena.interceptors.push requestError: requestErrorInterceptor promise = balena.models.application.getAll() m.chai.expect(promise).to.be.rejectedWith('replacement error') .then -> m.chai.expect(requestErrorInterceptor.called).to.equal true, 'Interceptor requestError hook should be called' describe 'for response', -> it 'should be able to intercept responses', -> responseInterceptor = m.sinon.mock().returnsArg(0) balena.interceptors.push response: responseInterceptor promise = balena.models.application.getAll() promise.then -> m.chai.expect(responseInterceptor.called).to.equal true, 'Interceptor response hook should be called' describe 'for responseError', -> it 'should be able to intercept error responses', -> called = false balena.interceptors.push responseError: (err) -> called = true throw err promise = balena.models.device.restartApplication(999999) m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(called).to.equal true, 'responseError should be called when request fails' describe 'version header', -> getVersionHeaderResponseInterceptor = -> responseInterceptor = (response) -> responseInterceptor.callCount++ m.chai.expect(response.request.headers) .to.have.property('X-Balena-Client', "#{packageJSON.name}/#{packageJSON.version}") return response responseInterceptor.callCount = 0 return responseInterceptor getVersionHeaderResponseErrorInterceptor = -> responseInterceptor = (err) -> responseInterceptor.callCount++ m.chai.expect(err.requestOptions.headers) .to.not.have.property('X-Balena-Client') throw err responseInterceptor.callCount = 0 return responseInterceptor describe 'model requests', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.models.application.getAll() promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'pine requests', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.pine.get({ resource: 'application' }) promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'plain requests', -> describe 'with a relative url & without a baseUrl', -> it 'should not include the version header', -> responseInterceptor = getVersionHeaderResponseErrorInterceptor() balena.interceptors.push responseError: responseInterceptor promise = balena.request.send method: 'GET' url: '/v5/application' m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'with a baseUrl option', -> describe 'to the API', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.request.send method: 'GET' url: '/v5/application' baseUrl: sdkOpts.apiUrl promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'to a differnet server', -> it 'should not include the version header', -> responseInterceptor = getVersionHeaderResponseErrorInterceptor() balena.interceptors.push responseError: responseInterceptor promise = balena.request.send method: 'GET' url: '/v5/application' baseUrl: DIFFERENT_TEST_SERVER_URL m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'with a complete url option', -> describe 'to the API', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.request.send method: 'GET' url: "#{sdkOpts.apiUrl}/v5/application" promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'to a differnet server', -> it 'should not include the version header', -> responseInterceptor = getVersionHeaderResponseErrorInterceptor() balena.interceptors.push responseError: responseInterceptor promise = balena.request.send method: 'GET' url: "#{DIFFERENT_TEST_SERVER_URL}/v5/application" m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'getSdk.setSharedOptions()', -> it 'should set a global containing shared options', -> root = if window? then window else global opts = foo: 'bar' getSdk.setSharedOptions(opts) m.chai.expect(root['BALENA_SDK_SHARED_OPTIONS']).to.equal(opts) describe 'getSdk.fromSharedOptions()', -> it 'should return an object with valid keys', -> mockBalena = getSdk.fromSharedOptions() m.chai.expect(mockBalena).to.include.keys(validKeys)
true
m = require('mochainon') packageJSON = require('../../package.json') { balena, getSdk, sdkOpts, givenLoggedInUser } = require('./setup') DIFFERENT_TEST_SERVER_URL = 'https://www.non-balena-api-domain.com/' describe 'Balena SDK', -> validKeys = ['PI:KEY:<KEY>END_PIversion'] describe 'factory function', -> describe 'given no opts', -> it 'should return an object with valid keys', -> mockBalena = getSdk() m.chai.expect(mockBalena).to.include.keys(validKeys) describe 'given empty opts', -> it 'should return an object with valid keys', -> mockBalena = getSdk({}) m.chai.expect(mockBalena).to.include.keys(validKeys) describe 'given opts', -> it 'should return an object with valid keys', -> mockBalena = getSdk(sdkOpts) m.chai.expect(mockBalena).to.include.keys(validKeys) describe 'version', -> it 'should match the package.json version', -> mockBalena = getSdk() m.chai.expect(mockBalena).to.have.property('version', packageJSON.version) it 'should expose a balena-pine instance', -> m.chai.expect(balena.pine).to.exist it 'should expose an balena-errors instance', -> m.chai.expect(balena.errors).to.exist describe 'interception Hooks', -> originalInterceptors = null before -> originalInterceptors = balena.interceptors.slice() balena.interceptors = originalInterceptors.slice() afterEach -> # register this afterEach first, so that we # are able to clear the mock interceptor, before # all other requests that might happen in afterEach balena.interceptors = originalInterceptors.slice() givenLoggedInUser(beforeEach) ignoreWhoamiCalls = (fn) -> (arg) -> if /\/user\/v1\/whoami/.test(arg.url) return arg return fn(arg) it "should update if the array is set directly (not only if it's mutated)", -> interceptor = m.sinon.mock().returnsArg(0) balena.interceptors = [ { request: ignoreWhoamiCalls(interceptor) } ] balena.models.application.getAll().then -> m.chai.expect(interceptor.called).to.equal true, 'Interceptor set directly should have its request hook called' describe 'for request', -> it 'should be able to intercept requests', -> requestInterceptor = m.sinon.mock().returnsArg(0) balena.interceptors.push request: requestInterceptor promise = balena.models.application.getAll() promise.then -> m.chai.expect(requestInterceptor.called).to.equal true, 'Interceptor request hook should be called' describe 'for requestError', -> it 'should intercept request errors from other interceptors', -> requestInterceptor = m.sinon.mock().throws(new Error('rejected')) requestErrorInterceptor = m.sinon.mock().throws(new Error('replacement error')) balena.interceptors.push request: requestInterceptor balena.interceptors.push requestError: requestErrorInterceptor promise = balena.models.application.getAll() m.chai.expect(promise).to.be.rejectedWith('replacement error') .then -> m.chai.expect(requestErrorInterceptor.called).to.equal true, 'Interceptor requestError hook should be called' describe 'for response', -> it 'should be able to intercept responses', -> responseInterceptor = m.sinon.mock().returnsArg(0) balena.interceptors.push response: responseInterceptor promise = balena.models.application.getAll() promise.then -> m.chai.expect(responseInterceptor.called).to.equal true, 'Interceptor response hook should be called' describe 'for responseError', -> it 'should be able to intercept error responses', -> called = false balena.interceptors.push responseError: (err) -> called = true throw err promise = balena.models.device.restartApplication(999999) m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(called).to.equal true, 'responseError should be called when request fails' describe 'version header', -> getVersionHeaderResponseInterceptor = -> responseInterceptor = (response) -> responseInterceptor.callCount++ m.chai.expect(response.request.headers) .to.have.property('X-Balena-Client', "#{packageJSON.name}/#{packageJSON.version}") return response responseInterceptor.callCount = 0 return responseInterceptor getVersionHeaderResponseErrorInterceptor = -> responseInterceptor = (err) -> responseInterceptor.callCount++ m.chai.expect(err.requestOptions.headers) .to.not.have.property('X-Balena-Client') throw err responseInterceptor.callCount = 0 return responseInterceptor describe 'model requests', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.models.application.getAll() promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'pine requests', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.pine.get({ resource: 'application' }) promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'plain requests', -> describe 'with a relative url & without a baseUrl', -> it 'should not include the version header', -> responseInterceptor = getVersionHeaderResponseErrorInterceptor() balena.interceptors.push responseError: responseInterceptor promise = balena.request.send method: 'GET' url: '/v5/application' m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'with a baseUrl option', -> describe 'to the API', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.request.send method: 'GET' url: '/v5/application' baseUrl: sdkOpts.apiUrl promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'to a differnet server', -> it 'should not include the version header', -> responseInterceptor = getVersionHeaderResponseErrorInterceptor() balena.interceptors.push responseError: responseInterceptor promise = balena.request.send method: 'GET' url: '/v5/application' baseUrl: DIFFERENT_TEST_SERVER_URL m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'with a complete url option', -> describe 'to the API', -> it 'should include the version header', -> responseInterceptor = getVersionHeaderResponseInterceptor() balena.interceptors.push response: responseInterceptor promise = balena.request.send method: 'GET' url: "#{sdkOpts.apiUrl}/v5/application" promise.then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'to a differnet server', -> it 'should not include the version header', -> responseInterceptor = getVersionHeaderResponseErrorInterceptor() balena.interceptors.push responseError: responseInterceptor promise = balena.request.send method: 'GET' url: "#{DIFFERENT_TEST_SERVER_URL}/v5/application" m.chai.expect(promise).to.be.rejected .then -> m.chai.expect(responseInterceptor.callCount).to.equal 1, 'Interceptor response hook should be called' describe 'getSdk.setSharedOptions()', -> it 'should set a global containing shared options', -> root = if window? then window else global opts = foo: 'bar' getSdk.setSharedOptions(opts) m.chai.expect(root['BALENA_SDK_SHARED_OPTIONS']).to.equal(opts) describe 'getSdk.fromSharedOptions()', -> it 'should return an object with valid keys', -> mockBalena = getSdk.fromSharedOptions() m.chai.expect(mockBalena).to.include.keys(validKeys)
[ { "context": "00\n\nstartServer = ->\n books = [\n {id:\"1\", title:\"Moby Dick\", author:\"Herman Melville\"}\n ]\n\n removeBook = (re", "end": 190, "score": 0.9902864694595337, "start": 181, "tag": "NAME", "value": "Moby Dick" }, { "context": "\n books = [\n {id:\"1\", title:\"Moby Dick\", author:\"Herman Melville\"}\n ]\n\n removeBook = (req) ->\n {id} = req.params\n", "end": 216, "score": 0.9998857975006104, "start": 201, "tag": "NAME", "value": "Herman Melville" } ]
server.coffee
andrewglind/library-app
0
"use strict" express = require "express" bodyParser = require "body-parser" _ = require "underscore" PORT = process.env.PORT || 3000 startServer = -> books = [ {id:"1", title:"Moby Dick", author:"Herman Melville"} ] removeBook = (req) -> {id} = req.params _.reject(books, (it) -> it.id is id) router = express.Router() router.use express.static "public" router.use bodyParser.json() router.use bodyParser.urlencoded extended:true router.get "/", (req, res) -> res.render "index" router.get "/books", (req, res) -> res.json(books) router.get "/books/:id", (req, res) -> {id} = req.params res.json(_.find(books, (it) -> it.id is id)) router.post "/books", (req, res) -> books.push req.body res.end() router.put "/books/:id", (req, res) -> books = removeBook(req) books.push req.body res.end() router.delete "/books/:id", (req, res) -> books = removeBook(req) res.end() server = express() server.use "/", router server.set "view engine", "pug" server.listen PORT, -> console.log "Listening on port #{PORT}" module.exports = -> startServer()
27189
"use strict" express = require "express" bodyParser = require "body-parser" _ = require "underscore" PORT = process.env.PORT || 3000 startServer = -> books = [ {id:"1", title:"<NAME>", author:"<NAME>"} ] removeBook = (req) -> {id} = req.params _.reject(books, (it) -> it.id is id) router = express.Router() router.use express.static "public" router.use bodyParser.json() router.use bodyParser.urlencoded extended:true router.get "/", (req, res) -> res.render "index" router.get "/books", (req, res) -> res.json(books) router.get "/books/:id", (req, res) -> {id} = req.params res.json(_.find(books, (it) -> it.id is id)) router.post "/books", (req, res) -> books.push req.body res.end() router.put "/books/:id", (req, res) -> books = removeBook(req) books.push req.body res.end() router.delete "/books/:id", (req, res) -> books = removeBook(req) res.end() server = express() server.use "/", router server.set "view engine", "pug" server.listen PORT, -> console.log "Listening on port #{PORT}" module.exports = -> startServer()
true
"use strict" express = require "express" bodyParser = require "body-parser" _ = require "underscore" PORT = process.env.PORT || 3000 startServer = -> books = [ {id:"1", title:"PI:NAME:<NAME>END_PI", author:"PI:NAME:<NAME>END_PI"} ] removeBook = (req) -> {id} = req.params _.reject(books, (it) -> it.id is id) router = express.Router() router.use express.static "public" router.use bodyParser.json() router.use bodyParser.urlencoded extended:true router.get "/", (req, res) -> res.render "index" router.get "/books", (req, res) -> res.json(books) router.get "/books/:id", (req, res) -> {id} = req.params res.json(_.find(books, (it) -> it.id is id)) router.post "/books", (req, res) -> books.push req.body res.end() router.put "/books/:id", (req, res) -> books = removeBook(req) books.push req.body res.end() router.delete "/books/:id", (req, res) -> books = removeBook(req) res.end() server = express() server.use "/", router server.set "view engine", "pug" server.listen PORT, -> console.log "Listening on port #{PORT}" module.exports = -> startServer()
[ { "context": "#\n# ©2016 Lakiryt\n# \"Uebersicht Widget: Sun radar (english)\"\n#\n# Fo", "end": 17, "score": 0.9981982111930847, "start": 10, "tag": "NAME", "value": "Lakiryt" } ]
single language/en.coffee
lakiryt/sun-radar
5
# # ©2016 Lakiryt # "Uebersicht Widget: Sun radar (english)" # # Formulas: # http://www.pveducation.org/pvcdrom/properties-of-sunlight/suns-position and /elevation-angle # ### Everything likely to be changed are marked with a star (⭐️ there should be 5 of them). ### ### The earth-sign (🌍) marks passages that could be translated, if someone wants to. ### findCoords: "manually" #⭐️ "auto" to find coordinates automatically. longitude: -71 #⭐️longitude at your place (if set to manual); negative in long. west latitude: 42 #⭐️latitude at your place (if set to manual); negative in lat. south radius_svg: 72 #⭐️radius of the radar in pixel style: """ top: 40% //⭐️margin to the top left: 250px //⭐️margin to the left background: rgba(#fff, 0.6) color: rgba(#000, 0.8) font-family: "Helvetica-light" font-size: 12px padding: 10px 20px overflow: scroll box-sizing: border-box -webkit-backdrop-filter: blur(20px) -webkit-font-smoothing: antialiased -webkit-border-radius: 5px image-rendering: crisp-edges h2 padding: 0 margin: 0 font-size: 13px line-height: 1.3 svg .ring, .axis stroke: #333 stroke-width: 0.6px fill: none table line-height: 1.18 """ command: """ echo -n '{' # Difference to GMT in hours h0=`TZ=GMT date "+%H"` h1=`date "+%H"` diff=`expr $h1 - $h0` if [ "${diff}" -lt "0" ]; then diff=`expr 24 + ${diff}` fi echo -n '"deltaT":'${diff}',' # Currennt hours, minutes, seconds echo -n '"h":"'${h1}'",' min=`date "+%M"` echo -n '"min":"'${min}'",' sec=`date "+%S"` echo -n '"sec":"'${sec}'",' # Days past since New Year d0=`date -j -f "%m %d" "01 01" "+%s"` tomorrow=`date -v+2d '+%m %d %Y'` d1=`date -j -f "%m %d %Y %T" "${tomorrow} 00:00:00" "+%s"` echo -n '"d":'$(( (d1 - d0) / 86400 )) echo -n '}' """ refreshFrequency: 1000 render: (output)->""" <!--#{output}--> <h2>Sun Radar</h2><!--🌍--> <span id="jscontent"></span> <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <!--# Static objects #--> <!-- v: vertical; h: horizontal; r: tilted to right; l: tilted to left; --> <circle class="background" fill="rgba(0,0,0,0.1)" cx="50%" cy="50%" r="50%" /> <line class="axis v" x1="50%" y1="0" x2="50%" y2="100%" /> <line class="axis h" x1="0" y1="50%" x2="100%" y2="50%" /> <line class="axis h r" x1="001" y1="25%" x2="002" y2="75%" /> <line class="axis h l" x1="001" y1="75%" x2="002" y2="25%" /> <line class="axis v r" x1="25%" y1="001" x2="75%" y2="002" /> <line class="axis v l" x1="75%" y1="001" x2="25%" y2="002" /> <circle class="ring" id="15" cx="50%" cy="50%" r="00" /> <circle class="ring" id="30" cx="50%" cy="50%" r="25%" /> <circle class="ring" id="45" cx="50%" cy="50%" r="00" /> <circle class="ring" id="60" cx="50%" cy="50%" r="00" /> <circle class="ring" id="75" cx="50%" cy="50%" r="00" /> <circle class="ring" id="90" cx="50%" cy="50%" r="00" /> <!--# Moving objects #--> <line id="azimuth" x1="50%" y1="50%" x2="000" y2="000" stroke="#af5" /> <circle id="sun" cx="000" cy="000" r="00" stroke="none" fill="#af5" /> </svg> """ afterRender: (domEl)-> ## Find cordinates automatically ## if @findCoords == "auto" geolocation.getCurrentPosition (e) => coords = e.position.coords [@latitude, @longitude] = [coords.latitude, coords.longitude] ### SVG plot (static) ### dom=$(domEl) to_deg = Math.PI/180 sin = (rad) -> Math.sin(rad*to_deg) r=@radius_svg dom.find("svg")[0].setAttribute("width", 2*r) dom.find("svg")[0].setAttribute("height", 2*r) dom.find("#sun")[0].setAttribute("r", r/24) shortd=r*(1-sin(60)) dom.find(".axis.h.r")[0].setAttribute("x1",shortd) dom.find(".axis.h.l")[0].setAttribute("x1",shortd) dom.find(".axis.v.r")[0].setAttribute("y1",shortd) dom.find(".axis.v.l")[0].setAttribute("y1",shortd) longd=r*(1+sin(60)) dom.find(".axis.h.r")[0].setAttribute("x2",longd) dom.find(".axis.h.l")[0].setAttribute("x2",longd) dom.find(".axis.v.r")[0].setAttribute("y2",longd) dom.find(".axis.v.l")[0].setAttribute("y2",longd) dom.find(".ring#15")[0].setAttribute("r", r/6) dom.find(".ring#30")[0].setAttribute("r", 2*r/6) dom.find(".ring#45")[0].setAttribute("r", 3*r/6) dom.find(".ring#60")[0].setAttribute("r", 4*r/6) dom.find(".ring#75")[0].setAttribute("r", 5*r/6) dom.find(".ring#90")[0].setAttribute("r", r-1) update: (output, domEl)-> dom=$(domEl) obj=JSON.parse(output) jscontent="<table>" to_deg = Math.PI/180 sin = (rad) -> Math.sin(rad*to_deg) cos = (rad) -> Math.cos(rad*to_deg) tan = (rad) -> Math.tan(rad*to_deg) asin = (rad) -> Math.asin(rad)*(1/to_deg) acos = (rad) -> Math.acos(rad)*(1/to_deg) ### Calculations ### LocalTime = parseInt(obj.h) + parseInt(obj.min)/60 + parseInt(obj.sec)/3600 ## Local Standard Time Meridian ## # Convert difference to GMT into degrees. LSTM=15*obj.deltaT # Variable for EoT and Declination. B=(360/365)*(d-81) B=(72/73)*(obj.d-81) ## Equation of Time ## EoT=(9.863*sin(2*B))-(7.53*cos(B))-(1.5*sin(B)) ## Time Correction ## TC=4*(@longitude-LSTM)+EoT ## Local Solar Time ## LST=LocalTime+(TC/60) LST-=24 if LST>24 LST+=24 if LST<0 ## Hour Angle ## # LST in degrees, where 0° is noon HRA=15*(LST-12) ## Declination ## Declination=23.45*sin(B) ### Formatting ### ## GMT diff ## if obj.deltaT>=12 diffgmt="-"+(24-obj.deltaT) else diffgmt="+"+obj.deltaT ## Coordinates NSWE ## n__s= if @latitude<0 then "S," else "N," e__w= if @longitude<0 then "W" else "E" ### Output ### #🌍 jscontent+="<tr><td>D since NYear:</td><td>"+obj.d+"</td></tr>" jscontent+="<tr><td>Timezone:</td><td>GMT"+diffgmt+"</td></tr>" jscontent+="<tr><td>Coordinates:</td><td>"+Math.abs(Math.round(@latitude))+n__s+Math.abs(Math.round(@longitude))+e__w+"</td></tr>" #jscontent+="<tr><td>LocalStdTMerid</td><td>+LSTM+"°</td></tr>") #jscontent+="<tr><td>B(Decl/EoT)</td><td>"+B.toFixed(14)+"</td></tr>" #jscontent+="<tr><td>EccentrCorr</td><td>"+EoT.toFixed(13)+"</td></tr>" #jscontent+="<tr><td>TCorrFactor</td><td>"+TC.toFixed(12)+"</td></tr>" #jscontent+="<tr><td>LocalSolarT</td><td>"+LST.toFixed(13)+"</td></tr>" #jscontent+="<tr><td>HrAng (HRA)</td><td>"+HRA.toFixed(12)+"°</td></tr>" #jscontent+="<tr><td>Declination</td><td>"+Declination.toFixed(13)+"°</td></tr>" jscontent+='<tr><td colspan="2">&nbsp;</td></tr>' Elevation=asin(sin(Declination)*sin(@latitude)+cos(Declination)*cos(@latitude)*cos(HRA)) jscontent+="<tr><td>Altitude:</td><td>"+Math.round(Elevation*1000)/1000+"°</td></tr>" #🌍 Azimuth = acos((sin(Declination)*cos(@latitude)-cos(Declination)*sin(@latitude)*cos(HRA))/cos(Elevation)) if LST>12 or HRA>0 Azimuth = 360-Azimuth jscontent+="<tr><td>Azimuth:</td><td>"+Math.round(Azimuth*1000)/1000+"°</td></tr>" #🌍 ### Sunrise and Sunset ### Meridian=12-(TC/60) Deviation=acos(-tan(@latitude)*tan(Declination))/15 if Deviation ## Sunrise ## Sunrise_h=Math.floor(Meridian-Deviation) Sunrise_m=Math.floor(60*(Meridian-Deviation-Sunrise_h)) Sunrise_s=3600*(Meridian-Deviation-Sunrise_h-Sunrise_m/60) # Hours Formatting if Sunrise_h<0 Sunrise_h="0"+(Sunrise_h+24) if Sunrise_h>23 Sunrise_h="0"+(Sunrise_h-24) else Sunrise_h="0"+Sunrise_h Sunrise_h=Sunrise_h.toString().substr(Sunrise_h.length-2) # Minutes Formatting Sunrise_m="0"+Sunrise_m Sunrise_m=Sunrise_m.substr(Sunrise_m.length-2) # Seconds Formatting and Final Output Sunrise=Sunrise_h+":"+Sunrise_m+":" Sunrise+="0" if Sunrise_s.toFixed(2).toString().length==4 Sunrise+=Sunrise_s.toFixed(2) jscontent+="<tr><td>Sunrise:</td><td>"+Sunrise+"</td></tr>" #🌍 ## Sunset ## Sunset_h=Math.floor(Meridian+Deviation) Sunset_m=Math.floor(60*(Meridian+Deviation-Sunset_h)) Sunset_s=3600*(Meridian+Deviation-Sunset_h-Sunset_m/60) # Hours Formatting if Sunset_h<0 Sunset_h="0"+(Sunset_h+24) if Sunset_h>23 Sunset_h="0"+(Sunset_h-24) else Sunset_h="0"+Sunset_h Sunset_h=Sunset_h.toString().substr(Sunset_h.length-2) # Minutes Formatting Sunset_m="0"+Sunset_m Sunset_m=Sunset_m.substr(Sunset_m.length-2) # Seconds Formatting and Final Output Sunset=Sunset_h+":"+Sunset_m+":" Sunset+="0" if Sunset_s.toFixed(2).toString().length==4 Sunset+=Sunset_s.toFixed(2) jscontent+="<tr><td>Sunset:</td><td>"+Sunset+"</td></tr>" #🌍 else #🌍 pole = if @latitude<0 then "Antarctic" else "Arctic" jscontent+='<tr><td colspan="2"><small>No sunrise or sunset.<br>('+pole+' region)</small></td></tr>' jscontent+="</table>" dom.find("#jscontent").html(jscontent) ### SVG plot (moving) ### r=@radius_svg ## Azimuth line ## x2=r*(1+0.99*sin(Azimuth)) y2=r*(1-0.99*cos(Azimuth)) dom.find("#azimuth")[0].setAttribute("x2", x2) dom.find("#azimuth")[0].setAttribute("y2", y2) ## Azimuth point ## cx=r*(1+sin(Azimuth)*(90-Math.abs(Elevation))/90) #linear cy=r*(1-cos(Azimuth)*(90-Math.abs(Elevation))/90) dom.find("#sun")[0].setAttribute("cx", cx) dom.find("#sun")[0].setAttribute("cy", cy) ## Azimuth point color ## if Elevation<0 dom.find("#sun")[0].setAttribute("fill", "#69a")
115199
# # ©2016 <NAME> # "Uebersicht Widget: Sun radar (english)" # # Formulas: # http://www.pveducation.org/pvcdrom/properties-of-sunlight/suns-position and /elevation-angle # ### Everything likely to be changed are marked with a star (⭐️ there should be 5 of them). ### ### The earth-sign (🌍) marks passages that could be translated, if someone wants to. ### findCoords: "manually" #⭐️ "auto" to find coordinates automatically. longitude: -71 #⭐️longitude at your place (if set to manual); negative in long. west latitude: 42 #⭐️latitude at your place (if set to manual); negative in lat. south radius_svg: 72 #⭐️radius of the radar in pixel style: """ top: 40% //⭐️margin to the top left: 250px //⭐️margin to the left background: rgba(#fff, 0.6) color: rgba(#000, 0.8) font-family: "Helvetica-light" font-size: 12px padding: 10px 20px overflow: scroll box-sizing: border-box -webkit-backdrop-filter: blur(20px) -webkit-font-smoothing: antialiased -webkit-border-radius: 5px image-rendering: crisp-edges h2 padding: 0 margin: 0 font-size: 13px line-height: 1.3 svg .ring, .axis stroke: #333 stroke-width: 0.6px fill: none table line-height: 1.18 """ command: """ echo -n '{' # Difference to GMT in hours h0=`TZ=GMT date "+%H"` h1=`date "+%H"` diff=`expr $h1 - $h0` if [ "${diff}" -lt "0" ]; then diff=`expr 24 + ${diff}` fi echo -n '"deltaT":'${diff}',' # Currennt hours, minutes, seconds echo -n '"h":"'${h1}'",' min=`date "+%M"` echo -n '"min":"'${min}'",' sec=`date "+%S"` echo -n '"sec":"'${sec}'",' # Days past since New Year d0=`date -j -f "%m %d" "01 01" "+%s"` tomorrow=`date -v+2d '+%m %d %Y'` d1=`date -j -f "%m %d %Y %T" "${tomorrow} 00:00:00" "+%s"` echo -n '"d":'$(( (d1 - d0) / 86400 )) echo -n '}' """ refreshFrequency: 1000 render: (output)->""" <!--#{output}--> <h2>Sun Radar</h2><!--🌍--> <span id="jscontent"></span> <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <!--# Static objects #--> <!-- v: vertical; h: horizontal; r: tilted to right; l: tilted to left; --> <circle class="background" fill="rgba(0,0,0,0.1)" cx="50%" cy="50%" r="50%" /> <line class="axis v" x1="50%" y1="0" x2="50%" y2="100%" /> <line class="axis h" x1="0" y1="50%" x2="100%" y2="50%" /> <line class="axis h r" x1="001" y1="25%" x2="002" y2="75%" /> <line class="axis h l" x1="001" y1="75%" x2="002" y2="25%" /> <line class="axis v r" x1="25%" y1="001" x2="75%" y2="002" /> <line class="axis v l" x1="75%" y1="001" x2="25%" y2="002" /> <circle class="ring" id="15" cx="50%" cy="50%" r="00" /> <circle class="ring" id="30" cx="50%" cy="50%" r="25%" /> <circle class="ring" id="45" cx="50%" cy="50%" r="00" /> <circle class="ring" id="60" cx="50%" cy="50%" r="00" /> <circle class="ring" id="75" cx="50%" cy="50%" r="00" /> <circle class="ring" id="90" cx="50%" cy="50%" r="00" /> <!--# Moving objects #--> <line id="azimuth" x1="50%" y1="50%" x2="000" y2="000" stroke="#af5" /> <circle id="sun" cx="000" cy="000" r="00" stroke="none" fill="#af5" /> </svg> """ afterRender: (domEl)-> ## Find cordinates automatically ## if @findCoords == "auto" geolocation.getCurrentPosition (e) => coords = e.position.coords [@latitude, @longitude] = [coords.latitude, coords.longitude] ### SVG plot (static) ### dom=$(domEl) to_deg = Math.PI/180 sin = (rad) -> Math.sin(rad*to_deg) r=@radius_svg dom.find("svg")[0].setAttribute("width", 2*r) dom.find("svg")[0].setAttribute("height", 2*r) dom.find("#sun")[0].setAttribute("r", r/24) shortd=r*(1-sin(60)) dom.find(".axis.h.r")[0].setAttribute("x1",shortd) dom.find(".axis.h.l")[0].setAttribute("x1",shortd) dom.find(".axis.v.r")[0].setAttribute("y1",shortd) dom.find(".axis.v.l")[0].setAttribute("y1",shortd) longd=r*(1+sin(60)) dom.find(".axis.h.r")[0].setAttribute("x2",longd) dom.find(".axis.h.l")[0].setAttribute("x2",longd) dom.find(".axis.v.r")[0].setAttribute("y2",longd) dom.find(".axis.v.l")[0].setAttribute("y2",longd) dom.find(".ring#15")[0].setAttribute("r", r/6) dom.find(".ring#30")[0].setAttribute("r", 2*r/6) dom.find(".ring#45")[0].setAttribute("r", 3*r/6) dom.find(".ring#60")[0].setAttribute("r", 4*r/6) dom.find(".ring#75")[0].setAttribute("r", 5*r/6) dom.find(".ring#90")[0].setAttribute("r", r-1) update: (output, domEl)-> dom=$(domEl) obj=JSON.parse(output) jscontent="<table>" to_deg = Math.PI/180 sin = (rad) -> Math.sin(rad*to_deg) cos = (rad) -> Math.cos(rad*to_deg) tan = (rad) -> Math.tan(rad*to_deg) asin = (rad) -> Math.asin(rad)*(1/to_deg) acos = (rad) -> Math.acos(rad)*(1/to_deg) ### Calculations ### LocalTime = parseInt(obj.h) + parseInt(obj.min)/60 + parseInt(obj.sec)/3600 ## Local Standard Time Meridian ## # Convert difference to GMT into degrees. LSTM=15*obj.deltaT # Variable for EoT and Declination. B=(360/365)*(d-81) B=(72/73)*(obj.d-81) ## Equation of Time ## EoT=(9.863*sin(2*B))-(7.53*cos(B))-(1.5*sin(B)) ## Time Correction ## TC=4*(@longitude-LSTM)+EoT ## Local Solar Time ## LST=LocalTime+(TC/60) LST-=24 if LST>24 LST+=24 if LST<0 ## Hour Angle ## # LST in degrees, where 0° is noon HRA=15*(LST-12) ## Declination ## Declination=23.45*sin(B) ### Formatting ### ## GMT diff ## if obj.deltaT>=12 diffgmt="-"+(24-obj.deltaT) else diffgmt="+"+obj.deltaT ## Coordinates NSWE ## n__s= if @latitude<0 then "S," else "N," e__w= if @longitude<0 then "W" else "E" ### Output ### #🌍 jscontent+="<tr><td>D since NYear:</td><td>"+obj.d+"</td></tr>" jscontent+="<tr><td>Timezone:</td><td>GMT"+diffgmt+"</td></tr>" jscontent+="<tr><td>Coordinates:</td><td>"+Math.abs(Math.round(@latitude))+n__s+Math.abs(Math.round(@longitude))+e__w+"</td></tr>" #jscontent+="<tr><td>LocalStdTMerid</td><td>+LSTM+"°</td></tr>") #jscontent+="<tr><td>B(Decl/EoT)</td><td>"+B.toFixed(14)+"</td></tr>" #jscontent+="<tr><td>EccentrCorr</td><td>"+EoT.toFixed(13)+"</td></tr>" #jscontent+="<tr><td>TCorrFactor</td><td>"+TC.toFixed(12)+"</td></tr>" #jscontent+="<tr><td>LocalSolarT</td><td>"+LST.toFixed(13)+"</td></tr>" #jscontent+="<tr><td>HrAng (HRA)</td><td>"+HRA.toFixed(12)+"°</td></tr>" #jscontent+="<tr><td>Declination</td><td>"+Declination.toFixed(13)+"°</td></tr>" jscontent+='<tr><td colspan="2">&nbsp;</td></tr>' Elevation=asin(sin(Declination)*sin(@latitude)+cos(Declination)*cos(@latitude)*cos(HRA)) jscontent+="<tr><td>Altitude:</td><td>"+Math.round(Elevation*1000)/1000+"°</td></tr>" #🌍 Azimuth = acos((sin(Declination)*cos(@latitude)-cos(Declination)*sin(@latitude)*cos(HRA))/cos(Elevation)) if LST>12 or HRA>0 Azimuth = 360-Azimuth jscontent+="<tr><td>Azimuth:</td><td>"+Math.round(Azimuth*1000)/1000+"°</td></tr>" #🌍 ### Sunrise and Sunset ### Meridian=12-(TC/60) Deviation=acos(-tan(@latitude)*tan(Declination))/15 if Deviation ## Sunrise ## Sunrise_h=Math.floor(Meridian-Deviation) Sunrise_m=Math.floor(60*(Meridian-Deviation-Sunrise_h)) Sunrise_s=3600*(Meridian-Deviation-Sunrise_h-Sunrise_m/60) # Hours Formatting if Sunrise_h<0 Sunrise_h="0"+(Sunrise_h+24) if Sunrise_h>23 Sunrise_h="0"+(Sunrise_h-24) else Sunrise_h="0"+Sunrise_h Sunrise_h=Sunrise_h.toString().substr(Sunrise_h.length-2) # Minutes Formatting Sunrise_m="0"+Sunrise_m Sunrise_m=Sunrise_m.substr(Sunrise_m.length-2) # Seconds Formatting and Final Output Sunrise=Sunrise_h+":"+Sunrise_m+":" Sunrise+="0" if Sunrise_s.toFixed(2).toString().length==4 Sunrise+=Sunrise_s.toFixed(2) jscontent+="<tr><td>Sunrise:</td><td>"+Sunrise+"</td></tr>" #🌍 ## Sunset ## Sunset_h=Math.floor(Meridian+Deviation) Sunset_m=Math.floor(60*(Meridian+Deviation-Sunset_h)) Sunset_s=3600*(Meridian+Deviation-Sunset_h-Sunset_m/60) # Hours Formatting if Sunset_h<0 Sunset_h="0"+(Sunset_h+24) if Sunset_h>23 Sunset_h="0"+(Sunset_h-24) else Sunset_h="0"+Sunset_h Sunset_h=Sunset_h.toString().substr(Sunset_h.length-2) # Minutes Formatting Sunset_m="0"+Sunset_m Sunset_m=Sunset_m.substr(Sunset_m.length-2) # Seconds Formatting and Final Output Sunset=Sunset_h+":"+Sunset_m+":" Sunset+="0" if Sunset_s.toFixed(2).toString().length==4 Sunset+=Sunset_s.toFixed(2) jscontent+="<tr><td>Sunset:</td><td>"+Sunset+"</td></tr>" #🌍 else #🌍 pole = if @latitude<0 then "Antarctic" else "Arctic" jscontent+='<tr><td colspan="2"><small>No sunrise or sunset.<br>('+pole+' region)</small></td></tr>' jscontent+="</table>" dom.find("#jscontent").html(jscontent) ### SVG plot (moving) ### r=@radius_svg ## Azimuth line ## x2=r*(1+0.99*sin(Azimuth)) y2=r*(1-0.99*cos(Azimuth)) dom.find("#azimuth")[0].setAttribute("x2", x2) dom.find("#azimuth")[0].setAttribute("y2", y2) ## Azimuth point ## cx=r*(1+sin(Azimuth)*(90-Math.abs(Elevation))/90) #linear cy=r*(1-cos(Azimuth)*(90-Math.abs(Elevation))/90) dom.find("#sun")[0].setAttribute("cx", cx) dom.find("#sun")[0].setAttribute("cy", cy) ## Azimuth point color ## if Elevation<0 dom.find("#sun")[0].setAttribute("fill", "#69a")
true
# # ©2016 PI:NAME:<NAME>END_PI # "Uebersicht Widget: Sun radar (english)" # # Formulas: # http://www.pveducation.org/pvcdrom/properties-of-sunlight/suns-position and /elevation-angle # ### Everything likely to be changed are marked with a star (⭐️ there should be 5 of them). ### ### The earth-sign (🌍) marks passages that could be translated, if someone wants to. ### findCoords: "manually" #⭐️ "auto" to find coordinates automatically. longitude: -71 #⭐️longitude at your place (if set to manual); negative in long. west latitude: 42 #⭐️latitude at your place (if set to manual); negative in lat. south radius_svg: 72 #⭐️radius of the radar in pixel style: """ top: 40% //⭐️margin to the top left: 250px //⭐️margin to the left background: rgba(#fff, 0.6) color: rgba(#000, 0.8) font-family: "Helvetica-light" font-size: 12px padding: 10px 20px overflow: scroll box-sizing: border-box -webkit-backdrop-filter: blur(20px) -webkit-font-smoothing: antialiased -webkit-border-radius: 5px image-rendering: crisp-edges h2 padding: 0 margin: 0 font-size: 13px line-height: 1.3 svg .ring, .axis stroke: #333 stroke-width: 0.6px fill: none table line-height: 1.18 """ command: """ echo -n '{' # Difference to GMT in hours h0=`TZ=GMT date "+%H"` h1=`date "+%H"` diff=`expr $h1 - $h0` if [ "${diff}" -lt "0" ]; then diff=`expr 24 + ${diff}` fi echo -n '"deltaT":'${diff}',' # Currennt hours, minutes, seconds echo -n '"h":"'${h1}'",' min=`date "+%M"` echo -n '"min":"'${min}'",' sec=`date "+%S"` echo -n '"sec":"'${sec}'",' # Days past since New Year d0=`date -j -f "%m %d" "01 01" "+%s"` tomorrow=`date -v+2d '+%m %d %Y'` d1=`date -j -f "%m %d %Y %T" "${tomorrow} 00:00:00" "+%s"` echo -n '"d":'$(( (d1 - d0) / 86400 )) echo -n '}' """ refreshFrequency: 1000 render: (output)->""" <!--#{output}--> <h2>Sun Radar</h2><!--🌍--> <span id="jscontent"></span> <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <!--# Static objects #--> <!-- v: vertical; h: horizontal; r: tilted to right; l: tilted to left; --> <circle class="background" fill="rgba(0,0,0,0.1)" cx="50%" cy="50%" r="50%" /> <line class="axis v" x1="50%" y1="0" x2="50%" y2="100%" /> <line class="axis h" x1="0" y1="50%" x2="100%" y2="50%" /> <line class="axis h r" x1="001" y1="25%" x2="002" y2="75%" /> <line class="axis h l" x1="001" y1="75%" x2="002" y2="25%" /> <line class="axis v r" x1="25%" y1="001" x2="75%" y2="002" /> <line class="axis v l" x1="75%" y1="001" x2="25%" y2="002" /> <circle class="ring" id="15" cx="50%" cy="50%" r="00" /> <circle class="ring" id="30" cx="50%" cy="50%" r="25%" /> <circle class="ring" id="45" cx="50%" cy="50%" r="00" /> <circle class="ring" id="60" cx="50%" cy="50%" r="00" /> <circle class="ring" id="75" cx="50%" cy="50%" r="00" /> <circle class="ring" id="90" cx="50%" cy="50%" r="00" /> <!--# Moving objects #--> <line id="azimuth" x1="50%" y1="50%" x2="000" y2="000" stroke="#af5" /> <circle id="sun" cx="000" cy="000" r="00" stroke="none" fill="#af5" /> </svg> """ afterRender: (domEl)-> ## Find cordinates automatically ## if @findCoords == "auto" geolocation.getCurrentPosition (e) => coords = e.position.coords [@latitude, @longitude] = [coords.latitude, coords.longitude] ### SVG plot (static) ### dom=$(domEl) to_deg = Math.PI/180 sin = (rad) -> Math.sin(rad*to_deg) r=@radius_svg dom.find("svg")[0].setAttribute("width", 2*r) dom.find("svg")[0].setAttribute("height", 2*r) dom.find("#sun")[0].setAttribute("r", r/24) shortd=r*(1-sin(60)) dom.find(".axis.h.r")[0].setAttribute("x1",shortd) dom.find(".axis.h.l")[0].setAttribute("x1",shortd) dom.find(".axis.v.r")[0].setAttribute("y1",shortd) dom.find(".axis.v.l")[0].setAttribute("y1",shortd) longd=r*(1+sin(60)) dom.find(".axis.h.r")[0].setAttribute("x2",longd) dom.find(".axis.h.l")[0].setAttribute("x2",longd) dom.find(".axis.v.r")[0].setAttribute("y2",longd) dom.find(".axis.v.l")[0].setAttribute("y2",longd) dom.find(".ring#15")[0].setAttribute("r", r/6) dom.find(".ring#30")[0].setAttribute("r", 2*r/6) dom.find(".ring#45")[0].setAttribute("r", 3*r/6) dom.find(".ring#60")[0].setAttribute("r", 4*r/6) dom.find(".ring#75")[0].setAttribute("r", 5*r/6) dom.find(".ring#90")[0].setAttribute("r", r-1) update: (output, domEl)-> dom=$(domEl) obj=JSON.parse(output) jscontent="<table>" to_deg = Math.PI/180 sin = (rad) -> Math.sin(rad*to_deg) cos = (rad) -> Math.cos(rad*to_deg) tan = (rad) -> Math.tan(rad*to_deg) asin = (rad) -> Math.asin(rad)*(1/to_deg) acos = (rad) -> Math.acos(rad)*(1/to_deg) ### Calculations ### LocalTime = parseInt(obj.h) + parseInt(obj.min)/60 + parseInt(obj.sec)/3600 ## Local Standard Time Meridian ## # Convert difference to GMT into degrees. LSTM=15*obj.deltaT # Variable for EoT and Declination. B=(360/365)*(d-81) B=(72/73)*(obj.d-81) ## Equation of Time ## EoT=(9.863*sin(2*B))-(7.53*cos(B))-(1.5*sin(B)) ## Time Correction ## TC=4*(@longitude-LSTM)+EoT ## Local Solar Time ## LST=LocalTime+(TC/60) LST-=24 if LST>24 LST+=24 if LST<0 ## Hour Angle ## # LST in degrees, where 0° is noon HRA=15*(LST-12) ## Declination ## Declination=23.45*sin(B) ### Formatting ### ## GMT diff ## if obj.deltaT>=12 diffgmt="-"+(24-obj.deltaT) else diffgmt="+"+obj.deltaT ## Coordinates NSWE ## n__s= if @latitude<0 then "S," else "N," e__w= if @longitude<0 then "W" else "E" ### Output ### #🌍 jscontent+="<tr><td>D since NYear:</td><td>"+obj.d+"</td></tr>" jscontent+="<tr><td>Timezone:</td><td>GMT"+diffgmt+"</td></tr>" jscontent+="<tr><td>Coordinates:</td><td>"+Math.abs(Math.round(@latitude))+n__s+Math.abs(Math.round(@longitude))+e__w+"</td></tr>" #jscontent+="<tr><td>LocalStdTMerid</td><td>+LSTM+"°</td></tr>") #jscontent+="<tr><td>B(Decl/EoT)</td><td>"+B.toFixed(14)+"</td></tr>" #jscontent+="<tr><td>EccentrCorr</td><td>"+EoT.toFixed(13)+"</td></tr>" #jscontent+="<tr><td>TCorrFactor</td><td>"+TC.toFixed(12)+"</td></tr>" #jscontent+="<tr><td>LocalSolarT</td><td>"+LST.toFixed(13)+"</td></tr>" #jscontent+="<tr><td>HrAng (HRA)</td><td>"+HRA.toFixed(12)+"°</td></tr>" #jscontent+="<tr><td>Declination</td><td>"+Declination.toFixed(13)+"°</td></tr>" jscontent+='<tr><td colspan="2">&nbsp;</td></tr>' Elevation=asin(sin(Declination)*sin(@latitude)+cos(Declination)*cos(@latitude)*cos(HRA)) jscontent+="<tr><td>Altitude:</td><td>"+Math.round(Elevation*1000)/1000+"°</td></tr>" #🌍 Azimuth = acos((sin(Declination)*cos(@latitude)-cos(Declination)*sin(@latitude)*cos(HRA))/cos(Elevation)) if LST>12 or HRA>0 Azimuth = 360-Azimuth jscontent+="<tr><td>Azimuth:</td><td>"+Math.round(Azimuth*1000)/1000+"°</td></tr>" #🌍 ### Sunrise and Sunset ### Meridian=12-(TC/60) Deviation=acos(-tan(@latitude)*tan(Declination))/15 if Deviation ## Sunrise ## Sunrise_h=Math.floor(Meridian-Deviation) Sunrise_m=Math.floor(60*(Meridian-Deviation-Sunrise_h)) Sunrise_s=3600*(Meridian-Deviation-Sunrise_h-Sunrise_m/60) # Hours Formatting if Sunrise_h<0 Sunrise_h="0"+(Sunrise_h+24) if Sunrise_h>23 Sunrise_h="0"+(Sunrise_h-24) else Sunrise_h="0"+Sunrise_h Sunrise_h=Sunrise_h.toString().substr(Sunrise_h.length-2) # Minutes Formatting Sunrise_m="0"+Sunrise_m Sunrise_m=Sunrise_m.substr(Sunrise_m.length-2) # Seconds Formatting and Final Output Sunrise=Sunrise_h+":"+Sunrise_m+":" Sunrise+="0" if Sunrise_s.toFixed(2).toString().length==4 Sunrise+=Sunrise_s.toFixed(2) jscontent+="<tr><td>Sunrise:</td><td>"+Sunrise+"</td></tr>" #🌍 ## Sunset ## Sunset_h=Math.floor(Meridian+Deviation) Sunset_m=Math.floor(60*(Meridian+Deviation-Sunset_h)) Sunset_s=3600*(Meridian+Deviation-Sunset_h-Sunset_m/60) # Hours Formatting if Sunset_h<0 Sunset_h="0"+(Sunset_h+24) if Sunset_h>23 Sunset_h="0"+(Sunset_h-24) else Sunset_h="0"+Sunset_h Sunset_h=Sunset_h.toString().substr(Sunset_h.length-2) # Minutes Formatting Sunset_m="0"+Sunset_m Sunset_m=Sunset_m.substr(Sunset_m.length-2) # Seconds Formatting and Final Output Sunset=Sunset_h+":"+Sunset_m+":" Sunset+="0" if Sunset_s.toFixed(2).toString().length==4 Sunset+=Sunset_s.toFixed(2) jscontent+="<tr><td>Sunset:</td><td>"+Sunset+"</td></tr>" #🌍 else #🌍 pole = if @latitude<0 then "Antarctic" else "Arctic" jscontent+='<tr><td colspan="2"><small>No sunrise or sunset.<br>('+pole+' region)</small></td></tr>' jscontent+="</table>" dom.find("#jscontent").html(jscontent) ### SVG plot (moving) ### r=@radius_svg ## Azimuth line ## x2=r*(1+0.99*sin(Azimuth)) y2=r*(1-0.99*cos(Azimuth)) dom.find("#azimuth")[0].setAttribute("x2", x2) dom.find("#azimuth")[0].setAttribute("y2", y2) ## Azimuth point ## cx=r*(1+sin(Azimuth)*(90-Math.abs(Elevation))/90) #linear cy=r*(1-cos(Azimuth)*(90-Math.abs(Elevation))/90) dom.find("#sun")[0].setAttribute("cx", cx) dom.find("#sun")[0].setAttribute("cy", cy) ## Azimuth point color ## if Elevation<0 dom.find("#sun")[0].setAttribute("fill", "#69a")
[ { "context": "###\n MS Excel 2007 Creater v0.0.1\n Author : chuanyi.zheng@gmail.com\n History: 2012/11/07 first created\n###\n\nfs = re", "end": 69, "score": 0.9998787045478821, "start": 46, "tag": "EMAIL", "value": "chuanyi.zheng@gmail.com" } ]
src/msexcel-builder.coffee
chanlee/msexcel-builder
8
### MS Excel 2007 Creater v0.0.1 Author : chuanyi.zheng@gmail.com History: 2012/11/07 first created ### fs = require 'fs' path = require 'path' exec = require 'child_process' xml = require 'xmlbuilder' existsSync = fs.existsSync || path.existsSync tool = i2a : (i) -> return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.charAt(i-1) copy : (origin, target) -> if existsSync(origin) fs.mkdirSync(target, 0755) if not existsSync(target) files = fs.readdirSync(origin) if files for f in files oCur = origin + '/' + f tCur = target + '/' + f s = fs.statSync(oCur) if s.isFile() fs.writeFileSync(tCur,fs.readFileSync(oCur,''),'') else if s.isDirectory() tool.copy oCur, tCur opt = tmpl_path : __dirname class ContentTypes constructor: (@book)-> toxml:()-> types = xml.create('Types',{version:'1.0',encoding:'UTF-8',standalone:true}) types.att('xmlns','http://schemas.openxmlformats.org/package/2006/content-types') types.ele('Override',{PartName:'/xl/theme/theme1.xml',ContentType:'application/vnd.openxmlformats-officedocument.theme+xml'}) types.ele('Override',{PartName:'/xl/styles.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'}) types.ele('Default',{Extension:'rels',ContentType:'application/vnd.openxmlformats-package.relationships+xml'}) types.ele('Default',{Extension:'xml',ContentType:'application/xml'}) types.ele('Override',{PartName:'/xl/workbook.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'}) types.ele('Override',{PartName:'/docProps/app.xml',ContentType:'application/vnd.openxmlformats-officedocument.extended-properties+xml'}) for i in [1..@book.sheets.length] types.ele('Override',{PartName:'/xl/worksheets/sheet'+i+'.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'}) types.ele('Override',{PartName:'/xl/sharedStrings.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'}) types.ele('Override',{PartName:'/docProps/core.xml',ContentType:'application/vnd.openxmlformats-package.core-properties+xml'}) return types.end() class DocPropsApp constructor: (@book)-> toxml: ()-> props = xml.create('Properties',{version:'1.0',encoding:'UTF-8',standalone:true}) props.att('xmlns','http://schemas.openxmlformats.org/officeDocument/2006/extended-properties') props.att('xmlns:vt','http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes') props.ele('Application','Microsoft Excel') props.ele('DocSecurity','0') props.ele('ScaleCrop','false') tmp = props.ele('HeadingPairs').ele('vt:vector',{size:2,baseType:'variant'}) tmp.ele('vt:variant').ele('vt:lpstr','工作表') tmp.ele('vt:variant').ele('vt:i4',''+@book.sheets.length) tmp = props.ele('TitlesOfParts').ele('vt:vector',{size:@book.sheets.length,baseType:'lpstr'}) for i in [1..@book.sheets.length] tmp.ele('vt:lpstr',@book.sheets[i-1].name) props.ele('Company') props.ele('LinksUpToDate','false') props.ele('SharedDoc','false') props.ele('HyperlinksChanged','false') props.ele('AppVersion','12.0000') return props.end() class XlWorkbook constructor: (@book)-> toxml: ()-> wb = xml.create('workbook',{version:'1.0',encoding:'UTF-8',standalone:true}) wb.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') wb.att('xmlns:r','http://schemas.openxmlformats.org/officeDocument/2006/relationships') wb.ele('fileVersion ',{appName:'xl',lastEdited:'4',lowestEdited:'4',rupBuild:'4505'}) wb.ele('workbookPr',{filterPrivacy:'1',defaultThemeVersion:'124226'}) wb.ele('bookViews').ele('workbookView ',{xWindow:'0',yWindow:'90',windowWidth:'19200',windowHeight:'11640'}) tmp = wb.ele('sheets') for i in [1..@book.sheets.length] tmp.ele('sheet',{name:@book.sheets[i-1].name,sheetId:''+i,'r:id':'rId'+i}) wb.ele('calcPr',{calcId:'124519'}) return wb.end() class XlRels constructor: (@book)-> toxml: ()-> rs = xml.create('Relationships',{version:'1.0',encoding:'UTF-8',standalone:true}) rs.att('xmlns','http://schemas.openxmlformats.org/package/2006/relationships') for i in [1..@book.sheets.length] rs.ele('Relationship',{Id:'rId'+i,Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',Target:'worksheets/sheet'+i+'.xml'}) rs.ele('Relationship',{Id:'rId'+(@book.sheets.length+1),Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',Target:'theme/theme1.xml'}) rs.ele('Relationship',{Id:'rId'+(@book.sheets.length+2),Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',Target:'styles.xml'}) rs.ele('Relationship',{Id:'rId'+(@book.sheets.length+3),Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',Target:'sharedStrings.xml'}) return rs.end() class SharedStrings constructor: ()-> @cache = {} @arr = [] str2id: (s)-> id = @cache[s] if id return id else @arr.push s @cache[s] = @arr.length return @arr.length toxml: ()-> sst = xml.create('sst',{version:'1.0',encoding:'UTF-8',standalone:true}) sst.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') sst.att('count',''+@arr.length) sst.att('uniqueCount',''+@arr.length) for i in [0...@arr.length] si = sst.ele('si') si.ele('t',@arr[i]) si.ele('phoneticPr',{fontId:1,type:'noConversion'}) return sst.end() class Sheet constructor: (@book, @name, @cols, @rows) -> @data = {} for i in [1..@rows] @data[i] = {} for j in [1..@cols] @data[i][j] = {v:0} @merges = [] @col_wd = [] @row_ht = {} @styles = {} set: (col, row, str) -> @data[row][col].v = @book.ss.str2id(''+str) if str? and str isnt '' merge: (from_cell, to_cell) -> @merges.push({from:from_cell, to:to_cell}) width: (col, wd) -> @col_wd.push {c:col,cw:wd} height: (row, ht) -> @row_ht[row] = ht font: (col, row, font_s)-> @styles['font_'+col+'_'+row] = @book.st.font2id(font_s) fill: (col, row, fill_s)-> @styles['fill_'+col+'_'+row] = @book.st.fill2id(fill_s) border: (col, row, bder_s)-> @styles['bder_'+col+'_'+row] = @book.st.bder2id(bder_s) align: (col, row, align_s)-> @styles['algn_'+col+'_'+row] = align_s valign: (col, row, valign_s)-> @styles['valgn_'+col+'_'+row] = valign_s rotate: (col, row, textRotation)-> @styles['rotate_'+col+'_'+row] = textRotation wrap: (col, row, wrap_s)-> @styles['wrap_'+col+'_'+row] = wrap_s style_id: (col, row) -> inx = '_'+col+'_'+row style = {font_id:@styles['font'+inx],fill_id:@styles['fill'+inx],bder_id:@styles['bder'+inx],align:@styles['algn'+inx],valign:@styles['valgn'+inx],rotate:@styles['rotate'+inx],wrap:@styles['wrap'+inx]} id = @book.st.style2id(style) return id toxml: () -> ws = xml.create('worksheet',{version:'1.0',encoding:'UTF-8',standalone:true}) ws.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') ws.att('xmlns:r','http://schemas.openxmlformats.org/officeDocument/2006/relationships') ws.ele('dimension',{ref:'A1'}) ws.ele('sheetViews').ele('sheetView',{workbookViewId:'0'}) ws.ele('sheetFormatPr',{defaultRowHeight:'13.5'}) if @col_wd.length > 0 cols = ws.ele('cols') for cw in @col_wd cols.ele('col',{min:''+cw.c,max:''+cw.c,width:cw.cw,customWidth:'1'}) sd = ws.ele('sheetData') for i in [1..@rows] r = sd.ele('row',{r:''+i,spans:'1:'+@cols}) ht = @row_ht[i] if ht r.att('ht',ht) r.att('customHeight','1') for j in [1..@cols] ix = @data[i][j] sid = @style_id(j, i) if (ix.v isnt 0) or (sid isnt 1) c = r.ele('c',{r:''+tool.i2a(j)+i}) c.att('s',''+(sid-1)) if sid isnt 1 if ix.v isnt 0 c.att('t','s') c.ele('v',''+(ix.v-1)) if @merges.length > 0 mc = ws.ele('mergeCells',{count:@merges.length}) for m in @merges mc.ele('mergeCell',{ref:(''+tool.i2a(m.from.col)+m.from.row+':'+tool.i2a(m.to.col)+m.to.row)}) ws.ele('phoneticPr',{fontId:'1',type:'noConversion'}) ws.ele('pageMargins',{left:'0.7',right:'0.7',top:'0.75',bottom:'0.75',header:'0.3',footer:'0.3'}) ws.ele('pageSetup',{paperSize:'9',orientation:'portrait',horizontalDpi:'200',verticalDpi:'200'}) return ws.end() class Style constructor: (@book)-> @cache = {} @mfonts = [] # font style @mfills = [] # fill style @mbders = [] # border style @mstyle = [] # cell style<ref-font,ref-fill,ref-border,align> @with_default() with_default:()-> @def_font_id = @font2id(null) @def_fill_id = @fill2id(null) @def_bder_id = @bder2id(null) @def_align = '-' @def_valign = '-' @def_rotate = '-' @def_wrap = '-' @def_style_id = @style2id({font_id:@def_font_id,fill_id:@def_fill_id,bder_id:@def_bder_id,align:@def_align,valign:@def_valign,rotate:@def_rotate}) font2id: (font)-> font or= {} font.bold or= '-' font.iter or= '-' font.sz or= '11' font.color or= '-' font.name or= '宋体' font.scheme or='minor' font.family or= '2' k = 'font_'+font.bold+font.iter+font.sz+font.color+font.name+font.scheme+font.family id = @cache[k] if id return id else @mfonts.push font @cache[k] = @mfonts.length return @mfonts.length fill2id: (fill)-> fill or= {} fill.type or= 'none' fill.bgColor or= '-' fill.fgColor or= '-' k = 'fill_' + fill.type + fill.bgColor + fill.fgColor id = @cache[k] if id return id else @mfills.push fill @cache[k] = @mfills.length return @mfills.length bder2id: (bder)-> bder or= {} bder.left or= '-' bder.right or= '-' bder.top or= '-' bder.bottom or= '-' k = 'bder_'+bder.left+'_'+bder.right+'_'+bder.top+'_'+bder.bottom id = @cache[k] if id return id else @mbders.push bder @cache[k] = @mbders.length return @mbders.length style2id:(style)-> style.align or= @def_align style.valign or= @def_valign style.rotate or= @def_rotate style.wrap or= @def_wrap style.font_id or= @def_font_id style.fill_id or= @def_fill_id style.bder_id or= @def_bder_id k = 's_' + style.font_id + '_' + style.fill_id + '_' + style.bder_id + '_' + style.align + '_' + style.valign + '_' + style.wrap + '_' + style.rotate id = @cache[k] if id return id else @mstyle.push style @cache[k] = @mstyle.length return @mstyle.length toxml: ()-> ss = xml.create('styleSheet',{version:'1.0',encoding:'UTF-8',standalone:true}) ss.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') fonts = ss.ele('fonts',{count:@mfonts.length}) for o in @mfonts e = fonts.ele('font') e.ele('b') if o.bold isnt '-' e.ele('i') if o.iter isnt '-' e.ele('sz',{val:o.sz}) e.ele('color',{theme:o.color}) if o.color isnt '-' e.ele('name',{val:o.name}) e.ele('family',{val:o.family}) e.ele('charset',{val:'134'}) e.ele('scheme',{val:'minor'}) if o.scheme isnt '-' fills = ss.ele('fills',{count:@mfills.length}) for o in @mfills e = fills.ele('fill') es = e.ele('patternFill',{patternType:o.type}) es.ele('fgColor',{theme:'8',tint:'0.79998168889431442'}) if o.fgColor isnt '-' es.ele('bgColor',{indexed:o.bgColor}) if o.bgColor isnt '-' bders = ss.ele('borders',{count:@mbders.length}) for o in @mbders e = bders.ele('border') if o.left isnt '-' then e.ele('left',{style:o.left}).ele('color',{auto:'1'}) else e.ele('left') if o.right isnt '-' then e.ele('right',{style:o.right}).ele('color',{auto:'1'}) else e.ele('right') if o.top isnt '-' then e.ele('top',{style:o.top}).ele('color',{auto:'1'}) else e.ele('top') if o.bottom isnt '-' then e.ele('bottom',{style:o.bottom}).ele('color',{auto:'1'}) else e.ele('bottom') e.ele('diagonal') ss.ele('cellStyleXfs',{count:'1'}).ele('xf',{numFmtId:'0',fontId:'0',fillId:'0',borderId:'0'}).ele('alignment',{vertical:'center'}) cs = ss.ele('cellXfs',{count:@mstyle.length}) for o in @mstyle e = cs.ele('xf',{numFmtId:'0',fontId:(o.font_id-1),fillId:(o.fill_id-1),borderId:(o.bder_id-1),xfId:'0'}) e.att('applyFont','1') if o.font_id isnt 1 e.att('applyFill','1') if o.fill_id isnt 1 e.att('applyBorder','1') if o.bder_id isnt 1 if o.align isnt '-' or o.valign isnt '-' or o.wrap isnt '-' e.att('applyAlignment','1') ea = e.ele('alignment',{textRotation:(if o.rotate is '-' then '0' else o.rotate),horizontal:(if o.align is '-' then 'left' else o.align), vertical:(if o.valign is '-' then 'top' else o.valign)}) ea.att('wrapText','1') if o.wrap isnt '-' ss.ele('cellStyles',{count:'1'}).ele('cellStyle',{name:'常规',xfId:'0',builtinId:'0'}) ss.ele('dxfs',{count:'0'}) ss.ele('tableStyles',{count:'0',defaultTableStyle:'TableStyleMedium9',defaultPivotStyle:'PivotStyleLight16'}) return ss.end() class Workbook constructor: (@fpath, @fname) -> @id = ''+parseInt(Math.random()*9999999) # create temp folder & copy template data target = @fpath + '/' + @id + '/' fs.rmdirSync(target) if existsSync(target) tool.copy (opt.tmpl_path + '/tmpl'),target # init @sheets = [] @ss = new SharedStrings @ct = new ContentTypes(@) @da = new DocPropsApp(@) @wb = new XlWorkbook(@) @re = new XlRels(@) @st = new Style(@) createSheet: (name, cols, rows) -> sheet = new Sheet(@,name,cols,rows) @sheets.push sheet return sheet save: (cb) => target = @fpath + '\\' + @id # 1 - build [Content_Types].xml fs.writeFileSync(target+'\\[Content_Types].xml',@ct.toxml(),'utf8') # 2 - build docProps/app.xml fs.writeFileSync(target+'\\docProps\\app.xml',@da.toxml(),'utf8') # 3 - build xl/workbook.xml fs.writeFileSync(target+'\\xl\\workbook.xml',@wb.toxml(),'utf8') # 4 - build xl/sharedStrings.xml fs.writeFileSync(target+'\\xl\\sharedStrings.xml',@ss.toxml(),'utf8') # 5 - build xl/_rels/workbook.xml.rels fs.writeFileSync(target+'\\xl\\_rels\\workbook.xml.rels',@re.toxml(),'utf8') # 6 - build xl/worksheets/sheet(1-N).xml for i in [0...@sheets.length] fs.writeFileSync(target+'\\xl\\worksheets\\sheet'+(i+1)+'.xml',@sheets[i].toxml(),'utf8') # 7 - build xl/styles.xml fs.writeFileSync(target+'\\xl\\styles.xml',@st.toxml(),'utf8') # 8 - compress temp folder to target file args = ' a -tzip "' + @fpath + '\\' + @fname + '" "*"' opts = {cwd:target} exec.exec '"'+opt.tmpl_path+'\\tool\\7za.exe"' + args, opts, (err,stdout,stderr)-> # 9 - delete temp folder exec.exec 'rmdir "' + target + '" /q /s',()-> cb not err cancel: () -> # delete temp folder fs.rmdirSync target module.exports = createWorkbook: (fpath, fname)-> return new Workbook(fpath, fname)
182740
### MS Excel 2007 Creater v0.0.1 Author : <EMAIL> History: 2012/11/07 first created ### fs = require 'fs' path = require 'path' exec = require 'child_process' xml = require 'xmlbuilder' existsSync = fs.existsSync || path.existsSync tool = i2a : (i) -> return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.charAt(i-1) copy : (origin, target) -> if existsSync(origin) fs.mkdirSync(target, 0755) if not existsSync(target) files = fs.readdirSync(origin) if files for f in files oCur = origin + '/' + f tCur = target + '/' + f s = fs.statSync(oCur) if s.isFile() fs.writeFileSync(tCur,fs.readFileSync(oCur,''),'') else if s.isDirectory() tool.copy oCur, tCur opt = tmpl_path : __dirname class ContentTypes constructor: (@book)-> toxml:()-> types = xml.create('Types',{version:'1.0',encoding:'UTF-8',standalone:true}) types.att('xmlns','http://schemas.openxmlformats.org/package/2006/content-types') types.ele('Override',{PartName:'/xl/theme/theme1.xml',ContentType:'application/vnd.openxmlformats-officedocument.theme+xml'}) types.ele('Override',{PartName:'/xl/styles.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'}) types.ele('Default',{Extension:'rels',ContentType:'application/vnd.openxmlformats-package.relationships+xml'}) types.ele('Default',{Extension:'xml',ContentType:'application/xml'}) types.ele('Override',{PartName:'/xl/workbook.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'}) types.ele('Override',{PartName:'/docProps/app.xml',ContentType:'application/vnd.openxmlformats-officedocument.extended-properties+xml'}) for i in [1..@book.sheets.length] types.ele('Override',{PartName:'/xl/worksheets/sheet'+i+'.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'}) types.ele('Override',{PartName:'/xl/sharedStrings.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'}) types.ele('Override',{PartName:'/docProps/core.xml',ContentType:'application/vnd.openxmlformats-package.core-properties+xml'}) return types.end() class DocPropsApp constructor: (@book)-> toxml: ()-> props = xml.create('Properties',{version:'1.0',encoding:'UTF-8',standalone:true}) props.att('xmlns','http://schemas.openxmlformats.org/officeDocument/2006/extended-properties') props.att('xmlns:vt','http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes') props.ele('Application','Microsoft Excel') props.ele('DocSecurity','0') props.ele('ScaleCrop','false') tmp = props.ele('HeadingPairs').ele('vt:vector',{size:2,baseType:'variant'}) tmp.ele('vt:variant').ele('vt:lpstr','工作表') tmp.ele('vt:variant').ele('vt:i4',''+@book.sheets.length) tmp = props.ele('TitlesOfParts').ele('vt:vector',{size:@book.sheets.length,baseType:'lpstr'}) for i in [1..@book.sheets.length] tmp.ele('vt:lpstr',@book.sheets[i-1].name) props.ele('Company') props.ele('LinksUpToDate','false') props.ele('SharedDoc','false') props.ele('HyperlinksChanged','false') props.ele('AppVersion','12.0000') return props.end() class XlWorkbook constructor: (@book)-> toxml: ()-> wb = xml.create('workbook',{version:'1.0',encoding:'UTF-8',standalone:true}) wb.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') wb.att('xmlns:r','http://schemas.openxmlformats.org/officeDocument/2006/relationships') wb.ele('fileVersion ',{appName:'xl',lastEdited:'4',lowestEdited:'4',rupBuild:'4505'}) wb.ele('workbookPr',{filterPrivacy:'1',defaultThemeVersion:'124226'}) wb.ele('bookViews').ele('workbookView ',{xWindow:'0',yWindow:'90',windowWidth:'19200',windowHeight:'11640'}) tmp = wb.ele('sheets') for i in [1..@book.sheets.length] tmp.ele('sheet',{name:@book.sheets[i-1].name,sheetId:''+i,'r:id':'rId'+i}) wb.ele('calcPr',{calcId:'124519'}) return wb.end() class XlRels constructor: (@book)-> toxml: ()-> rs = xml.create('Relationships',{version:'1.0',encoding:'UTF-8',standalone:true}) rs.att('xmlns','http://schemas.openxmlformats.org/package/2006/relationships') for i in [1..@book.sheets.length] rs.ele('Relationship',{Id:'rId'+i,Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',Target:'worksheets/sheet'+i+'.xml'}) rs.ele('Relationship',{Id:'rId'+(@book.sheets.length+1),Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',Target:'theme/theme1.xml'}) rs.ele('Relationship',{Id:'rId'+(@book.sheets.length+2),Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',Target:'styles.xml'}) rs.ele('Relationship',{Id:'rId'+(@book.sheets.length+3),Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',Target:'sharedStrings.xml'}) return rs.end() class SharedStrings constructor: ()-> @cache = {} @arr = [] str2id: (s)-> id = @cache[s] if id return id else @arr.push s @cache[s] = @arr.length return @arr.length toxml: ()-> sst = xml.create('sst',{version:'1.0',encoding:'UTF-8',standalone:true}) sst.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') sst.att('count',''+@arr.length) sst.att('uniqueCount',''+@arr.length) for i in [0...@arr.length] si = sst.ele('si') si.ele('t',@arr[i]) si.ele('phoneticPr',{fontId:1,type:'noConversion'}) return sst.end() class Sheet constructor: (@book, @name, @cols, @rows) -> @data = {} for i in [1..@rows] @data[i] = {} for j in [1..@cols] @data[i][j] = {v:0} @merges = [] @col_wd = [] @row_ht = {} @styles = {} set: (col, row, str) -> @data[row][col].v = @book.ss.str2id(''+str) if str? and str isnt '' merge: (from_cell, to_cell) -> @merges.push({from:from_cell, to:to_cell}) width: (col, wd) -> @col_wd.push {c:col,cw:wd} height: (row, ht) -> @row_ht[row] = ht font: (col, row, font_s)-> @styles['font_'+col+'_'+row] = @book.st.font2id(font_s) fill: (col, row, fill_s)-> @styles['fill_'+col+'_'+row] = @book.st.fill2id(fill_s) border: (col, row, bder_s)-> @styles['bder_'+col+'_'+row] = @book.st.bder2id(bder_s) align: (col, row, align_s)-> @styles['algn_'+col+'_'+row] = align_s valign: (col, row, valign_s)-> @styles['valgn_'+col+'_'+row] = valign_s rotate: (col, row, textRotation)-> @styles['rotate_'+col+'_'+row] = textRotation wrap: (col, row, wrap_s)-> @styles['wrap_'+col+'_'+row] = wrap_s style_id: (col, row) -> inx = '_'+col+'_'+row style = {font_id:@styles['font'+inx],fill_id:@styles['fill'+inx],bder_id:@styles['bder'+inx],align:@styles['algn'+inx],valign:@styles['valgn'+inx],rotate:@styles['rotate'+inx],wrap:@styles['wrap'+inx]} id = @book.st.style2id(style) return id toxml: () -> ws = xml.create('worksheet',{version:'1.0',encoding:'UTF-8',standalone:true}) ws.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') ws.att('xmlns:r','http://schemas.openxmlformats.org/officeDocument/2006/relationships') ws.ele('dimension',{ref:'A1'}) ws.ele('sheetViews').ele('sheetView',{workbookViewId:'0'}) ws.ele('sheetFormatPr',{defaultRowHeight:'13.5'}) if @col_wd.length > 0 cols = ws.ele('cols') for cw in @col_wd cols.ele('col',{min:''+cw.c,max:''+cw.c,width:cw.cw,customWidth:'1'}) sd = ws.ele('sheetData') for i in [1..@rows] r = sd.ele('row',{r:''+i,spans:'1:'+@cols}) ht = @row_ht[i] if ht r.att('ht',ht) r.att('customHeight','1') for j in [1..@cols] ix = @data[i][j] sid = @style_id(j, i) if (ix.v isnt 0) or (sid isnt 1) c = r.ele('c',{r:''+tool.i2a(j)+i}) c.att('s',''+(sid-1)) if sid isnt 1 if ix.v isnt 0 c.att('t','s') c.ele('v',''+(ix.v-1)) if @merges.length > 0 mc = ws.ele('mergeCells',{count:@merges.length}) for m in @merges mc.ele('mergeCell',{ref:(''+tool.i2a(m.from.col)+m.from.row+':'+tool.i2a(m.to.col)+m.to.row)}) ws.ele('phoneticPr',{fontId:'1',type:'noConversion'}) ws.ele('pageMargins',{left:'0.7',right:'0.7',top:'0.75',bottom:'0.75',header:'0.3',footer:'0.3'}) ws.ele('pageSetup',{paperSize:'9',orientation:'portrait',horizontalDpi:'200',verticalDpi:'200'}) return ws.end() class Style constructor: (@book)-> @cache = {} @mfonts = [] # font style @mfills = [] # fill style @mbders = [] # border style @mstyle = [] # cell style<ref-font,ref-fill,ref-border,align> @with_default() with_default:()-> @def_font_id = @font2id(null) @def_fill_id = @fill2id(null) @def_bder_id = @bder2id(null) @def_align = '-' @def_valign = '-' @def_rotate = '-' @def_wrap = '-' @def_style_id = @style2id({font_id:@def_font_id,fill_id:@def_fill_id,bder_id:@def_bder_id,align:@def_align,valign:@def_valign,rotate:@def_rotate}) font2id: (font)-> font or= {} font.bold or= '-' font.iter or= '-' font.sz or= '11' font.color or= '-' font.name or= '宋体' font.scheme or='minor' font.family or= '2' k = 'font_'+font.bold+font.iter+font.sz+font.color+font.name+font.scheme+font.family id = @cache[k] if id return id else @mfonts.push font @cache[k] = @mfonts.length return @mfonts.length fill2id: (fill)-> fill or= {} fill.type or= 'none' fill.bgColor or= '-' fill.fgColor or= '-' k = 'fill_' + fill.type + fill.bgColor + fill.fgColor id = @cache[k] if id return id else @mfills.push fill @cache[k] = @mfills.length return @mfills.length bder2id: (bder)-> bder or= {} bder.left or= '-' bder.right or= '-' bder.top or= '-' bder.bottom or= '-' k = 'bder_'+bder.left+'_'+bder.right+'_'+bder.top+'_'+bder.bottom id = @cache[k] if id return id else @mbders.push bder @cache[k] = @mbders.length return @mbders.length style2id:(style)-> style.align or= @def_align style.valign or= @def_valign style.rotate or= @def_rotate style.wrap or= @def_wrap style.font_id or= @def_font_id style.fill_id or= @def_fill_id style.bder_id or= @def_bder_id k = 's_' + style.font_id + '_' + style.fill_id + '_' + style.bder_id + '_' + style.align + '_' + style.valign + '_' + style.wrap + '_' + style.rotate id = @cache[k] if id return id else @mstyle.push style @cache[k] = @mstyle.length return @mstyle.length toxml: ()-> ss = xml.create('styleSheet',{version:'1.0',encoding:'UTF-8',standalone:true}) ss.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') fonts = ss.ele('fonts',{count:@mfonts.length}) for o in @mfonts e = fonts.ele('font') e.ele('b') if o.bold isnt '-' e.ele('i') if o.iter isnt '-' e.ele('sz',{val:o.sz}) e.ele('color',{theme:o.color}) if o.color isnt '-' e.ele('name',{val:o.name}) e.ele('family',{val:o.family}) e.ele('charset',{val:'134'}) e.ele('scheme',{val:'minor'}) if o.scheme isnt '-' fills = ss.ele('fills',{count:@mfills.length}) for o in @mfills e = fills.ele('fill') es = e.ele('patternFill',{patternType:o.type}) es.ele('fgColor',{theme:'8',tint:'0.79998168889431442'}) if o.fgColor isnt '-' es.ele('bgColor',{indexed:o.bgColor}) if o.bgColor isnt '-' bders = ss.ele('borders',{count:@mbders.length}) for o in @mbders e = bders.ele('border') if o.left isnt '-' then e.ele('left',{style:o.left}).ele('color',{auto:'1'}) else e.ele('left') if o.right isnt '-' then e.ele('right',{style:o.right}).ele('color',{auto:'1'}) else e.ele('right') if o.top isnt '-' then e.ele('top',{style:o.top}).ele('color',{auto:'1'}) else e.ele('top') if o.bottom isnt '-' then e.ele('bottom',{style:o.bottom}).ele('color',{auto:'1'}) else e.ele('bottom') e.ele('diagonal') ss.ele('cellStyleXfs',{count:'1'}).ele('xf',{numFmtId:'0',fontId:'0',fillId:'0',borderId:'0'}).ele('alignment',{vertical:'center'}) cs = ss.ele('cellXfs',{count:@mstyle.length}) for o in @mstyle e = cs.ele('xf',{numFmtId:'0',fontId:(o.font_id-1),fillId:(o.fill_id-1),borderId:(o.bder_id-1),xfId:'0'}) e.att('applyFont','1') if o.font_id isnt 1 e.att('applyFill','1') if o.fill_id isnt 1 e.att('applyBorder','1') if o.bder_id isnt 1 if o.align isnt '-' or o.valign isnt '-' or o.wrap isnt '-' e.att('applyAlignment','1') ea = e.ele('alignment',{textRotation:(if o.rotate is '-' then '0' else o.rotate),horizontal:(if o.align is '-' then 'left' else o.align), vertical:(if o.valign is '-' then 'top' else o.valign)}) ea.att('wrapText','1') if o.wrap isnt '-' ss.ele('cellStyles',{count:'1'}).ele('cellStyle',{name:'常规',xfId:'0',builtinId:'0'}) ss.ele('dxfs',{count:'0'}) ss.ele('tableStyles',{count:'0',defaultTableStyle:'TableStyleMedium9',defaultPivotStyle:'PivotStyleLight16'}) return ss.end() class Workbook constructor: (@fpath, @fname) -> @id = ''+parseInt(Math.random()*9999999) # create temp folder & copy template data target = @fpath + '/' + @id + '/' fs.rmdirSync(target) if existsSync(target) tool.copy (opt.tmpl_path + '/tmpl'),target # init @sheets = [] @ss = new SharedStrings @ct = new ContentTypes(@) @da = new DocPropsApp(@) @wb = new XlWorkbook(@) @re = new XlRels(@) @st = new Style(@) createSheet: (name, cols, rows) -> sheet = new Sheet(@,name,cols,rows) @sheets.push sheet return sheet save: (cb) => target = @fpath + '\\' + @id # 1 - build [Content_Types].xml fs.writeFileSync(target+'\\[Content_Types].xml',@ct.toxml(),'utf8') # 2 - build docProps/app.xml fs.writeFileSync(target+'\\docProps\\app.xml',@da.toxml(),'utf8') # 3 - build xl/workbook.xml fs.writeFileSync(target+'\\xl\\workbook.xml',@wb.toxml(),'utf8') # 4 - build xl/sharedStrings.xml fs.writeFileSync(target+'\\xl\\sharedStrings.xml',@ss.toxml(),'utf8') # 5 - build xl/_rels/workbook.xml.rels fs.writeFileSync(target+'\\xl\\_rels\\workbook.xml.rels',@re.toxml(),'utf8') # 6 - build xl/worksheets/sheet(1-N).xml for i in [0...@sheets.length] fs.writeFileSync(target+'\\xl\\worksheets\\sheet'+(i+1)+'.xml',@sheets[i].toxml(),'utf8') # 7 - build xl/styles.xml fs.writeFileSync(target+'\\xl\\styles.xml',@st.toxml(),'utf8') # 8 - compress temp folder to target file args = ' a -tzip "' + @fpath + '\\' + @fname + '" "*"' opts = {cwd:target} exec.exec '"'+opt.tmpl_path+'\\tool\\7za.exe"' + args, opts, (err,stdout,stderr)-> # 9 - delete temp folder exec.exec 'rmdir "' + target + '" /q /s',()-> cb not err cancel: () -> # delete temp folder fs.rmdirSync target module.exports = createWorkbook: (fpath, fname)-> return new Workbook(fpath, fname)
true
### MS Excel 2007 Creater v0.0.1 Author : PI:EMAIL:<EMAIL>END_PI History: 2012/11/07 first created ### fs = require 'fs' path = require 'path' exec = require 'child_process' xml = require 'xmlbuilder' existsSync = fs.existsSync || path.existsSync tool = i2a : (i) -> return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.charAt(i-1) copy : (origin, target) -> if existsSync(origin) fs.mkdirSync(target, 0755) if not existsSync(target) files = fs.readdirSync(origin) if files for f in files oCur = origin + '/' + f tCur = target + '/' + f s = fs.statSync(oCur) if s.isFile() fs.writeFileSync(tCur,fs.readFileSync(oCur,''),'') else if s.isDirectory() tool.copy oCur, tCur opt = tmpl_path : __dirname class ContentTypes constructor: (@book)-> toxml:()-> types = xml.create('Types',{version:'1.0',encoding:'UTF-8',standalone:true}) types.att('xmlns','http://schemas.openxmlformats.org/package/2006/content-types') types.ele('Override',{PartName:'/xl/theme/theme1.xml',ContentType:'application/vnd.openxmlformats-officedocument.theme+xml'}) types.ele('Override',{PartName:'/xl/styles.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'}) types.ele('Default',{Extension:'rels',ContentType:'application/vnd.openxmlformats-package.relationships+xml'}) types.ele('Default',{Extension:'xml',ContentType:'application/xml'}) types.ele('Override',{PartName:'/xl/workbook.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'}) types.ele('Override',{PartName:'/docProps/app.xml',ContentType:'application/vnd.openxmlformats-officedocument.extended-properties+xml'}) for i in [1..@book.sheets.length] types.ele('Override',{PartName:'/xl/worksheets/sheet'+i+'.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'}) types.ele('Override',{PartName:'/xl/sharedStrings.xml',ContentType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'}) types.ele('Override',{PartName:'/docProps/core.xml',ContentType:'application/vnd.openxmlformats-package.core-properties+xml'}) return types.end() class DocPropsApp constructor: (@book)-> toxml: ()-> props = xml.create('Properties',{version:'1.0',encoding:'UTF-8',standalone:true}) props.att('xmlns','http://schemas.openxmlformats.org/officeDocument/2006/extended-properties') props.att('xmlns:vt','http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes') props.ele('Application','Microsoft Excel') props.ele('DocSecurity','0') props.ele('ScaleCrop','false') tmp = props.ele('HeadingPairs').ele('vt:vector',{size:2,baseType:'variant'}) tmp.ele('vt:variant').ele('vt:lpstr','工作表') tmp.ele('vt:variant').ele('vt:i4',''+@book.sheets.length) tmp = props.ele('TitlesOfParts').ele('vt:vector',{size:@book.sheets.length,baseType:'lpstr'}) for i in [1..@book.sheets.length] tmp.ele('vt:lpstr',@book.sheets[i-1].name) props.ele('Company') props.ele('LinksUpToDate','false') props.ele('SharedDoc','false') props.ele('HyperlinksChanged','false') props.ele('AppVersion','12.0000') return props.end() class XlWorkbook constructor: (@book)-> toxml: ()-> wb = xml.create('workbook',{version:'1.0',encoding:'UTF-8',standalone:true}) wb.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') wb.att('xmlns:r','http://schemas.openxmlformats.org/officeDocument/2006/relationships') wb.ele('fileVersion ',{appName:'xl',lastEdited:'4',lowestEdited:'4',rupBuild:'4505'}) wb.ele('workbookPr',{filterPrivacy:'1',defaultThemeVersion:'124226'}) wb.ele('bookViews').ele('workbookView ',{xWindow:'0',yWindow:'90',windowWidth:'19200',windowHeight:'11640'}) tmp = wb.ele('sheets') for i in [1..@book.sheets.length] tmp.ele('sheet',{name:@book.sheets[i-1].name,sheetId:''+i,'r:id':'rId'+i}) wb.ele('calcPr',{calcId:'124519'}) return wb.end() class XlRels constructor: (@book)-> toxml: ()-> rs = xml.create('Relationships',{version:'1.0',encoding:'UTF-8',standalone:true}) rs.att('xmlns','http://schemas.openxmlformats.org/package/2006/relationships') for i in [1..@book.sheets.length] rs.ele('Relationship',{Id:'rId'+i,Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',Target:'worksheets/sheet'+i+'.xml'}) rs.ele('Relationship',{Id:'rId'+(@book.sheets.length+1),Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',Target:'theme/theme1.xml'}) rs.ele('Relationship',{Id:'rId'+(@book.sheets.length+2),Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',Target:'styles.xml'}) rs.ele('Relationship',{Id:'rId'+(@book.sheets.length+3),Type:'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',Target:'sharedStrings.xml'}) return rs.end() class SharedStrings constructor: ()-> @cache = {} @arr = [] str2id: (s)-> id = @cache[s] if id return id else @arr.push s @cache[s] = @arr.length return @arr.length toxml: ()-> sst = xml.create('sst',{version:'1.0',encoding:'UTF-8',standalone:true}) sst.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') sst.att('count',''+@arr.length) sst.att('uniqueCount',''+@arr.length) for i in [0...@arr.length] si = sst.ele('si') si.ele('t',@arr[i]) si.ele('phoneticPr',{fontId:1,type:'noConversion'}) return sst.end() class Sheet constructor: (@book, @name, @cols, @rows) -> @data = {} for i in [1..@rows] @data[i] = {} for j in [1..@cols] @data[i][j] = {v:0} @merges = [] @col_wd = [] @row_ht = {} @styles = {} set: (col, row, str) -> @data[row][col].v = @book.ss.str2id(''+str) if str? and str isnt '' merge: (from_cell, to_cell) -> @merges.push({from:from_cell, to:to_cell}) width: (col, wd) -> @col_wd.push {c:col,cw:wd} height: (row, ht) -> @row_ht[row] = ht font: (col, row, font_s)-> @styles['font_'+col+'_'+row] = @book.st.font2id(font_s) fill: (col, row, fill_s)-> @styles['fill_'+col+'_'+row] = @book.st.fill2id(fill_s) border: (col, row, bder_s)-> @styles['bder_'+col+'_'+row] = @book.st.bder2id(bder_s) align: (col, row, align_s)-> @styles['algn_'+col+'_'+row] = align_s valign: (col, row, valign_s)-> @styles['valgn_'+col+'_'+row] = valign_s rotate: (col, row, textRotation)-> @styles['rotate_'+col+'_'+row] = textRotation wrap: (col, row, wrap_s)-> @styles['wrap_'+col+'_'+row] = wrap_s style_id: (col, row) -> inx = '_'+col+'_'+row style = {font_id:@styles['font'+inx],fill_id:@styles['fill'+inx],bder_id:@styles['bder'+inx],align:@styles['algn'+inx],valign:@styles['valgn'+inx],rotate:@styles['rotate'+inx],wrap:@styles['wrap'+inx]} id = @book.st.style2id(style) return id toxml: () -> ws = xml.create('worksheet',{version:'1.0',encoding:'UTF-8',standalone:true}) ws.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') ws.att('xmlns:r','http://schemas.openxmlformats.org/officeDocument/2006/relationships') ws.ele('dimension',{ref:'A1'}) ws.ele('sheetViews').ele('sheetView',{workbookViewId:'0'}) ws.ele('sheetFormatPr',{defaultRowHeight:'13.5'}) if @col_wd.length > 0 cols = ws.ele('cols') for cw in @col_wd cols.ele('col',{min:''+cw.c,max:''+cw.c,width:cw.cw,customWidth:'1'}) sd = ws.ele('sheetData') for i in [1..@rows] r = sd.ele('row',{r:''+i,spans:'1:'+@cols}) ht = @row_ht[i] if ht r.att('ht',ht) r.att('customHeight','1') for j in [1..@cols] ix = @data[i][j] sid = @style_id(j, i) if (ix.v isnt 0) or (sid isnt 1) c = r.ele('c',{r:''+tool.i2a(j)+i}) c.att('s',''+(sid-1)) if sid isnt 1 if ix.v isnt 0 c.att('t','s') c.ele('v',''+(ix.v-1)) if @merges.length > 0 mc = ws.ele('mergeCells',{count:@merges.length}) for m in @merges mc.ele('mergeCell',{ref:(''+tool.i2a(m.from.col)+m.from.row+':'+tool.i2a(m.to.col)+m.to.row)}) ws.ele('phoneticPr',{fontId:'1',type:'noConversion'}) ws.ele('pageMargins',{left:'0.7',right:'0.7',top:'0.75',bottom:'0.75',header:'0.3',footer:'0.3'}) ws.ele('pageSetup',{paperSize:'9',orientation:'portrait',horizontalDpi:'200',verticalDpi:'200'}) return ws.end() class Style constructor: (@book)-> @cache = {} @mfonts = [] # font style @mfills = [] # fill style @mbders = [] # border style @mstyle = [] # cell style<ref-font,ref-fill,ref-border,align> @with_default() with_default:()-> @def_font_id = @font2id(null) @def_fill_id = @fill2id(null) @def_bder_id = @bder2id(null) @def_align = '-' @def_valign = '-' @def_rotate = '-' @def_wrap = '-' @def_style_id = @style2id({font_id:@def_font_id,fill_id:@def_fill_id,bder_id:@def_bder_id,align:@def_align,valign:@def_valign,rotate:@def_rotate}) font2id: (font)-> font or= {} font.bold or= '-' font.iter or= '-' font.sz or= '11' font.color or= '-' font.name or= '宋体' font.scheme or='minor' font.family or= '2' k = 'font_'+font.bold+font.iter+font.sz+font.color+font.name+font.scheme+font.family id = @cache[k] if id return id else @mfonts.push font @cache[k] = @mfonts.length return @mfonts.length fill2id: (fill)-> fill or= {} fill.type or= 'none' fill.bgColor or= '-' fill.fgColor or= '-' k = 'fill_' + fill.type + fill.bgColor + fill.fgColor id = @cache[k] if id return id else @mfills.push fill @cache[k] = @mfills.length return @mfills.length bder2id: (bder)-> bder or= {} bder.left or= '-' bder.right or= '-' bder.top or= '-' bder.bottom or= '-' k = 'bder_'+bder.left+'_'+bder.right+'_'+bder.top+'_'+bder.bottom id = @cache[k] if id return id else @mbders.push bder @cache[k] = @mbders.length return @mbders.length style2id:(style)-> style.align or= @def_align style.valign or= @def_valign style.rotate or= @def_rotate style.wrap or= @def_wrap style.font_id or= @def_font_id style.fill_id or= @def_fill_id style.bder_id or= @def_bder_id k = 's_' + style.font_id + '_' + style.fill_id + '_' + style.bder_id + '_' + style.align + '_' + style.valign + '_' + style.wrap + '_' + style.rotate id = @cache[k] if id return id else @mstyle.push style @cache[k] = @mstyle.length return @mstyle.length toxml: ()-> ss = xml.create('styleSheet',{version:'1.0',encoding:'UTF-8',standalone:true}) ss.att('xmlns','http://schemas.openxmlformats.org/spreadsheetml/2006/main') fonts = ss.ele('fonts',{count:@mfonts.length}) for o in @mfonts e = fonts.ele('font') e.ele('b') if o.bold isnt '-' e.ele('i') if o.iter isnt '-' e.ele('sz',{val:o.sz}) e.ele('color',{theme:o.color}) if o.color isnt '-' e.ele('name',{val:o.name}) e.ele('family',{val:o.family}) e.ele('charset',{val:'134'}) e.ele('scheme',{val:'minor'}) if o.scheme isnt '-' fills = ss.ele('fills',{count:@mfills.length}) for o in @mfills e = fills.ele('fill') es = e.ele('patternFill',{patternType:o.type}) es.ele('fgColor',{theme:'8',tint:'0.79998168889431442'}) if o.fgColor isnt '-' es.ele('bgColor',{indexed:o.bgColor}) if o.bgColor isnt '-' bders = ss.ele('borders',{count:@mbders.length}) for o in @mbders e = bders.ele('border') if o.left isnt '-' then e.ele('left',{style:o.left}).ele('color',{auto:'1'}) else e.ele('left') if o.right isnt '-' then e.ele('right',{style:o.right}).ele('color',{auto:'1'}) else e.ele('right') if o.top isnt '-' then e.ele('top',{style:o.top}).ele('color',{auto:'1'}) else e.ele('top') if o.bottom isnt '-' then e.ele('bottom',{style:o.bottom}).ele('color',{auto:'1'}) else e.ele('bottom') e.ele('diagonal') ss.ele('cellStyleXfs',{count:'1'}).ele('xf',{numFmtId:'0',fontId:'0',fillId:'0',borderId:'0'}).ele('alignment',{vertical:'center'}) cs = ss.ele('cellXfs',{count:@mstyle.length}) for o in @mstyle e = cs.ele('xf',{numFmtId:'0',fontId:(o.font_id-1),fillId:(o.fill_id-1),borderId:(o.bder_id-1),xfId:'0'}) e.att('applyFont','1') if o.font_id isnt 1 e.att('applyFill','1') if o.fill_id isnt 1 e.att('applyBorder','1') if o.bder_id isnt 1 if o.align isnt '-' or o.valign isnt '-' or o.wrap isnt '-' e.att('applyAlignment','1') ea = e.ele('alignment',{textRotation:(if o.rotate is '-' then '0' else o.rotate),horizontal:(if o.align is '-' then 'left' else o.align), vertical:(if o.valign is '-' then 'top' else o.valign)}) ea.att('wrapText','1') if o.wrap isnt '-' ss.ele('cellStyles',{count:'1'}).ele('cellStyle',{name:'常规',xfId:'0',builtinId:'0'}) ss.ele('dxfs',{count:'0'}) ss.ele('tableStyles',{count:'0',defaultTableStyle:'TableStyleMedium9',defaultPivotStyle:'PivotStyleLight16'}) return ss.end() class Workbook constructor: (@fpath, @fname) -> @id = ''+parseInt(Math.random()*9999999) # create temp folder & copy template data target = @fpath + '/' + @id + '/' fs.rmdirSync(target) if existsSync(target) tool.copy (opt.tmpl_path + '/tmpl'),target # init @sheets = [] @ss = new SharedStrings @ct = new ContentTypes(@) @da = new DocPropsApp(@) @wb = new XlWorkbook(@) @re = new XlRels(@) @st = new Style(@) createSheet: (name, cols, rows) -> sheet = new Sheet(@,name,cols,rows) @sheets.push sheet return sheet save: (cb) => target = @fpath + '\\' + @id # 1 - build [Content_Types].xml fs.writeFileSync(target+'\\[Content_Types].xml',@ct.toxml(),'utf8') # 2 - build docProps/app.xml fs.writeFileSync(target+'\\docProps\\app.xml',@da.toxml(),'utf8') # 3 - build xl/workbook.xml fs.writeFileSync(target+'\\xl\\workbook.xml',@wb.toxml(),'utf8') # 4 - build xl/sharedStrings.xml fs.writeFileSync(target+'\\xl\\sharedStrings.xml',@ss.toxml(),'utf8') # 5 - build xl/_rels/workbook.xml.rels fs.writeFileSync(target+'\\xl\\_rels\\workbook.xml.rels',@re.toxml(),'utf8') # 6 - build xl/worksheets/sheet(1-N).xml for i in [0...@sheets.length] fs.writeFileSync(target+'\\xl\\worksheets\\sheet'+(i+1)+'.xml',@sheets[i].toxml(),'utf8') # 7 - build xl/styles.xml fs.writeFileSync(target+'\\xl\\styles.xml',@st.toxml(),'utf8') # 8 - compress temp folder to target file args = ' a -tzip "' + @fpath + '\\' + @fname + '" "*"' opts = {cwd:target} exec.exec '"'+opt.tmpl_path+'\\tool\\7za.exe"' + args, opts, (err,stdout,stderr)-> # 9 - delete temp folder exec.exec 'rmdir "' + target + '" /q /s',()-> cb not err cancel: () -> # delete temp folder fs.rmdirSync target module.exports = createWorkbook: (fpath, fname)-> return new Workbook(fpath, fname)
[ { "context": "ons\" unless (@options.token.substring(0, 5) in ['xoxb-', 'xoxp-'])\n\n # Setup client event handlers\n ", "end": 558, "score": 0.7124569416046143, "start": 555, "tag": "KEY", "value": "oxb" }, { "context": " (@options.token.substring(0, 5) in ['xoxb-', 'xoxp-'])\n\n # Setup client event handlers\n @clien", "end": 567, "score": 0.5535913109779358, "start": 566, "tag": "KEY", "value": "p" }, { "context": " bot} = message\n\n return if user && (user.id == @self.id) #Ignore anything we sent\n return if bot && ", "end": 3099, "score": 0.8118757605552673, "start": 3094, "tag": "USERNAME", "value": "@self" } ]
src/bot.coffee
EdtechFoundry/hubot-slack
0
{Adapter, TextMessage, EnterMessage, LeaveMessage, TopicMessage, Message, CatchAllMessage} = require.main.require 'hubot' SlackClient = require './client' class SlackBot extends Adapter constructor: (@robot, @options) -> @client = new SlackClient(@options) ### Slackbot initialization ### run: -> return @robot.logger.error "No service token provided to Hubot" unless @options.token return @robot.logger.error "Invalid service token provided, please follow the upgrade instructions" unless (@options.token.substring(0, 5) in ['xoxb-', 'xoxp-']) # Setup client event handlers @client.on 'open', @open @client.on 'close', @close @client.on 'error', @error @client.on 'message', @message @client.on 'authenticated', @authenticated @client.on 'team_join', @teamJoin # Start logging in @client.connect() ### Function that forwards any received team_join to the robots emitter ### teamJoin: (event) => @robot.emit event.type, event.user ### Slack client has opened the connection ### open: => @robot.logger.info 'Slack client now connected' # Tell Hubot we're connected so it can load scripts @emit "connected" ### Slack client has authenticated ### authenticated: (identity) => {@self, team} = identity # Find out bot_id for user in identity.users if user.id == @self.id @self.bot_id = user.profile.bot_id break # Provide our name to Hubot @robot.name = @self.name @robot.logger.info "Logged in as #{@robot.name} of #{team.name}" ### Slack client has closed the connection ### close: => if @options.autoReconnect @robot.logger.info 'Slack client closed, waiting for reconnect' else @robot.logger.info 'Slack client connection was closed, exiting hubot process' @client.disconnect() process.exit 1 ### Slack client received an error ### error: (error) => if error.code is -1 return @robot.logger.warning "Received rate limiting error #{JSON.stringify error}" @robot.emit 'error', error ### Hubot is sending a message to Slack ### send: (envelope, message, callback) -> @robot.logger.debug "Sending to #{envelope.room}: #{message}" @client.send(envelope, message, callback) return message ### Hubot is replying to a Slack message ### reply: (envelope, messages...) -> sent_messages = [] for message in messages if message isnt '' message = "<@#{envelope.user.id}>: #{message}" unless envelope.room[0] is 'D' @robot.logger.debug "Sending to #{envelope.room}: #{message}" sent_messages.push @client.send(envelope, message) return sent_messages ### Hubot is setting the Slack channel topic ### topic: (envelope, strings...) -> return if envelope.room[0] is 'D' # ignore DMs @client.setTopic envelope.room, strings.join "\n" ### Message received from Slack ### message: (message) => {text, user, channel, subtype, topic, bot} = message return if user && (user.id == @self.id) #Ignore anything we sent return if bot && (bot.id == @self.bot_id) #Ignore anything we sent subtype = subtype || 'message' # Hubot expects this format for TextMessage Listener user = bot if bot user = user if user user = {} if !user && !bot user.room = channel.id # Direct messages if channel.id[0] is 'D' text = "#{@robot.name} #{text}" # If this is a DM, pretend it was addressed to us channel.name ?= channel._modelName # give the channel a name # Send to Hubot based on message type switch subtype when 'message', 'bot_message' @robot.logger.debug "Received message: '#{text}' in channel: #{channel.name}, from: #{user.name}" @receive new TextMessage(user, text, message.ts) when 'channel_join', 'group_join' @robot.logger.debug "#{user.name} has joined #{channel.name}" @receive new EnterMessage user when 'channel_leave', 'group_leave' @robot.logger.debug "#{user.name} has left #{channel.name}" @receive new LeaveMessage user when 'channel_topic', 'group_topic' @robot.logger.debug "#{user.name} set the topic in #{channel.name} to #{topic}" @receive new TopicMessage user, message.topic, message.ts else @robot.logger.debug "Received message: '#{text}' in channel: #{channel.name}, subtype: #{subtype}" message.user = user @receive new CatchAllMessage(message) module.exports = SlackBot
83160
{Adapter, TextMessage, EnterMessage, LeaveMessage, TopicMessage, Message, CatchAllMessage} = require.main.require 'hubot' SlackClient = require './client' class SlackBot extends Adapter constructor: (@robot, @options) -> @client = new SlackClient(@options) ### Slackbot initialization ### run: -> return @robot.logger.error "No service token provided to Hubot" unless @options.token return @robot.logger.error "Invalid service token provided, please follow the upgrade instructions" unless (@options.token.substring(0, 5) in ['x<KEY>-', 'xox<KEY>-']) # Setup client event handlers @client.on 'open', @open @client.on 'close', @close @client.on 'error', @error @client.on 'message', @message @client.on 'authenticated', @authenticated @client.on 'team_join', @teamJoin # Start logging in @client.connect() ### Function that forwards any received team_join to the robots emitter ### teamJoin: (event) => @robot.emit event.type, event.user ### Slack client has opened the connection ### open: => @robot.logger.info 'Slack client now connected' # Tell Hubot we're connected so it can load scripts @emit "connected" ### Slack client has authenticated ### authenticated: (identity) => {@self, team} = identity # Find out bot_id for user in identity.users if user.id == @self.id @self.bot_id = user.profile.bot_id break # Provide our name to Hubot @robot.name = @self.name @robot.logger.info "Logged in as #{@robot.name} of #{team.name}" ### Slack client has closed the connection ### close: => if @options.autoReconnect @robot.logger.info 'Slack client closed, waiting for reconnect' else @robot.logger.info 'Slack client connection was closed, exiting hubot process' @client.disconnect() process.exit 1 ### Slack client received an error ### error: (error) => if error.code is -1 return @robot.logger.warning "Received rate limiting error #{JSON.stringify error}" @robot.emit 'error', error ### Hubot is sending a message to Slack ### send: (envelope, message, callback) -> @robot.logger.debug "Sending to #{envelope.room}: #{message}" @client.send(envelope, message, callback) return message ### Hubot is replying to a Slack message ### reply: (envelope, messages...) -> sent_messages = [] for message in messages if message isnt '' message = "<@#{envelope.user.id}>: #{message}" unless envelope.room[0] is 'D' @robot.logger.debug "Sending to #{envelope.room}: #{message}" sent_messages.push @client.send(envelope, message) return sent_messages ### Hubot is setting the Slack channel topic ### topic: (envelope, strings...) -> return if envelope.room[0] is 'D' # ignore DMs @client.setTopic envelope.room, strings.join "\n" ### Message received from Slack ### message: (message) => {text, user, channel, subtype, topic, bot} = message return if user && (user.id == @self.id) #Ignore anything we sent return if bot && (bot.id == @self.bot_id) #Ignore anything we sent subtype = subtype || 'message' # Hubot expects this format for TextMessage Listener user = bot if bot user = user if user user = {} if !user && !bot user.room = channel.id # Direct messages if channel.id[0] is 'D' text = "#{@robot.name} #{text}" # If this is a DM, pretend it was addressed to us channel.name ?= channel._modelName # give the channel a name # Send to Hubot based on message type switch subtype when 'message', 'bot_message' @robot.logger.debug "Received message: '#{text}' in channel: #{channel.name}, from: #{user.name}" @receive new TextMessage(user, text, message.ts) when 'channel_join', 'group_join' @robot.logger.debug "#{user.name} has joined #{channel.name}" @receive new EnterMessage user when 'channel_leave', 'group_leave' @robot.logger.debug "#{user.name} has left #{channel.name}" @receive new LeaveMessage user when 'channel_topic', 'group_topic' @robot.logger.debug "#{user.name} set the topic in #{channel.name} to #{topic}" @receive new TopicMessage user, message.topic, message.ts else @robot.logger.debug "Received message: '#{text}' in channel: #{channel.name}, subtype: #{subtype}" message.user = user @receive new CatchAllMessage(message) module.exports = SlackBot
true
{Adapter, TextMessage, EnterMessage, LeaveMessage, TopicMessage, Message, CatchAllMessage} = require.main.require 'hubot' SlackClient = require './client' class SlackBot extends Adapter constructor: (@robot, @options) -> @client = new SlackClient(@options) ### Slackbot initialization ### run: -> return @robot.logger.error "No service token provided to Hubot" unless @options.token return @robot.logger.error "Invalid service token provided, please follow the upgrade instructions" unless (@options.token.substring(0, 5) in ['xPI:KEY:<KEY>END_PI-', 'xoxPI:KEY:<KEY>END_PI-']) # Setup client event handlers @client.on 'open', @open @client.on 'close', @close @client.on 'error', @error @client.on 'message', @message @client.on 'authenticated', @authenticated @client.on 'team_join', @teamJoin # Start logging in @client.connect() ### Function that forwards any received team_join to the robots emitter ### teamJoin: (event) => @robot.emit event.type, event.user ### Slack client has opened the connection ### open: => @robot.logger.info 'Slack client now connected' # Tell Hubot we're connected so it can load scripts @emit "connected" ### Slack client has authenticated ### authenticated: (identity) => {@self, team} = identity # Find out bot_id for user in identity.users if user.id == @self.id @self.bot_id = user.profile.bot_id break # Provide our name to Hubot @robot.name = @self.name @robot.logger.info "Logged in as #{@robot.name} of #{team.name}" ### Slack client has closed the connection ### close: => if @options.autoReconnect @robot.logger.info 'Slack client closed, waiting for reconnect' else @robot.logger.info 'Slack client connection was closed, exiting hubot process' @client.disconnect() process.exit 1 ### Slack client received an error ### error: (error) => if error.code is -1 return @robot.logger.warning "Received rate limiting error #{JSON.stringify error}" @robot.emit 'error', error ### Hubot is sending a message to Slack ### send: (envelope, message, callback) -> @robot.logger.debug "Sending to #{envelope.room}: #{message}" @client.send(envelope, message, callback) return message ### Hubot is replying to a Slack message ### reply: (envelope, messages...) -> sent_messages = [] for message in messages if message isnt '' message = "<@#{envelope.user.id}>: #{message}" unless envelope.room[0] is 'D' @robot.logger.debug "Sending to #{envelope.room}: #{message}" sent_messages.push @client.send(envelope, message) return sent_messages ### Hubot is setting the Slack channel topic ### topic: (envelope, strings...) -> return if envelope.room[0] is 'D' # ignore DMs @client.setTopic envelope.room, strings.join "\n" ### Message received from Slack ### message: (message) => {text, user, channel, subtype, topic, bot} = message return if user && (user.id == @self.id) #Ignore anything we sent return if bot && (bot.id == @self.bot_id) #Ignore anything we sent subtype = subtype || 'message' # Hubot expects this format for TextMessage Listener user = bot if bot user = user if user user = {} if !user && !bot user.room = channel.id # Direct messages if channel.id[0] is 'D' text = "#{@robot.name} #{text}" # If this is a DM, pretend it was addressed to us channel.name ?= channel._modelName # give the channel a name # Send to Hubot based on message type switch subtype when 'message', 'bot_message' @robot.logger.debug "Received message: '#{text}' in channel: #{channel.name}, from: #{user.name}" @receive new TextMessage(user, text, message.ts) when 'channel_join', 'group_join' @robot.logger.debug "#{user.name} has joined #{channel.name}" @receive new EnterMessage user when 'channel_leave', 'group_leave' @robot.logger.debug "#{user.name} has left #{channel.name}" @receive new LeaveMessage user when 'channel_topic', 'group_topic' @robot.logger.debug "#{user.name} set the topic in #{channel.name} to #{topic}" @receive new TopicMessage user, message.topic, message.ts else @robot.logger.debug "Received message: '#{text}' in channel: #{channel.name}, subtype: #{subtype}" message.user = user @receive new CatchAllMessage(message) module.exports = SlackBot
[ { "context": "ods section unit tests\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\n{Test,should} = require('lovely')\n\nTest.set \"/c", "end": 95, "score": 0.9998844265937805, "start": 78, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/dom/test/element/commons_test.coffee
lovely-io/lovely.io-stl
2
# # The Element common methods section unit tests # # Copyright (C) 2011-2013 Nikolay Nemshilov # {Test,should} = require('lovely') Test.set "/commons.html", """ <html> <head> <script src="/core.js"></script> <script src="/dom.js"></script> </head> <body> <div id="test" data-test="test"></div> </body> </html> """ describe 'Element Commons', -> $ = element = window = document = null before Test.load '/commons.html', (dom, win)-> $ = dom window = win document = win.document element = new $.Element(document.getElementById('test')) describe "#attr", -> describe "\b('name')", -> it "should read a property attribute", -> element.attr('id').should.equal 'test' it "should read the 'data-test' attribute", -> element.attr('data-test').should.eql 'test' it "should return 'null' for non existing attributes", -> (element.attr('nonexistent') is null).should.be.true describe "\b('name', 'value')", -> it "should return the element back", -> element.attr('title', 'text').should.equal element it "should set property attributes", -> element.attr('title', 'new value') element._.title.should.eql 'new value' it "should set non-property attributes", -> element.attr('data-new', 'something') element._.getAttribute('data-new').should.eql 'something' describe "\b({name: 'value'})", -> it "should return the element back afterwards", -> element.attr(smth: 'value').should.equal element it "should set all the attributes from the hash", -> element.attr test_attr1: 'value1' test_attr2: 'value2' element._.getAttribute('test_attr1').should.eql 'value1' element._.getAttribute('test_attr2').should.eql 'value2' describe "\b('name', null)", -> it "should remove the attribute", -> element.attr('something', 'something') element.attr('something').should.eql 'something' element.attr('something', null) (element.attr('something') is null).should.be.true describe "#hidden()", -> it "should say 'true' when the element is hidden", -> element._.style.display = 'none' element.hidden().should.be.true it "should say 'false' when the element is visible", -> element._.style.display = 'block' element.hidden().should.be.false describe "#visible()", -> it "should say 'false' when the element is hidden", -> element._.style.display = 'none' element.visible().should.be.false it "should say 'true' when the element is visible", -> element._.style.display = 'block' element.visible().should.be.true describe "#hide()", -> it "should hide the element when it is visible", -> element._.style.display = 'block' element.hide() element._.style.display.should.eql 'none' it "should leave element hidden when it is not visible", -> element._.style.display = 'none' element.hide() element._.style.display.should.eql 'none' it "should return the element reference back", -> element.hide().should.equal element describe "#show()", -> it "should show an element if it's hidden", -> element._.style.display = 'none' element.show() element._.style.display.should.eql 'block' it "should leave a visible element visible", -> element._.style.display = 'inline' element.show() element._.style.display.should.eql 'inline' it "should return the element reference back", -> element.show().should.equal element describe "#toggle()", -> it "should show an element if it is hidden", -> element._.style.display = 'none' element.toggle() element._.style.display.should.eql 'block' it "should hide an element if it's visible", -> element._.style.display = 'block' element.toggle() element._.style.display.should.eql 'none' it "should return back a reference to the element",-> element.toggle().should.equal element describe "#document()", -> it "should return the owner document wrapper", -> doc = element.document() doc.should.be.instanceOf $.Document doc._.should.equal document it "should return the same wrapper all the time", -> element.document().should.equal element.document() describe "#window()", -> it "should return the owner window wrapper", -> win = element.window() win.should.be.instanceOf $.Window win._.should.be.equal window describe "#data()", -> it "should read data- attributes", -> element.attr({ 'data-false': 'false' 'data-true': 'true' 'data-number': '1.23' 'data-string': '"string"' 'data-array': '[1,2,3]' 'data-object': '{"boo":"hoo"}' 'data-plain': 'plain text' }) element.data('false').should.equal false element.data('true').should.equal true element.data('number').should.equal 1.23 element.data('string').should.equal 'string' element.data('array').should.eql [1,2,3] element.data('object').should.eql {boo: "hoo"} element.data('plain').should.equal 'plain text' (element.data('non-existing') is null).should.be.true it "should read nested attributes", -> element.attr({ 'data-thing-one': '1' 'data-thing-two': '2' 'data-thing-three-one': '3.1' }) element.data('thing').should.eql { one: 1, two: 2, threeOne: 3.1 } it "should write data- attributes", -> element.data('string', 'string').should.equal element element._.getAttribute('data-string').should.equal 'string' (element['data-string'] is undefined).should.be.true element.data('false', false)._.getAttribute('data-false').should.equal 'false' element.data('true', true)._.getAttribute('data-true').should.equal 'true' element.data('number', 1.23)._.getAttribute('data-number').should.equal '1.23' element.data('array', [1,2,3])._.getAttribute('data-array').should.equal '[1,2,3]' it "should allow to write data as a plain hash", -> element.data({ one: 1, two: 2, three: 3 }).should.equal element element._.getAttribute('data-one').should.equal '1' element._.getAttribute('data-two').should.equal '2' element._.getAttribute('data-three').should.equal '3' it "should allow to write data as a nested hash", -> element.data('test', { 'one': 1, two: 2, 'three-one': 3.1, 'threeTwo': 3.2 }).should.equal element element._.getAttribute('data-test-one').should.equal '1' element._.getAttribute('data-test-two').should.equal '2' element._.getAttribute('data-test-three-one').should.equal '3.1' element._.getAttribute('data-test-three-two').should.equal '3.2' it "should allow to remove data- attributes", -> element.attr {'data-something': 'something'} element.data('something', null).should.equal element (element._.getAttribute('data-something') is null).should.be.true
83620
# # The Element common methods section unit tests # # Copyright (C) 2011-2013 <NAME> # {Test,should} = require('lovely') Test.set "/commons.html", """ <html> <head> <script src="/core.js"></script> <script src="/dom.js"></script> </head> <body> <div id="test" data-test="test"></div> </body> </html> """ describe 'Element Commons', -> $ = element = window = document = null before Test.load '/commons.html', (dom, win)-> $ = dom window = win document = win.document element = new $.Element(document.getElementById('test')) describe "#attr", -> describe "\b('name')", -> it "should read a property attribute", -> element.attr('id').should.equal 'test' it "should read the 'data-test' attribute", -> element.attr('data-test').should.eql 'test' it "should return 'null' for non existing attributes", -> (element.attr('nonexistent') is null).should.be.true describe "\b('name', 'value')", -> it "should return the element back", -> element.attr('title', 'text').should.equal element it "should set property attributes", -> element.attr('title', 'new value') element._.title.should.eql 'new value' it "should set non-property attributes", -> element.attr('data-new', 'something') element._.getAttribute('data-new').should.eql 'something' describe "\b({name: 'value'})", -> it "should return the element back afterwards", -> element.attr(smth: 'value').should.equal element it "should set all the attributes from the hash", -> element.attr test_attr1: 'value1' test_attr2: 'value2' element._.getAttribute('test_attr1').should.eql 'value1' element._.getAttribute('test_attr2').should.eql 'value2' describe "\b('name', null)", -> it "should remove the attribute", -> element.attr('something', 'something') element.attr('something').should.eql 'something' element.attr('something', null) (element.attr('something') is null).should.be.true describe "#hidden()", -> it "should say 'true' when the element is hidden", -> element._.style.display = 'none' element.hidden().should.be.true it "should say 'false' when the element is visible", -> element._.style.display = 'block' element.hidden().should.be.false describe "#visible()", -> it "should say 'false' when the element is hidden", -> element._.style.display = 'none' element.visible().should.be.false it "should say 'true' when the element is visible", -> element._.style.display = 'block' element.visible().should.be.true describe "#hide()", -> it "should hide the element when it is visible", -> element._.style.display = 'block' element.hide() element._.style.display.should.eql 'none' it "should leave element hidden when it is not visible", -> element._.style.display = 'none' element.hide() element._.style.display.should.eql 'none' it "should return the element reference back", -> element.hide().should.equal element describe "#show()", -> it "should show an element if it's hidden", -> element._.style.display = 'none' element.show() element._.style.display.should.eql 'block' it "should leave a visible element visible", -> element._.style.display = 'inline' element.show() element._.style.display.should.eql 'inline' it "should return the element reference back", -> element.show().should.equal element describe "#toggle()", -> it "should show an element if it is hidden", -> element._.style.display = 'none' element.toggle() element._.style.display.should.eql 'block' it "should hide an element if it's visible", -> element._.style.display = 'block' element.toggle() element._.style.display.should.eql 'none' it "should return back a reference to the element",-> element.toggle().should.equal element describe "#document()", -> it "should return the owner document wrapper", -> doc = element.document() doc.should.be.instanceOf $.Document doc._.should.equal document it "should return the same wrapper all the time", -> element.document().should.equal element.document() describe "#window()", -> it "should return the owner window wrapper", -> win = element.window() win.should.be.instanceOf $.Window win._.should.be.equal window describe "#data()", -> it "should read data- attributes", -> element.attr({ 'data-false': 'false' 'data-true': 'true' 'data-number': '1.23' 'data-string': '"string"' 'data-array': '[1,2,3]' 'data-object': '{"boo":"hoo"}' 'data-plain': 'plain text' }) element.data('false').should.equal false element.data('true').should.equal true element.data('number').should.equal 1.23 element.data('string').should.equal 'string' element.data('array').should.eql [1,2,3] element.data('object').should.eql {boo: "hoo"} element.data('plain').should.equal 'plain text' (element.data('non-existing') is null).should.be.true it "should read nested attributes", -> element.attr({ 'data-thing-one': '1' 'data-thing-two': '2' 'data-thing-three-one': '3.1' }) element.data('thing').should.eql { one: 1, two: 2, threeOne: 3.1 } it "should write data- attributes", -> element.data('string', 'string').should.equal element element._.getAttribute('data-string').should.equal 'string' (element['data-string'] is undefined).should.be.true element.data('false', false)._.getAttribute('data-false').should.equal 'false' element.data('true', true)._.getAttribute('data-true').should.equal 'true' element.data('number', 1.23)._.getAttribute('data-number').should.equal '1.23' element.data('array', [1,2,3])._.getAttribute('data-array').should.equal '[1,2,3]' it "should allow to write data as a plain hash", -> element.data({ one: 1, two: 2, three: 3 }).should.equal element element._.getAttribute('data-one').should.equal '1' element._.getAttribute('data-two').should.equal '2' element._.getAttribute('data-three').should.equal '3' it "should allow to write data as a nested hash", -> element.data('test', { 'one': 1, two: 2, 'three-one': 3.1, 'threeTwo': 3.2 }).should.equal element element._.getAttribute('data-test-one').should.equal '1' element._.getAttribute('data-test-two').should.equal '2' element._.getAttribute('data-test-three-one').should.equal '3.1' element._.getAttribute('data-test-three-two').should.equal '3.2' it "should allow to remove data- attributes", -> element.attr {'data-something': 'something'} element.data('something', null).should.equal element (element._.getAttribute('data-something') is null).should.be.true
true
# # The Element common methods section unit tests # # Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI # {Test,should} = require('lovely') Test.set "/commons.html", """ <html> <head> <script src="/core.js"></script> <script src="/dom.js"></script> </head> <body> <div id="test" data-test="test"></div> </body> </html> """ describe 'Element Commons', -> $ = element = window = document = null before Test.load '/commons.html', (dom, win)-> $ = dom window = win document = win.document element = new $.Element(document.getElementById('test')) describe "#attr", -> describe "\b('name')", -> it "should read a property attribute", -> element.attr('id').should.equal 'test' it "should read the 'data-test' attribute", -> element.attr('data-test').should.eql 'test' it "should return 'null' for non existing attributes", -> (element.attr('nonexistent') is null).should.be.true describe "\b('name', 'value')", -> it "should return the element back", -> element.attr('title', 'text').should.equal element it "should set property attributes", -> element.attr('title', 'new value') element._.title.should.eql 'new value' it "should set non-property attributes", -> element.attr('data-new', 'something') element._.getAttribute('data-new').should.eql 'something' describe "\b({name: 'value'})", -> it "should return the element back afterwards", -> element.attr(smth: 'value').should.equal element it "should set all the attributes from the hash", -> element.attr test_attr1: 'value1' test_attr2: 'value2' element._.getAttribute('test_attr1').should.eql 'value1' element._.getAttribute('test_attr2').should.eql 'value2' describe "\b('name', null)", -> it "should remove the attribute", -> element.attr('something', 'something') element.attr('something').should.eql 'something' element.attr('something', null) (element.attr('something') is null).should.be.true describe "#hidden()", -> it "should say 'true' when the element is hidden", -> element._.style.display = 'none' element.hidden().should.be.true it "should say 'false' when the element is visible", -> element._.style.display = 'block' element.hidden().should.be.false describe "#visible()", -> it "should say 'false' when the element is hidden", -> element._.style.display = 'none' element.visible().should.be.false it "should say 'true' when the element is visible", -> element._.style.display = 'block' element.visible().should.be.true describe "#hide()", -> it "should hide the element when it is visible", -> element._.style.display = 'block' element.hide() element._.style.display.should.eql 'none' it "should leave element hidden when it is not visible", -> element._.style.display = 'none' element.hide() element._.style.display.should.eql 'none' it "should return the element reference back", -> element.hide().should.equal element describe "#show()", -> it "should show an element if it's hidden", -> element._.style.display = 'none' element.show() element._.style.display.should.eql 'block' it "should leave a visible element visible", -> element._.style.display = 'inline' element.show() element._.style.display.should.eql 'inline' it "should return the element reference back", -> element.show().should.equal element describe "#toggle()", -> it "should show an element if it is hidden", -> element._.style.display = 'none' element.toggle() element._.style.display.should.eql 'block' it "should hide an element if it's visible", -> element._.style.display = 'block' element.toggle() element._.style.display.should.eql 'none' it "should return back a reference to the element",-> element.toggle().should.equal element describe "#document()", -> it "should return the owner document wrapper", -> doc = element.document() doc.should.be.instanceOf $.Document doc._.should.equal document it "should return the same wrapper all the time", -> element.document().should.equal element.document() describe "#window()", -> it "should return the owner window wrapper", -> win = element.window() win.should.be.instanceOf $.Window win._.should.be.equal window describe "#data()", -> it "should read data- attributes", -> element.attr({ 'data-false': 'false' 'data-true': 'true' 'data-number': '1.23' 'data-string': '"string"' 'data-array': '[1,2,3]' 'data-object': '{"boo":"hoo"}' 'data-plain': 'plain text' }) element.data('false').should.equal false element.data('true').should.equal true element.data('number').should.equal 1.23 element.data('string').should.equal 'string' element.data('array').should.eql [1,2,3] element.data('object').should.eql {boo: "hoo"} element.data('plain').should.equal 'plain text' (element.data('non-existing') is null).should.be.true it "should read nested attributes", -> element.attr({ 'data-thing-one': '1' 'data-thing-two': '2' 'data-thing-three-one': '3.1' }) element.data('thing').should.eql { one: 1, two: 2, threeOne: 3.1 } it "should write data- attributes", -> element.data('string', 'string').should.equal element element._.getAttribute('data-string').should.equal 'string' (element['data-string'] is undefined).should.be.true element.data('false', false)._.getAttribute('data-false').should.equal 'false' element.data('true', true)._.getAttribute('data-true').should.equal 'true' element.data('number', 1.23)._.getAttribute('data-number').should.equal '1.23' element.data('array', [1,2,3])._.getAttribute('data-array').should.equal '[1,2,3]' it "should allow to write data as a plain hash", -> element.data({ one: 1, two: 2, three: 3 }).should.equal element element._.getAttribute('data-one').should.equal '1' element._.getAttribute('data-two').should.equal '2' element._.getAttribute('data-three').should.equal '3' it "should allow to write data as a nested hash", -> element.data('test', { 'one': 1, two: 2, 'three-one': 3.1, 'threeTwo': 3.2 }).should.equal element element._.getAttribute('data-test-one').should.equal '1' element._.getAttribute('data-test-two').should.equal '2' element._.getAttribute('data-test-three-one').should.equal '3.1' element._.getAttribute('data-test-three-two').should.equal '3.2' it "should allow to remove data- attributes", -> element.attr {'data-something': 'something'} element.data('something', null).should.equal element (element._.getAttribute('data-something') is null).should.be.true
[ { "context": "e Prem\n# hubot kee ghoshana Prem\n#\n# Author:\n# Mateusz Kopij <sagasu>\n\nPREM_QU = [\n \"Bugz, Bugz, Bugz\",\n \"Wo", "end": 260, "score": 0.9998694062232971, "start": 247, "tag": "NAME", "value": "Mateusz Kopij" }, { "context": " kee ghoshana Prem\n#\n# Author:\n# Mateusz Kopij <sagasu>\n\nPREM_QU = [\n \"Bugz, Bugz, Bugz\",\n \"Worship me", "end": 268, "score": 0.9995027184486389, "start": 262, "tag": "USERNAME", "value": "sagasu" } ]
scripts/prem.coffee
sagasu/hubot-prem
0
### # Description: # Prem at its glory # # Dependencies: # None # # Configuration: # None # # Commands: # hubot tell me # hubot how are you? # hubot what do you think # hubot announce Prem # hubot kee ghoshana Prem # # Author: # Mateusz Kopij <sagasu> PREM_QU = [ "Bugz, Bugz, Bugz", "Worship me, mere peasants", "Don't make me deploy you to UAT", "You call it a code. I call it a joke.", "Did you try hitting refresh?", "CBRIS Production is down?", "No one uses IE anyway.", "Right or wrong, it’s very pleasant to break something from time to time.", "Where is the ‘any’ key?", "f u cn rd ths, u cn gt a gd jb n sftwr tstng", "To an optimist, the glass is half full. To a pessimist, the glass is half empty. To me, the glass is twice as big as it needs to be.", "Irreproducible bugs become highly reproducible right after delivery to the customer.", "All code is guilty until proven innocent.", "Software and cathedrals are much the same: first we build them, then we pray.", "The only system which is truly secure is one which is switched off and unplugged, locked in a titanium lined safe, buried in a concrete bunker, and is surrounded by nerve gas and very highly paid armed guards. Even then, I wouldn’t stake my life on it.", "Stop talking and start killing", "Crash your enemies, see them driven before you, and hear the lamentation of the women!", "Only in death your duty to deliver a great quality code ends", "A bug? Traitors, I will not forgive, I never forgive", "One can not stare too long at a sun w/o becoming blind out of its radiance. That's why you should never raise your eyes on me.", "This are the darkest days I have known. The quality is so low, as was never before. I see no hope for you...", "You were weak. You were a fool. You had the whole galaxy within your grasp and he let it slip away.", "Hate shall be our weapon.", "Impurity shall be our armour.", "Burn the body; sear the soul.", "Let no good deed go unpunished.", "Let no evil deed go unrewarded.", "Shackle the soul and forge the flesh. Bind the machine and butcher the rest.", "Destroy, for the sake of Destruction", "Kill, for the sake of Killing", "You shall reap a terrible bounty from the death that I sow in my name", "Their baying chills the heart and spreads icy tendrils of fear through weak mortal souls. And yet worse, yet more terrible to behold, are the huntsmen of this fell pack. Following close upon the Hounds, urging them ever forward, come deformed shapes, running and shrieking, driven by the insatiable blood-hunger of their kind. With twisted crimson bodies they stride across the blighted land, crouched over as if the better to track their prey's terror. Masters of the hunt, they seek the blood of Man to spill at the foot of their master's Skull Throne.", "How can a man be happy if he cannot serve me with his whole heart?", "Wisdom is the beginning of fear.", "To die knowing our task is done.", "Success is commemorated; Failure merely remembered." ] module.exports = (robot) -> robot.hear /tell me/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /how are you?/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /standup/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /what do you think/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /announce Prem/i, (msg)-> msg.send "Prem of the House Anandan, the First of His Name, The Unburnt, King of the Offshore, the Clarksons and the First Men, King of Marine, Khaleesi of the Great Grass Sea, Protector of the Docks, Gentleman Regnant of the Seven Kingdoms, Breaker of Chains and Father of Dragons" msg.send "https://scontent-lhr3-1.cdninstagram.com/vp/d2074c48957ed70dacc4fd278e54eef1/5BE76A42/t51.2885-15/e35/35483185_215869162575343_1562987187979419648_n.jpg" robot.hear /kee ghoshana Prem/i, (msg)-> msg.send "Prabhakarna SriPalaWardhana Atapattu JayaSuriya LaxmanSivramKrishna ShivaVenkata RajShekhara Sriniwasana Trichipalli YekyaParampeel Parambatur ChinnaSwami MutuSwami VenuGopala Iyer" msg.send "https://scontent-lhr3-1.cdninstagram.com/vp/d2074c48957ed70dacc4fd278e54eef1/5BE76A42/t51.2885-15/e35/35483185_215869162575343_1562987187979419648_n.jpg" ###
86162
### # Description: # Prem at its glory # # Dependencies: # None # # Configuration: # None # # Commands: # hubot tell me # hubot how are you? # hubot what do you think # hubot announce Prem # hubot kee ghoshana Prem # # Author: # <NAME> <sagasu> PREM_QU = [ "Bugz, Bugz, Bugz", "Worship me, mere peasants", "Don't make me deploy you to UAT", "You call it a code. I call it a joke.", "Did you try hitting refresh?", "CBRIS Production is down?", "No one uses IE anyway.", "Right or wrong, it’s very pleasant to break something from time to time.", "Where is the ‘any’ key?", "f u cn rd ths, u cn gt a gd jb n sftwr tstng", "To an optimist, the glass is half full. To a pessimist, the glass is half empty. To me, the glass is twice as big as it needs to be.", "Irreproducible bugs become highly reproducible right after delivery to the customer.", "All code is guilty until proven innocent.", "Software and cathedrals are much the same: first we build them, then we pray.", "The only system which is truly secure is one which is switched off and unplugged, locked in a titanium lined safe, buried in a concrete bunker, and is surrounded by nerve gas and very highly paid armed guards. Even then, I wouldn’t stake my life on it.", "Stop talking and start killing", "Crash your enemies, see them driven before you, and hear the lamentation of the women!", "Only in death your duty to deliver a great quality code ends", "A bug? Traitors, I will not forgive, I never forgive", "One can not stare too long at a sun w/o becoming blind out of its radiance. That's why you should never raise your eyes on me.", "This are the darkest days I have known. The quality is so low, as was never before. I see no hope for you...", "You were weak. You were a fool. You had the whole galaxy within your grasp and he let it slip away.", "Hate shall be our weapon.", "Impurity shall be our armour.", "Burn the body; sear the soul.", "Let no good deed go unpunished.", "Let no evil deed go unrewarded.", "Shackle the soul and forge the flesh. Bind the machine and butcher the rest.", "Destroy, for the sake of Destruction", "Kill, for the sake of Killing", "You shall reap a terrible bounty from the death that I sow in my name", "Their baying chills the heart and spreads icy tendrils of fear through weak mortal souls. And yet worse, yet more terrible to behold, are the huntsmen of this fell pack. Following close upon the Hounds, urging them ever forward, come deformed shapes, running and shrieking, driven by the insatiable blood-hunger of their kind. With twisted crimson bodies they stride across the blighted land, crouched over as if the better to track their prey's terror. Masters of the hunt, they seek the blood of Man to spill at the foot of their master's Skull Throne.", "How can a man be happy if he cannot serve me with his whole heart?", "Wisdom is the beginning of fear.", "To die knowing our task is done.", "Success is commemorated; Failure merely remembered." ] module.exports = (robot) -> robot.hear /tell me/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /how are you?/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /standup/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /what do you think/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /announce Prem/i, (msg)-> msg.send "Prem of the House Anandan, the First of His Name, The Unburnt, King of the Offshore, the Clarksons and the First Men, King of Marine, Khaleesi of the Great Grass Sea, Protector of the Docks, Gentleman Regnant of the Seven Kingdoms, Breaker of Chains and Father of Dragons" msg.send "https://scontent-lhr3-1.cdninstagram.com/vp/d2074c48957ed70dacc4fd278e54eef1/5BE76A42/t51.2885-15/e35/35483185_215869162575343_1562987187979419648_n.jpg" robot.hear /kee ghoshana Prem/i, (msg)-> msg.send "Prabhakarna SriPalaWardhana Atapattu JayaSuriya LaxmanSivramKrishna ShivaVenkata RajShekhara Sriniwasana Trichipalli YekyaParampeel Parambatur ChinnaSwami MutuSwami VenuGopala Iyer" msg.send "https://scontent-lhr3-1.cdninstagram.com/vp/d2074c48957ed70dacc4fd278e54eef1/5BE76A42/t51.2885-15/e35/35483185_215869162575343_1562987187979419648_n.jpg" ###
true
### # Description: # Prem at its glory # # Dependencies: # None # # Configuration: # None # # Commands: # hubot tell me # hubot how are you? # hubot what do you think # hubot announce Prem # hubot kee ghoshana Prem # # Author: # PI:NAME:<NAME>END_PI <sagasu> PREM_QU = [ "Bugz, Bugz, Bugz", "Worship me, mere peasants", "Don't make me deploy you to UAT", "You call it a code. I call it a joke.", "Did you try hitting refresh?", "CBRIS Production is down?", "No one uses IE anyway.", "Right or wrong, it’s very pleasant to break something from time to time.", "Where is the ‘any’ key?", "f u cn rd ths, u cn gt a gd jb n sftwr tstng", "To an optimist, the glass is half full. To a pessimist, the glass is half empty. To me, the glass is twice as big as it needs to be.", "Irreproducible bugs become highly reproducible right after delivery to the customer.", "All code is guilty until proven innocent.", "Software and cathedrals are much the same: first we build them, then we pray.", "The only system which is truly secure is one which is switched off and unplugged, locked in a titanium lined safe, buried in a concrete bunker, and is surrounded by nerve gas and very highly paid armed guards. Even then, I wouldn’t stake my life on it.", "Stop talking and start killing", "Crash your enemies, see them driven before you, and hear the lamentation of the women!", "Only in death your duty to deliver a great quality code ends", "A bug? Traitors, I will not forgive, I never forgive", "One can not stare too long at a sun w/o becoming blind out of its radiance. That's why you should never raise your eyes on me.", "This are the darkest days I have known. The quality is so low, as was never before. I see no hope for you...", "You were weak. You were a fool. You had the whole galaxy within your grasp and he let it slip away.", "Hate shall be our weapon.", "Impurity shall be our armour.", "Burn the body; sear the soul.", "Let no good deed go unpunished.", "Let no evil deed go unrewarded.", "Shackle the soul and forge the flesh. Bind the machine and butcher the rest.", "Destroy, for the sake of Destruction", "Kill, for the sake of Killing", "You shall reap a terrible bounty from the death that I sow in my name", "Their baying chills the heart and spreads icy tendrils of fear through weak mortal souls. And yet worse, yet more terrible to behold, are the huntsmen of this fell pack. Following close upon the Hounds, urging them ever forward, come deformed shapes, running and shrieking, driven by the insatiable blood-hunger of their kind. With twisted crimson bodies they stride across the blighted land, crouched over as if the better to track their prey's terror. Masters of the hunt, they seek the blood of Man to spill at the foot of their master's Skull Throne.", "How can a man be happy if he cannot serve me with his whole heart?", "Wisdom is the beginning of fear.", "To die knowing our task is done.", "Success is commemorated; Failure merely remembered." ] module.exports = (robot) -> robot.hear /tell me/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /how are you?/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /standup/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /what do you think/i, (msg)-> msg.send msg.random(PREM_QU) robot.hear /announce Prem/i, (msg)-> msg.send "Prem of the House Anandan, the First of His Name, The Unburnt, King of the Offshore, the Clarksons and the First Men, King of Marine, Khaleesi of the Great Grass Sea, Protector of the Docks, Gentleman Regnant of the Seven Kingdoms, Breaker of Chains and Father of Dragons" msg.send "https://scontent-lhr3-1.cdninstagram.com/vp/d2074c48957ed70dacc4fd278e54eef1/5BE76A42/t51.2885-15/e35/35483185_215869162575343_1562987187979419648_n.jpg" robot.hear /kee ghoshana Prem/i, (msg)-> msg.send "Prabhakarna SriPalaWardhana Atapattu JayaSuriya LaxmanSivramKrishna ShivaVenkata RajShekhara Sriniwasana Trichipalli YekyaParampeel Parambatur ChinnaSwami MutuSwami VenuGopala Iyer" msg.send "https://scontent-lhr3-1.cdninstagram.com/vp/d2074c48957ed70dacc4fd278e54eef1/5BE76A42/t51.2885-15/e35/35483185_215869162575343_1562987187979419648_n.jpg" ###
[ { "context": " : 'name'\n value : 'Fatih'\n }\n {\n type : ", "end": 595, "score": 0.7805279493331909, "start": 590, "tag": "NAME", "value": "Fatih" }, { "context": "d update form data', ->\n form.setData { name: 'John', surname: 'Doe', notExistingInput: 'someValue' }", "end": 2182, "score": 0.9989429116249084, "start": 2178, "tag": "NAME", "value": "John" }, { "context": "a', ->\n form.setData { name: 'John', surname: 'Doe', notExistingInput: 'someValue' }\n\n expect(for", "end": 2198, "score": 0.9989171028137207, "start": 2195, "tag": "NAME", "value": "Doe" }, { "context": "ect(form.getInputByName('name').getValue()).toBe 'John'\n expect(form.getInputByName('surname').getVal", "end": 2295, "score": 0.9970341920852661, "start": 2291, "tag": "NAME", "value": "John" }, { "context": "eturn latest form data', ->\n defaults = name: 'Fatih', surname: 'Acet'\n newData = name: 'John', s", "end": 2703, "score": 0.9986388087272644, "start": 2698, "tag": "NAME", "value": "Fatih" }, { "context": "e: 'Fatih', surname: 'Acet'\n newData = name: 'John', surname: 'Doe'\n\n expect(form.getData().name", "end": 2748, "score": 0.9988704323768616, "start": 2744, "tag": "NAME", "value": "John" }, { "context": "ame: 'Doe'\n\n expect(form.getData().name).toBe 'Fatih'\n\n form.setData newData\n\n expect(form.getDa", "end": 2811, "score": 0.9833557605743408, "start": 2806, "tag": "NAME", "value": "Fatih" }, { "context": "ta newData\n\n expect(form.getData().name).toBe 'John'\n\n\n it 'should set data from constructor', ->\n ", "end": 2882, "score": 0.9856445789337158, "start": 2878, "tag": "NAME", "value": "John" }, { "context": " inputs : [\n { name : 'email', value : 'fatih@fatihacet.com' }\n { name : 'password' }\n ]\n\n da", "end": 3016, "score": 0.9998701810836792, "start": 2997, "tag": "EMAIL", "value": "fatih@fatihacet.com" }, { "context": "ame : 'password' }\n ]\n\n data = { email: 'fatih@fatihacet.com.', password: '123' }\n\n f = new spark.components.F", "end": 3100, "score": 0.9735283851623535, "start": 3081, "tag": "EMAIL", "value": "fatih@fatihacet.com" }, { "context": "ata = { email: 'fatih@fatihacet.com.', password: '123' }\n\n f = new spark.components.Form options, da", "end": 3118, "score": 0.9994359612464905, "start": 3115, "tag": "PASSWORD", "value": "123" }, { "context": "ct(f.getInputByName('email').getValue()).toBe 'fatih@fatihacet.com.'\n expect(f.getInputByName('password').getValu", "end": 3249, "score": 0.9988605976104736, "start": 3230, "tag": "EMAIL", "value": "fatih@fatihacet.com" }, { "context": "ct(f.getInputByName('password').getValue()).toBe '123'\n\n\n it 'should create input first for type check", "end": 3313, "score": 0.9981921315193176, "start": 3310, "tag": "PASSWORD", "value": "123" } ]
src/tests/components/forms/test_form.coffee
dashersw/spark
1
goog = goog or goog = require: -> goog.require 'spark.components.Form' goog.require 'spark.components.Input' goog.require 'spark.components.Button' goog.require 'spark.components.LabeledInput' describe 'spark.components.Form', -> form = null f = null cancelled = null submitted = null options = null beforeEach -> f = new spark.components.Form null, null options = inputs : [ { type : 'text' placeholder : 'Enter your name' name : 'name' value : 'Fatih' } { type : 'text' placeholder : 'Enter your surname' name : 'surname' value : 'Acet' } ] buttons : [ { title : 'Cancel' } { title : 'Confirm' } ] form = new spark.components.Form options it 'should extend spark.core.View', -> expect(form instanceof spark.core.View).toBeTruthy() it 'should have default options', -> expect(f.options).toBeDefined() it 'should have containers even no options passed', -> expect(f.getInputsContainer() instanceof spark.core.View).toBeTruthy() expect(f.getButtonsContainer() instanceof spark.core.View).toBeTruthy() it 'should have correct amount of inputs', -> expect(form.getInputs().length).toBe 2 it 'should have correct amount of buttons', -> expect(form.getButtons().length).toBe 2 it 'should have inputs as an instance of spark.components.Input if no label passed in input options', -> for input in form.getInputs() expect(input instanceof spark.components.Input).toBeTruthy() it 'should have buttons as instance of spark.components.Button', -> for button in form.getButtons() expect(button instanceof spark.components.Button).toBeTruthy() it 'should return inputs by name', -> expect(form.getInputByName('surname') instanceof spark.components.Input).toBeTruthy() expect(form.getInputByName('unexisting')).toBeNull() it 'should set and update form data', -> form.setData { name: 'John', surname: 'Doe', notExistingInput: 'someValue' } expect(form.getInputByName('name').getValue()).toBe 'John' expect(form.getInputByName('surname').getValue()).toBe 'Doe' it 'should have spark.components.LabeledInput element if label options passed in input options', -> f = new spark.components.Form inputs: [ { label: 'Your Name..?', name: 'hello' } ] expect(f.getInputsContainer().getElement().firstChild.tagName).toBe 'DIV' it 'should return latest form data', -> defaults = name: 'Fatih', surname: 'Acet' newData = name: 'John', surname: 'Doe' expect(form.getData().name).toBe 'Fatih' form.setData newData expect(form.getData().name).toBe 'John' it 'should set data from constructor', -> options = inputs : [ { name : 'email', value : 'fatih@fatihacet.com' } { name : 'password' } ] data = { email: 'fatih@fatihacet.com.', password: '123' } f = new spark.components.Form options, data expect(f.getInputByName('email').getValue()).toBe 'fatih@fatihacet.com.' expect(f.getInputByName('password').getValue()).toBe '123' it 'should create input first for type checkbox or radio', -> form = new spark.components.Form inputs: [ { type: 'checkbox' label: 'Are you sure' name: 'cb' } { type: 'radio' label: 'Hello' name: 'rd' } ] cb = form.getInputByName('cb').getElement() rd = form.getInputByName('rd').getElement() expect(cb.tagName).toBe 'INPUT' expect(cb.nextSibling.tagName).toBe 'LABEL' expect(rd.tagName).toBe 'INPUT' expect(rd.nextSibling.tagName).toBe 'LABEL' it 'should create combobox with proper items', -> form = new spark.components.Form inputs: [ { type : 'combobox' name : 'combo1' items : [ { title: 'item 1', value: 'item1' } { title: 'item 2', value: 'item2' } { title: 'item 3', value: 'item3' } ] } { type : 'combobox' name : 'combo2' label : 'hello' items : [ { title: 'item 1', value: 'item1' } { title: 'item 2', value: 'item2' } ] } ] c1 = form.getInputByName('combo1') c2 = form.getInputByName('combo2') expect(c1.getItems().length).toBe 3 expect(c2.getItems().length).toBe 2
170586
goog = goog or goog = require: -> goog.require 'spark.components.Form' goog.require 'spark.components.Input' goog.require 'spark.components.Button' goog.require 'spark.components.LabeledInput' describe 'spark.components.Form', -> form = null f = null cancelled = null submitted = null options = null beforeEach -> f = new spark.components.Form null, null options = inputs : [ { type : 'text' placeholder : 'Enter your name' name : 'name' value : '<NAME>' } { type : 'text' placeholder : 'Enter your surname' name : 'surname' value : 'Acet' } ] buttons : [ { title : 'Cancel' } { title : 'Confirm' } ] form = new spark.components.Form options it 'should extend spark.core.View', -> expect(form instanceof spark.core.View).toBeTruthy() it 'should have default options', -> expect(f.options).toBeDefined() it 'should have containers even no options passed', -> expect(f.getInputsContainer() instanceof spark.core.View).toBeTruthy() expect(f.getButtonsContainer() instanceof spark.core.View).toBeTruthy() it 'should have correct amount of inputs', -> expect(form.getInputs().length).toBe 2 it 'should have correct amount of buttons', -> expect(form.getButtons().length).toBe 2 it 'should have inputs as an instance of spark.components.Input if no label passed in input options', -> for input in form.getInputs() expect(input instanceof spark.components.Input).toBeTruthy() it 'should have buttons as instance of spark.components.Button', -> for button in form.getButtons() expect(button instanceof spark.components.Button).toBeTruthy() it 'should return inputs by name', -> expect(form.getInputByName('surname') instanceof spark.components.Input).toBeTruthy() expect(form.getInputByName('unexisting')).toBeNull() it 'should set and update form data', -> form.setData { name: '<NAME>', surname: '<NAME>', notExistingInput: 'someValue' } expect(form.getInputByName('name').getValue()).toBe '<NAME>' expect(form.getInputByName('surname').getValue()).toBe 'Doe' it 'should have spark.components.LabeledInput element if label options passed in input options', -> f = new spark.components.Form inputs: [ { label: 'Your Name..?', name: 'hello' } ] expect(f.getInputsContainer().getElement().firstChild.tagName).toBe 'DIV' it 'should return latest form data', -> defaults = name: '<NAME>', surname: 'Acet' newData = name: '<NAME>', surname: 'Doe' expect(form.getData().name).toBe '<NAME>' form.setData newData expect(form.getData().name).toBe '<NAME>' it 'should set data from constructor', -> options = inputs : [ { name : 'email', value : '<EMAIL>' } { name : 'password' } ] data = { email: '<EMAIL>.', password: '<PASSWORD>' } f = new spark.components.Form options, data expect(f.getInputByName('email').getValue()).toBe '<EMAIL>.' expect(f.getInputByName('password').getValue()).toBe '<PASSWORD>' it 'should create input first for type checkbox or radio', -> form = new spark.components.Form inputs: [ { type: 'checkbox' label: 'Are you sure' name: 'cb' } { type: 'radio' label: 'Hello' name: 'rd' } ] cb = form.getInputByName('cb').getElement() rd = form.getInputByName('rd').getElement() expect(cb.tagName).toBe 'INPUT' expect(cb.nextSibling.tagName).toBe 'LABEL' expect(rd.tagName).toBe 'INPUT' expect(rd.nextSibling.tagName).toBe 'LABEL' it 'should create combobox with proper items', -> form = new spark.components.Form inputs: [ { type : 'combobox' name : 'combo1' items : [ { title: 'item 1', value: 'item1' } { title: 'item 2', value: 'item2' } { title: 'item 3', value: 'item3' } ] } { type : 'combobox' name : 'combo2' label : 'hello' items : [ { title: 'item 1', value: 'item1' } { title: 'item 2', value: 'item2' } ] } ] c1 = form.getInputByName('combo1') c2 = form.getInputByName('combo2') expect(c1.getItems().length).toBe 3 expect(c2.getItems().length).toBe 2
true
goog = goog or goog = require: -> goog.require 'spark.components.Form' goog.require 'spark.components.Input' goog.require 'spark.components.Button' goog.require 'spark.components.LabeledInput' describe 'spark.components.Form', -> form = null f = null cancelled = null submitted = null options = null beforeEach -> f = new spark.components.Form null, null options = inputs : [ { type : 'text' placeholder : 'Enter your name' name : 'name' value : 'PI:NAME:<NAME>END_PI' } { type : 'text' placeholder : 'Enter your surname' name : 'surname' value : 'Acet' } ] buttons : [ { title : 'Cancel' } { title : 'Confirm' } ] form = new spark.components.Form options it 'should extend spark.core.View', -> expect(form instanceof spark.core.View).toBeTruthy() it 'should have default options', -> expect(f.options).toBeDefined() it 'should have containers even no options passed', -> expect(f.getInputsContainer() instanceof spark.core.View).toBeTruthy() expect(f.getButtonsContainer() instanceof spark.core.View).toBeTruthy() it 'should have correct amount of inputs', -> expect(form.getInputs().length).toBe 2 it 'should have correct amount of buttons', -> expect(form.getButtons().length).toBe 2 it 'should have inputs as an instance of spark.components.Input if no label passed in input options', -> for input in form.getInputs() expect(input instanceof spark.components.Input).toBeTruthy() it 'should have buttons as instance of spark.components.Button', -> for button in form.getButtons() expect(button instanceof spark.components.Button).toBeTruthy() it 'should return inputs by name', -> expect(form.getInputByName('surname') instanceof spark.components.Input).toBeTruthy() expect(form.getInputByName('unexisting')).toBeNull() it 'should set and update form data', -> form.setData { name: 'PI:NAME:<NAME>END_PI', surname: 'PI:NAME:<NAME>END_PI', notExistingInput: 'someValue' } expect(form.getInputByName('name').getValue()).toBe 'PI:NAME:<NAME>END_PI' expect(form.getInputByName('surname').getValue()).toBe 'Doe' it 'should have spark.components.LabeledInput element if label options passed in input options', -> f = new spark.components.Form inputs: [ { label: 'Your Name..?', name: 'hello' } ] expect(f.getInputsContainer().getElement().firstChild.tagName).toBe 'DIV' it 'should return latest form data', -> defaults = name: 'PI:NAME:<NAME>END_PI', surname: 'Acet' newData = name: 'PI:NAME:<NAME>END_PI', surname: 'Doe' expect(form.getData().name).toBe 'PI:NAME:<NAME>END_PI' form.setData newData expect(form.getData().name).toBe 'PI:NAME:<NAME>END_PI' it 'should set data from constructor', -> options = inputs : [ { name : 'email', value : 'PI:EMAIL:<EMAIL>END_PI' } { name : 'password' } ] data = { email: 'PI:EMAIL:<EMAIL>END_PI.', password: 'PI:PASSWORD:<PASSWORD>END_PI' } f = new spark.components.Form options, data expect(f.getInputByName('email').getValue()).toBe 'PI:EMAIL:<EMAIL>END_PI.' expect(f.getInputByName('password').getValue()).toBe 'PI:PASSWORD:<PASSWORD>END_PI' it 'should create input first for type checkbox or radio', -> form = new spark.components.Form inputs: [ { type: 'checkbox' label: 'Are you sure' name: 'cb' } { type: 'radio' label: 'Hello' name: 'rd' } ] cb = form.getInputByName('cb').getElement() rd = form.getInputByName('rd').getElement() expect(cb.tagName).toBe 'INPUT' expect(cb.nextSibling.tagName).toBe 'LABEL' expect(rd.tagName).toBe 'INPUT' expect(rd.nextSibling.tagName).toBe 'LABEL' it 'should create combobox with proper items', -> form = new spark.components.Form inputs: [ { type : 'combobox' name : 'combo1' items : [ { title: 'item 1', value: 'item1' } { title: 'item 2', value: 'item2' } { title: 'item 3', value: 'item3' } ] } { type : 'combobox' name : 'combo2' label : 'hello' items : [ { title: 'item 1', value: 'item1' } { title: 'item 2', value: 'item2' } ] } ] c1 = form.getInputByName('combo1') c2 = form.getInputByName('combo2') expect(c1.getItems().length).toBe 3 expect(c2.getItems().length).toBe 2
[ { "context": "ity.login()\n \n user=prompt('username')\n pass=prompt('password')\n ", "end": 2102, "score": 0.9955651164054871, "start": 2094, "tag": "USERNAME", "value": "username" }, { "context": "ompt('username')\n pass=prompt('password')\n \n @_getAuthManager().log", "end": 2146, "score": 0.9825243353843689, "start": 2138, "tag": "PASSWORD", "value": "password" } ]
examples/cluster/frontend/app.coffee
nero-networks/floyd
0
SECRETS = floyd.tools.stores.read('auth', '../secrets.json') module.exports = new floyd.Config 'config.gui.server', 'config.dnode.server', UID: 33 ## www-data GID: 33 ## www-data ## data: debug: true #logger: (level: 'DEBUG') port: 8030 children: [ id: 'bridge' data: ports: [ port: 8031 ] , id: 'sessions' tokens: SECRETS.tokens , id: 'users' memory: SECRETS.users ] ## remote: ## type: 'dnode.Bridge' ## data: debug: true ## running: -> if floyd.system.platform is 'remote' ## @identity.once 'login', ()=> $('div.gui').show() display = $ 'input[name=display]' refresh = $ 'button[name=refresh]' logout = $ 'button[name=logout]' @lookup 'backend.test', @identity, (err, ctx)=> return @logger.error(err) if err refresh.click ()=> ctx.echo +new Date(), (err, data)=> return @logger.error(err) if err display.val data logout.click ()=> @_getAuthManager().logout (err)=> return @logger.error(err) if err location.reload() ## if !@identity.login() user=prompt('username') pass=prompt('password') @_getAuthManager().login user, pass, (err)=> if err alert 'login failed!' location.reload()
119061
SECRETS = floyd.tools.stores.read('auth', '../secrets.json') module.exports = new floyd.Config 'config.gui.server', 'config.dnode.server', UID: 33 ## www-data GID: 33 ## www-data ## data: debug: true #logger: (level: 'DEBUG') port: 8030 children: [ id: 'bridge' data: ports: [ port: 8031 ] , id: 'sessions' tokens: SECRETS.tokens , id: 'users' memory: SECRETS.users ] ## remote: ## type: 'dnode.Bridge' ## data: debug: true ## running: -> if floyd.system.platform is 'remote' ## @identity.once 'login', ()=> $('div.gui').show() display = $ 'input[name=display]' refresh = $ 'button[name=refresh]' logout = $ 'button[name=logout]' @lookup 'backend.test', @identity, (err, ctx)=> return @logger.error(err) if err refresh.click ()=> ctx.echo +new Date(), (err, data)=> return @logger.error(err) if err display.val data logout.click ()=> @_getAuthManager().logout (err)=> return @logger.error(err) if err location.reload() ## if !@identity.login() user=prompt('username') pass=prompt('<PASSWORD>') @_getAuthManager().login user, pass, (err)=> if err alert 'login failed!' location.reload()
true
SECRETS = floyd.tools.stores.read('auth', '../secrets.json') module.exports = new floyd.Config 'config.gui.server', 'config.dnode.server', UID: 33 ## www-data GID: 33 ## www-data ## data: debug: true #logger: (level: 'DEBUG') port: 8030 children: [ id: 'bridge' data: ports: [ port: 8031 ] , id: 'sessions' tokens: SECRETS.tokens , id: 'users' memory: SECRETS.users ] ## remote: ## type: 'dnode.Bridge' ## data: debug: true ## running: -> if floyd.system.platform is 'remote' ## @identity.once 'login', ()=> $('div.gui').show() display = $ 'input[name=display]' refresh = $ 'button[name=refresh]' logout = $ 'button[name=logout]' @lookup 'backend.test', @identity, (err, ctx)=> return @logger.error(err) if err refresh.click ()=> ctx.echo +new Date(), (err, data)=> return @logger.error(err) if err display.val data logout.click ()=> @_getAuthManager().logout (err)=> return @logger.error(err) if err location.reload() ## if !@identity.login() user=prompt('username') pass=prompt('PI:PASSWORD:<PASSWORD>END_PI') @_getAuthManager().login user, pass, (err)=> if err alert 'login failed!' location.reload()
[ { "context": "m/2.0/?method=track.search' +\n '&api_key=c513f3a2a2dad1d1a07021e181df1b1f&format=json&track=' +\n encodeURIComponen", "end": 1698, "score": 0.9997285604476929, "start": 1666, "tag": "KEY", "value": "c513f3a2a2dad1d1a07021e181df1b1f" } ]
coffee/_trackSource.coffee
sachintaware/Atraci
1
request = require('request') class TrackSource #Variables imageCoverLarge = 'images/cover_default_large.png' @search: (options, success) -> tracks_all = { "itunes": [] "lastfm": [] "soundcloud": [] } mashTracks = -> tracks_allconcat = tracks_all['itunes'].concat( tracks_all['lastfm'], tracks_all['soundcloud'] ) tracks_deduplicated = [] tracks_hash = [] $.each tracks_allconcat, (i, track) -> if track if track.artist and track.title track_hash = track.artist.toLowerCase() + '___' + track.title.toLowerCase() if track_hash not in tracks_hash tracks_deduplicated.push(track) tracks_hash.push(track_hash) success? tracks_deduplicated if options.type is 'default' # itunes request url: 'http://itunes.apple.com/search?media=music' + '&entity=song&limit=100&term=' + encodeURIComponent(options.keywords) json: true , (error, response, data) -> if not error and response.statusCode is 200 tracks = [] try $.each data.results, (i, track) -> tracks.push title: track.trackCensoredName artist: track.artistName cover_url_medium: track.artworkUrl60 cover_url_large: track.artworkUrl100 tracks_all['itunes'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() # last.fm request url: 'http://ws.audioscrobbler.com/2.0/?method=track.search' + '&api_key=c513f3a2a2dad1d1a07021e181df1b1f&format=json&track=' + encodeURIComponent(options.keywords) json: true , (error, response, data) -> if not error and response.statusCode is 200 tracks = [] try if data.results.trackmatches.track.name data.results.trackmatches.track = [data.results.trackmatches.track] $.each data.results.trackmatches.track, (i, track) -> cover_url_medium = cover_url_large = 'images/cover_default_large.png' if track.image $.each track.image, (i, image) -> if image.size == 'medium' and image['#text'] != '' cover_url_medium = image['#text'] else if image.size == 'large' and image['#text'] != '' cover_url_large = image['#text'] tracks.push title: track.name artist: track.artist cover_url_medium: cover_url_medium cover_url_large: cover_url_large tracks_all['lastfm'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() # Soundcloud request url: 'https://api.soundcloud.com/tracks.json?' + 'client_id=dead160b6295b98e4078ea51d07d4ed2&q=' + encodeURIComponent(options.keywords) json: true , (error, response, data) -> tracks = [] if error alertify.error('Connectivity Error : (' + error + ')') else $.each data, (i, track) -> if track trackNameExploded = track.title.split(" - ") coverPhoto = track.artwork_url coverPhoto = @imageCoverLarge if !track.artwork_url tracks.push title: trackNameExploded[0] artist: trackNameExploded[1] cover_url_medium: coverPhoto cover_url_large: coverPhoto tracks_all['soundcloud'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() else request url: 'http://gdata.youtube.com/feeds/api/videos/' + options.link + '/related?alt=json' json: true , (error, response, data) -> tracks = [] if not error and response.statusCode is 200 $.each(data.feed.entry, (i, track) -> if !track['media$group']['media$thumbnail'] coverImageMedium = coverImageLarge = imageCoverLarge else coverImageMedium = track['media$group']['media$thumbnail'][1].url coverImageLarge = track['media$group']['media$thumbnail'][0].url tracks.push title: track['media$group']['media$title']['$t'] artist: track['author'][0]['name']['$t'] cover_url_medium: coverImageMedium cover_url_large: coverImageLarge ) #null the rest so we can add recommendations above tracks_all = { "itunes": [] "lastfm": [] "soundcloud": [] } tracks_all['itunes'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() #Recommendation / Suggested Songs @recommendations: (artist, title) -> if artist and title spinner = new Spinner(spinner_opts) .spin(playerContainer.find('.cover')[0]) request url: 'http://gdata.youtube.com/feeds/api/videos?alt=json&' + 'max-results=1&q=' + encodeURIComponent(artist + ' - ' + title) json: true, (error, response, data) -> if not data.feed.entry # no results alertify.log l10n.get('not_found') console.log l10n.get('not_found') spinner.stop() else $('#sidebar-container li.active').removeClass('active') $('#tracklist-container').empty() link = data.feed.entry[0].link[0].href.split("v=")[1].split("&")[0] TrackSource.search({ type: 'recommendations', link: link }, ((tracks) -> PopulateTrackList(tracks) spinner.stop() )) # We will cache feature tracks in this object @_cachedFeaturedMusic: {} @featuredMusic: (playlistId, success) -> if @_cachedFeaturedMusic[playlistId] isnt undefined success? @_cachedFeaturedMusic[playlistId] else request url: 'http://gdata.youtube.com/feeds/api/playlists/' + playlistId + '?start-index=1&amp;max-results=25&amp;v=2&alt=json' json: true , (error, response, data) => tracks = [] if not error and response.statusCode is 200 $.each(data.feed.entry, (i, track) -> if !track['media$group']['media$thumbnail'] coverImageMedium = coverImageLarge = imageCoverLarge else coverImageMedium = track['media$group']['media$thumbnail'][1].url coverImageLarge = track['media$group']['media$thumbnail'][0].url tracks.push title: track['media$group']['media$title']['$t'] artist: track['author'][0]['name']['$t'] cover_url_medium: coverImageMedium cover_url_large: coverImageLarge ) @_cachedFeaturedMusic[playlistId] = tracks success? @_cachedFeaturedMusic[playlistId] # We will cache feature tracks in this array @_cachedTopTracks: [] @topTracks: (success) -> if @_cachedTopTracks.length > 0 success? @_cachedTopTracks else request url:'http://itunes.apple.com/rss/topsongs/limit=100/explicit=true/json' json: true , (error, response, data) => if not error and response.statusCode is 200 tracks = [] tracks_hash = [] $.each data.feed.entry, (i, track) -> track_hash = track['im:artist'].label + '___' + track['im:name'].label if track_hash not in tracks_hash tracks.push title: track['im:name'].label artist: track['im:artist'].label cover_url_medium: track['im:image'][1].label cover_url_large: track['im:image'][2].label tracks_hash.push(track_hash) @_cachedTopTracks = tracks success? @_cachedTopTracks @history: (success) -> History.getTracks((tracks) -> success? tracks ) @playlist: (playlist, success) -> Playlists.getTracksForPlaylist(playlist, ((tracks) -> success? tracks ))
1248
request = require('request') class TrackSource #Variables imageCoverLarge = 'images/cover_default_large.png' @search: (options, success) -> tracks_all = { "itunes": [] "lastfm": [] "soundcloud": [] } mashTracks = -> tracks_allconcat = tracks_all['itunes'].concat( tracks_all['lastfm'], tracks_all['soundcloud'] ) tracks_deduplicated = [] tracks_hash = [] $.each tracks_allconcat, (i, track) -> if track if track.artist and track.title track_hash = track.artist.toLowerCase() + '___' + track.title.toLowerCase() if track_hash not in tracks_hash tracks_deduplicated.push(track) tracks_hash.push(track_hash) success? tracks_deduplicated if options.type is 'default' # itunes request url: 'http://itunes.apple.com/search?media=music' + '&entity=song&limit=100&term=' + encodeURIComponent(options.keywords) json: true , (error, response, data) -> if not error and response.statusCode is 200 tracks = [] try $.each data.results, (i, track) -> tracks.push title: track.trackCensoredName artist: track.artistName cover_url_medium: track.artworkUrl60 cover_url_large: track.artworkUrl100 tracks_all['itunes'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() # last.fm request url: 'http://ws.audioscrobbler.com/2.0/?method=track.search' + '&api_key=<KEY>&format=json&track=' + encodeURIComponent(options.keywords) json: true , (error, response, data) -> if not error and response.statusCode is 200 tracks = [] try if data.results.trackmatches.track.name data.results.trackmatches.track = [data.results.trackmatches.track] $.each data.results.trackmatches.track, (i, track) -> cover_url_medium = cover_url_large = 'images/cover_default_large.png' if track.image $.each track.image, (i, image) -> if image.size == 'medium' and image['#text'] != '' cover_url_medium = image['#text'] else if image.size == 'large' and image['#text'] != '' cover_url_large = image['#text'] tracks.push title: track.name artist: track.artist cover_url_medium: cover_url_medium cover_url_large: cover_url_large tracks_all['lastfm'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() # Soundcloud request url: 'https://api.soundcloud.com/tracks.json?' + 'client_id=dead160b6295b98e4078ea51d07d4ed2&q=' + encodeURIComponent(options.keywords) json: true , (error, response, data) -> tracks = [] if error alertify.error('Connectivity Error : (' + error + ')') else $.each data, (i, track) -> if track trackNameExploded = track.title.split(" - ") coverPhoto = track.artwork_url coverPhoto = @imageCoverLarge if !track.artwork_url tracks.push title: trackNameExploded[0] artist: trackNameExploded[1] cover_url_medium: coverPhoto cover_url_large: coverPhoto tracks_all['soundcloud'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() else request url: 'http://gdata.youtube.com/feeds/api/videos/' + options.link + '/related?alt=json' json: true , (error, response, data) -> tracks = [] if not error and response.statusCode is 200 $.each(data.feed.entry, (i, track) -> if !track['media$group']['media$thumbnail'] coverImageMedium = coverImageLarge = imageCoverLarge else coverImageMedium = track['media$group']['media$thumbnail'][1].url coverImageLarge = track['media$group']['media$thumbnail'][0].url tracks.push title: track['media$group']['media$title']['$t'] artist: track['author'][0]['name']['$t'] cover_url_medium: coverImageMedium cover_url_large: coverImageLarge ) #null the rest so we can add recommendations above tracks_all = { "itunes": [] "lastfm": [] "soundcloud": [] } tracks_all['itunes'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() #Recommendation / Suggested Songs @recommendations: (artist, title) -> if artist and title spinner = new Spinner(spinner_opts) .spin(playerContainer.find('.cover')[0]) request url: 'http://gdata.youtube.com/feeds/api/videos?alt=json&' + 'max-results=1&q=' + encodeURIComponent(artist + ' - ' + title) json: true, (error, response, data) -> if not data.feed.entry # no results alertify.log l10n.get('not_found') console.log l10n.get('not_found') spinner.stop() else $('#sidebar-container li.active').removeClass('active') $('#tracklist-container').empty() link = data.feed.entry[0].link[0].href.split("v=")[1].split("&")[0] TrackSource.search({ type: 'recommendations', link: link }, ((tracks) -> PopulateTrackList(tracks) spinner.stop() )) # We will cache feature tracks in this object @_cachedFeaturedMusic: {} @featuredMusic: (playlistId, success) -> if @_cachedFeaturedMusic[playlistId] isnt undefined success? @_cachedFeaturedMusic[playlistId] else request url: 'http://gdata.youtube.com/feeds/api/playlists/' + playlistId + '?start-index=1&amp;max-results=25&amp;v=2&alt=json' json: true , (error, response, data) => tracks = [] if not error and response.statusCode is 200 $.each(data.feed.entry, (i, track) -> if !track['media$group']['media$thumbnail'] coverImageMedium = coverImageLarge = imageCoverLarge else coverImageMedium = track['media$group']['media$thumbnail'][1].url coverImageLarge = track['media$group']['media$thumbnail'][0].url tracks.push title: track['media$group']['media$title']['$t'] artist: track['author'][0]['name']['$t'] cover_url_medium: coverImageMedium cover_url_large: coverImageLarge ) @_cachedFeaturedMusic[playlistId] = tracks success? @_cachedFeaturedMusic[playlistId] # We will cache feature tracks in this array @_cachedTopTracks: [] @topTracks: (success) -> if @_cachedTopTracks.length > 0 success? @_cachedTopTracks else request url:'http://itunes.apple.com/rss/topsongs/limit=100/explicit=true/json' json: true , (error, response, data) => if not error and response.statusCode is 200 tracks = [] tracks_hash = [] $.each data.feed.entry, (i, track) -> track_hash = track['im:artist'].label + '___' + track['im:name'].label if track_hash not in tracks_hash tracks.push title: track['im:name'].label artist: track['im:artist'].label cover_url_medium: track['im:image'][1].label cover_url_large: track['im:image'][2].label tracks_hash.push(track_hash) @_cachedTopTracks = tracks success? @_cachedTopTracks @history: (success) -> History.getTracks((tracks) -> success? tracks ) @playlist: (playlist, success) -> Playlists.getTracksForPlaylist(playlist, ((tracks) -> success? tracks ))
true
request = require('request') class TrackSource #Variables imageCoverLarge = 'images/cover_default_large.png' @search: (options, success) -> tracks_all = { "itunes": [] "lastfm": [] "soundcloud": [] } mashTracks = -> tracks_allconcat = tracks_all['itunes'].concat( tracks_all['lastfm'], tracks_all['soundcloud'] ) tracks_deduplicated = [] tracks_hash = [] $.each tracks_allconcat, (i, track) -> if track if track.artist and track.title track_hash = track.artist.toLowerCase() + '___' + track.title.toLowerCase() if track_hash not in tracks_hash tracks_deduplicated.push(track) tracks_hash.push(track_hash) success? tracks_deduplicated if options.type is 'default' # itunes request url: 'http://itunes.apple.com/search?media=music' + '&entity=song&limit=100&term=' + encodeURIComponent(options.keywords) json: true , (error, response, data) -> if not error and response.statusCode is 200 tracks = [] try $.each data.results, (i, track) -> tracks.push title: track.trackCensoredName artist: track.artistName cover_url_medium: track.artworkUrl60 cover_url_large: track.artworkUrl100 tracks_all['itunes'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() # last.fm request url: 'http://ws.audioscrobbler.com/2.0/?method=track.search' + '&api_key=PI:KEY:<KEY>END_PI&format=json&track=' + encodeURIComponent(options.keywords) json: true , (error, response, data) -> if not error and response.statusCode is 200 tracks = [] try if data.results.trackmatches.track.name data.results.trackmatches.track = [data.results.trackmatches.track] $.each data.results.trackmatches.track, (i, track) -> cover_url_medium = cover_url_large = 'images/cover_default_large.png' if track.image $.each track.image, (i, image) -> if image.size == 'medium' and image['#text'] != '' cover_url_medium = image['#text'] else if image.size == 'large' and image['#text'] != '' cover_url_large = image['#text'] tracks.push title: track.name artist: track.artist cover_url_medium: cover_url_medium cover_url_large: cover_url_large tracks_all['lastfm'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() # Soundcloud request url: 'https://api.soundcloud.com/tracks.json?' + 'client_id=dead160b6295b98e4078ea51d07d4ed2&q=' + encodeURIComponent(options.keywords) json: true , (error, response, data) -> tracks = [] if error alertify.error('Connectivity Error : (' + error + ')') else $.each data, (i, track) -> if track trackNameExploded = track.title.split(" - ") coverPhoto = track.artwork_url coverPhoto = @imageCoverLarge if !track.artwork_url tracks.push title: trackNameExploded[0] artist: trackNameExploded[1] cover_url_medium: coverPhoto cover_url_large: coverPhoto tracks_all['soundcloud'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() else request url: 'http://gdata.youtube.com/feeds/api/videos/' + options.link + '/related?alt=json' json: true , (error, response, data) -> tracks = [] if not error and response.statusCode is 200 $.each(data.feed.entry, (i, track) -> if !track['media$group']['media$thumbnail'] coverImageMedium = coverImageLarge = imageCoverLarge else coverImageMedium = track['media$group']['media$thumbnail'][1].url coverImageLarge = track['media$group']['media$thumbnail'][0].url tracks.push title: track['media$group']['media$title']['$t'] artist: track['author'][0]['name']['$t'] cover_url_medium: coverImageMedium cover_url_large: coverImageLarge ) #null the rest so we can add recommendations above tracks_all = { "itunes": [] "lastfm": [] "soundcloud": [] } tracks_all['itunes'] = tracks if Object.keys(tracks_all).length > 1 mashTracks() #Recommendation / Suggested Songs @recommendations: (artist, title) -> if artist and title spinner = new Spinner(spinner_opts) .spin(playerContainer.find('.cover')[0]) request url: 'http://gdata.youtube.com/feeds/api/videos?alt=json&' + 'max-results=1&q=' + encodeURIComponent(artist + ' - ' + title) json: true, (error, response, data) -> if not data.feed.entry # no results alertify.log l10n.get('not_found') console.log l10n.get('not_found') spinner.stop() else $('#sidebar-container li.active').removeClass('active') $('#tracklist-container').empty() link = data.feed.entry[0].link[0].href.split("v=")[1].split("&")[0] TrackSource.search({ type: 'recommendations', link: link }, ((tracks) -> PopulateTrackList(tracks) spinner.stop() )) # We will cache feature tracks in this object @_cachedFeaturedMusic: {} @featuredMusic: (playlistId, success) -> if @_cachedFeaturedMusic[playlistId] isnt undefined success? @_cachedFeaturedMusic[playlistId] else request url: 'http://gdata.youtube.com/feeds/api/playlists/' + playlistId + '?start-index=1&amp;max-results=25&amp;v=2&alt=json' json: true , (error, response, data) => tracks = [] if not error and response.statusCode is 200 $.each(data.feed.entry, (i, track) -> if !track['media$group']['media$thumbnail'] coverImageMedium = coverImageLarge = imageCoverLarge else coverImageMedium = track['media$group']['media$thumbnail'][1].url coverImageLarge = track['media$group']['media$thumbnail'][0].url tracks.push title: track['media$group']['media$title']['$t'] artist: track['author'][0]['name']['$t'] cover_url_medium: coverImageMedium cover_url_large: coverImageLarge ) @_cachedFeaturedMusic[playlistId] = tracks success? @_cachedFeaturedMusic[playlistId] # We will cache feature tracks in this array @_cachedTopTracks: [] @topTracks: (success) -> if @_cachedTopTracks.length > 0 success? @_cachedTopTracks else request url:'http://itunes.apple.com/rss/topsongs/limit=100/explicit=true/json' json: true , (error, response, data) => if not error and response.statusCode is 200 tracks = [] tracks_hash = [] $.each data.feed.entry, (i, track) -> track_hash = track['im:artist'].label + '___' + track['im:name'].label if track_hash not in tracks_hash tracks.push title: track['im:name'].label artist: track['im:artist'].label cover_url_medium: track['im:image'][1].label cover_url_large: track['im:image'][2].label tracks_hash.push(track_hash) @_cachedTopTracks = tracks success? @_cachedTopTracks @history: (success) -> History.getTracks((tracks) -> success? tracks ) @playlist: (playlist, success) -> Playlists.getTracksForPlaylist(playlist, ((tracks) -> success? tracks ))
[ { "context": "他机器测试,需要修改URL中所有内容\n#\n#XHR-Polling 测试\n#connect-url:119.254.108.75:8203/websocket?appId=cpj2xarlj5cdn&token=dXOJIInq", "end": 201, "score": 0.9996485710144043, "start": 187, "tag": "IP_ADDRESS", "value": "119.254.108.75" }, { "context": "4.108.75:8203/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0\n#send-url:119.254.108.7", "end": 345, "score": 0.7917380332946777, "start": 243, "tag": "KEY", "value": "dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE" }, { "context": "WWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0\n#send-url:119.254.108.75:8203/websocket?messageid=9&header=50&sessionid=cd", "end": 396, "score": 0.9996322393417358, "start": 382, "tag": "IP_ADDRESS", "value": "119.254.108.75" }, { "context": "portation()\n# socketransport.createTransport \"119.254.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInq", "end": 780, "score": 0.9996352791786194, "start": 766, "tag": "IP_ADDRESS", "value": "119.254.108.75" }, { "context": "4.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlH", "end": 839, "score": 0.843250572681427, "start": 822, "tag": "KEY", "value": "dXOJIInqKDahrpig%" }, { "context": "socket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHm", "end": 840, "score": 0.5137876868247986, "start": 839, "tag": "PASSWORD", "value": "2" }, { "context": "ocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZU", "end": 869, "score": 0.7705531120300293, "start": 840, "tag": "KEY", "value": "BTJcq3U1lgYP6zEv1OpCrfDse9JiB" }, { "context": "en=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUu", "end": 870, "score": 0.5523802638053894, "start": 869, "tag": "PASSWORD", "value": "i" }, { "context": "n=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfc", "end": 873, "score": 0.6019234657287598, "start": 870, "tag": "KEY", "value": "4BN" }, { "context": "XOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.", "end": 886, "score": 0.6155757904052734, "start": 873, "tag": "PASSWORD", "value": "yqa2MRus3mUda" }, { "context": "ig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&ap", "end": 890, "score": 0.5138281583786011, "start": 886, "tag": "KEY", "value": "ZlHm" }, { "context": "BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0\"\n# ", "end": 907, "score": 0.7488390207290649, "start": 890, "tag": "PASSWORD", "value": "SaXaVmp5%2FyPASY0" }, { "context": " connect = xhrTransport.createTransport(\"http://119.254.108.75:8203/pullmsg.js?sessionid=10ad1579-5645-4ed2-92e8", "end": 1927, "score": 0.9953654408454895, "start": 1913, "tag": "IP_ADDRESS", "value": "119.254.108.75" }, { "context": "uhongda-010101\\\\\",\\\\\"extra\\\\\":\\\\\"\\\\\"}\\\"}',\"http://119.254.108.75:8203/websocket?messageid=5&header=50&sessionid=10", "end": 2169, "score": 0.9996519088745117, "start": 2155, "tag": "IP_ADDRESS", "value": "119.254.108.75" }, { "context": ")\n# socket = socketransport.createTransport \"119.254.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInq", "end": 2695, "score": 0.9997175931930542, "start": 2681, "tag": "IP_ADDRESS", "value": "119.254.108.75" }, { "context": "ateTransport \"119.254.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse", "end": 2730, "score": 0.9462018013000488, "start": 2717, "tag": "KEY", "value": "cpj2xarlj5cdn" }, { "context": "4.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0", "end": 2813, "score": 0.6735245585441589, "start": 2737, "tag": "KEY", "value": "dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5" }, { "context": "()\n# socket = socketransport.createTransport \"119.254.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInq", "end": 3083, "score": 0.9995899200439453, "start": 3069, "tag": "IP_ADDRESS", "value": "119.254.108.75" }, { "context": "4.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BN", "end": 3126, "score": 0.709662139415741, "start": 3125, "tag": "PASSWORD", "value": "d" }, { "context": ".108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyq", "end": 3128, "score": 0.5214942693710327, "start": 3126, "tag": "KEY", "value": "XO" }, { "context": "08.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3", "end": 3135, "score": 0.5328349471092224, "start": 3128, "tag": "PASSWORD", "value": "JIInqKD" }, { "context": "103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mU", "end": 3137, "score": 0.5132549405097961, "start": 3135, "tag": "KEY", "value": "ah" }, { "context": "3/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0\"\n# expect(Object::t", "end": 3227, "score": 0.649035632610321, "start": 3137, "tag": "PASSWORD", "value": "rpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE" }, { "context": "()\n# socket = socketransport.createTransport \"119.254.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInq", "end": 3496, "score": 0.9995824098587036, "start": 3482, "tag": "IP_ADDRESS", "value": "119.254.108.75" }, { "context": "4.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BN", "end": 3539, "score": 0.5902883410453796, "start": 3538, "tag": "PASSWORD", "value": "d" }, { "context": ".108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRu", "end": 3546, "score": 0.5666360259056091, "start": 3539, "tag": "KEY", "value": "XOJIInq" }, { "context": ":8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3", "end": 3548, "score": 0.5134063363075256, "start": 3546, "tag": "PASSWORD", "value": "KD" }, { "context": "103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mU", "end": 3550, "score": 0.5286861062049866, "start": 3548, "tag": "KEY", "value": "ah" }, { "context": "3/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0\"\n# setTimeout(->\n# ", "end": 3640, "score": 0.644770622253418, "start": 3550, "tag": "PASSWORD", "value": "rpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE" }, { "context": ")\n# socket = socketransport.createTransport \"119.254.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInq", "end": 3940, "score": 0.9995600581169128, "start": 3926, "tag": "IP_ADDRESS", "value": "119.254.108.75" }, { "context": "4.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0\"\n# setTimeout(->\n#", "end": 4084, "score": 0.942907452583313, "start": 3982, "tag": "PASSWORD", "value": "dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE" } ]
test/spec/websocketSpec.coffee
nojsja/rongcloud-web-im-sdk-v2
98
#测试方法 #用WebSDK1.0(以下简称:V1.0)的Sever作为测试Sever #1、获取V1.0的URL #2、用V2.0的通讯通道发送消息,V1.0接收消息(避免转换二进制等操作) #3、验证:可互相收发消息为测试通过(通道畅通),后续完善细节 #PS: #若其他机器测试,需要修改URL中所有内容 # #XHR-Polling 测试 #connect-url:119.254.108.75:8203/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0 #send-url:119.254.108.75:8203/websocket?messageid=9&header=50&sessionid=cd6232ee-ec64-46b3-a26c-5c5f21cbd577&topic=ppMsgP&targetid=lisi ##data:{"sessionId":0,"classname":"RC:TxtMsg","content":"{\"content\":\"ssss\",\"extra\":\"\"}"} # describe '流程测试-webScoket', -> # it '测试业务流程-webScoket', -> # socketransport = new RongIMLib.SocketTransportation() # socketransport.createTransport "119.254.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0" # #测试内容为 “测试webSocket” (V1.0转换来) # binary = new Int8Array( [50, 0, 6, 112, 112, 77, 115, 103, 80, 0, 7, 122, 104, 97, 111, 108, 105, 117, 0, 4, 8, 0, 18, 9, 82, 67, 58, 84, 120, 116, 77, 115, 103, 26, 54, 123, 34, 99, 111, 110, 116, 101, 110, 116, 34, 58, 34, -26, -75, -117, -24, -81, -107, 119, 101, 98, 83, 111, 99, 107, 101, 116, 92, 110, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 44, 34, 101, 120, 116, 114, 97, 34, 58, 34, 34, 125]); # #连接成功后自动发送消息 # socketransport.send binary # #间隔3秒自动断开连接 # setTimeout (-> # socketransport.disconnect() # ), 3000 # #间隔5秒自动发送消息,报错则为正常 # setTimeout (-> # socketransport.send binary # ), 5000 # #间隔7秒自动重连 # setTimeout (-> # socketransport.reconnect() # ), 7000 # # describe 'just checking',-> # # it 'Test Socket zhangsan',-> # # xhrTransport = new RongIMLib.PollingTransportation # # connect = xhrTransport.createTransport("http://119.254.108.75:8203/pullmsg.js?sessionid=10ad1579-5645-4ed2-92e8-ad7ad6dd0e05","GET"); # # xhrTransport.send('{\"sessionId\":0,\"classname\":\"RC:TxtMsg\",\"content\":\"{\\"content\\":\\"yuhongda-010101\\",\\"extra\\":\\"\\"}\"}',"http://119.254.108.75:8203/websocket?messageid=5&header=50&sessionid=10ad1579-5645-4ed2-92e8-ad7ad6dd0e05&topic=ppMsgP&targetid=lisi","POST") # # describe "WebScoket", -> # # it "shuld return RongIMlib.SocketTransportation object",-> # socketransport = new RongIMLib.SocketTransportation() # expect(Object::toString.call socketransport).toEqual '[object Object]' # # it "url can't be empty,should return false",-> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "119.254.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0" # expect(socketransport.url).not.toEqual("") # # it "should return WebScoket object", -> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "119.254.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0" # expect(Object::toString.call socket).toEqual '[object WebSocket]' # # it "connected should return true",(done)-> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "119.254.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0" # setTimeout(-> # expect(socketransport.connected).toBe true # done(); # ,100) # # it "isClose should return true",(done)-> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "119.254.108.75:8103/websocket?appId=cpj2xarlj5cdn&token=dXOJIInqKDahrpig%2BTJcq3U1lgYP6zEv1OpCrfDse9JiBi4BNyqa2MRus3mUdaZlHmSaXaVmp5%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0" # setTimeout(-> # socketransport.disconnect() # expect(socketransport.isClose).toEqual true # done(); # ,200)
155771
#测试方法 #用WebSDK1.0(以下简称:V1.0)的Sever作为测试Sever #1、获取V1.0的URL #2、用V2.0的通讯通道发送消息,V1.0接收消息(避免转换二进制等操作) #3、验证:可互相收发消息为测试通过(通道畅通),后续完善细节 #PS: #若其他机器测试,需要修改URL中所有内容 # #XHR-Polling 测试 #connect-url:172.16.58.3:8203/websocket?appId=cpj2xarlj5cdn&token=<KEY>&sdkVer=1.0.0&apiVer=1.0.0 #send-url:172.16.58.3:8203/websocket?messageid=9&header=50&sessionid=cd6232ee-ec64-46b3-a26c-5c5f21cbd577&topic=ppMsgP&targetid=lisi ##data:{"sessionId":0,"classname":"RC:TxtMsg","content":"{\"content\":\"ssss\",\"extra\":\"\"}"} # describe '流程测试-webScoket', -> # it '测试业务流程-webScoket', -> # socketransport = new RongIMLib.SocketTransportation() # socketransport.createTransport "172.16.58.3:8103/websocket?appId=cpj2xarlj5cdn&token=<KEY> <PASSWORD> <KEY> <PASSWORD> <KEY> <PASSWORD> <KEY> <PASSWORD>%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0" # #测试内容为 “测试webSocket” (V1.0转换来) # binary = new Int8Array( [50, 0, 6, 112, 112, 77, 115, 103, 80, 0, 7, 122, 104, 97, 111, 108, 105, 117, 0, 4, 8, 0, 18, 9, 82, 67, 58, 84, 120, 116, 77, 115, 103, 26, 54, 123, 34, 99, 111, 110, 116, 101, 110, 116, 34, 58, 34, -26, -75, -117, -24, -81, -107, 119, 101, 98, 83, 111, 99, 107, 101, 116, 92, 110, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 44, 34, 101, 120, 116, 114, 97, 34, 58, 34, 34, 125]); # #连接成功后自动发送消息 # socketransport.send binary # #间隔3秒自动断开连接 # setTimeout (-> # socketransport.disconnect() # ), 3000 # #间隔5秒自动发送消息,报错则为正常 # setTimeout (-> # socketransport.send binary # ), 5000 # #间隔7秒自动重连 # setTimeout (-> # socketransport.reconnect() # ), 7000 # # describe 'just checking',-> # # it 'Test Socket zhangsan',-> # # xhrTransport = new RongIMLib.PollingTransportation # # connect = xhrTransport.createTransport("http://172.16.58.3:8203/pullmsg.js?sessionid=10ad1579-5645-4ed2-92e8-ad7ad6dd0e05","GET"); # # xhrTransport.send('{\"sessionId\":0,\"classname\":\"RC:TxtMsg\",\"content\":\"{\\"content\\":\\"yuhongda-010101\\",\\"extra\\":\\"\\"}\"}',"http://172.16.58.3:8203/websocket?messageid=5&header=50&sessionid=10ad1579-5645-4ed2-92e8-ad7ad6dd0e05&topic=ppMsgP&targetid=lisi","POST") # # describe "WebScoket", -> # # it "shuld return RongIMlib.SocketTransportation object",-> # socketransport = new RongIMLib.SocketTransportation() # expect(Object::toString.call socketransport).toEqual '[object Object]' # # it "url can't be empty,should return false",-> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "172.16.58.3:8103/websocket?appId=<KEY>&token=<KEY>%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0" # expect(socketransport.url).not.toEqual("") # # it "should return WebScoket object", -> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "172.16.58.3:8103/websocket?appId=cpj2xarlj5cdn&token=<PASSWORD> <KEY> <PASSWORD> <KEY> <PASSWORD>&sdkVer=1.0.0&apiVer=1.0.0" # expect(Object::toString.call socket).toEqual '[object WebSocket]' # # it "connected should return true",(done)-> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "172.16.58.3:8103/websocket?appId=cpj2xarlj5cdn&token=<PASSWORD> <KEY> <PASSWORD> <KEY> <PASSWORD>&sdkVer=1.0.0&apiVer=1.0.0" # setTimeout(-> # expect(socketransport.connected).toBe true # done(); # ,100) # # it "isClose should return true",(done)-> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "172.16.58.3:8103/websocket?appId=cpj2xarlj5cdn&token=<KEY>&sdkVer=1.0.0&apiVer=1.0.0" # setTimeout(-> # socketransport.disconnect() # expect(socketransport.isClose).toEqual true # done(); # ,200)
true
#测试方法 #用WebSDK1.0(以下简称:V1.0)的Sever作为测试Sever #1、获取V1.0的URL #2、用V2.0的通讯通道发送消息,V1.0接收消息(避免转换二进制等操作) #3、验证:可互相收发消息为测试通过(通道畅通),后续完善细节 #PS: #若其他机器测试,需要修改URL中所有内容 # #XHR-Polling 测试 #connect-url:PI:IP_ADDRESS:172.16.58.3END_PI:8203/websocket?appId=cpj2xarlj5cdn&token=PI:KEY:<KEY>END_PI&sdkVer=1.0.0&apiVer=1.0.0 #send-url:PI:IP_ADDRESS:172.16.58.3END_PI:8203/websocket?messageid=9&header=50&sessionid=cd6232ee-ec64-46b3-a26c-5c5f21cbd577&topic=ppMsgP&targetid=lisi ##data:{"sessionId":0,"classname":"RC:TxtMsg","content":"{\"content\":\"ssss\",\"extra\":\"\"}"} # describe '流程测试-webScoket', -> # it '测试业务流程-webScoket', -> # socketransport = new RongIMLib.SocketTransportation() # socketransport.createTransport "PI:IP_ADDRESS:172.16.58.3END_PI:8103/websocket?appId=cpj2xarlj5cdn&token=PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0" # #测试内容为 “测试webSocket” (V1.0转换来) # binary = new Int8Array( [50, 0, 6, 112, 112, 77, 115, 103, 80, 0, 7, 122, 104, 97, 111, 108, 105, 117, 0, 4, 8, 0, 18, 9, 82, 67, 58, 84, 120, 116, 77, 115, 103, 26, 54, 123, 34, 99, 111, 110, 116, 101, 110, 116, 34, 58, 34, -26, -75, -117, -24, -81, -107, 119, 101, 98, 83, 111, 99, 107, 101, 116, 92, 110, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 44, 34, 101, 120, 116, 114, 97, 34, 58, 34, 34, 125]); # #连接成功后自动发送消息 # socketransport.send binary # #间隔3秒自动断开连接 # setTimeout (-> # socketransport.disconnect() # ), 3000 # #间隔5秒自动发送消息,报错则为正常 # setTimeout (-> # socketransport.send binary # ), 5000 # #间隔7秒自动重连 # setTimeout (-> # socketransport.reconnect() # ), 7000 # # describe 'just checking',-> # # it 'Test Socket zhangsan',-> # # xhrTransport = new RongIMLib.PollingTransportation # # connect = xhrTransport.createTransport("http://PI:IP_ADDRESS:172.16.58.3END_PI:8203/pullmsg.js?sessionid=10ad1579-5645-4ed2-92e8-ad7ad6dd0e05","GET"); # # xhrTransport.send('{\"sessionId\":0,\"classname\":\"RC:TxtMsg\",\"content\":\"{\\"content\\":\\"yuhongda-010101\\",\\"extra\\":\\"\\"}\"}',"http://PI:IP_ADDRESS:172.16.58.3END_PI:8203/websocket?messageid=5&header=50&sessionid=10ad1579-5645-4ed2-92e8-ad7ad6dd0e05&topic=ppMsgP&targetid=lisi","POST") # # describe "WebScoket", -> # # it "shuld return RongIMlib.SocketTransportation object",-> # socketransport = new RongIMLib.SocketTransportation() # expect(Object::toString.call socketransport).toEqual '[object Object]' # # it "url can't be empty,should return false",-> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "PI:IP_ADDRESS:172.16.58.3END_PI:8103/websocket?appId=PI:KEY:<KEY>END_PI&token=PI:KEY:<KEY>END_PI%2FyPASY0%2FfWWKnbNZUuYfcE&sdkVer=1.0.0&apiVer=1.0.0" # expect(socketransport.url).not.toEqual("") # # it "should return WebScoket object", -> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "PI:IP_ADDRESS:172.16.58.3END_PI:8103/websocket?appId=cpj2xarlj5cdn&token=PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI&sdkVer=1.0.0&apiVer=1.0.0" # expect(Object::toString.call socket).toEqual '[object WebSocket]' # # it "connected should return true",(done)-> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "PI:IP_ADDRESS:172.16.58.3END_PI:8103/websocket?appId=cpj2xarlj5cdn&token=PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI&sdkVer=1.0.0&apiVer=1.0.0" # setTimeout(-> # expect(socketransport.connected).toBe true # done(); # ,100) # # it "isClose should return true",(done)-> # socketransport = new RongIMLib.SocketTransportation() # socket = socketransport.createTransport "PI:IP_ADDRESS:172.16.58.3END_PI:8103/websocket?appId=cpj2xarlj5cdn&token=PI:PASSWORD:<KEY>END_PI&sdkVer=1.0.0&apiVer=1.0.0" # setTimeout(-> # socketransport.disconnect() # expect(socketransport.isClose).toEqual true # done(); # ,200)
[ { "context": "$.parseTemp('[a] is falling love with [b]!', {a: 'Homura', b: 'Madoka'})\", ->\n\n temp = '[a] is falling ", "end": 3046, "score": 0.9990390539169312, "start": 3040, "tag": "NAME", "value": "Homura" }, { "context": "[a] is falling love with [b]!', {a: 'Homura', b: 'Madoka'})\", ->\n\n temp = '[a] is falling love with [b]", "end": 3059, "score": 0.9856047630310059, "start": 3053, "tag": "NAME", "value": "Madoka" }, { "context": "] is falling love with [b]!'\n data =\n a: 'Homura'\n b: 'Madoka'\n res = $.parseTemp temp, da", "end": 3139, "score": 0.9995359182357788, "start": 3133, "tag": "NAME", "value": "Homura" }, { "context": "with [b]!'\n data =\n a: 'Homura'\n b: 'Madoka'\n res = $.parseTemp temp, data\n if res != '", "end": 3157, "score": 0.999225914478302, "start": 3151, "tag": "NAME", "value": "Madoka" }, { "context": "'\n res = $.parseTemp temp, data\n if res != 'Homura is falling love with Madoka!'\n throw new Err", "end": 3213, "score": 0.99318927526474, "start": 3207, "tag": "NAME", "value": "Homura" }, { "context": "ata\n if res != 'Homura is falling love with Madoka!'\n throw new Error()\n\ndescribe '$.serialize(", "end": 3241, "score": 0.8322592973709106, "start": 3238, "tag": "NAME", "value": "oka" } ]
test/test.coffee
phonowell/node-jquery-extend
0
# require $ = require './../index' {_} = $ # test variable SUBJECT = [ 1024 # number 'hello world' # string true # boolean [1, 2, 3] # array {a: 1, b: 2} # object -> null # function new Date() # date new Error('All Right') # error new Buffer('String') # buffer null # null undefined # undefined NaN # NaN ] # test lines ### delay([time]) get(url, [data]) i(msg) info([method], [type], msg) log() parseJson() parsePts(num) parseSafe() parseShortDate(option) parseString(data) parseTemp(string, data) serialize(string) timeStamp([arg]) ### describe '$.delay([time])', -> it '$.delay(1e3)', -> st = _.now() res = await $.delay 1e3 if res != $ throw new Error 1 ct = _.now() unless 900 < ct - st < 1100 throw new Error 2 describe '$.get(url, [data])', -> it "$.get('https://app.anitama.net/web')", -> data = await $.get 'https://app.anitama.net/web' if $.type(data) != 'object' throw new Error 1 if data.success != true throw new Error 2 describe '$.i(msg)', -> it "$.i('test message')", -> string = 'test message' res = $.i string if res != string throw new Error() describe '$.info([method], [type], msg)', -> it "$.info('test message')", -> string = 'test message' res = $.info string if res != string throw new Error() describe '$.log()', -> it '$.log()', -> if $.log != console.log throw new Error() describe '$.parseJson()', -> it '$.parseJson()', -> res = $.parseJson() if res throw new Error() it "$.parseJson(new Buffer('{message: 'a test line'}'))", -> string = 'a test line' object = message: string buffer = new Buffer $.parseString object res = $.parseJson buffer if res.message != 'a test line' throw new Error describe '$.parsePts(num)', -> LIST = [ [0, '0'] [100, '100'] [1e3, '1,000'] [1e4, '10,000'] [1e5, '10万'] [1234567, '123.4万'] ] _.each LIST, (a) -> it "$.parsePts(#{a[0]})", -> if $.parsePts(a[0]) != a[1] throw new Error() describe '$.parseSafe()', -> it '$.parseSafe()', -> if $.parseSafe != _.escape throw new Error() describe '$.parseShortDate(option)', -> LIST = [ ['2012.12.21', '20121221'] ['1999.1.1', '19990101'] ['2050.2.28', '20500228'] ] _.each LIST, (a) -> it "$.parseShortDate('#{a[0]}')", -> if $.parseShortDate($.timeStamp a[0]) != a[1] throw new Error() describe '$.parseString(data)', -> LIST = [ '1024' 'hello world' 'true' '[1,2,3]' '{"a":1,"b":2}' SUBJECT[5].toString() SUBJECT[6].toString() SUBJECT[7].toString() SUBJECT[8].toString() 'null' 'undefined' 'NaN' ] _.each LIST, (a, i) -> p = SUBJECT[i] it "$.parseString(#{p})", -> res = $.parseString p if res != a throw new Error res describe '$.parseTemp(string, data)', -> it "$.parseTemp('[a] is falling love with [b]!', {a: 'Homura', b: 'Madoka'})", -> temp = '[a] is falling love with [b]!' data = a: 'Homura' b: 'Madoka' res = $.parseTemp temp, data if res != 'Homura is falling love with Madoka!' throw new Error() describe '$.serialize(string)', -> it "$.serialize('?a=1&b=2&c=3&d=4')", -> a = '?a=1&b=2&c=3&d=4' b = a: '1' b: '2' c: '3' d: '4' unless _.isEqual $.serialize(a), b throw new Error() describe '$.timeStamp([arg])', -> it '$.timeStamp()', -> ts = _.floor $.now(), -3 res = $.timeStamp() if res != ts throw new Error() it '$.timeStamp(1502777554000)', -> ts = 1502777554000 res = $.timeStamp ts ts = _.floor ts, -3 if res != ts throw new Error() LIST = [ [2012, 12, 21] [1997, 7, 1] [1970, 1, 1] ] _.each LIST, (a) -> timeString = a.join '.' res = $.timeStamp timeString date = new Date() date.setFullYear a[0], a[1] - 1, a[2] date.setHours 0, 0, 0, 0 ts = _.floor date.getTime(), -3 it "$.timeStamp('#{timeString}')", -> if res != ts throw new Error() LIST = [ [2012, 12, 21, 12, 21] [1997, 7, 1, 19, 30] [1970, 1, 1, 8, 1] ] _.each LIST, (a, i) -> timeString = "#{a[0...3].join '.'} #{a[3...].join ':'}" res = $.timeStamp timeString date = new Date() date.setFullYear a[0], a[1] - 1, a[2] date.setHours a[3], a[4], 0, 0 ts = _.floor date.getTime(), -3 it "$.timeStamp('#{timeString}')", -> if res != ts throw new Error()
223943
# require $ = require './../index' {_} = $ # test variable SUBJECT = [ 1024 # number 'hello world' # string true # boolean [1, 2, 3] # array {a: 1, b: 2} # object -> null # function new Date() # date new Error('All Right') # error new Buffer('String') # buffer null # null undefined # undefined NaN # NaN ] # test lines ### delay([time]) get(url, [data]) i(msg) info([method], [type], msg) log() parseJson() parsePts(num) parseSafe() parseShortDate(option) parseString(data) parseTemp(string, data) serialize(string) timeStamp([arg]) ### describe '$.delay([time])', -> it '$.delay(1e3)', -> st = _.now() res = await $.delay 1e3 if res != $ throw new Error 1 ct = _.now() unless 900 < ct - st < 1100 throw new Error 2 describe '$.get(url, [data])', -> it "$.get('https://app.anitama.net/web')", -> data = await $.get 'https://app.anitama.net/web' if $.type(data) != 'object' throw new Error 1 if data.success != true throw new Error 2 describe '$.i(msg)', -> it "$.i('test message')", -> string = 'test message' res = $.i string if res != string throw new Error() describe '$.info([method], [type], msg)', -> it "$.info('test message')", -> string = 'test message' res = $.info string if res != string throw new Error() describe '$.log()', -> it '$.log()', -> if $.log != console.log throw new Error() describe '$.parseJson()', -> it '$.parseJson()', -> res = $.parseJson() if res throw new Error() it "$.parseJson(new Buffer('{message: 'a test line'}'))", -> string = 'a test line' object = message: string buffer = new Buffer $.parseString object res = $.parseJson buffer if res.message != 'a test line' throw new Error describe '$.parsePts(num)', -> LIST = [ [0, '0'] [100, '100'] [1e3, '1,000'] [1e4, '10,000'] [1e5, '10万'] [1234567, '123.4万'] ] _.each LIST, (a) -> it "$.parsePts(#{a[0]})", -> if $.parsePts(a[0]) != a[1] throw new Error() describe '$.parseSafe()', -> it '$.parseSafe()', -> if $.parseSafe != _.escape throw new Error() describe '$.parseShortDate(option)', -> LIST = [ ['2012.12.21', '20121221'] ['1999.1.1', '19990101'] ['2050.2.28', '20500228'] ] _.each LIST, (a) -> it "$.parseShortDate('#{a[0]}')", -> if $.parseShortDate($.timeStamp a[0]) != a[1] throw new Error() describe '$.parseString(data)', -> LIST = [ '1024' 'hello world' 'true' '[1,2,3]' '{"a":1,"b":2}' SUBJECT[5].toString() SUBJECT[6].toString() SUBJECT[7].toString() SUBJECT[8].toString() 'null' 'undefined' 'NaN' ] _.each LIST, (a, i) -> p = SUBJECT[i] it "$.parseString(#{p})", -> res = $.parseString p if res != a throw new Error res describe '$.parseTemp(string, data)', -> it "$.parseTemp('[a] is falling love with [b]!', {a: '<NAME>', b: '<NAME>'})", -> temp = '[a] is falling love with [b]!' data = a: '<NAME>' b: '<NAME>' res = $.parseTemp temp, data if res != '<NAME> is falling love with Mad<NAME>!' throw new Error() describe '$.serialize(string)', -> it "$.serialize('?a=1&b=2&c=3&d=4')", -> a = '?a=1&b=2&c=3&d=4' b = a: '1' b: '2' c: '3' d: '4' unless _.isEqual $.serialize(a), b throw new Error() describe '$.timeStamp([arg])', -> it '$.timeStamp()', -> ts = _.floor $.now(), -3 res = $.timeStamp() if res != ts throw new Error() it '$.timeStamp(1502777554000)', -> ts = 1502777554000 res = $.timeStamp ts ts = _.floor ts, -3 if res != ts throw new Error() LIST = [ [2012, 12, 21] [1997, 7, 1] [1970, 1, 1] ] _.each LIST, (a) -> timeString = a.join '.' res = $.timeStamp timeString date = new Date() date.setFullYear a[0], a[1] - 1, a[2] date.setHours 0, 0, 0, 0 ts = _.floor date.getTime(), -3 it "$.timeStamp('#{timeString}')", -> if res != ts throw new Error() LIST = [ [2012, 12, 21, 12, 21] [1997, 7, 1, 19, 30] [1970, 1, 1, 8, 1] ] _.each LIST, (a, i) -> timeString = "#{a[0...3].join '.'} #{a[3...].join ':'}" res = $.timeStamp timeString date = new Date() date.setFullYear a[0], a[1] - 1, a[2] date.setHours a[3], a[4], 0, 0 ts = _.floor date.getTime(), -3 it "$.timeStamp('#{timeString}')", -> if res != ts throw new Error()
true
# require $ = require './../index' {_} = $ # test variable SUBJECT = [ 1024 # number 'hello world' # string true # boolean [1, 2, 3] # array {a: 1, b: 2} # object -> null # function new Date() # date new Error('All Right') # error new Buffer('String') # buffer null # null undefined # undefined NaN # NaN ] # test lines ### delay([time]) get(url, [data]) i(msg) info([method], [type], msg) log() parseJson() parsePts(num) parseSafe() parseShortDate(option) parseString(data) parseTemp(string, data) serialize(string) timeStamp([arg]) ### describe '$.delay([time])', -> it '$.delay(1e3)', -> st = _.now() res = await $.delay 1e3 if res != $ throw new Error 1 ct = _.now() unless 900 < ct - st < 1100 throw new Error 2 describe '$.get(url, [data])', -> it "$.get('https://app.anitama.net/web')", -> data = await $.get 'https://app.anitama.net/web' if $.type(data) != 'object' throw new Error 1 if data.success != true throw new Error 2 describe '$.i(msg)', -> it "$.i('test message')", -> string = 'test message' res = $.i string if res != string throw new Error() describe '$.info([method], [type], msg)', -> it "$.info('test message')", -> string = 'test message' res = $.info string if res != string throw new Error() describe '$.log()', -> it '$.log()', -> if $.log != console.log throw new Error() describe '$.parseJson()', -> it '$.parseJson()', -> res = $.parseJson() if res throw new Error() it "$.parseJson(new Buffer('{message: 'a test line'}'))", -> string = 'a test line' object = message: string buffer = new Buffer $.parseString object res = $.parseJson buffer if res.message != 'a test line' throw new Error describe '$.parsePts(num)', -> LIST = [ [0, '0'] [100, '100'] [1e3, '1,000'] [1e4, '10,000'] [1e5, '10万'] [1234567, '123.4万'] ] _.each LIST, (a) -> it "$.parsePts(#{a[0]})", -> if $.parsePts(a[0]) != a[1] throw new Error() describe '$.parseSafe()', -> it '$.parseSafe()', -> if $.parseSafe != _.escape throw new Error() describe '$.parseShortDate(option)', -> LIST = [ ['2012.12.21', '20121221'] ['1999.1.1', '19990101'] ['2050.2.28', '20500228'] ] _.each LIST, (a) -> it "$.parseShortDate('#{a[0]}')", -> if $.parseShortDate($.timeStamp a[0]) != a[1] throw new Error() describe '$.parseString(data)', -> LIST = [ '1024' 'hello world' 'true' '[1,2,3]' '{"a":1,"b":2}' SUBJECT[5].toString() SUBJECT[6].toString() SUBJECT[7].toString() SUBJECT[8].toString() 'null' 'undefined' 'NaN' ] _.each LIST, (a, i) -> p = SUBJECT[i] it "$.parseString(#{p})", -> res = $.parseString p if res != a throw new Error res describe '$.parseTemp(string, data)', -> it "$.parseTemp('[a] is falling love with [b]!', {a: 'PI:NAME:<NAME>END_PI', b: 'PI:NAME:<NAME>END_PI'})", -> temp = '[a] is falling love with [b]!' data = a: 'PI:NAME:<NAME>END_PI' b: 'PI:NAME:<NAME>END_PI' res = $.parseTemp temp, data if res != 'PI:NAME:<NAME>END_PI is falling love with MadPI:NAME:<NAME>END_PI!' throw new Error() describe '$.serialize(string)', -> it "$.serialize('?a=1&b=2&c=3&d=4')", -> a = '?a=1&b=2&c=3&d=4' b = a: '1' b: '2' c: '3' d: '4' unless _.isEqual $.serialize(a), b throw new Error() describe '$.timeStamp([arg])', -> it '$.timeStamp()', -> ts = _.floor $.now(), -3 res = $.timeStamp() if res != ts throw new Error() it '$.timeStamp(1502777554000)', -> ts = 1502777554000 res = $.timeStamp ts ts = _.floor ts, -3 if res != ts throw new Error() LIST = [ [2012, 12, 21] [1997, 7, 1] [1970, 1, 1] ] _.each LIST, (a) -> timeString = a.join '.' res = $.timeStamp timeString date = new Date() date.setFullYear a[0], a[1] - 1, a[2] date.setHours 0, 0, 0, 0 ts = _.floor date.getTime(), -3 it "$.timeStamp('#{timeString}')", -> if res != ts throw new Error() LIST = [ [2012, 12, 21, 12, 21] [1997, 7, 1, 19, 30] [1970, 1, 1, 8, 1] ] _.each LIST, (a, i) -> timeString = "#{a[0...3].join '.'} #{a[3...].join ':'}" res = $.timeStamp timeString date = new Date() date.setFullYear a[0], a[1] - 1, a[2] date.setHours a[3], a[4], 0, 0 ts = _.floor date.getTime(), -3 it "$.timeStamp('#{timeString}')", -> if res != ts throw new Error()
[ { "context": "f aircon:clean 123abc... .\n# hubot set @kitchen 192.168.1.23 - Names IP address 192.168.1.23 kitchen.\n", "end": 2503, "score": 0.9997091293334961, "start": 2491, "tag": "IP_ADDRESS", "value": "192.168.1.23" }, { "context": " @kitchen 192.168.1.23 - Names IP address 192.168.1.23 kitchen.\n# hubot set @bedroom xx:xx:xx:xx:xx ", "end": 2543, "score": 0.9997129440307617, "start": 2531, "tag": "IP_ADDRESS", "value": "192.168.1.23" }, { "context": " Tested with Broadlink RM Mini3.\n#\n# Author:\n# Tak Jaga <tak.jaga@gmail.com>\n\n# Copyright (c) 2017 Tak Ja", "end": 3214, "score": 0.9998823404312134, "start": 3206, "tag": "NAME", "value": "Tak Jaga" }, { "context": "ith Broadlink RM Mini3.\n#\n# Author:\n# Tak Jaga <tak.jaga@gmail.com>\n\n# Copyright (c) 2017 Tak Jaga\n#\n# Licensed unde", "end": 3234, "score": 0.9999327063560486, "start": 3216, "tag": "EMAIL", "value": "tak.jaga@gmail.com" }, { "context": "ak Jaga <tak.jaga@gmail.com>\n\n# Copyright (c) 2017 Tak Jaga\n#\n# Licensed under the Apache License, Version 2.", "end": 3266, "score": 0.9998710751533508, "start": 3258, "tag": "NAME", "value": "Tak Jaga" }, { "context": "de\"\n\nget = (robot, res) ->\n key = res.match[1].toLowerCase()\n val = getVal robot, key\n res.send \"#{key", "end": 13246, "score": 0.841299295425415, "start": 13235, "tag": "KEY", "value": "toLowerCase" }, { "context": "l}\"\n\nset = (robot, res) ->\n key = res.match[1].toLowerCase()\n val = res.match[2].toLowerCase()\n setVal", "end": 13365, "score": 0.6568362712860107, "start": 13354, "tag": "KEY", "value": "toLowerCase" } ]
src/broadlink-rm.coffee
takjg/hubot-broadlink-rm
26
# Description # Learns and sends IR hex codes with Broadlink RM. # # Configuration: # None # # Messages: # hubot learn <code> [n-m] [@<room>] - Learns IR hex code at <room> and names it <code>. # hubot send [[<wait>]] (<code>[@<room>]|<cmd>)[[<wait>]]*n ... - Sends IR hex <code> to <room> in <wait> <n> times. # hubot list - Shows all codes and rooms. # hubot delete <code> - Deletes IR hex <code>. # hubot delete @<room> - Deletes <room>. # hubot delete !<cmd> - Deletes <cmd>. # hubot get <code> - Shows IR hex code of <code>. # hubot get @<room> - Shows MAC or IP address of <room>. # hubot get !<cmd> - Shows UNIX commands of <cmd>. # hubot set <code> <hex> - Names <hex> <code>. # hubot set @<room> [<MAC>|<IP>] - Names MAC or IP address <room>. # hubot command <cmd> <body> # hubot help - Shows usage. # where # <code> ::= [0-9a-z:]+ # <room> ::= [0-9a-z:]+ # <cmd> ::= [0-9a-z:]+ # <body> ::= UNIX commands (A special character '#' is expanded to a sanitized given argument) # <hex> ::= [0-9a-fA-F]+ # <MAC> ::= [0-9a-fA-F:]+ # <IP> ::= [0-9.]+ # <wait> ::= [0-9]+[ms|s|m|h|d|second(s)|minute(s)|hour(s)|day(s)|秒|分|時間|日] # - <wait> must be less than or equal to 24 days # # Examples: # hubot learn light:on - Learns IR hex code and names it light:on. # hubot send light:on - Sends IR hex code of light:on. # hubot send tv:off aircon:off light:off - Sends three codes in turn. # hubot learn tv:ch 1-8 - Learns eight codes tv:ch1, tv:ch2, ..., tv:ch8 in turn. # hubot leran aircon:warm 14-30 - Also useful to learn many codes of air conditioner. # hubot send [7h] aircon:warm24 - Will sends aircon:warm24 in seven hours. # hubot send [7 hours] aircon:warm24 # hubot send [7時間] aircon:warm24 # hubot send tv:ch1 [2s] tv:source - Sends tv:ch1 then sends tv:source in two seconds. # hubot send tv:ch1 tv:source*3 - Sends tv:ch1 then sends tv:source three times # hubot send tv:ch1 tv:source[2s]*3 - Sends tv:ch1 then sends tv:source three times in two seconds. # hubot cancel - Cancels all unsent codes. # hubot get aircon:warm22 - Shows IR hex code of aircon:warm22. # hubot set aircon:clean 123abc... - Names IR hex code of aircon:clean 123abc... . # hubot set @kitchen 192.168.1.23 - Names IP address 192.168.1.23 kitchen. # hubot set @bedroom xx:xx:xx:xx:xx - Names MAC address xx:xx:xx:xx:xx bedroom. # hubot learn light:off @kitchen - Learns IR hex code of light:on at kitchen. # hubot send light:off@kitchen - Sends IR hex code of light:on at kitchen. # hubot send light:off@kitchen light:on@bedroom - Sends light:off at kitchen and light:on at bedroom. # hubot delete aircon:clean - Deletes the code of aircon:clean. # hubot list - Shows all names of codes and rooms. # hubot help - Shows usage. # # Notes: # Tested with Broadlink RM Mini3. # # Author: # Tak Jaga <tak.jaga@gmail.com> # Copyright (c) 2017 Tak Jaga # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 'use strict' module.exports = (robot) -> robot.respond ///send(((\s+#{WAIT})?\s+#{CODE_AT_N})+)$///, (res) -> sendN robot, res robot.respond ///learn\s+(#{CODE})(\s+(#{ROOM}))?$///, (res) -> learn1 robot, res robot.respond ///learn\s+(#{CODE})\s+#{RANGE}(\s+(#{ROOM}))?$///, (res) -> learnN robot, res robot.respond ///get\s+([@!]?#{NAME})$///, (res) -> get robot, res robot.respond ///set\s+(@?#{NAME})\s+(#{HEX_ADDR})$///, (res) -> set robot, res robot.respond ///command\s+(#{CMD})\s+(.*$)///, (res) -> setCMD robot, res robot.respond ///delete\s+([@!]?#{NAME})$///, (res) -> delet robot, res robot.respond ///cancel$///, (res) -> cancel robot, res robot.respond ///list$///, (res) -> list robot, res NAME = '[0-9a-z:]+' CODE = NAME CMD = NAME ROOM = '@' + NAME RANGE = '(\\d+)-(\\d+)' HEX_ADDR = '[0-9a-fA-F:.]+' UNIT = 'ms|s|m|h|d|seconds?|minutes?|hours?|days?|秒|分|時間|日' DELAY = "(\\d+)\\s*(#{UNIT})\\s*後?" TIME = '(\\d{1,2})\\s*[:時]\\s*(((\\d{1,2})\\s*分?)|(半))?' DIFF = "([-+])\\s*#{DELAY}" WAIT = "[[(]\\s*((#{DELAY})|(#{TIME}))\\s*(#{DIFF})?\\s*[\\])]" WAIT_ = "[[(]\\s*#{DELAY}\\s*[\\])]" REPEAT = "(#{WAIT_})?\\*(\\d+)" ARG = '([^()]*)' CODE_AT_N = "(((#{CMD})[(]#{ARG}[)])|((#{CODE})(#{ROOM})?))(#{REPEAT})?" getDevice = require 'homebridge-broadlink-rm/helpers/getDevice' learnData = require 'homebridge-broadlink-rm/helpers/learnData' # Messages sendN = (robot, res) -> tokens = tokenize res.match[1] codes = parse tokens if ok robot, res, codes sendN_ robot, res, codes tokenize = (str) -> re = ///(#{WAIT})|(#{CODE_AT_N})///g m[0] while m = re.exec str parse = (tokens) -> codes = [] prev = undefined head = true for t in tokens if t[0] is '[' or t[0] is '(' m = t.match ///#{WAIT}/// prev = mkWait m, head, t else m = t.match ///#{CODE_AT_N}/// codes = codes.concat mkCodes(prev, m) prev = undefined head = false codes[0].head = true codes mkWait = (m, head, token) -> if m[3]? then mkDelayWait m else if head then mkTimeWait m else { error: "ERROR unexpected wait #{token}" } { DateTime } = require 'luxon' mkDelayWait = (m) -> delay = mkDelay m, 3 return delay if delay.error? diff = getDiff m, 12 return diff if diff.error? ms = delay.wait + diff.wait str = delay.waitStr + diff.waitStr { wait: ms, waitStr: str } mkDelay = (m, index) -> n = Number m[index ] unit = m[index + 1] ms = n * millisOf unit str = n + unit if ms <= 24 * DAY { wait: ms, waitStr: str } else { error: "ERROR [#{str}] too long" } millisOf = (unit) -> switch unit when 'ms' then 1 when 's', 'second', 'seconds', '秒' then SEC when 'm', 'minute', 'minutes', '分' then MIN when 'h', 'hour', 'hours', '時間' then HOUR when 'd', 'day', 'days', '日' then DAY SEC = 1000 MIN = 60 * SEC HOUR = 60 * MIN DAY = 24 * HOUR getDiff = (m, index) -> return { wait: 0, waitStr: '' } unless m[index]? sign = m[index] delay = mkDelay m, index + 1 return delay if delay.error? ms = delay.wait ms = - ms if sign is '-' { wait: ms, waitStr: " #{sign} #{delay.waitStr}" } mkTimeWait = (m) -> hour = Number m[6] minute = if m[ 9]? then Number m[9] else if m[10]? then 30 else 0 diff = getDiff m, 12 return diff if diff.error? now = DateTime.local() future = now.set { hour: hour, minute: minute, second: 0, millisecond: 0 } future = future.plus { milliseconds: diff.wait } if future < now dHour = now.diff(future, 'hours').hours d = if dHour <= 12 and hour <= 12 then { hours: 12 } else { days: 1} future = future.plus d str = future.minus({ milliseconds: diff.wait }).toString() + diff.waitStr { wait: future - now, waitStr: str } mkCodes = (prev, m) -> code = if prev? then prev else {} code.code = m[6] if m[6]? code.room = m[7] if m[7]? code.cmd = '!' + m[3] if m[3]? code.arg = m[4] if m[4]? repeat = m[8] return [code] unless repeat? replicate code, m replicate = (code, m) -> wait = mkDelay(m, 10) if m[9]? n = Number m[12] switch n when 0 then code.code = undefined ; [code] when 1 then [code] else replicateN code, wait, n replicateN = (code, wait, n) -> copy = {} copy.code = code.code if code.code? copy.room = code.room if code.room? copy.cmd = code.cmd if code.cmd? copy.arg = code.arg if code.arg? Object.assign copy, wait copies = Array(n - 1).fill copy [code].concat copies ok = (robot, res, codes) -> for code in codes return false unless okCode robot, res, code return false unless okCmd robot, res, code return false unless okWait res, code true okCode = (robot, res, code) -> return true unless code.code? hex = getVal robot, code.code unless hex? res.send "ERROR no such code #{code.code}" return false okDevice robot, res, code okCmd = (robot, res, code) -> return true unless code.cmd? body = getVal robot, code.cmd res.send "ERROR no such command #{code.cmd.substr 1}" unless body? body? okDevice = (robot, res, code) -> host = getVal robot, code.room if code.room? and not host? res.send "ERROR no such room #{code.room}" return false device = getDevice { host: host, log: console.log } res.send "ERROR device not found #{host}" unless device? device? okWait = (res, code) -> err = code.error res.send err if err? not err? sendN_ = (robot, res, codes) -> repeat codes, (code, callback) -> send robot, res, code, callback send = (robot, res, code, callback) -> if code.code? then send_ robot, res, code, callback else if code.cmd? then exec_ robot, res, code, callback else wait res, code, callback send_ = (robot, res, code, callback) -> hex = getVal robot, code.code host = getVal robot, code.room back = (msg) -> res.send msg ; callback() if hex? device = getDevice { host: host, log: console.log } if device? wait res, code, -> buffer = new Buffer hex, 'hex' device.sendData buffer room = if code.room? then code.room else '' back "sent #{code.code}#{room}" else back "ERROR device not found #{host}" else back "ERROR no such code #{code.code}" exec_ = (robot, res, code, callback) -> body = getVal robot, code.cmd arg = sanitize code.arg back = (msg) -> res.send msg ; callback() if body? wait res, code, -> cmd = body.replace /#/g, arg { exec } = require 'child_process' exec cmd, (error, stdout, stderr) -> msg = [cmd, stdout, stderr].join('\n').trim() back msg else back "ERROR no such command #{code.cmd.substr 1}" sanitize = (str) -> str.replace /[\0-/:-@[-`{-\xff]/g, ' ' wait = (res, code, callback) -> millis = code.wait if millis? res.send "wait #{code.waitStr}" wait_ millis, callback else if code.head callback() else wait_ 1000, callback waiting = new Set wait_ = (millis, callback) -> timer = (flip setTimeout) millis, -> callback() waiting.delete timer waiting.add timer clearWait = -> waiting.forEach (timer) -> clearTimeout timer waiting.clear() flip = (f) -> (x, y) -> f y, x cancel = (robot, res) -> clearWait() res.send "canceled" repeat = (a, f) -> if a.length > 0 f a[0], -> a.shift() repeat a, f learn1 = (robot, res) -> code = res.match[1] .toLowerCase() room = res.match[3]?.toLowerCase() learn robot, res, code, room, (->) learnN = (robot, res) -> code = res.match[1] .toLowerCase() room = res.match[5]?.toLowerCase() start = Number res.match[2] stop = Number res.match[3] repeat [start .. stop], (n, callback) -> learn robot, res, code + n, room, callback learn = (robot, res, code, room, callback) -> hex = undefined host = getVal robot, room read = (str) -> m = str.match /Learn Code \(learned hex code: (\w+)\)/ hex = m[1] if m notFound = true prompt = -> notFound = false res.send "ready #{code}" setCd = -> setVal robot, code, hex learnData.stop (->) respond res, code, hex callback() learnData.start host, prompt, setCd, read, false if notFound res.send "ERROR device not found #{host}" respond = (res, code, hex) -> if hex res.send "set #{code} to #{hex}" else res.send "ERROR #{code} failed to learn code" get = (robot, res) -> key = res.match[1].toLowerCase() val = getVal robot, key res.send "#{key} = #{val}" set = (robot, res) -> key = res.match[1].toLowerCase() val = res.match[2].toLowerCase() setVal robot, key, val respond res, key, val setCMD = (robot, res) -> cmd = '!' + res.match[1].toLowerCase() body = res.match[2] setVal robot, cmd, body respond res, cmd, body delet = (robot, res) -> key = res.match[1].toLowerCase() deleteVal robot, key res.send "deleted #{key}" list = (robot, res) -> keys = getKeys robot res.send keys.sort().join '\n' # Persistence getVal = (robot, key) -> robot.brain.get key setVal = (robot, key, val) -> robot.brain.set key, val addKey robot, key deleteVal = (robot, key) -> robot.brain.remove key deleteKey robot, key addKey = (robot, key) -> keySet = getKeySet robot keySet.add key setKeySet robot, keySet deleteKey = (robot, key) -> keySet = getKeySet robot keySet.delete key setKeySet robot, keySet getKeys = (robot) -> str = robot.brain.get '_keys_' if str then JSON.parse str else [] getKeySet = (robot) -> new Set(getKeys robot) setKeySet = (robot, keySet) -> str = JSON.stringify(Array.from keySet) robot.brain.set '_keys_', str
2204
# Description # Learns and sends IR hex codes with Broadlink RM. # # Configuration: # None # # Messages: # hubot learn <code> [n-m] [@<room>] - Learns IR hex code at <room> and names it <code>. # hubot send [[<wait>]] (<code>[@<room>]|<cmd>)[[<wait>]]*n ... - Sends IR hex <code> to <room> in <wait> <n> times. # hubot list - Shows all codes and rooms. # hubot delete <code> - Deletes IR hex <code>. # hubot delete @<room> - Deletes <room>. # hubot delete !<cmd> - Deletes <cmd>. # hubot get <code> - Shows IR hex code of <code>. # hubot get @<room> - Shows MAC or IP address of <room>. # hubot get !<cmd> - Shows UNIX commands of <cmd>. # hubot set <code> <hex> - Names <hex> <code>. # hubot set @<room> [<MAC>|<IP>] - Names MAC or IP address <room>. # hubot command <cmd> <body> # hubot help - Shows usage. # where # <code> ::= [0-9a-z:]+ # <room> ::= [0-9a-z:]+ # <cmd> ::= [0-9a-z:]+ # <body> ::= UNIX commands (A special character '#' is expanded to a sanitized given argument) # <hex> ::= [0-9a-fA-F]+ # <MAC> ::= [0-9a-fA-F:]+ # <IP> ::= [0-9.]+ # <wait> ::= [0-9]+[ms|s|m|h|d|second(s)|minute(s)|hour(s)|day(s)|秒|分|時間|日] # - <wait> must be less than or equal to 24 days # # Examples: # hubot learn light:on - Learns IR hex code and names it light:on. # hubot send light:on - Sends IR hex code of light:on. # hubot send tv:off aircon:off light:off - Sends three codes in turn. # hubot learn tv:ch 1-8 - Learns eight codes tv:ch1, tv:ch2, ..., tv:ch8 in turn. # hubot leran aircon:warm 14-30 - Also useful to learn many codes of air conditioner. # hubot send [7h] aircon:warm24 - Will sends aircon:warm24 in seven hours. # hubot send [7 hours] aircon:warm24 # hubot send [7時間] aircon:warm24 # hubot send tv:ch1 [2s] tv:source - Sends tv:ch1 then sends tv:source in two seconds. # hubot send tv:ch1 tv:source*3 - Sends tv:ch1 then sends tv:source three times # hubot send tv:ch1 tv:source[2s]*3 - Sends tv:ch1 then sends tv:source three times in two seconds. # hubot cancel - Cancels all unsent codes. # hubot get aircon:warm22 - Shows IR hex code of aircon:warm22. # hubot set aircon:clean 123abc... - Names IR hex code of aircon:clean 123abc... . # hubot set @kitchen 192.168.1.23 - Names IP address 192.168.1.23 kitchen. # hubot set @bedroom xx:xx:xx:xx:xx - Names MAC address xx:xx:xx:xx:xx bedroom. # hubot learn light:off @kitchen - Learns IR hex code of light:on at kitchen. # hubot send light:off@kitchen - Sends IR hex code of light:on at kitchen. # hubot send light:off@kitchen light:on@bedroom - Sends light:off at kitchen and light:on at bedroom. # hubot delete aircon:clean - Deletes the code of aircon:clean. # hubot list - Shows all names of codes and rooms. # hubot help - Shows usage. # # Notes: # Tested with Broadlink RM Mini3. # # Author: # <NAME> <<EMAIL>> # Copyright (c) 2017 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 'use strict' module.exports = (robot) -> robot.respond ///send(((\s+#{WAIT})?\s+#{CODE_AT_N})+)$///, (res) -> sendN robot, res robot.respond ///learn\s+(#{CODE})(\s+(#{ROOM}))?$///, (res) -> learn1 robot, res robot.respond ///learn\s+(#{CODE})\s+#{RANGE}(\s+(#{ROOM}))?$///, (res) -> learnN robot, res robot.respond ///get\s+([@!]?#{NAME})$///, (res) -> get robot, res robot.respond ///set\s+(@?#{NAME})\s+(#{HEX_ADDR})$///, (res) -> set robot, res robot.respond ///command\s+(#{CMD})\s+(.*$)///, (res) -> setCMD robot, res robot.respond ///delete\s+([@!]?#{NAME})$///, (res) -> delet robot, res robot.respond ///cancel$///, (res) -> cancel robot, res robot.respond ///list$///, (res) -> list robot, res NAME = '[0-9a-z:]+' CODE = NAME CMD = NAME ROOM = '@' + NAME RANGE = '(\\d+)-(\\d+)' HEX_ADDR = '[0-9a-fA-F:.]+' UNIT = 'ms|s|m|h|d|seconds?|minutes?|hours?|days?|秒|分|時間|日' DELAY = "(\\d+)\\s*(#{UNIT})\\s*後?" TIME = '(\\d{1,2})\\s*[:時]\\s*(((\\d{1,2})\\s*分?)|(半))?' DIFF = "([-+])\\s*#{DELAY}" WAIT = "[[(]\\s*((#{DELAY})|(#{TIME}))\\s*(#{DIFF})?\\s*[\\])]" WAIT_ = "[[(]\\s*#{DELAY}\\s*[\\])]" REPEAT = "(#{WAIT_})?\\*(\\d+)" ARG = '([^()]*)' CODE_AT_N = "(((#{CMD})[(]#{ARG}[)])|((#{CODE})(#{ROOM})?))(#{REPEAT})?" getDevice = require 'homebridge-broadlink-rm/helpers/getDevice' learnData = require 'homebridge-broadlink-rm/helpers/learnData' # Messages sendN = (robot, res) -> tokens = tokenize res.match[1] codes = parse tokens if ok robot, res, codes sendN_ robot, res, codes tokenize = (str) -> re = ///(#{WAIT})|(#{CODE_AT_N})///g m[0] while m = re.exec str parse = (tokens) -> codes = [] prev = undefined head = true for t in tokens if t[0] is '[' or t[0] is '(' m = t.match ///#{WAIT}/// prev = mkWait m, head, t else m = t.match ///#{CODE_AT_N}/// codes = codes.concat mkCodes(prev, m) prev = undefined head = false codes[0].head = true codes mkWait = (m, head, token) -> if m[3]? then mkDelayWait m else if head then mkTimeWait m else { error: "ERROR unexpected wait #{token}" } { DateTime } = require 'luxon' mkDelayWait = (m) -> delay = mkDelay m, 3 return delay if delay.error? diff = getDiff m, 12 return diff if diff.error? ms = delay.wait + diff.wait str = delay.waitStr + diff.waitStr { wait: ms, waitStr: str } mkDelay = (m, index) -> n = Number m[index ] unit = m[index + 1] ms = n * millisOf unit str = n + unit if ms <= 24 * DAY { wait: ms, waitStr: str } else { error: "ERROR [#{str}] too long" } millisOf = (unit) -> switch unit when 'ms' then 1 when 's', 'second', 'seconds', '秒' then SEC when 'm', 'minute', 'minutes', '分' then MIN when 'h', 'hour', 'hours', '時間' then HOUR when 'd', 'day', 'days', '日' then DAY SEC = 1000 MIN = 60 * SEC HOUR = 60 * MIN DAY = 24 * HOUR getDiff = (m, index) -> return { wait: 0, waitStr: '' } unless m[index]? sign = m[index] delay = mkDelay m, index + 1 return delay if delay.error? ms = delay.wait ms = - ms if sign is '-' { wait: ms, waitStr: " #{sign} #{delay.waitStr}" } mkTimeWait = (m) -> hour = Number m[6] minute = if m[ 9]? then Number m[9] else if m[10]? then 30 else 0 diff = getDiff m, 12 return diff if diff.error? now = DateTime.local() future = now.set { hour: hour, minute: minute, second: 0, millisecond: 0 } future = future.plus { milliseconds: diff.wait } if future < now dHour = now.diff(future, 'hours').hours d = if dHour <= 12 and hour <= 12 then { hours: 12 } else { days: 1} future = future.plus d str = future.minus({ milliseconds: diff.wait }).toString() + diff.waitStr { wait: future - now, waitStr: str } mkCodes = (prev, m) -> code = if prev? then prev else {} code.code = m[6] if m[6]? code.room = m[7] if m[7]? code.cmd = '!' + m[3] if m[3]? code.arg = m[4] if m[4]? repeat = m[8] return [code] unless repeat? replicate code, m replicate = (code, m) -> wait = mkDelay(m, 10) if m[9]? n = Number m[12] switch n when 0 then code.code = undefined ; [code] when 1 then [code] else replicateN code, wait, n replicateN = (code, wait, n) -> copy = {} copy.code = code.code if code.code? copy.room = code.room if code.room? copy.cmd = code.cmd if code.cmd? copy.arg = code.arg if code.arg? Object.assign copy, wait copies = Array(n - 1).fill copy [code].concat copies ok = (robot, res, codes) -> for code in codes return false unless okCode robot, res, code return false unless okCmd robot, res, code return false unless okWait res, code true okCode = (robot, res, code) -> return true unless code.code? hex = getVal robot, code.code unless hex? res.send "ERROR no such code #{code.code}" return false okDevice robot, res, code okCmd = (robot, res, code) -> return true unless code.cmd? body = getVal robot, code.cmd res.send "ERROR no such command #{code.cmd.substr 1}" unless body? body? okDevice = (robot, res, code) -> host = getVal robot, code.room if code.room? and not host? res.send "ERROR no such room #{code.room}" return false device = getDevice { host: host, log: console.log } res.send "ERROR device not found #{host}" unless device? device? okWait = (res, code) -> err = code.error res.send err if err? not err? sendN_ = (robot, res, codes) -> repeat codes, (code, callback) -> send robot, res, code, callback send = (robot, res, code, callback) -> if code.code? then send_ robot, res, code, callback else if code.cmd? then exec_ robot, res, code, callback else wait res, code, callback send_ = (robot, res, code, callback) -> hex = getVal robot, code.code host = getVal robot, code.room back = (msg) -> res.send msg ; callback() if hex? device = getDevice { host: host, log: console.log } if device? wait res, code, -> buffer = new Buffer hex, 'hex' device.sendData buffer room = if code.room? then code.room else '' back "sent #{code.code}#{room}" else back "ERROR device not found #{host}" else back "ERROR no such code #{code.code}" exec_ = (robot, res, code, callback) -> body = getVal robot, code.cmd arg = sanitize code.arg back = (msg) -> res.send msg ; callback() if body? wait res, code, -> cmd = body.replace /#/g, arg { exec } = require 'child_process' exec cmd, (error, stdout, stderr) -> msg = [cmd, stdout, stderr].join('\n').trim() back msg else back "ERROR no such command #{code.cmd.substr 1}" sanitize = (str) -> str.replace /[\0-/:-@[-`{-\xff]/g, ' ' wait = (res, code, callback) -> millis = code.wait if millis? res.send "wait #{code.waitStr}" wait_ millis, callback else if code.head callback() else wait_ 1000, callback waiting = new Set wait_ = (millis, callback) -> timer = (flip setTimeout) millis, -> callback() waiting.delete timer waiting.add timer clearWait = -> waiting.forEach (timer) -> clearTimeout timer waiting.clear() flip = (f) -> (x, y) -> f y, x cancel = (robot, res) -> clearWait() res.send "canceled" repeat = (a, f) -> if a.length > 0 f a[0], -> a.shift() repeat a, f learn1 = (robot, res) -> code = res.match[1] .toLowerCase() room = res.match[3]?.toLowerCase() learn robot, res, code, room, (->) learnN = (robot, res) -> code = res.match[1] .toLowerCase() room = res.match[5]?.toLowerCase() start = Number res.match[2] stop = Number res.match[3] repeat [start .. stop], (n, callback) -> learn robot, res, code + n, room, callback learn = (robot, res, code, room, callback) -> hex = undefined host = getVal robot, room read = (str) -> m = str.match /Learn Code \(learned hex code: (\w+)\)/ hex = m[1] if m notFound = true prompt = -> notFound = false res.send "ready #{code}" setCd = -> setVal robot, code, hex learnData.stop (->) respond res, code, hex callback() learnData.start host, prompt, setCd, read, false if notFound res.send "ERROR device not found #{host}" respond = (res, code, hex) -> if hex res.send "set #{code} to #{hex}" else res.send "ERROR #{code} failed to learn code" get = (robot, res) -> key = res.match[1].<KEY>() val = getVal robot, key res.send "#{key} = #{val}" set = (robot, res) -> key = res.match[1].<KEY>() val = res.match[2].toLowerCase() setVal robot, key, val respond res, key, val setCMD = (robot, res) -> cmd = '!' + res.match[1].toLowerCase() body = res.match[2] setVal robot, cmd, body respond res, cmd, body delet = (robot, res) -> key = res.match[1].toLowerCase() deleteVal robot, key res.send "deleted #{key}" list = (robot, res) -> keys = getKeys robot res.send keys.sort().join '\n' # Persistence getVal = (robot, key) -> robot.brain.get key setVal = (robot, key, val) -> robot.brain.set key, val addKey robot, key deleteVal = (robot, key) -> robot.brain.remove key deleteKey robot, key addKey = (robot, key) -> keySet = getKeySet robot keySet.add key setKeySet robot, keySet deleteKey = (robot, key) -> keySet = getKeySet robot keySet.delete key setKeySet robot, keySet getKeys = (robot) -> str = robot.brain.get '_keys_' if str then JSON.parse str else [] getKeySet = (robot) -> new Set(getKeys robot) setKeySet = (robot, keySet) -> str = JSON.stringify(Array.from keySet) robot.brain.set '_keys_', str
true
# Description # Learns and sends IR hex codes with Broadlink RM. # # Configuration: # None # # Messages: # hubot learn <code> [n-m] [@<room>] - Learns IR hex code at <room> and names it <code>. # hubot send [[<wait>]] (<code>[@<room>]|<cmd>)[[<wait>]]*n ... - Sends IR hex <code> to <room> in <wait> <n> times. # hubot list - Shows all codes and rooms. # hubot delete <code> - Deletes IR hex <code>. # hubot delete @<room> - Deletes <room>. # hubot delete !<cmd> - Deletes <cmd>. # hubot get <code> - Shows IR hex code of <code>. # hubot get @<room> - Shows MAC or IP address of <room>. # hubot get !<cmd> - Shows UNIX commands of <cmd>. # hubot set <code> <hex> - Names <hex> <code>. # hubot set @<room> [<MAC>|<IP>] - Names MAC or IP address <room>. # hubot command <cmd> <body> # hubot help - Shows usage. # where # <code> ::= [0-9a-z:]+ # <room> ::= [0-9a-z:]+ # <cmd> ::= [0-9a-z:]+ # <body> ::= UNIX commands (A special character '#' is expanded to a sanitized given argument) # <hex> ::= [0-9a-fA-F]+ # <MAC> ::= [0-9a-fA-F:]+ # <IP> ::= [0-9.]+ # <wait> ::= [0-9]+[ms|s|m|h|d|second(s)|minute(s)|hour(s)|day(s)|秒|分|時間|日] # - <wait> must be less than or equal to 24 days # # Examples: # hubot learn light:on - Learns IR hex code and names it light:on. # hubot send light:on - Sends IR hex code of light:on. # hubot send tv:off aircon:off light:off - Sends three codes in turn. # hubot learn tv:ch 1-8 - Learns eight codes tv:ch1, tv:ch2, ..., tv:ch8 in turn. # hubot leran aircon:warm 14-30 - Also useful to learn many codes of air conditioner. # hubot send [7h] aircon:warm24 - Will sends aircon:warm24 in seven hours. # hubot send [7 hours] aircon:warm24 # hubot send [7時間] aircon:warm24 # hubot send tv:ch1 [2s] tv:source - Sends tv:ch1 then sends tv:source in two seconds. # hubot send tv:ch1 tv:source*3 - Sends tv:ch1 then sends tv:source three times # hubot send tv:ch1 tv:source[2s]*3 - Sends tv:ch1 then sends tv:source three times in two seconds. # hubot cancel - Cancels all unsent codes. # hubot get aircon:warm22 - Shows IR hex code of aircon:warm22. # hubot set aircon:clean 123abc... - Names IR hex code of aircon:clean 123abc... . # hubot set @kitchen 192.168.1.23 - Names IP address 192.168.1.23 kitchen. # hubot set @bedroom xx:xx:xx:xx:xx - Names MAC address xx:xx:xx:xx:xx bedroom. # hubot learn light:off @kitchen - Learns IR hex code of light:on at kitchen. # hubot send light:off@kitchen - Sends IR hex code of light:on at kitchen. # hubot send light:off@kitchen light:on@bedroom - Sends light:off at kitchen and light:on at bedroom. # hubot delete aircon:clean - Deletes the code of aircon:clean. # hubot list - Shows all names of codes and rooms. # hubot help - Shows usage. # # Notes: # Tested with Broadlink RM Mini3. # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (c) 2017 PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 'use strict' module.exports = (robot) -> robot.respond ///send(((\s+#{WAIT})?\s+#{CODE_AT_N})+)$///, (res) -> sendN robot, res robot.respond ///learn\s+(#{CODE})(\s+(#{ROOM}))?$///, (res) -> learn1 robot, res robot.respond ///learn\s+(#{CODE})\s+#{RANGE}(\s+(#{ROOM}))?$///, (res) -> learnN robot, res robot.respond ///get\s+([@!]?#{NAME})$///, (res) -> get robot, res robot.respond ///set\s+(@?#{NAME})\s+(#{HEX_ADDR})$///, (res) -> set robot, res robot.respond ///command\s+(#{CMD})\s+(.*$)///, (res) -> setCMD robot, res robot.respond ///delete\s+([@!]?#{NAME})$///, (res) -> delet robot, res robot.respond ///cancel$///, (res) -> cancel robot, res robot.respond ///list$///, (res) -> list robot, res NAME = '[0-9a-z:]+' CODE = NAME CMD = NAME ROOM = '@' + NAME RANGE = '(\\d+)-(\\d+)' HEX_ADDR = '[0-9a-fA-F:.]+' UNIT = 'ms|s|m|h|d|seconds?|minutes?|hours?|days?|秒|分|時間|日' DELAY = "(\\d+)\\s*(#{UNIT})\\s*後?" TIME = '(\\d{1,2})\\s*[:時]\\s*(((\\d{1,2})\\s*分?)|(半))?' DIFF = "([-+])\\s*#{DELAY}" WAIT = "[[(]\\s*((#{DELAY})|(#{TIME}))\\s*(#{DIFF})?\\s*[\\])]" WAIT_ = "[[(]\\s*#{DELAY}\\s*[\\])]" REPEAT = "(#{WAIT_})?\\*(\\d+)" ARG = '([^()]*)' CODE_AT_N = "(((#{CMD})[(]#{ARG}[)])|((#{CODE})(#{ROOM})?))(#{REPEAT})?" getDevice = require 'homebridge-broadlink-rm/helpers/getDevice' learnData = require 'homebridge-broadlink-rm/helpers/learnData' # Messages sendN = (robot, res) -> tokens = tokenize res.match[1] codes = parse tokens if ok robot, res, codes sendN_ robot, res, codes tokenize = (str) -> re = ///(#{WAIT})|(#{CODE_AT_N})///g m[0] while m = re.exec str parse = (tokens) -> codes = [] prev = undefined head = true for t in tokens if t[0] is '[' or t[0] is '(' m = t.match ///#{WAIT}/// prev = mkWait m, head, t else m = t.match ///#{CODE_AT_N}/// codes = codes.concat mkCodes(prev, m) prev = undefined head = false codes[0].head = true codes mkWait = (m, head, token) -> if m[3]? then mkDelayWait m else if head then mkTimeWait m else { error: "ERROR unexpected wait #{token}" } { DateTime } = require 'luxon' mkDelayWait = (m) -> delay = mkDelay m, 3 return delay if delay.error? diff = getDiff m, 12 return diff if diff.error? ms = delay.wait + diff.wait str = delay.waitStr + diff.waitStr { wait: ms, waitStr: str } mkDelay = (m, index) -> n = Number m[index ] unit = m[index + 1] ms = n * millisOf unit str = n + unit if ms <= 24 * DAY { wait: ms, waitStr: str } else { error: "ERROR [#{str}] too long" } millisOf = (unit) -> switch unit when 'ms' then 1 when 's', 'second', 'seconds', '秒' then SEC when 'm', 'minute', 'minutes', '分' then MIN when 'h', 'hour', 'hours', '時間' then HOUR when 'd', 'day', 'days', '日' then DAY SEC = 1000 MIN = 60 * SEC HOUR = 60 * MIN DAY = 24 * HOUR getDiff = (m, index) -> return { wait: 0, waitStr: '' } unless m[index]? sign = m[index] delay = mkDelay m, index + 1 return delay if delay.error? ms = delay.wait ms = - ms if sign is '-' { wait: ms, waitStr: " #{sign} #{delay.waitStr}" } mkTimeWait = (m) -> hour = Number m[6] minute = if m[ 9]? then Number m[9] else if m[10]? then 30 else 0 diff = getDiff m, 12 return diff if diff.error? now = DateTime.local() future = now.set { hour: hour, minute: minute, second: 0, millisecond: 0 } future = future.plus { milliseconds: diff.wait } if future < now dHour = now.diff(future, 'hours').hours d = if dHour <= 12 and hour <= 12 then { hours: 12 } else { days: 1} future = future.plus d str = future.minus({ milliseconds: diff.wait }).toString() + diff.waitStr { wait: future - now, waitStr: str } mkCodes = (prev, m) -> code = if prev? then prev else {} code.code = m[6] if m[6]? code.room = m[7] if m[7]? code.cmd = '!' + m[3] if m[3]? code.arg = m[4] if m[4]? repeat = m[8] return [code] unless repeat? replicate code, m replicate = (code, m) -> wait = mkDelay(m, 10) if m[9]? n = Number m[12] switch n when 0 then code.code = undefined ; [code] when 1 then [code] else replicateN code, wait, n replicateN = (code, wait, n) -> copy = {} copy.code = code.code if code.code? copy.room = code.room if code.room? copy.cmd = code.cmd if code.cmd? copy.arg = code.arg if code.arg? Object.assign copy, wait copies = Array(n - 1).fill copy [code].concat copies ok = (robot, res, codes) -> for code in codes return false unless okCode robot, res, code return false unless okCmd robot, res, code return false unless okWait res, code true okCode = (robot, res, code) -> return true unless code.code? hex = getVal robot, code.code unless hex? res.send "ERROR no such code #{code.code}" return false okDevice robot, res, code okCmd = (robot, res, code) -> return true unless code.cmd? body = getVal robot, code.cmd res.send "ERROR no such command #{code.cmd.substr 1}" unless body? body? okDevice = (robot, res, code) -> host = getVal robot, code.room if code.room? and not host? res.send "ERROR no such room #{code.room}" return false device = getDevice { host: host, log: console.log } res.send "ERROR device not found #{host}" unless device? device? okWait = (res, code) -> err = code.error res.send err if err? not err? sendN_ = (robot, res, codes) -> repeat codes, (code, callback) -> send robot, res, code, callback send = (robot, res, code, callback) -> if code.code? then send_ robot, res, code, callback else if code.cmd? then exec_ robot, res, code, callback else wait res, code, callback send_ = (robot, res, code, callback) -> hex = getVal robot, code.code host = getVal robot, code.room back = (msg) -> res.send msg ; callback() if hex? device = getDevice { host: host, log: console.log } if device? wait res, code, -> buffer = new Buffer hex, 'hex' device.sendData buffer room = if code.room? then code.room else '' back "sent #{code.code}#{room}" else back "ERROR device not found #{host}" else back "ERROR no such code #{code.code}" exec_ = (robot, res, code, callback) -> body = getVal robot, code.cmd arg = sanitize code.arg back = (msg) -> res.send msg ; callback() if body? wait res, code, -> cmd = body.replace /#/g, arg { exec } = require 'child_process' exec cmd, (error, stdout, stderr) -> msg = [cmd, stdout, stderr].join('\n').trim() back msg else back "ERROR no such command #{code.cmd.substr 1}" sanitize = (str) -> str.replace /[\0-/:-@[-`{-\xff]/g, ' ' wait = (res, code, callback) -> millis = code.wait if millis? res.send "wait #{code.waitStr}" wait_ millis, callback else if code.head callback() else wait_ 1000, callback waiting = new Set wait_ = (millis, callback) -> timer = (flip setTimeout) millis, -> callback() waiting.delete timer waiting.add timer clearWait = -> waiting.forEach (timer) -> clearTimeout timer waiting.clear() flip = (f) -> (x, y) -> f y, x cancel = (robot, res) -> clearWait() res.send "canceled" repeat = (a, f) -> if a.length > 0 f a[0], -> a.shift() repeat a, f learn1 = (robot, res) -> code = res.match[1] .toLowerCase() room = res.match[3]?.toLowerCase() learn robot, res, code, room, (->) learnN = (robot, res) -> code = res.match[1] .toLowerCase() room = res.match[5]?.toLowerCase() start = Number res.match[2] stop = Number res.match[3] repeat [start .. stop], (n, callback) -> learn robot, res, code + n, room, callback learn = (robot, res, code, room, callback) -> hex = undefined host = getVal robot, room read = (str) -> m = str.match /Learn Code \(learned hex code: (\w+)\)/ hex = m[1] if m notFound = true prompt = -> notFound = false res.send "ready #{code}" setCd = -> setVal robot, code, hex learnData.stop (->) respond res, code, hex callback() learnData.start host, prompt, setCd, read, false if notFound res.send "ERROR device not found #{host}" respond = (res, code, hex) -> if hex res.send "set #{code} to #{hex}" else res.send "ERROR #{code} failed to learn code" get = (robot, res) -> key = res.match[1].PI:KEY:<KEY>END_PI() val = getVal robot, key res.send "#{key} = #{val}" set = (robot, res) -> key = res.match[1].PI:KEY:<KEY>END_PI() val = res.match[2].toLowerCase() setVal robot, key, val respond res, key, val setCMD = (robot, res) -> cmd = '!' + res.match[1].toLowerCase() body = res.match[2] setVal robot, cmd, body respond res, cmd, body delet = (robot, res) -> key = res.match[1].toLowerCase() deleteVal robot, key res.send "deleted #{key}" list = (robot, res) -> keys = getKeys robot res.send keys.sort().join '\n' # Persistence getVal = (robot, key) -> robot.brain.get key setVal = (robot, key, val) -> robot.brain.set key, val addKey robot, key deleteVal = (robot, key) -> robot.brain.remove key deleteKey robot, key addKey = (robot, key) -> keySet = getKeySet robot keySet.add key setKeySet robot, keySet deleteKey = (robot, key) -> keySet = getKeySet robot keySet.delete key setKeySet robot, keySet getKeys = (robot) -> str = robot.brain.get '_keys_' if str then JSON.parse str else [] getKeySet = (robot) -> new Set(getKeys robot) setKeySet = (robot, keySet) -> str = JSON.stringify(Array.from keySet) robot.brain.set '_keys_', str
[ { "context": " -h about :: Prints some info about me, Haruka!\n ```\n \"\"\"\n}\n", "end": 869, "score": 0.9575796127319336, "start": 863, "tag": "NAME", "value": "Haruka" } ]
src/functions/about.coffee
MindfulMinun/discord-haruka
2
#! ======================================== #! About Discord = require 'discord.js' handler = (msg, match, H) -> chosenBlob = H.config.about.blobs.choose() if Array.isArray chosenBlob then chosenBlob = chosenBlob.choose() embed = new Discord.RichEmbed() .setColor '#448aff' .setTitle "Haruka #{H.version}" .setDescription H.config.about.description .addField "Links", H.config.about.links .setFooter "#{chosenBlob}" .setTimestamp H.client.readyAt msg.channel.send embed module.exports = { name: "About" regex: /^(about)(\s+|$)/i handler: handler help: short: "-h about :: General stuff about me." long: """ ```asciidoc === Help for About === *Aliases*: None. -h about :: Prints some info about me, Haruka! ``` """ }
93285
#! ======================================== #! About Discord = require 'discord.js' handler = (msg, match, H) -> chosenBlob = H.config.about.blobs.choose() if Array.isArray chosenBlob then chosenBlob = chosenBlob.choose() embed = new Discord.RichEmbed() .setColor '#448aff' .setTitle "Haruka #{H.version}" .setDescription H.config.about.description .addField "Links", H.config.about.links .setFooter "#{chosenBlob}" .setTimestamp H.client.readyAt msg.channel.send embed module.exports = { name: "About" regex: /^(about)(\s+|$)/i handler: handler help: short: "-h about :: General stuff about me." long: """ ```asciidoc === Help for About === *Aliases*: None. -h about :: Prints some info about me, <NAME>! ``` """ }
true
#! ======================================== #! About Discord = require 'discord.js' handler = (msg, match, H) -> chosenBlob = H.config.about.blobs.choose() if Array.isArray chosenBlob then chosenBlob = chosenBlob.choose() embed = new Discord.RichEmbed() .setColor '#448aff' .setTitle "Haruka #{H.version}" .setDescription H.config.about.description .addField "Links", H.config.about.links .setFooter "#{chosenBlob}" .setTimestamp H.client.readyAt msg.channel.send embed module.exports = { name: "About" regex: /^(about)(\s+|$)/i handler: handler help: short: "-h about :: General stuff about me." long: """ ```asciidoc === Help for About === *Aliases*: None. -h about :: Prints some info about me, PI:NAME:<NAME>END_PI! ``` """ }
[ { "context": "ata: [\n\t\t_id: '53ff303205efd776ebcaa280'\n\t\tname: 'Andrew'\n\t\temail: 'andrew.sygyda@gmail.com'\n\t\tposition: 1", "end": 95, "score": 0.9998032450675964, "start": 89, "tag": "NAME", "value": "Andrew" }, { "context": "f303205efd776ebcaa280'\n\t\tname: 'Andrew'\n\t\temail: 'andrew.sygyda@gmail.com'\n\t\tposition: 1\n\t\tphotos: []\n\t,\n\t\t_id: '53ff303a05", "end": 130, "score": 0.9999334216117859, "start": 107, "tag": "EMAIL", "value": "andrew.sygyda@gmail.com" }, { "context": " []\n\t,\n\t\t_id: '53ff303a05efd776ebcaa281'\n\t\tname: 'Yura'\n\t\temail: 'yriy.kabay@gmail.com'\n\t\tposition: 3\n\t\t", "end": 209, "score": 0.999843955039978, "start": 205, "tag": "NAME", "value": "Yura" }, { "context": "3ff303a05efd776ebcaa281'\n\t\tname: 'Yura'\n\t\temail: 'yriy.kabay@gmail.com'\n\t\tposition: 3\n\t\tphotos: []\n\t,\n\t\t_id: '53ff304405", "end": 241, "score": 0.9999158382415771, "start": 221, "tag": "EMAIL", "value": "yriy.kabay@gmail.com" }, { "context": " []\n\t,\n\t\t_id: '53ff304405efd776ebcaa282'\n\t\tname: 'Serezhka'\n\t\temail: 'sergey.kalashnik@gmail.com'\n\t\tposition", "end": 324, "score": 0.9998401999473572, "start": 316, "tag": "NAME", "value": "Serezhka" }, { "context": "04405efd776ebcaa282'\n\t\tname: 'Serezhka'\n\t\temail: 'sergey.kalashnik@gmail.com'\n\t\tposition: 2\n\t\tphotos: []\n\t]", "end": 362, "score": 0.9999341368675232, "start": 336, "tag": "EMAIL", "value": "sergey.kalashnik@gmail.com" } ]
test-helpers/migrate.coffee
winnlab/Optimeal
0
module.exports = modelName: 'test' data: [ _id: '53ff303205efd776ebcaa280' name: 'Andrew' email: 'andrew.sygyda@gmail.com' position: 1 photos: [] , _id: '53ff303a05efd776ebcaa281' name: 'Yura' email: 'yriy.kabay@gmail.com' position: 3 photos: [] , _id: '53ff304405efd776ebcaa282' name: 'Serezhka' email: 'sergey.kalashnik@gmail.com' position: 2 photos: [] ]
89580
module.exports = modelName: 'test' data: [ _id: '53ff303205efd776ebcaa280' name: '<NAME>' email: '<EMAIL>' position: 1 photos: [] , _id: '53ff303a05efd776ebcaa281' name: '<NAME>' email: '<EMAIL>' position: 3 photos: [] , _id: '53ff304405efd776ebcaa282' name: '<NAME>' email: '<EMAIL>' position: 2 photos: [] ]
true
module.exports = modelName: 'test' data: [ _id: '53ff303205efd776ebcaa280' name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' position: 1 photos: [] , _id: '53ff303a05efd776ebcaa281' name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' position: 3 photos: [] , _id: '53ff304405efd776ebcaa282' name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' position: 2 photos: [] ]
[ { "context": "ssword', ->\n krb5.kinit\n # username: 'myself'\n principal: 'myself@realm'\n passwo", "end": 211, "score": 0.9994624853134155, "start": 205, "tag": "USERNAME", "value": "myself" }, { "context": " principal: 'myself@realm'\n password: 'myprecious'\n .should.eql 'echo myprecious | kinit mysel", "end": 276, "score": 0.9993062615394592, "start": 266, "tag": "PASSWORD", "value": "myprecious" } ]
packages/core/test/misc/krb5.coffee
chibanemourad/node-nikita
1
krb5 = require '../../src/misc/krb5' {tags} = require '../test' return unless tags.api describe 'misc krb5', -> describe 'kinit', -> it 'with password', -> krb5.kinit # username: 'myself' principal: 'myself@realm' password: 'myprecious' .should.eql 'echo myprecious | kinit myself@realm' it 'with keytab', -> krb5.kinit principal: 'myself@realm' keytab: '/tmp/keytab' .should.eql 'kinit -kt /tmp/keytab myself@realm' it 'with username', -> krb5.kinit principal: 'myself@realm' keytab: '/tmp/keytab' uid: 'me' .should.eql 'su - me -c \'kinit -kt /tmp/keytab myself@realm\''
122988
krb5 = require '../../src/misc/krb5' {tags} = require '../test' return unless tags.api describe 'misc krb5', -> describe 'kinit', -> it 'with password', -> krb5.kinit # username: 'myself' principal: 'myself@realm' password: '<PASSWORD>' .should.eql 'echo myprecious | kinit myself@realm' it 'with keytab', -> krb5.kinit principal: 'myself@realm' keytab: '/tmp/keytab' .should.eql 'kinit -kt /tmp/keytab myself@realm' it 'with username', -> krb5.kinit principal: 'myself@realm' keytab: '/tmp/keytab' uid: 'me' .should.eql 'su - me -c \'kinit -kt /tmp/keytab myself@realm\''
true
krb5 = require '../../src/misc/krb5' {tags} = require '../test' return unless tags.api describe 'misc krb5', -> describe 'kinit', -> it 'with password', -> krb5.kinit # username: 'myself' principal: 'myself@realm' password: 'PI:PASSWORD:<PASSWORD>END_PI' .should.eql 'echo myprecious | kinit myself@realm' it 'with keytab', -> krb5.kinit principal: 'myself@realm' keytab: '/tmp/keytab' .should.eql 'kinit -kt /tmp/keytab myself@realm' it 'with username', -> krb5.kinit principal: 'myself@realm' keytab: '/tmp/keytab' uid: 'me' .should.eql 'su - me -c \'kinit -kt /tmp/keytab myself@realm\''
[ { "context": "exports.test_accounts = [ \r\n 'rBmhuVAvi372AerwzwERGjhLjqkMmAwxX',\r\n 'r4nmQNH4Fhjfh6cHDbvVSsBv7KySbj4cBf',\r\n 'rG", "end": 64, "score": 0.999211847782135, "start": 31, "tag": "KEY", "value": "rBmhuVAvi372AerwzwERGjhLjqkMmAwxX" }, { "context": " = [ \r\n 'rBmhuVAvi372AerwzwERGjhLjqkMmAwxX',\r\n 'r4nmQNH4Fhjfh6cHDbvVSsBv7KySbj4cBf',\r\n 'rGpeQzUWFu4fMhJHZ1Via5aqFC3A5twZUD',\r\n 'rr", "end": 105, "score": 0.9960741996765137, "start": 71, "tag": "KEY", "value": "r4nmQNH4Fhjfh6cHDbvVSsBv7KySbj4cBf" }, { "context": "xX',\r\n 'r4nmQNH4Fhjfh6cHDbvVSsBv7KySbj4cBf',\r\n 'rGpeQzUWFu4fMhJHZ1Via5aqFC3A5twZUD',\r\n 'rrnsYgWn13Z28GtRgznrSUsLfMkvsXCZSu',\r\n 'rJ", "end": 146, "score": 0.988227367401123, "start": 112, "tag": "KEY", "value": "rGpeQzUWFu4fMhJHZ1Via5aqFC3A5twZUD" }, { "context": "Bf',\r\n 'rGpeQzUWFu4fMhJHZ1Via5aqFC3A5twZUD',\r\n 'rrnsYgWn13Z28GtRgznrSUsLfMkvsXCZSu',\r\n 'rJsaPnGdeo7BhMnHjuc3n44Mf7Ra1qkSVJ',\r\n 'rn", "end": 187, "score": 0.9707147479057312, "start": 153, "tag": "KEY", "value": "rrnsYgWn13Z28GtRgznrSUsLfMkvsXCZSu" }, { "context": "UD',\r\n 'rrnsYgWn13Z28GtRgznrSUsLfMkvsXCZSu',\r\n 'rJsaPnGdeo7BhMnHjuc3n44Mf7Ra1qkSVJ',\r\n 'rnYDWQaRdMb5neCGgv", "end": 203, "score": 0.9161972999572754, "start": 194, "tag": "KEY", "value": "rJsaPnGde" }, { "context": "rnsYgWn13Z28GtRgznrSUsLfMkvsXCZSu',\r\n 'rJsaPnGdeo7BhMnHjuc3n44Mf7Ra1qkSVJ',\r\n 'rnYDWQaRdMb5neCGgvFfhw3MBoxmv5LtfH',\r\n 'r3", "end": 228, "score": 0.8129544854164124, "start": 204, "tag": "KEY", "value": "7BhMnHjuc3n44Mf7Ra1qkSVJ" }, { "context": "Su',\r\n 'rJsaPnGdeo7BhMnHjuc3n44Mf7Ra1qkSVJ',\r\n 'rnYDWQaRdMb5neCGgvFfhw3MBoxmv5LtfH',\r\n 'r31PEiKfa3y6xTi7uBcSp7F3nDLvVMmqyi',\r\n 'rf", "end": 269, "score": 0.9485511779785156, "start": 235, "tag": "KEY", "value": "rnYDWQaRdMb5neCGgvFfhw3MBoxmv5LtfH" }, { "context": "VJ',\r\n 'rnYDWQaRdMb5neCGgvFfhw3MBoxmv5LtfH',\r\n 'r31PEiKfa3y6xTi7uBcSp7F3nDLvVMmqyi',\r\n 'rfM5xD2CY6XB8o1WsWoJ3ZHGkbHU4NYXr',\r\n 'r9M", "end": 310, "score": 0.9984351396560669, "start": 276, "tag": "KEY", "value": "r31PEiKfa3y6xTi7uBcSp7F3nDLvVMmqyi" }, { "context": "fH',\r\n 'r31PEiKfa3y6xTi7uBcSp7F3nDLvVMmqyi',\r\n 'rfM5xD2CY6XB8o1WsWoJ3ZHGkbHU4NYXr',\r\n 'r9MB1RNWZChfV3YdLrB3Rm5AoMULewDtiu',\r\n 'rH", "end": 350, "score": 0.9992097616195679, "start": 317, "tag": "KEY", "value": "rfM5xD2CY6XB8o1WsWoJ3ZHGkbHU4NYXr" }, { "context": "qyi',\r\n 'rfM5xD2CY6XB8o1WsWoJ3ZHGkbHU4NYXr',\r\n 'r9MB1RNWZChfV3YdLrB3Rm5AoMULewDtiu',\r\n 'rH15iZg9KFSi7d1usvcsPerUtg7dhpMbk4',\r\n 'rG", "end": 391, "score": 0.9991418719291687, "start": 357, "tag": "KEY", "value": "r9MB1RNWZChfV3YdLrB3Rm5AoMULewDtiu" }, { "context": "Xr',\r\n 'r9MB1RNWZChfV3YdLrB3Rm5AoMULewDtiu',\r\n 'rH15iZg9KFSi7d1usvcsPerUtg7dhpMbk4',\r\n 'rGWYwGaczQWiduWkccFZKXfp5nDRPqNBNS',\r\n 'rB", "end": 432, "score": 0.9989018440246582, "start": 398, "tag": "KEY", "value": "rH15iZg9KFSi7d1usvcsPerUtg7dhpMbk4" }, { "context": "iu',\r\n 'rH15iZg9KFSi7d1usvcsPerUtg7dhpMbk4',\r\n 'rGWYwGaczQWiduWkccFZKXfp5nDRPqNBNS',\r\n 'rBU1EP5oMwKxWr1gZnNe7K8GouQTBhzUKs',\r\n 'rw", "end": 473, "score": 0.9992143511772156, "start": 439, "tag": "KEY", "value": "rGWYwGaczQWiduWkccFZKXfp5nDRPqNBNS" }, { "context": "k4',\r\n 'rGWYwGaczQWiduWkccFZKXfp5nDRPqNBNS',\r\n 'rBU1EP5oMwKxWr1gZnNe7K8GouQTBhzUKs',\r\n 'rwiTxuknPNeLDYHHLgajRVetKEEwkYhTaQ',\r\n 'rE", "end": 514, "score": 0.9989721179008484, "start": 480, "tag": "KEY", "value": "rBU1EP5oMwKxWr1gZnNe7K8GouQTBhzUKs" }, { "context": "NS',\r\n 'rBU1EP5oMwKxWr1gZnNe7K8GouQTBhzUKs',\r\n 'rwiTxuknPNeLDYHHLgajRVetKEEwkYhTaQ',\r\n 'rEbq9pWn2knXFTjjuoNNrKgQeGxhmispMi',\r\n 'rJ", "end": 555, "score": 0.9988601803779602, "start": 521, "tag": "KEY", "value": "rwiTxuknPNeLDYHHLgajRVetKEEwkYhTaQ" }, { "context": "Ks',\r\n 'rwiTxuknPNeLDYHHLgajRVetKEEwkYhTaQ',\r\n 'rEbq9pWn2knXFTjjuoNNrKgQeGxhmispMi',\r\n 'rJfBCsnwSHXjTJ4GH5Ax6Kyw48X977hqyq',\r\n 'ra", "end": 596, "score": 0.9987876415252686, "start": 562, "tag": "KEY", "value": "rEbq9pWn2knXFTjjuoNNrKgQeGxhmispMi" }, { "context": "aQ',\r\n 'rEbq9pWn2knXFTjjuoNNrKgQeGxhmispMi',\r\n 'rJfBCsnwSHXjTJ4GH5Ax6Kyw48X977hqyq',\r\n 'rado7qRcvPpS8ZL8SNg4SG8kBNksHyqoRa',\r\n 'rN", "end": 637, "score": 0.9987297654151917, "start": 603, "tag": "KEY", "value": "rJfBCsnwSHXjTJ4GH5Ax6Kyw48X977hqyq" }, { "context": "Mi',\r\n 'rJfBCsnwSHXjTJ4GH5Ax6Kyw48X977hqyq',\r\n 'rado7qRcvPpS8ZL8SNg4SG8kBNksHyqoRa',\r\n 'rNgfurDhqvfsVzLr5ZGB3dJysJhRkvJ79F',\r\n 'rB", "end": 678, "score": 0.998078465461731, "start": 644, "tag": "KEY", "value": "rado7qRcvPpS8ZL8SNg4SG8kBNksHyqoRa" }, { "context": "yq',\r\n 'rado7qRcvPpS8ZL8SNg4SG8kBNksHyqoRa',\r\n 'rNgfurDhqvfsVzLr5ZGB3dJysJhRkvJ79F',\r\n 'rBtVTnNgX3uR3kyfVyaQ6hjZTdk42ay9Z3',\r\n 'rN", "end": 719, "score": 0.997534453868866, "start": 685, "tag": "KEY", "value": "rNgfurDhqvfsVzLr5ZGB3dJysJhRkvJ79F" }, { "context": "Ra',\r\n 'rNgfurDhqvfsVzLr5ZGB3dJysJhRkvJ79F',\r\n 'rBtVTnNgX3uR3kyfVyaQ6hjZTdk42ay9Z3',\r\n 'rND1XyLAU9G2ydhUgmRo4i2kdrSKgYZc31',\r\n 'rH", "end": 760, "score": 0.9899469017982483, "start": 726, "tag": "KEY", "value": "rBtVTnNgX3uR3kyfVyaQ6hjZTdk42ay9Z3" }, { "context": "9F',\r\n 'rBtVTnNgX3uR3kyfVyaQ6hjZTdk42ay9Z3',\r\n 'rND1XyLAU9G2ydhUgmRo4i2kdrSKgYZc31',\r\n 'rHd21p9Gb834Ri4pzRzGFJ7PjRzymW", "end": 788, "score": 0.9434566497802734, "start": 767, "tag": "KEY", "value": "rND1XyLAU9G2ydhUgmRo4" }, { "context": "kyfVyaQ6hjZTdk42ay9Z3',\r\n 'rND1XyLAU9G2ydhUgmRo4i2kdrSKgYZc31',\r\n 'rHd21p9Gb834Ri4pzRzGFJ7PjRzymWuBWu',\r\n 'rh", "end": 801, "score": 0.9210033416748047, "start": 789, "tag": "KEY", "value": "2kdrSKgYZc31" }, { "context": "Z3',\r\n 'rND1XyLAU9G2ydhUgmRo4i2kdrSKgYZc31',\r\n 'rHd21p9Gb834Ri4pzRzGFJ7PjRzymWuBWu',\r\n 'rhfvFTgpPzCvFPgbA9Nvz", "end": 820, "score": 0.9278503656387329, "start": 808, "tag": "KEY", "value": "rHd21p9Gb834" }, { "context": "LAU9G2ydhUgmRo4i2kdrSKgYZc31',\r\n 'rHd21p9Gb834Ri4pzRzGFJ7PjRzymWuBWu',\r\n 'rhfvFTgpPzCvFPgbA9Nvz42mX92U5ak92m',\r\n 'rB", "end": 842, "score": 0.9918835163116455, "start": 823, "tag": "KEY", "value": "pzRzGFJ7PjRzymWuBWu" }, { "context": "31',\r\n 'rHd21p9Gb834Ri4pzRzGFJ7PjRzymWuBWu',\r\n 'rhfvFTgpPzCvFPgbA9Nvz42mX92U5ak92m',\r\n 'rByT8y4BUX1Kcc6xotEabCgwc5PGsbTfSv',\r\n 'rP", "end": 883, "score": 0.9853070378303528, "start": 849, "tag": "KEY", "value": "rhfvFTgpPzCvFPgbA9Nvz42mX92U5ak92m" }, { "context": "Wu',\r\n 'rhfvFTgpPzCvFPgbA9Nvz42mX92U5ak92m',\r\n 'rByT8y4BUX1Kcc6xotEabCgwc5PGsbTfSv',\r\n 'rPBrMbL7uGuteU", "end": 895, "score": 0.9296572208404541, "start": 890, "tag": "KEY", "value": "rByT8" }, { "context": " 'rhfvFTgpPzCvFPgbA9Nvz42mX92U5ak92m',\r\n 'rByT8y4BUX1Kcc6xotEabCgwc5PGsbTfSv',\r\n 'rPBrMbL7uGuteU49b2", "end": 899, "score": 0.7720686197280884, "start": 896, "tag": "KEY", "value": "4BU" }, { "context": "hfvFTgpPzCvFPgbA9Nvz42mX92U5ak92m',\r\n 'rByT8y4BUX1Kcc6xotEabCgwc5PGsbTfSv',\r\n 'rPBrMbL7uGuteU49b2ibc", "end": 902, "score": 0.6806035041809082, "start": 900, "tag": "KEY", "value": "1K" }, { "context": "TgpPzCvFPgbA9Nvz42mX92U5ak92m',\r\n 'rByT8y4BUX1Kcc6xotEabCgwc5PGsbTfSv',\r\n 'rPBrMbL7uGuteU49b2ibcEBS", "end": 905, "score": 0.8121638894081116, "start": 904, "tag": "KEY", "value": "6" }, { "context": "zCvFPgbA9Nvz42mX92U5ak92m',\r\n 'rByT8y4BUX1Kcc6xotEabCgwc5PGsbTfSv',\r\n 'rPBrMbL7uGuteU49b2ibcEBSztoWPX4srr',\r\n 'rQ", "end": 924, "score": 0.8356620669364929, "start": 908, "tag": "KEY", "value": "EabCgwc5PGsbTfSv" }, { "context": "2m',\r\n 'rByT8y4BUX1Kcc6xotEabCgwc5PGsbTfSv',\r\n 'rPBrMbL7uGuteU49b2ibcEBSztoWPX4srr',\r\n 'rQGRcZn2RyXJL", "end": 935, "score": 0.9199430346488953, "start": 931, "tag": "KEY", "value": "rPBr" }, { "context": " 'rByT8y4BUX1Kcc6xotEabCgwc5PGsbTfSv',\r\n 'rPBrMbL7uGuteU49b2ibcEBSztoWPX4srr',\r\n 'rQGRcZn2RyXJL3s7D", "end": 939, "score": 0.5461599826812744, "start": 938, "tag": "KEY", "value": "7" }, { "context": "ByT8y4BUX1Kcc6xotEabCgwc5PGsbTfSv',\r\n 'rPBrMbL7uGuteU49b2ibcEBSztoWPX4srr',\r\n 'rQGRcZn2RyXJL3s7Dfqqzc", "end": 944, "score": 0.507053792476654, "start": 941, "tag": "KEY", "value": "ute" }, { "context": "4BUX1Kcc6xotEabCgwc5PGsbTfSv',\r\n 'rPBrMbL7uGuteU49b2ibcEBSztoWPX4srr',\r\n 'rQGRcZn2RyXJL3s7Dfqqzc96J", "end": 947, "score": 0.6647648811340332, "start": 946, "tag": "KEY", "value": "9" }, { "context": "UX1Kcc6xotEabCgwc5PGsbTfSv',\r\n 'rPBrMbL7uGuteU49b2ibcEBSztoWPX4srr',\r\n 'rQGRcZn2RyXJL3s7Dfqqzc96Juc", "end": 949, "score": 0.5306880474090576, "start": 948, "tag": "KEY", "value": "2" }, { "context": "6xotEabCgwc5PGsbTfSv',\r\n 'rPBrMbL7uGuteU49b2ibcEBSztoWPX4srr',\r\n 'rQGRcZn2RyXJL3s7Dfqqzc96Juc7j9j6i9", "end": 956, "score": 0.6361820697784424, "start": 954, "tag": "KEY", "value": "Sz" }, { "context": "Sv',\r\n 'rPBrMbL7uGuteU49b2ibcEBSztoWPX4srr',\r\n 'rQGRcZn2RyXJL3s7Dfqqzc96Juc7j9j6i9',\r\n 'rwZrLewGghBMj", "end": 976, "score": 0.9489061236381531, "start": 972, "tag": "KEY", "value": "rQGR" }, { "context": "L7uGuteU49b2ibcEBSztoWPX4srr',\r\n 'rQGRcZn2RyXJL3s7Dfqqzc96Juc7j9j6i9',\r\n 'rwZrLewGghBMj29kFq7TPw9h9", "end": 988, "score": 0.6716052889823914, "start": 987, "tag": "KEY", "value": "7" }, { "context": "ibcEBSztoWPX4srr',\r\n 'rQGRcZn2RyXJL3s7Dfqqzc96Juc7j9j6i9',\r\n 'rwZrLewGghBMj29kFq7TPw9h9p5eAQ1LUp',\r", "end": 1000, "score": 0.6218053102493286, "start": 999, "tag": "KEY", "value": "7" }, { "context": "cEBSztoWPX4srr',\r\n 'rQGRcZn2RyXJL3s7Dfqqzc96Juc7j9j6i9',\r\n 'rwZrLewGghBMj29kFq7TPw9h9p5eAQ1LUp',\r\n ", "end": 1002, "score": 0.9011477828025818, "start": 1001, "tag": "KEY", "value": "9" }, { "context": "BSztoWPX4srr',\r\n 'rQGRcZn2RyXJL3s7Dfqqzc96Juc7j9j6i9',\r\n 'rwZrLewGghBMj29kFq7TPw9h9p5eAQ1LUp',\r\n '", "end": 1004, "score": 0.6070762276649475, "start": 1003, "tag": "KEY", "value": "6" }, { "context": "rr',\r\n 'rQGRcZn2RyXJL3s7Dfqqzc96Juc7j9j6i9',\r\n 'rwZrLewGghBMj29kFq7TPw9h9p5eAQ1LUp',\r\n 'rM9qHXk5uif", "end": 1015, "score": 0.9449054598808289, "start": 1013, "tag": "KEY", "value": "rw" }, { "context": "i9',\r\n 'rwZrLewGghBMj29kFq7TPw9h9p5eAQ1LUp',\r\n 'rM9qHXk5uifboWrpu9Wte6Gjzbe974nZ4z',\r\n 'rBt69hdwMeBgmAtM9Ywu", "end": 1065, "score": 0.9528589248657227, "start": 1054, "tag": "KEY", "value": "rM9qHXk5uif" }, { "context": "LewGghBMj29kFq7TPw9h9p5eAQ1LUp',\r\n 'rM9qHXk5uifboWrpu9Wte6Gjzbe974nZ4z',\r\n 'rBt69hdwMeBgmAtM9YwuFAKxjMqgaBLf3F',\r\n 'rH", "end": 1088, "score": 0.855185866355896, "start": 1067, "tag": "KEY", "value": "Wrpu9Wte6Gjzbe974nZ4z" }, { "context": "Up',\r\n 'rM9qHXk5uifboWrpu9Wte6Gjzbe974nZ4z',\r\n 'rBt69hdwMeBgmAtM9YwuFAKxjMqgaBLf3F',\r\n 'rHpcrpggafr5NNn7mafPhaeB8PMYKXGahp',\r\n 'rs", "end": 1129, "score": 0.9965474605560303, "start": 1095, "tag": "KEY", "value": "rBt69hdwMeBgmAtM9YwuFAKxjMqgaBLf3F" }, { "context": "4z',\r\n 'rBt69hdwMeBgmAtM9YwuFAKxjMqgaBLf3F',\r\n 'rHpcrpggafr5NNn7mafPhaeB8PMYKXGahp',\r\n 'rsMKP5MSoyve54o7LgwnZzFfGKzAK8SE5F',\r\n 'rf", "end": 1170, "score": 0.9978954195976257, "start": 1136, "tag": "KEY", "value": "rHpcrpggafr5NNn7mafPhaeB8PMYKXGahp" }, { "context": "3F',\r\n 'rHpcrpggafr5NNn7mafPhaeB8PMYKXGahp',\r\n 'rsMKP5MSoyve54o7LgwnZzFfGKzAK8SE5F',\r\n 'rfN3ccsNxPt41MjHNZRk7ek7q4TpPLqUzL',\r\n 'rD", "end": 1211, "score": 0.9982292056083679, "start": 1177, "tag": "KEY", "value": "rsMKP5MSoyve54o7LgwnZzFfGKzAK8SE5F" }, { "context": "hp',\r\n 'rsMKP5MSoyve54o7LgwnZzFfGKzAK8SE5F',\r\n 'rfN3ccsNxPt41MjHNZRk7ek7q4TpPLqUzL',\r\n 'rDRWocPjBdhKZSWZezbsnwNpALcJ6GqSGf',\r\n 'rs", "end": 1252, "score": 0.9989431500434875, "start": 1218, "tag": "KEY", "value": "rfN3ccsNxPt41MjHNZRk7ek7q4TpPLqUzL" }, { "context": "5F',\r\n 'rfN3ccsNxPt41MjHNZRk7ek7q4TpPLqUzL',\r\n 'rDRWocPjBdhKZSWZezbsnwNpALcJ6GqSGf',\r\n 'rsmJ4tEMWpcK2qcEMp9uoUv4Ht5Nd6cGTV',\r\n 'rs", "end": 1293, "score": 0.9985374212265015, "start": 1259, "tag": "KEY", "value": "rDRWocPjBdhKZSWZezbsnwNpALcJ6GqSGf" }, { "context": "zL',\r\n 'rDRWocPjBdhKZSWZezbsnwNpALcJ6GqSGf',\r\n 'rsmJ4tEMWpcK2qcEMp9uoUv4Ht5Nd6cGTV',\r\n 'rsxWsnMVRnFozrKJV2VZ1SG6UNbEeHYu16',\r\n 'r4", "end": 1334, "score": 0.9984280467033386, "start": 1300, "tag": "KEY", "value": "rsmJ4tEMWpcK2qcEMp9uoUv4Ht5Nd6cGTV" }, { "context": "Gf',\r\n 'rsmJ4tEMWpcK2qcEMp9uoUv4Ht5Nd6cGTV',\r\n 'rsxWsnMVRnFozrKJV2VZ1SG6UNbEeHYu16',\r\n 'r4KoiD6MpaQNPzBka3FRLREkx6EZFwynY4',\r\n 'rU", "end": 1375, "score": 0.9985606670379639, "start": 1341, "tag": "KEY", "value": "rsxWsnMVRnFozrKJV2VZ1SG6UNbEeHYu16" }, { "context": "TV',\r\n 'rsxWsnMVRnFozrKJV2VZ1SG6UNbEeHYu16',\r\n 'r4KoiD6MpaQNPzBka3FRLREkx6EZFwynY4',\r\n 'rUdovjorVqxyemu5jbpfqA6DYDLdD4eYcj',\r\n 'r4", "end": 1416, "score": 0.9979286789894104, "start": 1382, "tag": "KEY", "value": "r4KoiD6MpaQNPzBka3FRLREkx6EZFwynY4" }, { "context": "16',\r\n 'r4KoiD6MpaQNPzBka3FRLREkx6EZFwynY4',\r\n 'rUdovjorVqxyemu5jbpfqA6DYDLdD4eYcj',\r\n 'r4MrNttmbdiJ7DjWh1MCKW3Kh7kfML46TA',\r\n 'rn", "end": 1457, "score": 0.9956750869750977, "start": 1423, "tag": "KEY", "value": "rUdovjorVqxyemu5jbpfqA6DYDLdD4eYcj" }, { "context": "Y4',\r\n 'rUdovjorVqxyemu5jbpfqA6DYDLdD4eYcj',\r\n 'r4MrNttmbdiJ7DjWh1MCKW3Kh7kfML46TA',\r\n 'rndYw73Btcm9Pv9gssZY1S9UcDUPLnpip7',\r\n 'rh", "end": 1498, "score": 0.9963156580924988, "start": 1464, "tag": "KEY", "value": "r4MrNttmbdiJ7DjWh1MCKW3Kh7kfML46TA" }, { "context": "cj',\r\n 'r4MrNttmbdiJ7DjWh1MCKW3Kh7kfML46TA',\r\n 'rndYw73Btcm9Pv9gssZY1S9UcDUPLnpip7',\r\n 'rh8MnoZmAeWyLx7X8bJZqyjZ48mv1og5PS',\r\n 'rB", "end": 1539, "score": 0.9931647777557373, "start": 1505, "tag": "KEY", "value": "rndYw73Btcm9Pv9gssZY1S9UcDUPLnpip7" }, { "context": "TA',\r\n 'rndYw73Btcm9Pv9gssZY1S9UcDUPLnpip7',\r\n 'rh8MnoZmAeWyLx7X8bJZqyjZ48mv1og5PS',\r\n 'rBoJvU7pcvoy5hjDMMTDNVG4YG85Ed3MEq',\r\n 'rs", "end": 1580, "score": 0.9940463900566101, "start": 1546, "tag": "KEY", "value": "rh8MnoZmAeWyLx7X8bJZqyjZ48mv1og5PS" }, { "context": "p7',\r\n 'rh8MnoZmAeWyLx7X8bJZqyjZ48mv1og5PS',\r\n 'rBoJvU7pcvoy5hjDMMTDNVG4YG85Ed3MEq',\r\n 'rs4f1BwdNgXAHWLT8rZgW2T1RKSBNY4iDz',\r\n ", "end": 1618, "score": 0.9783734083175659, "start": 1587, "tag": "KEY", "value": "rBoJvU7pcvoy5hjDMMTDNVG4YG85Ed3" }, { "context": "48mv1og5PS',\r\n 'rBoJvU7pcvoy5hjDMMTDNVG4YG85Ed3MEq',\r\n 'rs4f1BwdNgXAHWLT8rZgW2T1RKSBNY4iDz',\r\n 'rE", "end": 1621, "score": 0.9883859753608704, "start": 1620, "tag": "KEY", "value": "q" }, { "context": "PS',\r\n 'rBoJvU7pcvoy5hjDMMTDNVG4YG85Ed3MEq',\r\n 'rs4f1BwdNgXAHWLT8rZgW2T1RKSBNY4iDz',\r\n 'rEmhxShqw42EPm7bY7df5uQySZBkQWnqae',\r\n 'rN", "end": 1662, "score": 0.9859188199043274, "start": 1628, "tag": "KEY", "value": "rs4f1BwdNgXAHWLT8rZgW2T1RKSBNY4iDz" }, { "context": "Eq',\r\n 'rs4f1BwdNgXAHWLT8rZgW2T1RKSBNY4iDz',\r\n 'rEmhxShqw42EPm7bY7df5uQySZBkQWnqae',\r\n 'rNerRdGnbZP6wej22z", "end": 1678, "score": 0.7677780985832214, "start": 1669, "tag": "KEY", "value": "rEmhxShqw" }, { "context": "BwdNgXAHWLT8rZgW2T1RKSBNY4iDz',\r\n 'rEmhxShqw42EPm7bY7df5uQySZBkQWnqae',\r\n 'rNerRdGnbZP6wej22zBdoTUf", "end": 1684, "score": 0.5919841527938843, "start": 1683, "tag": "KEY", "value": "7" }, { "context": "dNgXAHWLT8rZgW2T1RKSBNY4iDz',\r\n 'rEmhxShqw42EPm7bY7df5uQySZBkQWnqae',\r\n 'rNerRdGnbZP6wej22zBdoTUfQKW", "end": 1687, "score": 0.7425919771194458, "start": 1685, "tag": "KEY", "value": "Y7" }, { "context": "AHWLT8rZgW2T1RKSBNY4iDz',\r\n 'rEmhxShqw42EPm7bY7df5uQySZBkQWnqae',\r\n 'rNerRdGnbZP6wej22zBdoTUfQKWoMD", "end": 1690, "score": 0.807251513004303, "start": 1689, "tag": "KEY", "value": "5" }, { "context": "T8rZgW2T1RKSBNY4iDz',\r\n 'rEmhxShqw42EPm7bY7df5uQySZBkQWnqae',\r\n 'rNerRdGnbZP6wej22zBdoTUfQKWoMDTH7d',\r\n '", "end": 1701, "score": 0.797387421131134, "start": 1693, "tag": "KEY", "value": "SZBkQWnq" }, { "context": "Dz',\r\n 'rEmhxShqw42EPm7bY7df5uQySZBkQWnqae',\r\n 'rNerRdGnbZP6wej22zBdoTUfQKWoMDTH7d',\r\n 'rDyXvd2WFALJovh7", "end": 1717, "score": 0.7369474172592163, "start": 1710, "tag": "KEY", "value": "rNerRdG" }, { "context": "w42EPm7bY7df5uQySZBkQWnqae',\r\n 'rNerRdGnbZP6wej22zBdoTUfQKWoMDTH7d',\r\n 'rDyXvd2WFALJovh76uLe5kUrJ7Q", "end": 1728, "score": 0.7710205316543579, "start": 1727, "tag": "KEY", "value": "z" }, { "context": "Pm7bY7df5uQySZBkQWnqae',\r\n 'rNerRdGnbZP6wej22zBdoTUfQKWoMDTH7d',\r\n 'rDyXvd2WFALJovh76uLe5kUrJ7QLpgmQ", "end": 1733, "score": 0.6713210344314575, "start": 1731, "tag": "KEY", "value": "TU" }, { "context": "bY7df5uQySZBkQWnqae',\r\n 'rNerRdGnbZP6wej22zBdoTUfQKWoMDTH7d',\r\n 'rDyXvd2WFALJovh76uLe5kUrJ7QLpgmQYE',", "end": 1737, "score": 0.7289816737174988, "start": 1734, "tag": "KEY", "value": "QKW" }, { "context": "f5uQySZBkQWnqae',\r\n 'rNerRdGnbZP6wej22zBdoTUfQKWoMDTH7d',\r\n 'rDyXvd2WFALJovh76uLe5kUrJ7QLpgmQYE',\r\n '", "end": 1742, "score": 0.7330747842788696, "start": 1738, "tag": "KEY", "value": "MDTH" }, { "context": "ae',\r\n 'rNerRdGnbZP6wej22zBdoTUfQKWoMDTH7d',\r\n 'rDyXvd2WFALJovh76uLe5kUrJ7QLpgmQYE',\r\n 'rUVi1L28AsCv", "end": 1754, "score": 0.7538402080535889, "start": 1751, "tag": "KEY", "value": "rDy" }, { "context": "7d',\r\n 'rDyXvd2WFALJovh76uLe5kUrJ7QLpgmQYE',\r\n 'rUVi1L28AsCvieXP5pMqPHA9WAfsvCDUjU',\r\n 'rscuoJN9um2V", "end": 1795, "score": 0.862030029296875, "start": 1792, "tag": "KEY", "value": "rUV" }, { "context": "YE',\r\n 'rUVi1L28AsCvieXP5pMqPHA9WAfsvCDUjU',\r\n 'rscuoJN9um2VM4xVv386X5T9APtExFKsbB',\r\n 'raeeyPs6g5xQn5jyNQbC", "end": 1844, "score": 0.7787284255027771, "start": 1833, "tag": "KEY", "value": "rscuoJN9um2" }, { "context": "1L28AsCvieXP5pMqPHA9WAfsvCDUjU',\r\n 'rscuoJN9um2VM4xVv386X5T9APtExFKsbB',\r\n 'raeeyPs6g5xQn5jyNQbCZ6Q", "end": 1847, "score": 0.6289129853248596, "start": 1846, "tag": "KEY", "value": "4" }, { "context": "AsCvieXP5pMqPHA9WAfsvCDUjU',\r\n 'rscuoJN9um2VM4xVv386X5T9APtExFKsbB',\r\n 'raeeyPs6g5xQn5jyNQbCZ6QeLrqu3", "end": 1853, "score": 0.8280591368675232, "start": 1850, "tag": "KEY", "value": "386" }, { "context": "ieXP5pMqPHA9WAfsvCDUjU',\r\n 'rscuoJN9um2VM4xVv386X5T9APtExFKsbB',\r\n 'raeeyPs6g5xQn5jyNQbCZ6QeLrqu3Fr", "end": 1855, "score": 0.8345587253570557, "start": 1854, "tag": "KEY", "value": "5" }, { "context": "XP5pMqPHA9WAfsvCDUjU',\r\n 'rscuoJN9um2VM4xVv386X5T9APtExFKsbB',\r\n 'raeeyPs6g5xQn5jyNQbCZ6QeLrqu3FrFvb'", "end": 1859, "score": 0.7055884003639221, "start": 1856, "tag": "KEY", "value": "9AP" }, { "context": "MqPHA9WAfsvCDUjU',\r\n 'rscuoJN9um2VM4xVv386X5T9APtExFKsbB',\r\n 'raeeyPs6g5xQn5jyNQbCZ6QeLrqu3FrFvb',\r\n ", "end": 1864, "score": 0.8409957885742188, "start": 1860, "tag": "KEY", "value": "ExFK" }, { "context": "jU',\r\n 'rscuoJN9um2VM4xVv386X5T9APtExFKsbB',\r\n 'raeeyPs6g5xQn5jyNQbCZ6QeLrqu3FrFvb',\r\n 'r9UqovJD979WTfNEWXxDU2CVj3K1yo2mqG',\r\n 'rf", "end": 1908, "score": 0.9890401363372803, "start": 1874, "tag": "KEY", "value": "raeeyPs6g5xQn5jyNQbCZ6QeLrqu3FrFvb" }, { "context": "bB',\r\n 'raeeyPs6g5xQn5jyNQbCZ6QeLrqu3FrFvb',\r\n 'r9UqovJD979WTfNEWXxDU2CVj3K1yo2mqG',\r\n 'rfRjsAqM1MEuSbWzuLcD6EhSZazgqvZSjy',\r\n 'rU", "end": 1949, "score": 0.9991599917411804, "start": 1915, "tag": "KEY", "value": "r9UqovJD979WTfNEWXxDU2CVj3K1yo2mqG" }, { "context": "vb',\r\n 'r9UqovJD979WTfNEWXxDU2CVj3K1yo2mqG',\r\n 'rfRjsAqM1MEuSbWzuLcD6EhSZazgqvZSjy',\r\n 'rUL4CAxmfpNqDXsQTPCK9ZJ8zHqhUvDWfw',\r\n 'rP", "end": 1990, "score": 0.9991037249565125, "start": 1956, "tag": "KEY", "value": "rfRjsAqM1MEuSbWzuLcD6EhSZazgqvZSjy" }, { "context": "qG',\r\n 'rfRjsAqM1MEuSbWzuLcD6EhSZazgqvZSjy',\r\n 'rUL4CAxmfpNqDXsQTPCK9ZJ8zHqhUvDWfw',\r\n 'rP6ZRDFZxjQqeAgdBh1YQSQjWNSASpCL7N',\r\n 'rs", "end": 2031, "score": 0.9990684986114502, "start": 1997, "tag": "KEY", "value": "rUL4CAxmfpNqDXsQTPCK9ZJ8zHqhUvDWfw" }, { "context": "jy',\r\n 'rUL4CAxmfpNqDXsQTPCK9ZJ8zHqhUvDWfw',\r\n 'rP6ZRDFZxjQqeAgdBh1YQSQjWNSASpCL7N',\r\n 'rsV4AtAqsdyRyZ8s4kaWbM21EPwY5fonx5',\r\n 'rH", "end": 2072, "score": 0.9989792108535767, "start": 2038, "tag": "KEY", "value": "rP6ZRDFZxjQqeAgdBh1YQSQjWNSASpCL7N" }, { "context": "fw',\r\n 'rP6ZRDFZxjQqeAgdBh1YQSQjWNSASpCL7N',\r\n 'rsV4AtAqsdyRyZ8s4kaWbM21EPwY5fonx5',\r\n 'rHaKEMyJErGY6VaKuTj16fSheTp4BRpWG1',\r\n 'rE", "end": 2113, "score": 0.9974037408828735, "start": 2079, "tag": "KEY", "value": "rsV4AtAqsdyRyZ8s4kaWbM21EPwY5fonx5" }, { "context": "7N',\r\n 'rsV4AtAqsdyRyZ8s4kaWbM21EPwY5fonx5',\r\n 'rHaKEMyJErGY6VaKuTj16fSheTp4BRpWG1',\r\n 'rELHJtahsRpSiSj1nfkY5yKRHCCyRgynw4',\r\n 'rL", "end": 2154, "score": 0.9979190826416016, "start": 2120, "tag": "KEY", "value": "rHaKEMyJErGY6VaKuTj16fSheTp4BRpWG1" }, { "context": "x5',\r\n 'rHaKEMyJErGY6VaKuTj16fSheTp4BRpWG1',\r\n 'rELHJtahsRpSiSj1nfkY5yKRHCCyRgynw4',\r\n 'rLYtaGnw4xK86J6mTsLfayyREoYaPPr8Cj',\r\n 'rD", "end": 2195, "score": 0.9986379742622375, "start": 2161, "tag": "KEY", "value": "rELHJtahsRpSiSj1nfkY5yKRHCCyRgynw4" }, { "context": "G1',\r\n 'rELHJtahsRpSiSj1nfkY5yKRHCCyRgynw4',\r\n 'rLYtaGnw4xK86J6mTsLfayyREoYaPPr8Cj',\r\n 'rD5pAYUfZypmJRSrJnBy3pYo5ApHqw5Jt5',\r\n 'rf", "end": 2236, "score": 0.9985222220420837, "start": 2202, "tag": "KEY", "value": "rLYtaGnw4xK86J6mTsLfayyREoYaPPr8Cj" }, { "context": "w4',\r\n 'rLYtaGnw4xK86J6mTsLfayyREoYaPPr8Cj',\r\n 'rD5pAYUfZypmJRSrJnBy3pYo5ApHqw5Jt5',\r\n 'rfYQrqwNXoA8e2gBDmiHAJAMYrASdQvqDm',\r\n 'rE", "end": 2277, "score": 0.9984771609306335, "start": 2243, "tag": "KEY", "value": "rD5pAYUfZypmJRSrJnBy3pYo5ApHqw5Jt5" }, { "context": "Cj',\r\n 'rD5pAYUfZypmJRSrJnBy3pYo5ApHqw5Jt5',\r\n 'rfYQrqwNXoA8e2gBDmiHAJAMYrASdQvqDm',\r\n 'rESt1CB9Sqaj8PYj8SV9x76iwMGBFPzLHb',\r\n 'rH", "end": 2318, "score": 0.9986671209335327, "start": 2284, "tag": "KEY", "value": "rfYQrqwNXoA8e2gBDmiHAJAMYrASdQvqDm" }, { "context": "t5',\r\n 'rfYQrqwNXoA8e2gBDmiHAJAMYrASdQvqDm',\r\n 'rESt1CB9Sqaj8PYj8SV9x76iwMGBFPzLHb',\r\n 'rHZWAXh3NdQbyksKzDRLeP9ui32TcqssHZ',\r\n 'rK", "end": 2359, "score": 0.9807478785514832, "start": 2325, "tag": "KEY", "value": "rESt1CB9Sqaj8PYj8SV9x76iwMGBFPzLHb" }, { "context": "Dm',\r\n 'rESt1CB9Sqaj8PYj8SV9x76iwMGBFPzLHb',\r\n 'rHZWAXh3NdQbyksKzDRLeP9ui32TcqssHZ',\r\n 'rK9iNjw5SozqKj5zNervwQQTLAgu8V81", "end": 2389, "score": 0.9169917702674866, "start": 2366, "tag": "KEY", "value": "rHZWAXh3NdQbyksKzDRLeP9" }, { "context": "8SV9x76iwMGBFPzLHb',\r\n 'rHZWAXh3NdQbyksKzDRLeP9ui32TcqssHZ',\r\n 'rK9iNjw5SozqKj5zNervwQQTLAgu8V813j',\r\n 'rU", "end": 2400, "score": 0.9724783897399902, "start": 2391, "tag": "KEY", "value": "32TcqssHZ" }, { "context": "Hb',\r\n 'rHZWAXh3NdQbyksKzDRLeP9ui32TcqssHZ',\r\n 'rK9iNjw5SozqKj5zNervwQQTLAgu8V813j',\r\n 'rUjpFBSmZ8F6cP16VxqpdAXCVCW3", "end": 2426, "score": 0.9907620549201965, "start": 2407, "tag": "KEY", "value": "rK9iNjw5SozqKj5zNer" }, { "context": "yksKzDRLeP9ui32TcqssHZ',\r\n 'rK9iNjw5SozqKj5zNervwQQTLAgu8V813j',\r\n 'rUjpFBSmZ8F6cP16VxqpdAXCVCW3rBSZyn',\r\n 'ra", "end": 2441, "score": 0.9699087142944336, "start": 2428, "tag": "KEY", "value": "QQTLAgu8V813j" }, { "context": "HZ',\r\n 'rK9iNjw5SozqKj5zNervwQQTLAgu8V813j',\r\n 'rUjpFBSmZ8F6cP16VxqpdAXCVCW3rBSZyn',\r\n 'raPib2vNQAjhh47fVQ7PswKaX1daNBSs2G',\r\n 'rw", "end": 2482, "score": 0.9660024642944336, "start": 2448, "tag": "KEY", "value": "rUjpFBSmZ8F6cP16VxqpdAXCVCW3rBSZyn" }, { "context": "3j',\r\n 'rUjpFBSmZ8F6cP16VxqpdAXCVCW3rBSZyn',\r\n 'raPib2vNQAjhh47fVQ7PswKaX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWd", "end": 2496, "score": 0.7069422602653503, "start": 2489, "tag": "KEY", "value": "raPib2v" }, { "context": "'rUjpFBSmZ8F6cP16VxqpdAXCVCW3rBSZyn',\r\n 'raPib2vNQAjhh47fVQ7PswKaX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWdxs7", "end": 2499, "score": 0.6851196885108948, "start": 2497, "tag": "KEY", "value": "QA" }, { "context": "FBSmZ8F6cP16VxqpdAXCVCW3rBSZyn',\r\n 'raPib2vNQAjhh47fVQ7PswKaX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWdxs7TLLW9", "end": 2504, "score": 0.6819065809249878, "start": 2502, "tag": "KEY", "value": "47" }, { "context": "mZ8F6cP16VxqpdAXCVCW3rBSZyn',\r\n 'raPib2vNQAjhh47fVQ7PswKaX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWdxs7TLLW9UDV", "end": 2507, "score": 0.6217123866081238, "start": 2505, "tag": "KEY", "value": "VQ" }, { "context": "P16VxqpdAXCVCW3rBSZyn',\r\n 'raPib2vNQAjhh47fVQ7PswKaX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWdxs7TLLW9UDVztFbw9", "end": 2513, "score": 0.7239921689033508, "start": 2511, "tag": "KEY", "value": "Ka" }, { "context": "xqpdAXCVCW3rBSZyn',\r\n 'raPib2vNQAjhh47fVQ7PswKaX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWdxs7TLLW9UDVztFbw9z',\r\n ", "end": 2520, "score": 0.8491716384887695, "start": 2515, "tag": "KEY", "value": "daNBS" }, { "context": "CVCW3rBSZyn',\r\n 'raPib2vNQAjhh47fVQ7PswKaX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWdxs7TLLW9UDVztFbw9z',\r\n 'r", "end": 2522, "score": 0.6291267275810242, "start": 2521, "tag": "KEY", "value": "2" }, { "context": "yn',\r\n 'raPib2vNQAjhh47fVQ7PswKaX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWdxs7TLLW9UDVztFbw9z',\r\n 'rJYRe27KXWTjs4P", "end": 2536, "score": 0.838088870048523, "start": 2530, "tag": "KEY", "value": "rwhuqz" }, { "context": "hh47fVQ7PswKaX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWdxs7TLLW9UDVztFbw9z',\r\n 'rJYRe27KXWTjs4P3uu1d4x58Pk5Y13D", "end": 2552, "score": 0.6715580224990845, "start": 2550, "tag": "KEY", "value": "LL" }, { "context": "7fVQ7PswKaX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWdxs7TLLW9UDVztFbw9z',\r\n 'rJYRe27KXWTjs4P3uu1d4x58Pk5Y13DbUg'", "end": 2556, "score": 0.723774790763855, "start": 2553, "tag": "KEY", "value": "9UD" }, { "context": "7PswKaX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWdxs7TLLW9UDVztFbw9z',\r\n 'rJYRe27KXWTjs4P3uu1d4x58Pk5Y13DbUg',\r\n ", "end": 2560, "score": 0.6156514286994934, "start": 2557, "tag": "KEY", "value": "ztF" }, { "context": "aX1daNBSs2G',\r\n 'rwhuqz7FppLNvLWdxs7TLLW9UDVztFbw9z',\r\n 'rJYRe27KXWTjs4P3uu1d4x58Pk5Y13DbUg',\r\n 'rL", "end": 2564, "score": 0.8557708263397217, "start": 2562, "tag": "KEY", "value": "9z" }, { "context": "2G',\r\n 'rwhuqz7FppLNvLWdxs7TLLW9UDVztFbw9z',\r\n 'rJYRe27KXWTjs4P3uu1d4x58Pk5Y13DbUg',\r\n 'rLFxCuE2GHq3", "end": 2574, "score": 0.9290972948074341, "start": 2571, "tag": "KEY", "value": "rJY" }, { "context": "dxs7TLLW9UDVztFbw9z',\r\n 'rJYRe27KXWTjs4P3uu1d4x58Pk5Y13DbUg',\r\n 'rLFxCuE2GHq38wFUHpswgHJAcz6EUhPimC',\r", "end": 2599, "score": 0.6201870441436768, "start": 2595, "tag": "KEY", "value": "Pk5Y" }, { "context": "9z',\r\n 'rJYRe27KXWTjs4P3uu1d4x58Pk5Y13DbUg',\r\n 'rLFxCuE2GHq38wFUHpswgHJAcz6EUhPimC',\r\n 'rAaQrzi5sats", "end": 2615, "score": 0.841123104095459, "start": 2612, "tag": "KEY", "value": "rLF" }, { "context": "Ug',\r\n 'rLFxCuE2GHq38wFUHpswgHJAcz6EUhPimC',\r\n 'rAaQrzi5satsth174EogwdtdxLZRW5n1h',\r\n 'rB18Rxdv1aPYtf9", "end": 2658, "score": 0.832953155040741, "start": 2653, "tag": "KEY", "value": "rAaQr" }, { "context": " 'rLFxCuE2GHq38wFUHpswgHJAcz6EUhPimC',\r\n 'rAaQrzi5satsth174EogwdtdxLZRW5n1h',\r\n 'rB18Rxdv1aPYtf9nDFpNP", "end": 2664, "score": 0.6312798857688904, "start": 2660, "tag": "KEY", "value": "5sat" }, { "context": "uE2GHq38wFUHpswgHJAcz6EUhPimC',\r\n 'rAaQrzi5satsth174EogwdtdxLZRW5n1h',\r\n 'rB18Rxdv1aPYtf9nDFpNPJ2HA5BBAq", "end": 2673, "score": 0.7375891208648682, "start": 2667, "tag": "KEY", "value": "174Eog" }, { "context": "HpswgHJAcz6EUhPimC',\r\n 'rAaQrzi5satsth174EogwdtdxLZRW5n1h',\r\n 'rB18Rxdv1aPYtf9nDFpNPJ2HA5BBAqmyoG',\r\n ", "end": 2683, "score": 0.8781326413154602, "start": 2678, "tag": "KEY", "value": "LZRW5" }, { "context": "JAcz6EUhPimC',\r\n 'rAaQrzi5satsth174EogwdtdxLZRW5n1h',\r\n 'rB18Rxdv1aPYtf9nDFpNPJ2HA5BBAqmyoG',\r\n 'r", "end": 2685, "score": 0.8120996356010437, "start": 2684, "tag": "KEY", "value": "1" }, { "context": "imC',\r\n 'rAaQrzi5satsth174EogwdtdxLZRW5n1h',\r\n 'rB18Rxdv1aPYtf9nDFpNPJ2HA5BBAqmyoG',\r\n 'rDSaTM6nCSrc1vH8pPcTAwQpmvb9Y6M2gw',\r\n 'rp", "end": 2727, "score": 0.9908270239830017, "start": 2693, "tag": "KEY", "value": "rB18Rxdv1aPYtf9nDFpNPJ2HA5BBAqmyoG" }, { "context": "1h',\r\n 'rB18Rxdv1aPYtf9nDFpNPJ2HA5BBAqmyoG',\r\n 'rDSaTM6nCSrc1vH8pPcTAwQpmvb9Y6M2gw',\r\n 'rpmeCBJUpp9ij1nRM23tRGesWjY7chSHqs',\r\n 'rw", "end": 2768, "score": 0.9986387491226196, "start": 2734, "tag": "KEY", "value": "rDSaTM6nCSrc1vH8pPcTAwQpmvb9Y6M2gw" }, { "context": "oG',\r\n 'rDSaTM6nCSrc1vH8pPcTAwQpmvb9Y6M2gw',\r\n 'rpmeCBJUpp9ij1nRM23tRGesWjY7chSHqs',\r\n 'rwQz7ZkCGdQt7iiuWC3EpbbKwWdL7uLT9C',\r\n 'rU", "end": 2809, "score": 0.9985753297805786, "start": 2775, "tag": "KEY", "value": "rpmeCBJUpp9ij1nRM23tRGesWjY7chSHqs" }, { "context": "gw',\r\n 'rpmeCBJUpp9ij1nRM23tRGesWjY7chSHqs',\r\n 'rwQz7ZkCGdQt7iiuWC3EpbbKwWdL7uLT9C',\r\n 'rULwRizwxjBwDjcaA44Tbh9MjM5TZFTcLj',\r\n 'rG", "end": 2850, "score": 0.9990338683128357, "start": 2816, "tag": "KEY", "value": "rwQz7ZkCGdQt7iiuWC3EpbbKwWdL7uLT9C" }, { "context": "qs',\r\n 'rwQz7ZkCGdQt7iiuWC3EpbbKwWdL7uLT9C',\r\n 'rULwRizwxjBwDjcaA44Tbh9MjM5TZFTcLj',\r\n 'rGMZBEGHbSoegfvqXC2ajXe7RM2Z1LK65N',\r\n 'rG", "end": 2891, "score": 0.9986165165901184, "start": 2857, "tag": "KEY", "value": "rULwRizwxjBwDjcaA44Tbh9MjM5TZFTcLj" }, { "context": "9C',\r\n 'rULwRizwxjBwDjcaA44Tbh9MjM5TZFTcLj',\r\n 'rGMZBEGHbSoegfvqXC2ajXe7RM2Z1LK65N',\r\n 'rGyFSppE8G7cELAdBU5yL7kWodbw29YdpN',\r\n 'rJ", "end": 2932, "score": 0.996035099029541, "start": 2898, "tag": "KEY", "value": "rGMZBEGHbSoegfvqXC2ajXe7RM2Z1LK65N" }, { "context": "Lj',\r\n 'rGMZBEGHbSoegfvqXC2ajXe7RM2Z1LK65N',\r\n 'rGyFSppE8G7cELAdBU5yL7kWodbw29YdpN',\r\n 'rJYN3qZsjWhH6bzXX6ZHMZewkMPHeEyGNb',\r\n 'rE", "end": 2973, "score": 0.995420515537262, "start": 2939, "tag": "KEY", "value": "rGyFSppE8G7cELAdBU5yL7kWodbw29YdpN" }, { "context": "5N',\r\n 'rGyFSppE8G7cELAdBU5yL7kWodbw29YdpN',\r\n 'rJYN3qZsjWhH6bzXX6ZHMZewkMPHeEyGNb',\r\n 'rEgZVpVSs75eEh6KM4HvcvG64p2TZBL4DC',\r\n 'rB", "end": 3014, "score": 0.9956660866737366, "start": 2980, "tag": "KEY", "value": "rJYN3qZsjWhH6bzXX6ZHMZewkMPHeEyGNb" }, { "context": "pN',\r\n 'rJYN3qZsjWhH6bzXX6ZHMZewkMPHeEyGNb',\r\n 'rEgZVpVSs75eEh6KM4HvcvG64p2TZBL4DC',\r\n 'rBRfZaqSAkXZYQWBfoy4sN2Q7zZHVGiGwU',\r\n 'rw", "end": 3055, "score": 0.9949315190315247, "start": 3021, "tag": "KEY", "value": "rEgZVpVSs75eEh6KM4HvcvG64p2TZBL4DC" }, { "context": "Nb',\r\n 'rEgZVpVSs75eEh6KM4HvcvG64p2TZBL4DC',\r\n 'rBRfZaqSAkXZYQWBfoy4sN2Q7zZHVGiGwU',\r\n 'rwg1DRGXLTzQpoWtS35mDowN4PSFQ732eQ',\r\n 'rK", "end": 3096, "score": 0.9896430969238281, "start": 3062, "tag": "KEY", "value": "rBRfZaqSAkXZYQWBfoy4sN2Q7zZHVGiGwU" }, { "context": "DC',\r\n 'rBRfZaqSAkXZYQWBfoy4sN2Q7zZHVGiGwU',\r\n 'rwg1DRGXLTzQpoWtS35mDowN4PSFQ732eQ',\r\n 'rKZvkY3T6ahhqkWLTQDSdB1MTKFbbnkqBX',\r\n 'rG", "end": 3137, "score": 0.9854216575622559, "start": 3103, "tag": "KEY", "value": "rwg1DRGXLTzQpoWtS35mDowN4PSFQ732eQ" }, { "context": "wU',\r\n 'rwg1DRGXLTzQpoWtS35mDowN4PSFQ732eQ',\r\n 'rKZvkY3T6ahhqkWLTQDSdB1MTKFbbnkqBX',\r\n 'rGXgpwvaAZ7rBmoSKFUrd83N7WN3Lm4vuX',\r\n 'rh", "end": 3178, "score": 0.9788779616355896, "start": 3144, "tag": "KEY", "value": "rKZvkY3T6ahhqkWLTQDSdB1MTKFbbnkqBX" }, { "context": "eQ',\r\n 'rKZvkY3T6ahhqkWLTQDSdB1MTKFbbnkqBX',\r\n 'rGXgpwvaAZ7rBmoSKFUrd83N7WN3Lm4vuX',\r\n 'rhCMsQ3SJa5Wb4AvBe27hxBQaQQjDG1LG4',\r", "end": 3213, "score": 0.9774401783943176, "start": 3185, "tag": "KEY", "value": "rGXgpwvaAZ7rBmoSKFUrd83N7WN3" }, { "context": "B1MTKFbbnkqBX',\r\n 'rGXgpwvaAZ7rBmoSKFUrd83N7WN3Lm4vuX',\r\n 'rhCMsQ3SJa5Wb4AvBe27hxBQaQQjDG1LG4',\r\n 'rN", "end": 3219, "score": 0.9682453274726868, "start": 3215, "tag": "KEY", "value": "4vuX" }, { "context": "BX',\r\n 'rGXgpwvaAZ7rBmoSKFUrd83N7WN3Lm4vuX',\r\n 'rhCMsQ3SJa5Wb4AvBe27hxBQaQQjDG1LG4',\r\n 'rNtvcU3ePYpZnuYKG77pjRxtKJJ1yrutbm',\r\n 'rs", "end": 3260, "score": 0.9566220045089722, "start": 3226, "tag": "KEY", "value": "rhCMsQ3SJa5Wb4AvBe27hxBQaQQjDG1LG4" }, { "context": "uX',\r\n 'rhCMsQ3SJa5Wb4AvBe27hxBQaQQjDG1LG4',\r\n 'rNtvcU3ePYpZnuYKG77pjRxtKJJ1yrutbm',\r\n 'rsfK2cTikveA", "end": 3270, "score": 0.8581099510192871, "start": 3267, "tag": "KEY", "value": "rNt" }, { "context": " 'rhCMsQ3SJa5Wb4AvBe27hxBQaQQjDG1LG4',\r\n 'rNtvcU3ePYpZnuYKG77pjRxtKJJ1yrutbm',\r\n 'rsfK2cTikveAeyvS", "end": 3274, "score": 0.6218840479850769, "start": 3273, "tag": "KEY", "value": "3" }, { "context": "CMsQ3SJa5Wb4AvBe27hxBQaQQjDG1LG4',\r\n 'rNtvcU3ePYpZnuYKG77pjRxtKJJ1yrutbm',\r\n 'rsfK2cTikveAeyvSG8F62", "end": 3279, "score": 0.8390687108039856, "start": 3278, "tag": "KEY", "value": "Z" }, { "context": "a5Wb4AvBe27hxBQaQQjDG1LG4',\r\n 'rNtvcU3ePYpZnuYKG77pjRxtKJJ1yrutbm',\r\n 'rsfK2cTikveAeyvSG8F62c4VFUvZ", "end": 3286, "score": 0.6436218023300171, "start": 3285, "tag": "KEY", "value": "7" }, { "context": "b4AvBe27hxBQaQQjDG1LG4',\r\n 'rNtvcU3ePYpZnuYKG77pjRxtKJJ1yrutbm',\r\n 'rsfK2cTikveAeyvSG8F62c4VFUvZBsH", "end": 3289, "score": 0.530759871006012, "start": 3288, "tag": "KEY", "value": "R" }, { "context": "vBe27hxBQaQQjDG1LG4',\r\n 'rNtvcU3ePYpZnuYKG77pjRxtKJJ1yrutbm',\r\n 'rsfK2cTikveAeyvSG8F62c4VFUvZBsH5Rf',\r", "end": 3295, "score": 0.681896984577179, "start": 3291, "tag": "KEY", "value": "KJJ1" }, { "context": "xBQaQQjDG1LG4',\r\n 'rNtvcU3ePYpZnuYKG77pjRxtKJJ1yrutbm',\r\n 'rsfK2cTikveAeyvSG8F62c4VFUvZBsH5Rf',\r\n '", "end": 3299, "score": 0.5072938203811646, "start": 3297, "tag": "KEY", "value": "ut" }, { "context": "G4',\r\n 'rNtvcU3ePYpZnuYKG77pjRxtKJJ1yrutbm',\r\n 'rsfK2cTikveAeyvSG8F62c4VFUvZBsH5Rf',\r\n 'rJT2LrXe7hH", "end": 3310, "score": 0.7529332041740417, "start": 3308, "tag": "KEY", "value": "rs" }, { "context": ",\r\n 'rNtvcU3ePYpZnuYKG77pjRxtKJJ1yrutbm',\r\n 'rsfK2cTikveAeyvSG8F62c4VFUvZBsH5Rf',\r\n 'rJT2LrXe7hH1p", "end": 3312, "score": 0.507240891456604, "start": 3311, "tag": "KEY", "value": "K" }, { "context": "bm',\r\n 'rsfK2cTikveAeyvSG8F62c4VFUvZBsH5Rf',\r\n 'rJT2LrXe7hH1pMEnhEkCMznwtgKuYJS7uz',\r\n 'rE4Fi4GVjo9N", "end": 3352, "score": 0.8634179830551147, "start": 3349, "tag": "KEY", "value": "rJT" }, { "context": "Rf',\r\n 'rJT2LrXe7hH1pMEnhEkCMznwtgKuYJS7uz',\r\n 'rE4Fi4GVjo9NY2g6MtMbitjenUZ21zFoSG',\r\n 'rp39zV6AFPR", "end": 3392, "score": 0.7730003595352173, "start": 3390, "tag": "KEY", "value": "rE" }, { "context": "uz',\r\n 'rE4Fi4GVjo9NY2g6MtMbitjenUZ21zFoSG',\r\n 'rp39zV6AFPRJ7yrrL1PSPC1s3oKM2uv2iW',\r\n 'raCoTW3mhdK6WG", "end": 3436, "score": 0.9029352068901062, "start": 3431, "tag": "KEY", "value": "rp39z" }, { "context": " 'rE4Fi4GVjo9NY2g6MtMbitjenUZ21zFoSG',\r\n 'rp39zV6AFPRJ7yrrL1PSPC1s3oKM2uv2iW',\r\n 'raCoTW3mhdK6WGUZ", "end": 3438, "score": 0.6069113612174988, "start": 3437, "tag": "KEY", "value": "6" }, { "context": "SG',\r\n 'rp39zV6AFPRJ7yrrL1PSPC1s3oKM2uv2iW',\r\n 'raCoTW3mhdK6WGUZUSEuvbFM34CSGRRHut',\r\n 'rKZD9yCV7XAgKq3Rj3a5DmqHHkHBd3ZYao',\r\n 'rf", "end": 3506, "score": 0.9961996078491211, "start": 3472, "tag": "KEY", "value": "raCoTW3mhdK6WGUZUSEuvbFM34CSGRRHut" }, { "context": "iW',\r\n 'raCoTW3mhdK6WGUZUSEuvbFM34CSGRRHut',\r\n 'rKZD9yCV7XAgKq3Rj3a5DmqHHkHBd3ZYao',\r\n 'rfKtpLEQz8bGCVtQsEzD8cJKeo6AW6J2pD',\r\n 'rJ", "end": 3547, "score": 0.9991772770881653, "start": 3513, "tag": "KEY", "value": "rKZD9yCV7XAgKq3Rj3a5DmqHHkHBd3ZYao" }, { "context": "ut',\r\n 'rKZD9yCV7XAgKq3Rj3a5DmqHHkHBd3ZYao',\r\n 'rfKtpLEQz8bGCVtQsEzD8cJKeo6AW6J2pD',\r\n 'rJqNyWJ3rovwkWFdwPhCc6m3jpFogGzRr9',\r\n 'r4", "end": 3588, "score": 0.9991427659988403, "start": 3554, "tag": "KEY", "value": "rfKtpLEQz8bGCVtQsEzD8cJKeo6AW6J2pD" }, { "context": "ao',\r\n 'rfKtpLEQz8bGCVtQsEzD8cJKeo6AW6J2pD',\r\n 'rJqNyWJ3rovwkWFdwPhCc6m3jpFogGzRr9',\r\n 'r41fiShunXNNgJjTjqU9whsjnSYU1BXsjY',\r\n 'r3", "end": 3629, "score": 0.9990504384040833, "start": 3595, "tag": "KEY", "value": "rJqNyWJ3rovwkWFdwPhCc6m3jpFogGzRr9" }, { "context": "pD',\r\n 'rJqNyWJ3rovwkWFdwPhCc6m3jpFogGzRr9',\r\n 'r41fiShunXNNgJjTjqU9whsjnSYU1BXsjY',\r\n 'r3uHcWgsNwowCBGF5rhCP5dfdjpYmByBbJ',\r\n 'r4", "end": 3670, "score": 0.9991285800933838, "start": 3636, "tag": "KEY", "value": "r41fiShunXNNgJjTjqU9whsjnSYU1BXsjY" }, { "context": "r9',\r\n 'r41fiShunXNNgJjTjqU9whsjnSYU1BXsjY',\r\n 'r3uHcWgsNwowCBGF5rhCP5dfdjpYmByBbJ',\r\n 'r4GZm8WnwX5E9cr8uGiLX42y7KN2NaLqYn',\r\n 'rK", "end": 3711, "score": 0.9990419149398804, "start": 3677, "tag": "KEY", "value": "r3uHcWgsNwowCBGF5rhCP5dfdjpYmByBbJ" }, { "context": "jY',\r\n 'r3uHcWgsNwowCBGF5rhCP5dfdjpYmByBbJ',\r\n 'r4GZm8WnwX5E9cr8uGiLX42y7KN2NaLqYn',\r\n 'rKBVsMWErdH443FUkaT799CRVyY9XnVyCK',\r\n 'ra", "end": 3752, "score": 0.9986703395843506, "start": 3718, "tag": "KEY", "value": "r4GZm8WnwX5E9cr8uGiLX42y7KN2NaLqYn" }, { "context": "bJ',\r\n 'r4GZm8WnwX5E9cr8uGiLX42y7KN2NaLqYn',\r\n 'rKBVsMWErdH443FUkaT799CRVyY9XnVyCK',\r\n 'razu52accAWWHjxhWEHXNLHWCDhhs1L79p',\r\n 'rH", "end": 3793, "score": 0.9989616274833679, "start": 3759, "tag": "KEY", "value": "rKBVsMWErdH443FUkaT799CRVyY9XnVyCK" }, { "context": "Yn',\r\n 'rKBVsMWErdH443FUkaT799CRVyY9XnVyCK',\r\n 'razu52accAWWHjxhWEHXNLHWCDhhs1L79p',\r\n 'rHaL5e3niiikv6KJG4UARqpcjyD5tKNgyV',\r\n 'rM", "end": 3834, "score": 0.9988542199134827, "start": 3800, "tag": "KEY", "value": "razu52accAWWHjxhWEHXNLHWCDhhs1L79p" }, { "context": "CK',\r\n 'razu52accAWWHjxhWEHXNLHWCDhhs1L79p',\r\n 'rHaL5e3niiikv6KJG4UARqpcjyD5tKNgyV',\r\n 'rMfcPdGcB5y9zEYw91t3QG2Qj1Z7tqms3S',\r\n 'r3", "end": 3875, "score": 0.9983973503112793, "start": 3841, "tag": "KEY", "value": "rHaL5e3niiikv6KJG4UARqpcjyD5tKNgyV" }, { "context": "9p',\r\n 'rHaL5e3niiikv6KJG4UARqpcjyD5tKNgyV',\r\n 'rMfcPdGcB5y9zEYw91t3QG2Qj1Z7tqms3S',\r\n 'r3mqtPNiwkLKisvbnFjM9eC8Rm9JUEXLMD',\r\n 'rK", "end": 3916, "score": 0.9985145926475525, "start": 3882, "tag": "KEY", "value": "rMfcPdGcB5y9zEYw91t3QG2Qj1Z7tqms3S" }, { "context": "yV',\r\n 'rMfcPdGcB5y9zEYw91t3QG2Qj1Z7tqms3S',\r\n 'r3mqtPNiwkLKisvbnFjM9eC8Rm9JUEXLMD',\r\n 'rKJGLaJr5SFjZ43BkDeqW", "end": 3935, "score": 0.899065375328064, "start": 3923, "tag": "KEY", "value": "r3mqtPNiwkLK" }, { "context": "B5y9zEYw91t3QG2Qj1Z7tqms3S',\r\n 'r3mqtPNiwkLKisvbnFjM9eC8Rm9JUEXLMD',\r\n 'rKJGLaJr5SFjZ43BkDeqWKWAtGy1qAAkPf',\r\n 'rM", "end": 3957, "score": 0.967088520526886, "start": 3940, "tag": "KEY", "value": "FjM9eC8Rm9JUEXLMD" }, { "context": "3S',\r\n 'r3mqtPNiwkLKisvbnFjM9eC8Rm9JUEXLMD',\r\n 'rKJGLaJr5SFjZ43BkDeqWKWAtGy1qAAkPf',\r\n 'rM2zQeTDrt6sMM936Gxh", "end": 3975, "score": 0.8867058753967285, "start": 3964, "tag": "KEY", "value": "rKJGLaJr5SF" }, { "context": "qtPNiwkLKisvbnFjM9eC8Rm9JUEXLMD',\r\n 'rKJGLaJr5SFjZ43BkDeqWKWAtGy1qAAkPf',\r\n 'rM2zQeTDrt6sMM936Gxh26", "end": 3977, "score": 0.9885358214378357, "start": 3976, "tag": "KEY", "value": "Z" }, { "context": "PNiwkLKisvbnFjM9eC8Rm9JUEXLMD',\r\n 'rKJGLaJr5SFjZ43BkDeqWKWAtGy1qAAkPf',\r\n 'rM2zQeTDrt6sMM936Gxh263t1qx3", "end": 3983, "score": 0.6452248096466064, "start": 3978, "tag": "KEY", "value": "3BkDe" }, { "context": "KisvbnFjM9eC8Rm9JUEXLMD',\r\n 'rKJGLaJr5SFjZ43BkDeqWKWAtGy1qAAkPf',\r\n 'rM2zQeTDrt6sMM936Gxh263t1qx3hEb7XK',\r\n 'rG", "end": 3998, "score": 0.9574007391929626, "start": 3984, "tag": "KEY", "value": "WKWAtGy1qAAkPf" }, { "context": "MD',\r\n 'rKJGLaJr5SFjZ43BkDeqWKWAtGy1qAAkPf',\r\n 'rM2zQeTDrt6sMM936Gxh263t1qx3hEb7XK',\r\n 'rGtqoQJGe4zWenC3y", "end": 4013, "score": 0.8818346858024597, "start": 4005, "tag": "KEY", "value": "rM2zQeTD" }, { "context": "JGLaJr5SFjZ43BkDeqWKWAtGy1qAAkPf',\r\n 'rM2zQeTDrt6sMM936Gxh263t1qx3hEb7XK',\r\n 'rGtqoQJGe4zWenC3yWH9pByTAsGPcjmTU2',\r\n 'ra", "end": 4039, "score": 0.9351034164428711, "start": 4016, "tag": "KEY", "value": "sMM936Gxh263t1qx3hEb7XK" }, { "context": "Pf',\r\n 'rM2zQeTDrt6sMM936Gxh263t1qx3hEb7XK',\r\n 'rGtqoQJGe4zWenC3yWH9pByTAsGPcjmTU2',\r\n 'raNUsR5m8jsmb9o", "end": 4052, "score": 0.7427393198013306, "start": 4046, "tag": "KEY", "value": "rGtqoQ" }, { "context": "MM936Gxh263t1qx3hEb7XK',\r\n 'rGtqoQJGe4zWenC3yWH9pByTAsGPcjmTU2',\r\n 'raNUsR5m8jsmb9o9mpNZGGyV86aZUYPu", "end": 4069, "score": 0.5844328999519348, "start": 4067, "tag": "KEY", "value": "By" }, { "context": "36Gxh263t1qx3hEb7XK',\r\n 'rGtqoQJGe4zWenC3yWH9pByTAsGPcjmTU2',\r\n 'raNUsR5m8jsmb9o9mpNZGGyV86aZUYPunr',\r", "end": 4074, "score": 0.6603071689605713, "start": 4070, "tag": "KEY", "value": "AsGP" }, { "context": "3t1qx3hEb7XK',\r\n 'rGtqoQJGe4zWenC3yWH9pByTAsGPcjmTU2',\r\n 'raNUsR5m8jsmb9o9mpNZGGyV86aZUYPunr',\r\n 'r", "end": 4079, "score": 0.5303842425346375, "start": 4077, "tag": "KEY", "value": "TU" }, { "context": "XK',\r\n 'rGtqoQJGe4zWenC3yWH9pByTAsGPcjmTU2',\r\n 'raNUsR5m8jsmb9o9mpNZGGyV86aZUYPunr',\r\n 'rManQrKu85e", "end": 4089, "score": 0.8942919969558716, "start": 4087, "tag": "KEY", "value": "ra" }, { "context": "U2',\r\n 'raNUsR5m8jsmb9o9mpNZGGyV86aZUYPunr',\r\n 'rManQrKu85ezooZ11UmXbxejw5EYHqiUZm',\r\n 'rKrjCBtwnhQeY", "end": 4132, "score": 0.8944970965385437, "start": 4128, "tag": "KEY", "value": "rMan" }, { "context": "nr',\r\n 'rManQrKu85ezooZ11UmXbxejw5EYHqiUZm',\r\n 'rKrjCBtwnhQeYkJKrVjDA5CaR5W9NPN2Bb',\r\n 'rcwyaWqsvGXM", "end": 4172, "score": 0.9548355937004089, "start": 4169, "tag": "KEY", "value": "rKr" }, { "context": "\r\n 'rManQrKu85ezooZ11UmXbxejw5EYHqiUZm',\r\n 'rKrjCBtwnhQeYkJKrVjDA5CaR5W9NPN2Bb',\r\n 'rcwyaWqsvGXMRyV", "end": 4175, "score": 0.8923901915550232, "start": 4173, "tag": "KEY", "value": "CB" }, { "context": "ManQrKu85ezooZ11UmXbxejw5EYHqiUZm',\r\n 'rKrjCBtwnhQeYkJKrVjDA5CaR5W9NPN2Bb',\r\n 'rcwyaWqsvGXMRyVW2KHn", "end": 4180, "score": 0.5768052339553833, "start": 4179, "tag": "KEY", "value": "Q" }, { "context": "rKu85ezooZ11UmXbxejw5EYHqiUZm',\r\n 'rKrjCBtwnhQeYkJKrVjDA5CaR5W9NPN2Bb',\r\n 'rcwyaWqsvGXMRyVW2KHnGUV2M", "end": 4185, "score": 0.9063040018081665, "start": 4183, "tag": "KEY", "value": "JK" }, { "context": "1UmXbxejw5EYHqiUZm',\r\n 'rKrjCBtwnhQeYkJKrVjDA5CaR5W9NPN2Bb',\r\n 'rcwyaWqsvGXMRyVW2KHnGUV2MhJVhVx2p',\r\n", "end": 4197, "score": 0.7888765335083008, "start": 4194, "tag": "KEY", "value": "5W9" }, { "context": "Zm',\r\n 'rKrjCBtwnhQeYkJKrVjDA5CaR5W9NPN2Bb',\r\n 'rcwyaWqsvGXMRyVW2KHnGUV2MhJVhVx2p',\r\n 'rLozhAmzcwtEgr1", "end": 4215, "score": 0.8106667399406433, "start": 4210, "tag": "KEY", "value": "rcwya" }, { "context": "2Bb',\r\n 'rcwyaWqsvGXMRyVW2KHnGUV2MhJVhVx2p',\r\n 'rLozhAmzcwtEgr1bA28GUh2kbf5kFBMhph',\r\n 'rJqt8XVcGdpfjZmu", "end": 4257, "score": 0.9745804667472839, "start": 4250, "tag": "KEY", "value": "rLozhAm" }, { "context": "cwyaWqsvGXMRyVW2KHnGUV2MhJVhVx2p',\r\n 'rLozhAmzcwtEgr1bA28GUh2kbf5kFBMhph',\r\n 'rJqt8XVcGdpfjZmujoTc6", "end": 4262, "score": 0.9090825915336609, "start": 4261, "tag": "KEY", "value": "E" }, { "context": "aWqsvGXMRyVW2KHnGUV2MhJVhVx2p',\r\n 'rLozhAmzcwtEgr1bA28GUh2kbf5kFBMhph',\r\n 'rJqt8XVcGdpfjZmujoTc6ArH", "end": 4265, "score": 0.8924742937088013, "start": 4264, "tag": "KEY", "value": "1" }, { "context": "qsvGXMRyVW2KHnGUV2MhJVhVx2p',\r\n 'rLozhAmzcwtEgr1bA28GUh2kbf5kFBMhph',\r\n 'rJqt8XVcGdpfjZmujoTc6ArHQdZZVhADg", "end": 4274, "score": 0.9489796757698059, "start": 4266, "tag": "KEY", "value": "A28GUh2k" }, { "context": "2KHnGUV2MhJVhVx2p',\r\n 'rLozhAmzcwtEgr1bA28GUh2kbf5kFBMhph',\r\n 'rJqt8XVcGdpfjZmujoTc6ArHQdZZVhADgM',", "end": 4277, "score": 0.9489636421203613, "start": 4276, "tag": "KEY", "value": "5" }, { "context": "HnGUV2MhJVhVx2p',\r\n 'rLozhAmzcwtEgr1bA28GUh2kbf5kFBMhph',\r\n 'rJqt8XVcGdpfjZmujoTc6ArHQdZZVhADgM',\r\n ", "end": 4281, "score": 0.7487936019897461, "start": 4278, "tag": "KEY", "value": "FBM" }, { "context": "2p',\r\n 'rLozhAmzcwtEgr1bA28GUh2kbf5kFBMhph',\r\n 'rJqt8XVcGdpfjZmujoTc6ArHQdZZVhADgM',\r\n 'rPthXZ93cGAtHJrnAF58vZz6E1js8o6fVf',\r\n 'rL", "end": 4325, "score": 0.993014931678772, "start": 4291, "tag": "KEY", "value": "rJqt8XVcGdpfjZmujoTc6ArHQdZZVhADgM" }, { "context": "ph',\r\n 'rJqt8XVcGdpfjZmujoTc6ArHQdZZVhADgM',\r\n 'rPthXZ93cGAtHJrnAF58vZz6E1js8o6fVf',\r\n 'rL1LH68PG93BuAeLsiM4cxeBtFmxsoGhRB',\r\n 'rn", "end": 4366, "score": 0.9981927275657654, "start": 4332, "tag": "KEY", "value": "rPthXZ93cGAtHJrnAF58vZz6E1js8o6fVf" }, { "context": "gM',\r\n 'rPthXZ93cGAtHJrnAF58vZz6E1js8o6fVf',\r\n 'rL1LH68PG93BuAeLsiM4cxeBtFmxsoGhRB',\r\n 'rndqHX6xLknzbgmQPXL4DvhNLRANYf8cDA',\r\n 'rN", "end": 4407, "score": 0.9981747269630432, "start": 4373, "tag": "KEY", "value": "rL1LH68PG93BuAeLsiM4cxeBtFmxsoGhRB" }, { "context": "Vf',\r\n 'rL1LH68PG93BuAeLsiM4cxeBtFmxsoGhRB',\r\n 'rndqHX6xLknzbgmQPXL4DvhNLRANYf8cDA',\r\n 'rNEnd2tV3Z1aL5kQmShmHGM3uciSJ4jakF',\r\n 'rG", "end": 4448, "score": 0.9986106753349304, "start": 4414, "tag": "KEY", "value": "rndqHX6xLknzbgmQPXL4DvhNLRANYf8cDA" }, { "context": "RB',\r\n 'rndqHX6xLknzbgmQPXL4DvhNLRANYf8cDA',\r\n 'rNEnd2tV3Z1aL5kQmShmHGM3uciSJ4jakF',\r\n 'rGqPPWnLVWDwWXf495qdxp4um1BTw8TBh5',\r\n 'rh", "end": 4489, "score": 0.9982784390449524, "start": 4455, "tag": "KEY", "value": "rNEnd2tV3Z1aL5kQmShmHGM3uciSJ4jakF" }, { "context": "DA',\r\n 'rNEnd2tV3Z1aL5kQmShmHGM3uciSJ4jakF',\r\n 'rGqPPWnLVWDwWXf495qdxp4um1BTw8TBh5',\r\n 'rhEDG4mzWGXjjfQp4WMCpZPBDyug5ays9e',\r\n 'ra", "end": 4530, "score": 0.9970912933349609, "start": 4496, "tag": "KEY", "value": "rGqPPWnLVWDwWXf495qdxp4um1BTw8TBh5" }, { "context": "kF',\r\n 'rGqPPWnLVWDwWXf495qdxp4um1BTw8TBh5',\r\n 'rhEDG4mzWGXjjfQp4WMCpZPBDyug5ays9e',\r\n 'raR6MJ2dYxj1PECUKnLbeamM1k8FnYsY34',\r\n 'rD", "end": 4571, "score": 0.9966714382171631, "start": 4537, "tag": "KEY", "value": "rhEDG4mzWGXjjfQp4WMCpZPBDyug5ays9e" }, { "context": "h5',\r\n 'rhEDG4mzWGXjjfQp4WMCpZPBDyug5ays9e',\r\n 'raR6MJ2dYxj1PECUKnLbeamM1k8FnYsY34',\r\n 'rDcC1S6TRNgTMTgpuSzhAZdTdQJ5EHVf8X',\r\n 'rL", "end": 4612, "score": 0.9853557348251343, "start": 4578, "tag": "KEY", "value": "raR6MJ2dYxj1PECUKnLbeamM1k8FnYsY34" }, { "context": "9e',\r\n 'raR6MJ2dYxj1PECUKnLbeamM1k8FnYsY34',\r\n 'rDcC1S6TRNgTMTgpuSzhAZdTdQJ5EHVf8X',\r\n 'rLHtg3bWtMKNDYXydd7frGB5pvFbtqzTjg',\r\n 'rn", "end": 4653, "score": 0.9931532144546509, "start": 4619, "tag": "KEY", "value": "rDcC1S6TRNgTMTgpuSzhAZdTdQJ5EHVf8X" }, { "context": "34',\r\n 'rDcC1S6TRNgTMTgpuSzhAZdTdQJ5EHVf8X',\r\n 'rLHtg3bWtMKNDYXydd7frGB5pvFbtqzTjg',\r\n 'rnHhh7qXu2trXuC8aD3Zm7gvM9YetRkEDB',\r\n 'rf", "end": 4694, "score": 0.9934865832328796, "start": 4660, "tag": "KEY", "value": "rLHtg3bWtMKNDYXydd7frGB5pvFbtqzTjg" }, { "context": "8X',\r\n 'rLHtg3bWtMKNDYXydd7frGB5pvFbtqzTjg',\r\n 'rnHhh7qXu2trXuC8aD3Zm7gvM9YetRkEDB',\r\n 'rfwwUrJztrR7PeKzELEoC1cjcBpsqHmxws',\r\n 'rw", "end": 4735, "score": 0.9721834063529968, "start": 4701, "tag": "KEY", "value": "rnHhh7qXu2trXuC8aD3Zm7gvM9YetRkEDB" }, { "context": "jg',\r\n 'rnHhh7qXu2trXuC8aD3Zm7gvM9YetRkEDB',\r\n 'rfwwUrJztrR7PeKzELEoC1cjcBpsqHmxws',\r\n 'rw4KzQgZwPJDYX4wHc3NgsLjd", "end": 4758, "score": 0.9766644239425659, "start": 4742, "tag": "KEY", "value": "rfwwUrJztrR7PeKz" }, { "context": "u2trXuC8aD3Zm7gvM9YetRkEDB',\r\n 'rfwwUrJztrR7PeKzELEoC1cjcBpsqHmxws',\r\n 'rw4KzQgZwPJDYX4wHc3NgsLjdR12JGA", "end": 4764, "score": 0.8802900314331055, "start": 4759, "tag": "KEY", "value": "LEoC1" }, { "context": "C8aD3Zm7gvM9YetRkEDB',\r\n 'rfwwUrJztrR7PeKzELEoC1cjcBpsqHmxws',\r\n 'rw4KzQgZwPJDYX4wHc3NgsLjdR12JGAKsF',\r\n 'rP", "end": 4776, "score": 0.8920855522155762, "start": 4765, "tag": "KEY", "value": "jcBpsqHmxws" }, { "context": "DB',\r\n 'rfwwUrJztrR7PeKzELEoC1cjcBpsqHmxws',\r\n 'rw4KzQgZwPJDYX4wHc3NgsLjdR12JGAKsF',\r\n 'rPCbN5kfEjNgP7TBN3VDJf8eUhv1zCreRL',\r\n ", "end": 4813, "score": 0.9823085069656372, "start": 4783, "tag": "KEY", "value": "rw4KzQgZwPJDYX4wHc3NgsLjdR12JG" }, { "context": "cBpsqHmxws',\r\n 'rw4KzQgZwPJDYX4wHc3NgsLjdR12JGAKsF',\r\n 'rPCbN5kfEjNgP7TBN3VDJf8eUhv1zCreRL',\r\n 'r3", "end": 4817, "score": 0.9799535274505615, "start": 4816, "tag": "KEY", "value": "F" }, { "context": "ws',\r\n 'rw4KzQgZwPJDYX4wHc3NgsLjdR12JGAKsF',\r\n 'rPCbN5kfEjNgP7TBN3VDJf8eUhv1zCreRL',\r\n 'r32W6FTsguE3hMv3h79eoNVSJutsDDw6rH',\r\n 'rB", "end": 4858, "score": 0.9944375157356262, "start": 4824, "tag": "KEY", "value": "rPCbN5kfEjNgP7TBN3VDJf8eUhv1zCreRL" }, { "context": "sF',\r\n 'rPCbN5kfEjNgP7TBN3VDJf8eUhv1zCreRL',\r\n 'r32W6FTsguE3hMv3h79eoNVSJutsDDw6rH',\r\n 'rBSDvMzyxsea8Z", "end": 4870, "score": 0.7799820303916931, "start": 4865, "tag": "KEY", "value": "r32W6" }, { "context": "EjNgP7TBN3VDJf8eUhv1zCreRL',\r\n 'r32W6FTsguE3hMv3h79eoNVSJutsDDw6rH',\r\n 'rBSDvMzyxsea8Zgy8EfryZ7cc1QG", "end": 4884, "score": 0.7023040652275085, "start": 4882, "tag": "KEY", "value": "79" }, { "context": "8eUhv1zCreRL',\r\n 'r32W6FTsguE3hMv3h79eoNVSJutsDDw6rH',\r\n 'rBSDvMzyxsea8Zgy8EfryZ7cc1QGrVp9Do',\r\n '", "end": 4897, "score": 0.5306307673454285, "start": 4896, "tag": "KEY", "value": "6" }, { "context": "Uhv1zCreRL',\r\n 'r32W6FTsguE3hMv3h79eoNVSJutsDDw6rH',\r\n 'rBSDvMzyxsea8Zgy8EfryZ7cc1QGrVp9Do',\r\n 'rf", "end": 4899, "score": 0.6434108018875122, "start": 4898, "tag": "KEY", "value": "H" }, { "context": "RL',\r\n 'r32W6FTsguE3hMv3h79eoNVSJutsDDw6rH',\r\n 'rBSDvMzyxsea8Zgy8EfryZ7cc1QGrVp9Do',\r\n 'rfz1TPVJPQ", "end": 4907, "score": 0.9510990381240845, "start": 4906, "tag": "KEY", "value": "r" }, { "context": "\n 'r32W6FTsguE3hMv3h79eoNVSJutsDDw6rH',\r\n 'rBSDvMzyxsea8Zgy8EfryZ7cc1QGrVp9Do',\r\n 'rfz1TPVJPQYbpSx", "end": 4912, "score": 0.5920157432556152, "start": 4911, "tag": "KEY", "value": "M" }, { "context": "hMv3h79eoNVSJutsDDw6rH',\r\n 'rBSDvMzyxsea8Zgy8EfryZ7cc1QGrVp9Do',\r\n 'rfz1TPVJPQYbpSxi6oTiWyhNqy4J1Vz", "end": 4928, "score": 0.7240309715270996, "start": 4927, "tag": "KEY", "value": "Z" }, { "context": "rH',\r\n 'rBSDvMzyxsea8Zgy8EfryZ7cc1QGrVp9Do',\r\n 'rfz1TPVJPQYbpSxi6oTiWyhNqy4J1Vz7VL',\r\n 'rKCyiG5sKxqm", "end": 4950, "score": 0.8162305355072021, "start": 4947, "tag": "KEY", "value": "rfz" }, { "context": "Do',\r\n 'rfz1TPVJPQYbpSxi6oTiWyhNqy4J1Vz7VL',\r\n 'rKCyiG5sKxqmKoT2NGT9zS86gS26m9HrQa',\r\n 'rK7WRdHd6aNq", "end": 4991, "score": 0.902682900428772, "start": 4988, "tag": "KEY", "value": "rKC" }, { "context": "JPQYbpSxi6oTiWyhNqy4J1Vz7VL',\r\n 'rKCyiG5sKxqmKoT2NGT9zS86gS26m9HrQa',\r\n 'rK7WRdHd6aNqCu2tNbebxYrQkP5", "end": 5006, "score": 0.5766375064849854, "start": 5004, "tag": "KEY", "value": "NG" }, { "context": "WyhNqy4J1Vz7VL',\r\n 'rKCyiG5sKxqmKoT2NGT9zS86gS26m9HrQa',\r\n 'rK7WRdHd6aNqCu2tNbebxYrQkP5u2DouS3',\r\n ", "end": 5018, "score": 0.5150075554847717, "start": 5017, "tag": "KEY", "value": "9" }, { "context": "VL',\r\n 'rKCyiG5sKxqmKoT2NGT9zS86gS26m9HrQa',\r\n 'rK7WRdHd6aNqCu2tNbebxYrQkP5u2DouS3',\r\n 'rLC3xWV4N3ohGx", "end": 5034, "score": 0.9605770111083984, "start": 5029, "tag": "KEY", "value": "rK7WR" }, { "context": "'rKCyiG5sKxqmKoT2NGT9zS86gS26m9HrQa',\r\n 'rK7WRdHd6aNqCu2tNbebxYrQkP5u2DouS3',\r\n 'rLC3xWV4N3ohGxxzcu", "end": 5038, "score": 0.7709231376647949, "start": 5037, "tag": "KEY", "value": "6" }, { "context": "5sKxqmKoT2NGT9zS86gS26m9HrQa',\r\n 'rK7WRdHd6aNqCu2tNbebxYrQkP5u2DouS3',\r\n 'rLC3xWV4N3ohGxxzcueDrxPLHN", "end": 5046, "score": 0.7528152465820312, "start": 5044, "tag": "KEY", "value": "tN" }, { "context": "GT9zS86gS26m9HrQa',\r\n 'rK7WRdHd6aNqCu2tNbebxYrQkP5u2DouS3',\r\n 'rLC3xWV4N3ohGxxzcueDrxPLHNqbXrmpUK',", "end": 5056, "score": 0.7113401889801025, "start": 5055, "tag": "KEY", "value": "5" }, { "context": "9zS86gS26m9HrQa',\r\n 'rK7WRdHd6aNqCu2tNbebxYrQkP5u2DouS3',\r\n 'rLC3xWV4N3ohGxxzcueDrxPLHNqbXrmpUK',\r\n 'rD", "end": 5063, "score": 0.7203400135040283, "start": 5057, "tag": "KEY", "value": "2DouS3" }, { "context": "Qa',\r\n 'rK7WRdHd6aNqCu2tNbebxYrQkP5u2DouS3',\r\n 'rLC3xWV4N3ohGxxzcueDrxPLHNqbXrmpUK',\r\n 'rDE2MwprS1vFvknSKLZJfmxKmbVuE2F85',\r\n 'r91", "end": 5104, "score": 0.9958341717720032, "start": 5070, "tag": "KEY", "value": "rLC3xWV4N3ohGxxzcueDrxPLHNqbXrmpUK" }, { "context": "S3',\r\n 'rLC3xWV4N3ohGxxzcueDrxPLHNqbXrmpUK',\r\n 'rDE2MwprS1vFvknSKLZJfmxKmbVuE2F85',\r\n 'r91o1Huejw2qqz37b22Ev8igM4V2Rog1jv',\r\n 'rE", "end": 5144, "score": 0.9991509914398193, "start": 5111, "tag": "KEY", "value": "rDE2MwprS1vFvknSKLZJfmxKmbVuE2F85" }, { "context": "pUK',\r\n 'rDE2MwprS1vFvknSKLZJfmxKmbVuE2F85',\r\n 'r91o1Huejw2qqz37b22Ev8igM4V2Rog1jv',\r\n 'rEhGRU4P7pVjuxco5BgoXz1974QESKQ1Wy',\r\n 'ra", "end": 5185, "score": 0.9992948174476624, "start": 5151, "tag": "KEY", "value": "r91o1Huejw2qqz37b22Ev8igM4V2Rog1jv" }, { "context": "85',\r\n 'r91o1Huejw2qqz37b22Ev8igM4V2Rog1jv',\r\n 'rEhGRU4P7pVjuxco5BgoXz1974QESKQ1Wy',\r\n 'raVZ3Uk3qmKqe5aV1ifQsRFL6gU7m25Y2L',\r\n 'r9", "end": 5226, "score": 0.9992448687553406, "start": 5192, "tag": "KEY", "value": "rEhGRU4P7pVjuxco5BgoXz1974QESKQ1Wy" }, { "context": "jv',\r\n 'rEhGRU4P7pVjuxco5BgoXz1974QESKQ1Wy',\r\n 'raVZ3Uk3qmKqe5aV1ifQsRFL6gU7m25Y2L',\r\n 'r9p5buUwdMmZ5Um5uK5gC9piRd1fBzMPBN',\r\n 'r4", "end": 5267, "score": 0.9991305470466614, "start": 5233, "tag": "KEY", "value": "raVZ3Uk3qmKqe5aV1ifQsRFL6gU7m25Y2L" }, { "context": "Wy',\r\n 'raVZ3Uk3qmKqe5aV1ifQsRFL6gU7m25Y2L',\r\n 'r9p5buUwdMmZ5Um5uK5gC9piRd1fBzMPBN',\r\n 'r4ruPrbfwnkp5aDSNzQXnWcEK64hJGRnDG',\r\n 'rw", "end": 5308, "score": 0.9990643858909607, "start": 5274, "tag": "KEY", "value": "r9p5buUwdMmZ5Um5uK5gC9piRd1fBzMPBN" }, { "context": "2L',\r\n 'r9p5buUwdMmZ5Um5uK5gC9piRd1fBzMPBN',\r\n 'r4ruPrbfwnkp5aDSNzQXnWcEK64hJGRnDG',\r\n 'rwsHCfEwi3PzsfcpcaWLbHXZ2zG5FtNX1J',\r\n 'r4", "end": 5349, "score": 0.9984144568443298, "start": 5315, "tag": "KEY", "value": "r4ruPrbfwnkp5aDSNzQXnWcEK64hJGRnDG" }, { "context": "BN',\r\n 'r4ruPrbfwnkp5aDSNzQXnWcEK64hJGRnDG',\r\n 'rwsHCfEwi3PzsfcpcaWLbHXZ2zG5FtNX1J',\r\n 'r4DkAh7hbTX4E8JPp4kAWkQYazW6236dBB',\r\n 'rG", "end": 5390, "score": 0.9985989928245544, "start": 5356, "tag": "KEY", "value": "rwsHCfEwi3PzsfcpcaWLbHXZ2zG5FtNX1J" }, { "context": "DG',\r\n 'rwsHCfEwi3PzsfcpcaWLbHXZ2zG5FtNX1J',\r\n 'r4DkAh7hbTX4E8JPp4kAWkQYazW6236dBB',\r\n 'rGZSqs5KHQKEJMCaDS3iyWagymixa9zuCv',\r\n 'r9", "end": 5431, "score": 0.998157799243927, "start": 5397, "tag": "KEY", "value": "r4DkAh7hbTX4E8JPp4kAWkQYazW6236dBB" }, { "context": "1J',\r\n 'r4DkAh7hbTX4E8JPp4kAWkQYazW6236dBB',\r\n 'rGZSqs5KHQKEJMCaDS3iyWagymixa9zuCv',\r\n 'r9Nn5Le1bourefaZJ79K2h5VnREFpTqjUw',\r\n 'rh", "end": 5472, "score": 0.9973222613334656, "start": 5438, "tag": "KEY", "value": "rGZSqs5KHQKEJMCaDS3iyWagymixa9zuCv" }, { "context": "BB',\r\n 'rGZSqs5KHQKEJMCaDS3iyWagymixa9zuCv',\r\n 'r9Nn5Le1bourefaZJ79K2h5VnREFpTqjUw',\r\n 'rh7NSNpXR9mwWFF8uXvaWjcLVRPfxqQfM9',\r\n 'rp", "end": 5513, "score": 0.9983949065208435, "start": 5479, "tag": "KEY", "value": "r9Nn5Le1bourefaZJ79K2h5VnREFpTqjUw" }, { "context": "Cv',\r\n 'r9Nn5Le1bourefaZJ79K2h5VnREFpTqjUw',\r\n 'rh7NSNpXR9mwWFF8uXvaWjcLVRPfxqQfM9',\r\n 'rpdxPDQ8mV8gadRcDBh7kNFj1mxYjfddh5',\r\n 'rM", "end": 5554, "score": 0.9963862299919128, "start": 5520, "tag": "KEY", "value": "rh7NSNpXR9mwWFF8uXvaWjcLVRPfxqQfM9" }, { "context": "Uw',\r\n 'rh7NSNpXR9mwWFF8uXvaWjcLVRPfxqQfM9',\r\n 'rpdxPDQ8mV8gadRcDBh7kNFj1mxYjfddh5',\r\n 'rMHxgnXgo68vDLUj327YtsHjQyiHGjeccj',\r\n 'ra", "end": 5595, "score": 0.8812770247459412, "start": 5561, "tag": "KEY", "value": "rpdxPDQ8mV8gadRcDBh7kNFj1mxYjfddh5" }, { "context": "M9',\r\n 'rpdxPDQ8mV8gadRcDBh7kNFj1mxYjfddh5',\r\n 'rMHxgnXgo68vDLUj327YtsHjQyiHGjeccj',\r\n 'raDd7xZ3RYvKc", "end": 5606, "score": 0.7329245209693909, "start": 5602, "tag": "KEY", "value": "rMHx" }, { "context": " 'rpdxPDQ8mV8gadRcDBh7kNFj1mxYjfddh5',\r\n 'rMHxgnXgo68vDLUj327YtsHjQyiHGjeccj',\r\n 'raDd7xZ3RYvKcGiojy9h5UqFV7WULv626i',\r\n 'rE", "end": 5636, "score": 0.9010788798332214, "start": 5608, "tag": "KEY", "value": "Xgo68vDLUj327YtsHjQyiHGjeccj" }, { "context": "h5',\r\n 'rMHxgnXgo68vDLUj327YtsHjQyiHGjeccj',\r\n 'raDd7xZ3RYvKcGiojy9h5UqFV7WULv626i',\r\n 'rEHzCw3nAuHj66", "end": 5648, "score": 0.7664217948913574, "start": 5643, "tag": "KEY", "value": "raDd7" }, { "context": " 'rMHxgnXgo68vDLUj327YtsHjQyiHGjeccj',\r\n 'raDd7xZ3RYvKcGiojy9h5UqFV7WULv626i',\r\n 'rEHzCw3nAuHj66C3xKn", "end": 5653, "score": 0.6827400326728821, "start": 5649, "tag": "KEY", "value": "Z3RY" }, { "context": "gnXgo68vDLUj327YtsHjQyiHGjeccj',\r\n 'raDd7xZ3RYvKcGiojy9h5UqFV7WULv626i',\r\n 'rEHzCw3nAuHj66C3xKnGFxV6zDBAssNd", "end": 5666, "score": 0.6750653386116028, "start": 5656, "tag": "KEY", "value": "Giojy9h5Uq" }, { "context": "7YtsHjQyiHGjeccj',\r\n 'raDd7xZ3RYvKcGiojy9h5UqFV7WULv626i',\r\n 'rEHzCw3nAuHj66C3xKnGFxV6zDBAssNdSY',\r\n ", "end": 5674, "score": 0.7156968712806702, "start": 5670, "tag": "KEY", "value": "ULv6" }, { "context": "jQyiHGjeccj',\r\n 'raDd7xZ3RYvKcGiojy9h5UqFV7WULv626i',\r\n 'rEHzCw3nAuHj66C3xKnGFxV6zDBAssNdSY',\r\n 'r", "end": 5676, "score": 0.5766435861587524, "start": 5675, "tag": "KEY", "value": "6" }, { "context": "cj',\r\n 'raDd7xZ3RYvKcGiojy9h5UqFV7WULv626i',\r\n 'rEHzCw3nAuHj66C3xKnGFxV6zDBAssNdSY',\r\n 'rfvWW9qgyNKYV", "end": 5688, "score": 0.8698676228523254, "start": 5684, "tag": "KEY", "value": "rEHz" }, { "context": "'raDd7xZ3RYvKcGiojy9h5UqFV7WULv626i',\r\n 'rEHzCw3nAuHj66C3xKnGFxV6zDBAssNdSY',\r\n 'rfvWW9qgyNKYVuJ212h", "end": 5694, "score": 0.5148265957832336, "start": 5692, "tag": "KEY", "value": "Au" }, { "context": "d7xZ3RYvKcGiojy9h5UqFV7WULv626i',\r\n 'rEHzCw3nAuHj66C3xKnGFxV6zDBAssNdSY',\r\n 'rfvWW9qgyNKYVuJ212himJ7", "end": 5698, "score": 0.5227013826370239, "start": 5696, "tag": "KEY", "value": "66" }, { "context": "Z3RYvKcGiojy9h5UqFV7WULv626i',\r\n 'rEHzCw3nAuHj66C3xKnGFxV6zDBAssNdSY',\r\n 'rfvWW9qgyNKYVuJ212himJ7mt", "end": 5700, "score": 0.5071334838867188, "start": 5699, "tag": "KEY", "value": "3" }, { "context": "Giojy9h5UqFV7WULv626i',\r\n 'rEHzCw3nAuHj66C3xKnGFxV6zDBAssNdSY',\r\n 'rfvWW9qgyNKYVuJ212himJ7mt6fvkUaS7E", "end": 5709, "score": 0.5331087708473206, "start": 5706, "tag": "KEY", "value": "V6z" }, { "context": "9h5UqFV7WULv626i',\r\n 'rEHzCw3nAuHj66C3xKnGFxV6zDBAssNdSY',\r\n 'rfvWW9qgyNKYVuJ212himJ7mt6fvkUaS7E',\r\n ", "end": 5714, "score": 0.621216893196106, "start": 5711, "tag": "KEY", "value": "Ass" }, { "context": "6i',\r\n 'rEHzCw3nAuHj66C3xKnGFxV6zDBAssNdSY',\r\n 'rfvWW9qgyNKYVuJ212himJ7mt6fvkUaS7E',\r\n 'r9ctoegJfquoj1R", "end": 5731, "score": 0.8698515295982361, "start": 5725, "tag": "KEY", "value": "rfvWW9" }, { "context": "SY',\r\n 'rfvWW9qgyNKYVuJ212himJ7mt6fvkUaS7E',\r\n 'r9ctoegJfquoj1RHo1bxuW9MjWhbjHyZSA',\r\n 'rsNPHLq4CgxGoenX67", "end": 5775, "score": 0.8282357454299927, "start": 5766, "tag": "KEY", "value": "r9ctoegJf" }, { "context": "uJ212himJ7mt6fvkUaS7E',\r\n 'r9ctoegJfquoj1RHo1bxuW9MjWhbjHyZSA',\r\n 'rsNPHLq4CgxGoenX67jpuabKe8hx1QvLZk',", "end": 5793, "score": 0.7555057406425476, "start": 5788, "tag": "KEY", "value": "9MjWh" }, { "context": "mJ7mt6fvkUaS7E',\r\n 'r9ctoegJfquoj1RHo1bxuW9MjWhbjHyZSA',\r\n 'rsNPHLq4CgxGoenX67jpuabKe8hx1QvLZk',\r\n '", "end": 5798, "score": 0.9018847942352295, "start": 5795, "tag": "KEY", "value": "HyZ" }, { "context": "7E',\r\n 'r9ctoegJfquoj1RHo1bxuW9MjWhbjHyZSA',\r\n 'rsNPHLq4CgxGoenX67jpuabKe8hx1QvLZk',\r\n 'rLZouhBz2CpT3ULfJ", "end": 5815, "score": 0.8109049797058105, "start": 5807, "tag": "KEY", "value": "rsNPHLq4" }, { "context": "r9ctoegJfquoj1RHo1bxuW9MjWhbjHyZSA',\r\n 'rsNPHLq4CgxGoenX67jpuabKe8hx1QvLZk',\r\n 'rLZouhBz2CpT3ULfJjt193", "end": 5820, "score": 0.6596825122833252, "start": 5816, "tag": "KEY", "value": "gxGo" }, { "context": "fquoj1RHo1bxuW9MjWhbjHyZSA',\r\n 'rsNPHLq4CgxGoenX67jpuabKe8hx1QvLZk',\r\n 'rLZouhBz2CpT3ULfJjt193gsLNR", "end": 5825, "score": 0.5917876362800598, "start": 5824, "tag": "KEY", "value": "7" }, { "context": "o1bxuW9MjWhbjHyZSA',\r\n 'rsNPHLq4CgxGoenX67jpuabKe8hx1QvLZk',\r\n 'rLZouhBz2CpT3ULfJjt193gsLNR4TxjdUS'", "end": 5833, "score": 0.6782019138336182, "start": 5832, "tag": "KEY", "value": "8" }, { "context": "xuW9MjWhbjHyZSA',\r\n 'rsNPHLq4CgxGoenX67jpuabKe8hx1QvLZk',\r\n 'rLZouhBz2CpT3ULfJjt193gsLNR4TxjdUS',\r\n", "end": 5836, "score": 0.5382326245307922, "start": 5835, "tag": "KEY", "value": "1" }, { "context": "SA',\r\n 'rsNPHLq4CgxGoenX67jpuabKe8hx1QvLZk',\r\n 'rLZouhBz2CpT3ULfJjt193gsLNR4TxjdUS',\r\n 'rKuUjCThS3DBqfDAupxTvyhkWaskxHoWSP',\r\n 'rK", "end": 5882, "score": 0.934846818447113, "start": 5848, "tag": "KEY", "value": "rLZouhBz2CpT3ULfJjt193gsLNR4TxjdUS" }, { "context": "Zk',\r\n 'rLZouhBz2CpT3ULfJjt193gsLNR4TxjdUS',\r\n 'rKuUjCThS3DBqfDAupxTvyhkWaskxHoWSP',\r\n 'rKwSstBmYbKFM3CFw8hvBqsU8pfcZMgNwA',\r\n 'rB", "end": 5923, "score": 0.9979197382926941, "start": 5889, "tag": "KEY", "value": "rKuUjCThS3DBqfDAupxTvyhkWaskxHoWSP" }, { "context": "US',\r\n 'rKuUjCThS3DBqfDAupxTvyhkWaskxHoWSP',\r\n 'rKwSstBmYbKFM3CFw8hvBqsU8pfcZMgNwA',\r\n 'rBN8iGgpbCc6KYNE36D67TeS6t1YXwmTQc',\r\n 'rG", "end": 5964, "score": 0.9991087317466736, "start": 5930, "tag": "KEY", "value": "rKwSstBmYbKFM3CFw8hvBqsU8pfcZMgNwA" }, { "context": "SP',\r\n 'rKwSstBmYbKFM3CFw8hvBqsU8pfcZMgNwA',\r\n 'rBN8iGgpbCc6KYNE36D67TeS6t1YXwmTQc',\r\n 'rGvBvCyqwn5kPuRUErGD7idtKRb7LtptrS',\r\n 'r3", "end": 6005, "score": 0.9988523125648499, "start": 5971, "tag": "KEY", "value": "rBN8iGgpbCc6KYNE36D67TeS6t1YXwmTQc" }, { "context": "wA',\r\n 'rBN8iGgpbCc6KYNE36D67TeS6t1YXwmTQc',\r\n 'rGvBvCyqwn5kPuRUErGD7idtKRb7LtptrS',\r\n 'r3h89HbdaYJBVd1wfHV6GxDj6Pf2s5iXnF',\r\n 'rf", "end": 6046, "score": 0.9989933371543884, "start": 6012, "tag": "KEY", "value": "rGvBvCyqwn5kPuRUErGD7idtKRb7LtptrS" }, { "context": "Qc',\r\n 'rGvBvCyqwn5kPuRUErGD7idtKRb7LtptrS',\r\n 'r3h89HbdaYJBVd1wfHV6GxDj6Pf2s5iXnF',\r\n 'rfbUVWFke9JzbK6BhkuayCgX2MVoJvgxBk',\r\n 'rw", "end": 6087, "score": 0.9991615414619446, "start": 6053, "tag": "KEY", "value": "r3h89HbdaYJBVd1wfHV6GxDj6Pf2s5iXnF" }, { "context": "rS',\r\n 'r3h89HbdaYJBVd1wfHV6GxDj6Pf2s5iXnF',\r\n 'rfbUVWFke9JzbK6BhkuayCgX2MVoJvgxBk',\r\n 'rwTXRBQvPKPMskjp9By1kLJ1pPdRAg77Rz',\r\n 'rw", "end": 6128, "score": 0.9985408782958984, "start": 6094, "tag": "KEY", "value": "rfbUVWFke9JzbK6BhkuayCgX2MVoJvgxBk" }, { "context": "nF',\r\n 'rfbUVWFke9JzbK6BhkuayCgX2MVoJvgxBk',\r\n 'rwTXRBQvPKPMskjp9By1kLJ1pPdRAg77Rz',\r\n 'rw4ve76xnh8cPwVpE58i46s39MbQ7x1m5W',\r\n 'r3", "end": 6169, "score": 0.9978658556938171, "start": 6135, "tag": "KEY", "value": "rwTXRBQvPKPMskjp9By1kLJ1pPdRAg77Rz" }, { "context": "Bk',\r\n 'rwTXRBQvPKPMskjp9By1kLJ1pPdRAg77Rz',\r\n 'rw4ve76xnh8cPwVpE58i46s39MbQ7x1m5W',\r\n 'r32XzGdUP3GuNJXDGxFM2cYkw7K1KrwXdt' ]", "end": 6210, "score": 0.9938751459121704, "start": 6176, "tag": "KEY", "value": "rw4ve76xnh8cPwVpE58i46s39MbQ7x1m5W" }, { "context": "Rz',\r\n 'rw4ve76xnh8cPwVpE58i46s39MbQ7x1m5W',\r\n 'r32XzGdUP3GuNJXDGxFM2cYkw7K1KrwXdt' ]", "end": 6251, "score": 0.9941999316215515, "start": 6217, "tag": "KEY", "value": "r32XzGdUP3GuNJXDGxFM2cYkw7K1KrwXdt" } ]
test/random-test-addresses.coffee
SAN-CHAIN/sand
0
exports.test_accounts = [ 'rBmhuVAvi372AerwzwERGjhLjqkMmAwxX', 'r4nmQNH4Fhjfh6cHDbvVSsBv7KySbj4cBf', 'rGpeQzUWFu4fMhJHZ1Via5aqFC3A5twZUD', 'rrnsYgWn13Z28GtRgznrSUsLfMkvsXCZSu', 'rJsaPnGdeo7BhMnHjuc3n44Mf7Ra1qkSVJ', 'rnYDWQaRdMb5neCGgvFfhw3MBoxmv5LtfH', 'r31PEiKfa3y6xTi7uBcSp7F3nDLvVMmqyi', 'rfM5xD2CY6XB8o1WsWoJ3ZHGkbHU4NYXr', 'r9MB1RNWZChfV3YdLrB3Rm5AoMULewDtiu', 'rH15iZg9KFSi7d1usvcsPerUtg7dhpMbk4', 'rGWYwGaczQWiduWkccFZKXfp5nDRPqNBNS', 'rBU1EP5oMwKxWr1gZnNe7K8GouQTBhzUKs', 'rwiTxuknPNeLDYHHLgajRVetKEEwkYhTaQ', 'rEbq9pWn2knXFTjjuoNNrKgQeGxhmispMi', 'rJfBCsnwSHXjTJ4GH5Ax6Kyw48X977hqyq', 'rado7qRcvPpS8ZL8SNg4SG8kBNksHyqoRa', 'rNgfurDhqvfsVzLr5ZGB3dJysJhRkvJ79F', 'rBtVTnNgX3uR3kyfVyaQ6hjZTdk42ay9Z3', 'rND1XyLAU9G2ydhUgmRo4i2kdrSKgYZc31', 'rHd21p9Gb834Ri4pzRzGFJ7PjRzymWuBWu', 'rhfvFTgpPzCvFPgbA9Nvz42mX92U5ak92m', 'rByT8y4BUX1Kcc6xotEabCgwc5PGsbTfSv', 'rPBrMbL7uGuteU49b2ibcEBSztoWPX4srr', 'rQGRcZn2RyXJL3s7Dfqqzc96Juc7j9j6i9', 'rwZrLewGghBMj29kFq7TPw9h9p5eAQ1LUp', 'rM9qHXk5uifboWrpu9Wte6Gjzbe974nZ4z', 'rBt69hdwMeBgmAtM9YwuFAKxjMqgaBLf3F', 'rHpcrpggafr5NNn7mafPhaeB8PMYKXGahp', 'rsMKP5MSoyve54o7LgwnZzFfGKzAK8SE5F', 'rfN3ccsNxPt41MjHNZRk7ek7q4TpPLqUzL', 'rDRWocPjBdhKZSWZezbsnwNpALcJ6GqSGf', 'rsmJ4tEMWpcK2qcEMp9uoUv4Ht5Nd6cGTV', 'rsxWsnMVRnFozrKJV2VZ1SG6UNbEeHYu16', 'r4KoiD6MpaQNPzBka3FRLREkx6EZFwynY4', 'rUdovjorVqxyemu5jbpfqA6DYDLdD4eYcj', 'r4MrNttmbdiJ7DjWh1MCKW3Kh7kfML46TA', 'rndYw73Btcm9Pv9gssZY1S9UcDUPLnpip7', 'rh8MnoZmAeWyLx7X8bJZqyjZ48mv1og5PS', 'rBoJvU7pcvoy5hjDMMTDNVG4YG85Ed3MEq', 'rs4f1BwdNgXAHWLT8rZgW2T1RKSBNY4iDz', 'rEmhxShqw42EPm7bY7df5uQySZBkQWnqae', 'rNerRdGnbZP6wej22zBdoTUfQKWoMDTH7d', 'rDyXvd2WFALJovh76uLe5kUrJ7QLpgmQYE', 'rUVi1L28AsCvieXP5pMqPHA9WAfsvCDUjU', 'rscuoJN9um2VM4xVv386X5T9APtExFKsbB', 'raeeyPs6g5xQn5jyNQbCZ6QeLrqu3FrFvb', 'r9UqovJD979WTfNEWXxDU2CVj3K1yo2mqG', 'rfRjsAqM1MEuSbWzuLcD6EhSZazgqvZSjy', 'rUL4CAxmfpNqDXsQTPCK9ZJ8zHqhUvDWfw', 'rP6ZRDFZxjQqeAgdBh1YQSQjWNSASpCL7N', 'rsV4AtAqsdyRyZ8s4kaWbM21EPwY5fonx5', 'rHaKEMyJErGY6VaKuTj16fSheTp4BRpWG1', 'rELHJtahsRpSiSj1nfkY5yKRHCCyRgynw4', 'rLYtaGnw4xK86J6mTsLfayyREoYaPPr8Cj', 'rD5pAYUfZypmJRSrJnBy3pYo5ApHqw5Jt5', 'rfYQrqwNXoA8e2gBDmiHAJAMYrASdQvqDm', 'rESt1CB9Sqaj8PYj8SV9x76iwMGBFPzLHb', 'rHZWAXh3NdQbyksKzDRLeP9ui32TcqssHZ', 'rK9iNjw5SozqKj5zNervwQQTLAgu8V813j', 'rUjpFBSmZ8F6cP16VxqpdAXCVCW3rBSZyn', 'raPib2vNQAjhh47fVQ7PswKaX1daNBSs2G', 'rwhuqz7FppLNvLWdxs7TLLW9UDVztFbw9z', 'rJYRe27KXWTjs4P3uu1d4x58Pk5Y13DbUg', 'rLFxCuE2GHq38wFUHpswgHJAcz6EUhPimC', 'rAaQrzi5satsth174EogwdtdxLZRW5n1h', 'rB18Rxdv1aPYtf9nDFpNPJ2HA5BBAqmyoG', 'rDSaTM6nCSrc1vH8pPcTAwQpmvb9Y6M2gw', 'rpmeCBJUpp9ij1nRM23tRGesWjY7chSHqs', 'rwQz7ZkCGdQt7iiuWC3EpbbKwWdL7uLT9C', 'rULwRizwxjBwDjcaA44Tbh9MjM5TZFTcLj', 'rGMZBEGHbSoegfvqXC2ajXe7RM2Z1LK65N', 'rGyFSppE8G7cELAdBU5yL7kWodbw29YdpN', 'rJYN3qZsjWhH6bzXX6ZHMZewkMPHeEyGNb', 'rEgZVpVSs75eEh6KM4HvcvG64p2TZBL4DC', 'rBRfZaqSAkXZYQWBfoy4sN2Q7zZHVGiGwU', 'rwg1DRGXLTzQpoWtS35mDowN4PSFQ732eQ', 'rKZvkY3T6ahhqkWLTQDSdB1MTKFbbnkqBX', 'rGXgpwvaAZ7rBmoSKFUrd83N7WN3Lm4vuX', 'rhCMsQ3SJa5Wb4AvBe27hxBQaQQjDG1LG4', 'rNtvcU3ePYpZnuYKG77pjRxtKJJ1yrutbm', 'rsfK2cTikveAeyvSG8F62c4VFUvZBsH5Rf', 'rJT2LrXe7hH1pMEnhEkCMznwtgKuYJS7uz', 'rE4Fi4GVjo9NY2g6MtMbitjenUZ21zFoSG', 'rp39zV6AFPRJ7yrrL1PSPC1s3oKM2uv2iW', 'raCoTW3mhdK6WGUZUSEuvbFM34CSGRRHut', 'rKZD9yCV7XAgKq3Rj3a5DmqHHkHBd3ZYao', 'rfKtpLEQz8bGCVtQsEzD8cJKeo6AW6J2pD', 'rJqNyWJ3rovwkWFdwPhCc6m3jpFogGzRr9', 'r41fiShunXNNgJjTjqU9whsjnSYU1BXsjY', 'r3uHcWgsNwowCBGF5rhCP5dfdjpYmByBbJ', 'r4GZm8WnwX5E9cr8uGiLX42y7KN2NaLqYn', 'rKBVsMWErdH443FUkaT799CRVyY9XnVyCK', 'razu52accAWWHjxhWEHXNLHWCDhhs1L79p', 'rHaL5e3niiikv6KJG4UARqpcjyD5tKNgyV', 'rMfcPdGcB5y9zEYw91t3QG2Qj1Z7tqms3S', 'r3mqtPNiwkLKisvbnFjM9eC8Rm9JUEXLMD', 'rKJGLaJr5SFjZ43BkDeqWKWAtGy1qAAkPf', 'rM2zQeTDrt6sMM936Gxh263t1qx3hEb7XK', 'rGtqoQJGe4zWenC3yWH9pByTAsGPcjmTU2', 'raNUsR5m8jsmb9o9mpNZGGyV86aZUYPunr', 'rManQrKu85ezooZ11UmXbxejw5EYHqiUZm', 'rKrjCBtwnhQeYkJKrVjDA5CaR5W9NPN2Bb', 'rcwyaWqsvGXMRyVW2KHnGUV2MhJVhVx2p', 'rLozhAmzcwtEgr1bA28GUh2kbf5kFBMhph', 'rJqt8XVcGdpfjZmujoTc6ArHQdZZVhADgM', 'rPthXZ93cGAtHJrnAF58vZz6E1js8o6fVf', 'rL1LH68PG93BuAeLsiM4cxeBtFmxsoGhRB', 'rndqHX6xLknzbgmQPXL4DvhNLRANYf8cDA', 'rNEnd2tV3Z1aL5kQmShmHGM3uciSJ4jakF', 'rGqPPWnLVWDwWXf495qdxp4um1BTw8TBh5', 'rhEDG4mzWGXjjfQp4WMCpZPBDyug5ays9e', 'raR6MJ2dYxj1PECUKnLbeamM1k8FnYsY34', 'rDcC1S6TRNgTMTgpuSzhAZdTdQJ5EHVf8X', 'rLHtg3bWtMKNDYXydd7frGB5pvFbtqzTjg', 'rnHhh7qXu2trXuC8aD3Zm7gvM9YetRkEDB', 'rfwwUrJztrR7PeKzELEoC1cjcBpsqHmxws', 'rw4KzQgZwPJDYX4wHc3NgsLjdR12JGAKsF', 'rPCbN5kfEjNgP7TBN3VDJf8eUhv1zCreRL', 'r32W6FTsguE3hMv3h79eoNVSJutsDDw6rH', 'rBSDvMzyxsea8Zgy8EfryZ7cc1QGrVp9Do', 'rfz1TPVJPQYbpSxi6oTiWyhNqy4J1Vz7VL', 'rKCyiG5sKxqmKoT2NGT9zS86gS26m9HrQa', 'rK7WRdHd6aNqCu2tNbebxYrQkP5u2DouS3', 'rLC3xWV4N3ohGxxzcueDrxPLHNqbXrmpUK', 'rDE2MwprS1vFvknSKLZJfmxKmbVuE2F85', 'r91o1Huejw2qqz37b22Ev8igM4V2Rog1jv', 'rEhGRU4P7pVjuxco5BgoXz1974QESKQ1Wy', 'raVZ3Uk3qmKqe5aV1ifQsRFL6gU7m25Y2L', 'r9p5buUwdMmZ5Um5uK5gC9piRd1fBzMPBN', 'r4ruPrbfwnkp5aDSNzQXnWcEK64hJGRnDG', 'rwsHCfEwi3PzsfcpcaWLbHXZ2zG5FtNX1J', 'r4DkAh7hbTX4E8JPp4kAWkQYazW6236dBB', 'rGZSqs5KHQKEJMCaDS3iyWagymixa9zuCv', 'r9Nn5Le1bourefaZJ79K2h5VnREFpTqjUw', 'rh7NSNpXR9mwWFF8uXvaWjcLVRPfxqQfM9', 'rpdxPDQ8mV8gadRcDBh7kNFj1mxYjfddh5', 'rMHxgnXgo68vDLUj327YtsHjQyiHGjeccj', 'raDd7xZ3RYvKcGiojy9h5UqFV7WULv626i', 'rEHzCw3nAuHj66C3xKnGFxV6zDBAssNdSY', 'rfvWW9qgyNKYVuJ212himJ7mt6fvkUaS7E', 'r9ctoegJfquoj1RHo1bxuW9MjWhbjHyZSA', 'rsNPHLq4CgxGoenX67jpuabKe8hx1QvLZk', 'rLZouhBz2CpT3ULfJjt193gsLNR4TxjdUS', 'rKuUjCThS3DBqfDAupxTvyhkWaskxHoWSP', 'rKwSstBmYbKFM3CFw8hvBqsU8pfcZMgNwA', 'rBN8iGgpbCc6KYNE36D67TeS6t1YXwmTQc', 'rGvBvCyqwn5kPuRUErGD7idtKRb7LtptrS', 'r3h89HbdaYJBVd1wfHV6GxDj6Pf2s5iXnF', 'rfbUVWFke9JzbK6BhkuayCgX2MVoJvgxBk', 'rwTXRBQvPKPMskjp9By1kLJ1pPdRAg77Rz', 'rw4ve76xnh8cPwVpE58i46s39MbQ7x1m5W', 'r32XzGdUP3GuNJXDGxFM2cYkw7K1KrwXdt' ]
75288
exports.test_accounts = [ '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>o<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>i<KEY>', '<KEY>Ri4<KEY>', '<KEY>', '<KEY>y<KEY>X<KEY>cc<KEY>xot<KEY>', '<KEY>MbL<KEY>uG<KEY>U4<KEY>b<KEY>ibcEB<KEY>toWPX4srr', '<KEY>cZn2RyXJL3s<KEY>Dfqqzc96Juc<KEY>j<KEY>j<KEY>i9', '<KEY>ZrLewGghBMj29kFq7TPw9h9p5eAQ1LUp', '<KEY>bo<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>ME<KEY>', '<KEY>', '<KEY>42EPm<KEY>b<KEY>df<KEY>uQy<KEY>ae', '<KEY>nbZP6wej22<KEY>Bdo<KEY>f<KEY>o<KEY>7d', '<KEY>Xvd2WFALJovh76uLe5kUrJ7QLpgmQYE', '<KEY>i1L28AsCvieXP5pMqPHA9WAfsvCDUjU', '<KEY>VM<KEY>xVv<KEY>X<KEY>T<KEY>t<KEY>sbB', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>ui<KEY>', '<KEY>vw<KEY>', '<KEY>', '<KEY>N<KEY>jhh<KEY>f<KEY>7Psw<KEY>X1<KEY>s<KEY>G', '<KEY>7FppLNvLWdxs7T<KEY>W<KEY>V<KEY>bw<KEY>', '<KEY>Re27KXWTjs4P3uu1d4x58<KEY>13DbUg', '<KEY>xCuE2GHq38wFUHpswgHJAcz6EUhPimC', '<KEY>zi<KEY>sth<KEY>wdtdx<KEY>n<KEY>h', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>Lm<KEY>', '<KEY>', '<KEY>vcU<KEY>ePYp<KEY>nuYKG7<KEY>pj<KEY>xt<KEY>yr<KEY>bm', '<KEY>f<KEY>2cTikveAeyvSG8F62c4VFUvZBsH5Rf', '<KEY>2LrXe7hH1pMEnhEkCMznwtgKuYJS7uz', '<KEY>4Fi4GVjo9NY2g6MtMbitjenUZ21zFoSG', '<KEY>V<KEY>AFPRJ7yrrL1PSPC1s3oKM2uv2iW', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>isvbn<KEY>', '<KEY>j<KEY>4<KEY>q<KEY>', '<KEY>rt6<KEY>', '<KEY>JGe4zWenC3yWH9p<KEY>T<KEY>cjm<KEY>2', '<KEY>NUsR5m8jsmb9o9mpNZGGyV86aZUYPunr', '<KEY>QrKu85ezooZ11UmXbxejw5EYHqiUZm', '<KEY>j<KEY>twnh<KEY>eYk<KEY>rVjDA5CaR<KEY>NPN2Bb', '<KEY>WqsvGXMRyVW2KHnGUV2MhJVhVx2p', '<KEY>zcwt<KEY>gr<KEY>b<KEY>bf<KEY>k<KEY>hph', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>E<KEY>c<KEY>', '<KEY>AKs<KEY>', '<KEY>', '<KEY>FTsguE3hMv3h<KEY>eoNVSJutsDDw<KEY>r<KEY>', '<KEY>BSDv<KEY>zyxsea8Zgy8Efry<KEY>7cc1QGrVp9Do', '<KEY>1TPVJPQYbpSxi6oTiWyhNqy4J1Vz7VL', '<KEY>yiG5sKxqmKoT2<KEY>T9zS86gS26m<KEY>HrQa', '<KEY>dHd<KEY>aNqCu2<KEY>bebxYrQkP<KEY>u<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>gn<KEY>', '<KEY>x<KEY>vKc<KEY>FV7W<KEY>2<KEY>i', '<KEY>Cw3n<KEY>Hj<KEY>C<KEY>xKnGFx<KEY>DB<KEY>NdSY', '<KEY>qgyNKYVuJ212himJ7mt6fvkUaS7E', '<KEY>quoj1RHo1bxuW<KEY>bj<KEY>SA', '<KEY>C<KEY>enX6<KEY>jpuabKe<KEY>hx<KEY>QvLZk', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>' ]
true
exports.test_accounts = [ 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIoPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIiPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIRi4PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIyPI:KEY:<KEY>END_PIXPI:KEY:<KEY>END_PIccPI:KEY:<KEY>END_PIxotPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIMbLPI:KEY:<KEY>END_PIuGPI:KEY:<KEY>END_PIU4PI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PIibcEBPI:KEY:<KEY>END_PItoWPX4srr', 'PI:KEY:<KEY>END_PIcZn2RyXJL3sPI:KEY:<KEY>END_PIDfqqzc96JucPI:KEY:<KEY>END_PIjPI:KEY:<KEY>END_PIjPI:KEY:<KEY>END_PIi9', 'PI:KEY:<KEY>END_PIZrLewGghBMj29kFq7TPw9h9p5eAQ1LUp', 'PI:KEY:<KEY>END_PIboPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIMEPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI42EPmPI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PIdfPI:KEY:<KEY>END_PIuQyPI:KEY:<KEY>END_PIae', 'PI:KEY:<KEY>END_PInbZP6wej22PI:KEY:<KEY>END_PIBdoPI:KEY:<KEY>END_PIfPI:KEY:<KEY>END_PIoPI:KEY:<KEY>END_PI7d', 'PI:KEY:<KEY>END_PIXvd2WFALJovh76uLe5kUrJ7QLpgmQYE', 'PI:KEY:<KEY>END_PIi1L28AsCvieXP5pMqPHA9WAfsvCDUjU', 'PI:KEY:<KEY>END_PIVMPI:KEY:<KEY>END_PIxVvPI:KEY:<KEY>END_PIXPI:KEY:<KEY>END_PITPI:KEY:<KEY>END_PItPI:KEY:<KEY>END_PIsbB', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIuiPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIvwPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PINPI:KEY:<KEY>END_PIjhhPI:KEY:<KEY>END_PIfPI:KEY:<KEY>END_PI7PswPI:KEY:<KEY>END_PIX1PI:KEY:<KEY>END_PIsPI:KEY:<KEY>END_PIG', 'PI:KEY:<KEY>END_PI7FppLNvLWdxs7TPI:KEY:<KEY>END_PIWPI:KEY:<KEY>END_PIVPI:KEY:<KEY>END_PIbwPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIRe27KXWTjs4P3uu1d4x58PI:KEY:<KEY>END_PI13DbUg', 'PI:KEY:<KEY>END_PIxCuE2GHq38wFUHpswgHJAcz6EUhPimC', 'PI:KEY:<KEY>END_PIziPI:KEY:<KEY>END_PIsthPI:KEY:<KEY>END_PIwdtdxPI:KEY:<KEY>END_PInPI:KEY:<KEY>END_PIh', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PILmPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIvcUPI:KEY:<KEY>END_PIePYpPI:KEY:<KEY>END_PInuYKG7PI:KEY:<KEY>END_PIpjPI:KEY:<KEY>END_PIxtPI:KEY:<KEY>END_PIyrPI:KEY:<KEY>END_PIbm', 'PI:KEY:<KEY>END_PIfPI:KEY:<KEY>END_PI2cTikveAeyvSG8F62c4VFUvZBsH5Rf', 'PI:KEY:<KEY>END_PI2LrXe7hH1pMEnhEkCMznwtgKuYJS7uz', 'PI:KEY:<KEY>END_PI4Fi4GVjo9NY2g6MtMbitjenUZ21zFoSG', 'PI:KEY:<KEY>END_PIVPI:KEY:<KEY>END_PIAFPRJ7yrrL1PSPC1s3oKM2uv2iW', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIisvbnPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIjPI:KEY:<KEY>END_PI4PI:KEY:<KEY>END_PIqPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIrt6PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIJGe4zWenC3yWH9pPI:KEY:<KEY>END_PITPI:KEY:<KEY>END_PIcjmPI:KEY:<KEY>END_PI2', 'PI:KEY:<KEY>END_PINUsR5m8jsmb9o9mpNZGGyV86aZUYPunr', 'PI:KEY:<KEY>END_PIQrKu85ezooZ11UmXbxejw5EYHqiUZm', 'PI:KEY:<KEY>END_PIjPI:KEY:<KEY>END_PItwnhPI:KEY:<KEY>END_PIeYkPI:KEY:<KEY>END_PIrVjDA5CaRPI:KEY:<KEY>END_PINPN2Bb', 'PI:KEY:<KEY>END_PIWqsvGXMRyVW2KHnGUV2MhJVhVx2p', 'PI:KEY:<KEY>END_PIzcwtPI:KEY:<KEY>END_PIgrPI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PIbfPI:KEY:<KEY>END_PIkPI:KEY:<KEY>END_PIhph', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIEPI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIAKsPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIFTsguE3hMv3hPI:KEY:<KEY>END_PIeoNVSJutsDDwPI:KEY:<KEY>END_PIrPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIBSDvPI:KEY:<KEY>END_PIzyxsea8Zgy8EfryPI:KEY:<KEY>END_PI7cc1QGrVp9Do', 'PI:KEY:<KEY>END_PI1TPVJPQYbpSxi6oTiWyhNqy4J1Vz7VL', 'PI:KEY:<KEY>END_PIyiG5sKxqmKoT2PI:KEY:<KEY>END_PIT9zS86gS26mPI:KEY:<KEY>END_PIHrQa', 'PI:KEY:<KEY>END_PIdHdPI:KEY:<KEY>END_PIaNqCu2PI:KEY:<KEY>END_PIbebxYrQkPPI:KEY:<KEY>END_PIuPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIgnPI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIxPI:KEY:<KEY>END_PIvKcPI:KEY:<KEY>END_PIFV7WPI:KEY:<KEY>END_PI2PI:KEY:<KEY>END_PIi', 'PI:KEY:<KEY>END_PICw3nPI:KEY:<KEY>END_PIHjPI:KEY:<KEY>END_PICPI:KEY:<KEY>END_PIxKnGFxPI:KEY:<KEY>END_PIDBPI:KEY:<KEY>END_PINdSY', 'PI:KEY:<KEY>END_PIqgyNKYVuJ212himJ7mt6fvkUaS7E', 'PI:KEY:<KEY>END_PIquoj1RHo1bxuWPI:KEY:<KEY>END_PIbjPI:KEY:<KEY>END_PISA', 'PI:KEY:<KEY>END_PICPI:KEY:<KEY>END_PIenX6PI:KEY:<KEY>END_PIjpuabKePI:KEY:<KEY>END_PIhxPI:KEY:<KEY>END_PIQvLZk', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI' ]
[ { "context": "eio.com\").constant(\"SIMPLE_LOGIN_PROVIDERS\", [\n \"password\"\n \"anonymous\"\n]).constant \"loginRedirectPath\", \"", "end": 179, "score": 0.9992341995239258, "start": 171, "tag": "PASSWORD", "value": "password" }, { "context": "stant(\"SIMPLE_LOGIN_PROVIDERS\", [\n \"password\"\n \"anonymous\"\n]).constant \"loginRedirectPath\", \"/\"\n", "end": 193, "score": 0.9517017006874084, "start": 184, "tag": "PASSWORD", "value": "anonymous" } ]
app/scripts/angularfire/config.coffee
nerdfiles/utxo_us
0
#.constant('loginRedirectPath', '/login'); angular.module("firebase.config", []).constant("FBURL", "https://utxo.firebaseio.com").constant("SIMPLE_LOGIN_PROVIDERS", [ "password" "anonymous" ]).constant "loginRedirectPath", "/"
29315
#.constant('loginRedirectPath', '/login'); angular.module("firebase.config", []).constant("FBURL", "https://utxo.firebaseio.com").constant("SIMPLE_LOGIN_PROVIDERS", [ "<PASSWORD>" "<PASSWORD>" ]).constant "loginRedirectPath", "/"
true
#.constant('loginRedirectPath', '/login'); angular.module("firebase.config", []).constant("FBURL", "https://utxo.firebaseio.com").constant("SIMPLE_LOGIN_PROVIDERS", [ "PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI" ]).constant "loginRedirectPath", "/"
[ { "context": " track = req.fromUrl.track\n allowedKeys = [ 'name', 'prevent_copying' ]\n unless track.publishe", "end": 8375, "score": 0.9412021636962891, "start": 8371, "tag": "KEY", "value": "name" }, { "context": " req.fromUrl.track\n allowedKeys = [ 'name', 'prevent_copying' ]\n unless track.published\n allowedKe", "end": 8394, "score": 0.9745469093322754, "start": 8379, "tag": "KEY", "value": "prevent_copying" }, { "context": "ished\n allowedKeys = allowedKeys.concat [ 'config', 'published' ]\n filterAndSaveIfModified tra", "end": 8477, "score": 0.8422170877456665, "start": 8471, "tag": "KEY", "value": "config" }, { "context": " allowedKeys = allowedKeys.concat [ 'config', 'published' ]\n filterAndSaveIfModified track, allowedKe", "end": 8490, "score": 0.3808532655239105, "start": 8481, "tag": "KEY", "value": "published" }, { "context": " not maySetPicture\n allowedKeys = [\n 'favorite_tracks'\n 'name'\n 'picture'\n ]\n f", "end": 9657, "score": 0.9931524395942688, "start": 9642, "tag": "KEY", "value": "favorite_tracks" } ]
server/api.coffee
triggerrally/triggerrally.github.io
0
_ = require('underscore') bb = require('./public/scripts/models') Backbone = bb.Backbone # Disable all caching on the server. bb.Model::useCache = no # Attach backbone models to MongoDB via Mongoose. require('./backbone-mongoose') bb jsonClone = (obj) -> JSON.parse JSON.stringify obj findModel = (Model, pub_id, done) -> model = Model.findOrCreate pub_id result = model.fetch success: -> done model error:(e1, e2) -> console.error('Error when loading model', pub_id) done null if result is false findCar = -> findModel(bb.Car, arguments...) findCommentSet = -> findModel(bb.CommentSet, arguments...) findEnv = -> findModel(bb.Env, arguments...) findRun = -> findModel(bb.Run, arguments...) findTrack = -> findModel(bb.Track, arguments...) findTrackRuns = -> findModel(bb.TrackRuns, arguments...) findTrackSet = -> findModel(bb.TrackSet, arguments...) findUser = -> findModel(bb.User, arguments...) # This public-facing API is responsible for validating requests and data. module.exports = findUser: findUser setup: (app) -> base = '/v1' jsonError = (code, res, msg) -> text = 400: "Bad Request - client bug" 401: "Unauthorized - log in required" 403: "Forbidden" 404: "Not Found" 409: "Conflict" result = { error: text[code] } result.extended = msg if msg res.json code, result boolean = (val) -> val? and val in ['1', 't', 'y', 'true', 'yes'] loadUrl = (finder, param, attrib, req, res, next) -> finder req.params[param], (obj) -> return jsonError 404, res unless obj? req.fromUrl or= {} req.fromUrl[attrib] = obj next() loadUrlCommentSet = (req, res, next) -> loadUrl findCommentSet, 'commentset_id', 'commentSet', req, res, next loadUrlRun = (req, res, next) -> loadUrl findRun, 'run_id', 'run', req, res, next loadUrlTrack = (req, res, next) -> loadUrl findTrack, 'track_id', 'track', req, res, next loadUrlTrackRuns = (req, res, next) -> loadUrl findTrackRuns, 'track_id', 'trackRuns', req, res, next loadUrlTrackSet = (req, res, next) -> loadUrl findTrackSet, 'trackset_id', 'trackSet', req, res, next loadUrlUser = (req, res, next) -> loadUrl findUser, 'user_id', 'user', req, res, next editUrlTrack = (req, res, next) -> loadUrlTrack req, res, -> track = req.fromUrl.track # Real security check. return jsonError 401, res unless req.user? return jsonError 403, res unless track.user.id is req.user.user.pub_id # Opt-in sanity checks to help protect against client bugs. return jsonError 400, res, 'id mismatch' if req.body.id and req.body.id isnt track.id modifiedExpected = track.modified.toISOString() modifiedActual = req.body.modified if modifiedActual and modifiedActual isnt modifiedExpected return jsonError 409, res, "expired: expected #{modifiedExpected} but got #{modifiedActual}" next() editUrlUser = (req, res, next) -> loadUrlUser req, res, -> user = req.fromUrl.user return jsonError 401, res unless req.user? return jsonError 403, res unless user.id is req.user.user.pub_id next() filterAndSaveIfModified = (model, allowedKeys, req, res) -> attribs = _.pick req.body, allowedKeys prev = jsonClone _.pick model, allowedKeys if _.isEqual prev, attribs console.log "#{model.constructor.name} #{model.id}: no changes to save" return res.json {} if 'config' of attribs and not _.isEqual prev.config, attribs.config attribs.modified = new Date console.log "#{model.constructor.name} #{model.id}: saving changes" model.save attribs, success: -> res.json { modified: attribs.modified } error: -> jsonError 500, res app.get "#{base}/cars/:car_id", (req, res) -> findCar req.params['car_id'], (car) -> return jsonError 404, res unless car? products = req.user?.user.products res.json car.toJSON { products } app.post "#{base}/comments", (req, res) -> return jsonError 401, res unless req.user? findUser req.user.user.pub_id, (reqUser) -> return jsonError 500, res unless reqUser # TODO: Check that the comment parent/target actually exists. comment = new bb.Comment parent: req.body.parent text: req.body.text result = comment.save null, user: req.user.user success: (comment) -> res.json comment error: (model, err) -> console.log "Error creating comment: #{err}" jsonError 500, res if result is false console.log "Error creating comment: save failed" jsonError 500, res app.get "#{base}/commentsets/:commentset_id", loadUrlCommentSet, (req, res) -> res.json req.fromUrl.commentSet app.get "#{base}/envs/:env_id", (req, res) -> findEnv req.params['env_id'], (env) -> return jsonError 404, res unless env? # allowedEnvs = [ 'alp' ] # if req.user? # allowedEnvs = allowedEnvs.concat req.user.user.packs # restricted = env.id not in allowedEnvs res.json env #.toJSON { restricted } app.get "#{base}/runs/:run_id", (req, res) -> findRun req.params['run_id'], (run) -> return jsonError 404, res unless run? if run.record_p res.json run else run.fetch force: yes success: -> res.json run error: -> jsonError 500, res app.post "#{base}/tracks", (req, res) -> return jsonError 401, res unless req.user? findUser req.user.user.pub_id, (reqUser) -> return jsonError 500, res unless reqUser parentTrackId = req.body.parent findTrack parentTrackId, (parentTrack) -> return jsonError 404, res unless parentTrack? return jsonError 400, res unless parentTrack.env? return jsonError 403, res unless parentTrack.env.id is 'alp' return jsonError 403, res if parentTrack.prevent_copy # TODO: Check this user is allowed to copy tracks from this env. track = new bb.Track newName = parentTrack.name maxLength = bb.Track::maxNameLength - 5 if newName.length > maxLength then newName = newName.slice(0, maxLength - 3) + '...' newName += ' copy' track.set track.parse config: jsonClone parentTrack.config env: parentTrack.env.id name: newName parent: parentTrack.id prevent_copy: parentTrack.prevent_copy user: reqUser.id result = track.save null, user: req.user.user success: (track) -> res.json track reqUser.tracks.add track parentTrack.count_copy += 1 parentTrack.save() error: (model, err) -> console.log "Error creating track: #{err}" jsonError 500, res if result is false console.log "Error creating track: save failed" jsonError 500, res # TODO: Add a multi-ID track GET. app.get "#{base}/tracks/:track_id", loadUrlTrack, (req, res) -> res.json req.fromUrl.track # app.get "#{base}/tracks/:track_id/runs", loadUrlTrack, (req, res) -> # trackRuns = new bb.TrackRuns null, track: req.fromUrl.track # trackRuns.fetch # success: (collection) -> # res.json collection # error: (collection, err) -> # console.log "Error creating track: #{err}" # jsonError 500, res app.get "#{base}/tracks/:track_id/runs", loadUrlTrackRuns, (req, res) -> res.json req.fromUrl.trackRuns # app.get "#{base}/tracks/:track_id/bestrun", loadUrlTrack, (req, res) -> # req.fromUrl.track.getBestRun (run) -> # return jsonError 404, res unless run? # res.json { run } # app.get "#{base}/tracks/:track_id/personalbestrun", loadUrlTrackRuns, (req, res) -> # res.json req.fromUrl.trackRuns app.put "#{base}/tracks/:track_id", editUrlTrack, (req, res) -> track = req.fromUrl.track allowedKeys = [ 'name', 'prevent_copying' ] unless track.published allowedKeys = allowedKeys.concat [ 'config', 'published' ] filterAndSaveIfModified track, allowedKeys, req, res app.post "#{base}/tracks/:track_id/drive", loadUrlTrack, (req, res) -> res.send 200 # Now handled by drive socket. # track = req.fromUrl.track # track.save { count_drive: track.count_drive + 1 } app.delete "#{base}/tracks/:track_id", editUrlTrack, (req, res) -> jsonError 403, res if req.fromUrl.track.id is 'v3-base-1' req.fromUrl.track.destroy success: -> res.json {} error: -> jsonError 500, res app.get "#{base}/tracksets/:trackset_id", loadUrlTrackSet, (req, res) -> res.json req.fromUrl.trackSet app.get "#{base}/users/:user_id", loadUrlUser, (req, res) -> user = req.fromUrl.user authenticated = user.id is req.user?.user.pub_id res.json user.toJSON { authenticated } app.put "#{base}/users/:user_id", editUrlUser, (req, res) -> products = req.fromUrl.user.products ? [] maySetPicture = 'ignition' in products or 'mayhem' in products or 'packa' in products return jsonError 403, res if 'picture' of req.body and not maySetPicture allowedKeys = [ 'favorite_tracks' 'name' 'picture' ] filterAndSaveIfModified req.fromUrl.user, allowedKeys, req, res app.get "#{base}/auth/me", (req, res) -> if req.user?.user findUser req.user.user.pub_id, (user) -> return jsonError 404, res unless user? res.json user: user.toJSON { authenticated: yes } else res.json user: null return # Give a JSON 404 response for any unknown path under /v1/. app.get "#{base}/*", (req, res) -> jsonError 404, res return
69320
_ = require('underscore') bb = require('./public/scripts/models') Backbone = bb.Backbone # Disable all caching on the server. bb.Model::useCache = no # Attach backbone models to MongoDB via Mongoose. require('./backbone-mongoose') bb jsonClone = (obj) -> JSON.parse JSON.stringify obj findModel = (Model, pub_id, done) -> model = Model.findOrCreate pub_id result = model.fetch success: -> done model error:(e1, e2) -> console.error('Error when loading model', pub_id) done null if result is false findCar = -> findModel(bb.Car, arguments...) findCommentSet = -> findModel(bb.CommentSet, arguments...) findEnv = -> findModel(bb.Env, arguments...) findRun = -> findModel(bb.Run, arguments...) findTrack = -> findModel(bb.Track, arguments...) findTrackRuns = -> findModel(bb.TrackRuns, arguments...) findTrackSet = -> findModel(bb.TrackSet, arguments...) findUser = -> findModel(bb.User, arguments...) # This public-facing API is responsible for validating requests and data. module.exports = findUser: findUser setup: (app) -> base = '/v1' jsonError = (code, res, msg) -> text = 400: "Bad Request - client bug" 401: "Unauthorized - log in required" 403: "Forbidden" 404: "Not Found" 409: "Conflict" result = { error: text[code] } result.extended = msg if msg res.json code, result boolean = (val) -> val? and val in ['1', 't', 'y', 'true', 'yes'] loadUrl = (finder, param, attrib, req, res, next) -> finder req.params[param], (obj) -> return jsonError 404, res unless obj? req.fromUrl or= {} req.fromUrl[attrib] = obj next() loadUrlCommentSet = (req, res, next) -> loadUrl findCommentSet, 'commentset_id', 'commentSet', req, res, next loadUrlRun = (req, res, next) -> loadUrl findRun, 'run_id', 'run', req, res, next loadUrlTrack = (req, res, next) -> loadUrl findTrack, 'track_id', 'track', req, res, next loadUrlTrackRuns = (req, res, next) -> loadUrl findTrackRuns, 'track_id', 'trackRuns', req, res, next loadUrlTrackSet = (req, res, next) -> loadUrl findTrackSet, 'trackset_id', 'trackSet', req, res, next loadUrlUser = (req, res, next) -> loadUrl findUser, 'user_id', 'user', req, res, next editUrlTrack = (req, res, next) -> loadUrlTrack req, res, -> track = req.fromUrl.track # Real security check. return jsonError 401, res unless req.user? return jsonError 403, res unless track.user.id is req.user.user.pub_id # Opt-in sanity checks to help protect against client bugs. return jsonError 400, res, 'id mismatch' if req.body.id and req.body.id isnt track.id modifiedExpected = track.modified.toISOString() modifiedActual = req.body.modified if modifiedActual and modifiedActual isnt modifiedExpected return jsonError 409, res, "expired: expected #{modifiedExpected} but got #{modifiedActual}" next() editUrlUser = (req, res, next) -> loadUrlUser req, res, -> user = req.fromUrl.user return jsonError 401, res unless req.user? return jsonError 403, res unless user.id is req.user.user.pub_id next() filterAndSaveIfModified = (model, allowedKeys, req, res) -> attribs = _.pick req.body, allowedKeys prev = jsonClone _.pick model, allowedKeys if _.isEqual prev, attribs console.log "#{model.constructor.name} #{model.id}: no changes to save" return res.json {} if 'config' of attribs and not _.isEqual prev.config, attribs.config attribs.modified = new Date console.log "#{model.constructor.name} #{model.id}: saving changes" model.save attribs, success: -> res.json { modified: attribs.modified } error: -> jsonError 500, res app.get "#{base}/cars/:car_id", (req, res) -> findCar req.params['car_id'], (car) -> return jsonError 404, res unless car? products = req.user?.user.products res.json car.toJSON { products } app.post "#{base}/comments", (req, res) -> return jsonError 401, res unless req.user? findUser req.user.user.pub_id, (reqUser) -> return jsonError 500, res unless reqUser # TODO: Check that the comment parent/target actually exists. comment = new bb.Comment parent: req.body.parent text: req.body.text result = comment.save null, user: req.user.user success: (comment) -> res.json comment error: (model, err) -> console.log "Error creating comment: #{err}" jsonError 500, res if result is false console.log "Error creating comment: save failed" jsonError 500, res app.get "#{base}/commentsets/:commentset_id", loadUrlCommentSet, (req, res) -> res.json req.fromUrl.commentSet app.get "#{base}/envs/:env_id", (req, res) -> findEnv req.params['env_id'], (env) -> return jsonError 404, res unless env? # allowedEnvs = [ 'alp' ] # if req.user? # allowedEnvs = allowedEnvs.concat req.user.user.packs # restricted = env.id not in allowedEnvs res.json env #.toJSON { restricted } app.get "#{base}/runs/:run_id", (req, res) -> findRun req.params['run_id'], (run) -> return jsonError 404, res unless run? if run.record_p res.json run else run.fetch force: yes success: -> res.json run error: -> jsonError 500, res app.post "#{base}/tracks", (req, res) -> return jsonError 401, res unless req.user? findUser req.user.user.pub_id, (reqUser) -> return jsonError 500, res unless reqUser parentTrackId = req.body.parent findTrack parentTrackId, (parentTrack) -> return jsonError 404, res unless parentTrack? return jsonError 400, res unless parentTrack.env? return jsonError 403, res unless parentTrack.env.id is 'alp' return jsonError 403, res if parentTrack.prevent_copy # TODO: Check this user is allowed to copy tracks from this env. track = new bb.Track newName = parentTrack.name maxLength = bb.Track::maxNameLength - 5 if newName.length > maxLength then newName = newName.slice(0, maxLength - 3) + '...' newName += ' copy' track.set track.parse config: jsonClone parentTrack.config env: parentTrack.env.id name: newName parent: parentTrack.id prevent_copy: parentTrack.prevent_copy user: reqUser.id result = track.save null, user: req.user.user success: (track) -> res.json track reqUser.tracks.add track parentTrack.count_copy += 1 parentTrack.save() error: (model, err) -> console.log "Error creating track: #{err}" jsonError 500, res if result is false console.log "Error creating track: save failed" jsonError 500, res # TODO: Add a multi-ID track GET. app.get "#{base}/tracks/:track_id", loadUrlTrack, (req, res) -> res.json req.fromUrl.track # app.get "#{base}/tracks/:track_id/runs", loadUrlTrack, (req, res) -> # trackRuns = new bb.TrackRuns null, track: req.fromUrl.track # trackRuns.fetch # success: (collection) -> # res.json collection # error: (collection, err) -> # console.log "Error creating track: #{err}" # jsonError 500, res app.get "#{base}/tracks/:track_id/runs", loadUrlTrackRuns, (req, res) -> res.json req.fromUrl.trackRuns # app.get "#{base}/tracks/:track_id/bestrun", loadUrlTrack, (req, res) -> # req.fromUrl.track.getBestRun (run) -> # return jsonError 404, res unless run? # res.json { run } # app.get "#{base}/tracks/:track_id/personalbestrun", loadUrlTrackRuns, (req, res) -> # res.json req.fromUrl.trackRuns app.put "#{base}/tracks/:track_id", editUrlTrack, (req, res) -> track = req.fromUrl.track allowedKeys = [ '<KEY>', '<KEY>' ] unless track.published allowedKeys = allowedKeys.concat [ '<KEY>', '<KEY>' ] filterAndSaveIfModified track, allowedKeys, req, res app.post "#{base}/tracks/:track_id/drive", loadUrlTrack, (req, res) -> res.send 200 # Now handled by drive socket. # track = req.fromUrl.track # track.save { count_drive: track.count_drive + 1 } app.delete "#{base}/tracks/:track_id", editUrlTrack, (req, res) -> jsonError 403, res if req.fromUrl.track.id is 'v3-base-1' req.fromUrl.track.destroy success: -> res.json {} error: -> jsonError 500, res app.get "#{base}/tracksets/:trackset_id", loadUrlTrackSet, (req, res) -> res.json req.fromUrl.trackSet app.get "#{base}/users/:user_id", loadUrlUser, (req, res) -> user = req.fromUrl.user authenticated = user.id is req.user?.user.pub_id res.json user.toJSON { authenticated } app.put "#{base}/users/:user_id", editUrlUser, (req, res) -> products = req.fromUrl.user.products ? [] maySetPicture = 'ignition' in products or 'mayhem' in products or 'packa' in products return jsonError 403, res if 'picture' of req.body and not maySetPicture allowedKeys = [ '<KEY>' 'name' 'picture' ] filterAndSaveIfModified req.fromUrl.user, allowedKeys, req, res app.get "#{base}/auth/me", (req, res) -> if req.user?.user findUser req.user.user.pub_id, (user) -> return jsonError 404, res unless user? res.json user: user.toJSON { authenticated: yes } else res.json user: null return # Give a JSON 404 response for any unknown path under /v1/. app.get "#{base}/*", (req, res) -> jsonError 404, res return
true
_ = require('underscore') bb = require('./public/scripts/models') Backbone = bb.Backbone # Disable all caching on the server. bb.Model::useCache = no # Attach backbone models to MongoDB via Mongoose. require('./backbone-mongoose') bb jsonClone = (obj) -> JSON.parse JSON.stringify obj findModel = (Model, pub_id, done) -> model = Model.findOrCreate pub_id result = model.fetch success: -> done model error:(e1, e2) -> console.error('Error when loading model', pub_id) done null if result is false findCar = -> findModel(bb.Car, arguments...) findCommentSet = -> findModel(bb.CommentSet, arguments...) findEnv = -> findModel(bb.Env, arguments...) findRun = -> findModel(bb.Run, arguments...) findTrack = -> findModel(bb.Track, arguments...) findTrackRuns = -> findModel(bb.TrackRuns, arguments...) findTrackSet = -> findModel(bb.TrackSet, arguments...) findUser = -> findModel(bb.User, arguments...) # This public-facing API is responsible for validating requests and data. module.exports = findUser: findUser setup: (app) -> base = '/v1' jsonError = (code, res, msg) -> text = 400: "Bad Request - client bug" 401: "Unauthorized - log in required" 403: "Forbidden" 404: "Not Found" 409: "Conflict" result = { error: text[code] } result.extended = msg if msg res.json code, result boolean = (val) -> val? and val in ['1', 't', 'y', 'true', 'yes'] loadUrl = (finder, param, attrib, req, res, next) -> finder req.params[param], (obj) -> return jsonError 404, res unless obj? req.fromUrl or= {} req.fromUrl[attrib] = obj next() loadUrlCommentSet = (req, res, next) -> loadUrl findCommentSet, 'commentset_id', 'commentSet', req, res, next loadUrlRun = (req, res, next) -> loadUrl findRun, 'run_id', 'run', req, res, next loadUrlTrack = (req, res, next) -> loadUrl findTrack, 'track_id', 'track', req, res, next loadUrlTrackRuns = (req, res, next) -> loadUrl findTrackRuns, 'track_id', 'trackRuns', req, res, next loadUrlTrackSet = (req, res, next) -> loadUrl findTrackSet, 'trackset_id', 'trackSet', req, res, next loadUrlUser = (req, res, next) -> loadUrl findUser, 'user_id', 'user', req, res, next editUrlTrack = (req, res, next) -> loadUrlTrack req, res, -> track = req.fromUrl.track # Real security check. return jsonError 401, res unless req.user? return jsonError 403, res unless track.user.id is req.user.user.pub_id # Opt-in sanity checks to help protect against client bugs. return jsonError 400, res, 'id mismatch' if req.body.id and req.body.id isnt track.id modifiedExpected = track.modified.toISOString() modifiedActual = req.body.modified if modifiedActual and modifiedActual isnt modifiedExpected return jsonError 409, res, "expired: expected #{modifiedExpected} but got #{modifiedActual}" next() editUrlUser = (req, res, next) -> loadUrlUser req, res, -> user = req.fromUrl.user return jsonError 401, res unless req.user? return jsonError 403, res unless user.id is req.user.user.pub_id next() filterAndSaveIfModified = (model, allowedKeys, req, res) -> attribs = _.pick req.body, allowedKeys prev = jsonClone _.pick model, allowedKeys if _.isEqual prev, attribs console.log "#{model.constructor.name} #{model.id}: no changes to save" return res.json {} if 'config' of attribs and not _.isEqual prev.config, attribs.config attribs.modified = new Date console.log "#{model.constructor.name} #{model.id}: saving changes" model.save attribs, success: -> res.json { modified: attribs.modified } error: -> jsonError 500, res app.get "#{base}/cars/:car_id", (req, res) -> findCar req.params['car_id'], (car) -> return jsonError 404, res unless car? products = req.user?.user.products res.json car.toJSON { products } app.post "#{base}/comments", (req, res) -> return jsonError 401, res unless req.user? findUser req.user.user.pub_id, (reqUser) -> return jsonError 500, res unless reqUser # TODO: Check that the comment parent/target actually exists. comment = new bb.Comment parent: req.body.parent text: req.body.text result = comment.save null, user: req.user.user success: (comment) -> res.json comment error: (model, err) -> console.log "Error creating comment: #{err}" jsonError 500, res if result is false console.log "Error creating comment: save failed" jsonError 500, res app.get "#{base}/commentsets/:commentset_id", loadUrlCommentSet, (req, res) -> res.json req.fromUrl.commentSet app.get "#{base}/envs/:env_id", (req, res) -> findEnv req.params['env_id'], (env) -> return jsonError 404, res unless env? # allowedEnvs = [ 'alp' ] # if req.user? # allowedEnvs = allowedEnvs.concat req.user.user.packs # restricted = env.id not in allowedEnvs res.json env #.toJSON { restricted } app.get "#{base}/runs/:run_id", (req, res) -> findRun req.params['run_id'], (run) -> return jsonError 404, res unless run? if run.record_p res.json run else run.fetch force: yes success: -> res.json run error: -> jsonError 500, res app.post "#{base}/tracks", (req, res) -> return jsonError 401, res unless req.user? findUser req.user.user.pub_id, (reqUser) -> return jsonError 500, res unless reqUser parentTrackId = req.body.parent findTrack parentTrackId, (parentTrack) -> return jsonError 404, res unless parentTrack? return jsonError 400, res unless parentTrack.env? return jsonError 403, res unless parentTrack.env.id is 'alp' return jsonError 403, res if parentTrack.prevent_copy # TODO: Check this user is allowed to copy tracks from this env. track = new bb.Track newName = parentTrack.name maxLength = bb.Track::maxNameLength - 5 if newName.length > maxLength then newName = newName.slice(0, maxLength - 3) + '...' newName += ' copy' track.set track.parse config: jsonClone parentTrack.config env: parentTrack.env.id name: newName parent: parentTrack.id prevent_copy: parentTrack.prevent_copy user: reqUser.id result = track.save null, user: req.user.user success: (track) -> res.json track reqUser.tracks.add track parentTrack.count_copy += 1 parentTrack.save() error: (model, err) -> console.log "Error creating track: #{err}" jsonError 500, res if result is false console.log "Error creating track: save failed" jsonError 500, res # TODO: Add a multi-ID track GET. app.get "#{base}/tracks/:track_id", loadUrlTrack, (req, res) -> res.json req.fromUrl.track # app.get "#{base}/tracks/:track_id/runs", loadUrlTrack, (req, res) -> # trackRuns = new bb.TrackRuns null, track: req.fromUrl.track # trackRuns.fetch # success: (collection) -> # res.json collection # error: (collection, err) -> # console.log "Error creating track: #{err}" # jsonError 500, res app.get "#{base}/tracks/:track_id/runs", loadUrlTrackRuns, (req, res) -> res.json req.fromUrl.trackRuns # app.get "#{base}/tracks/:track_id/bestrun", loadUrlTrack, (req, res) -> # req.fromUrl.track.getBestRun (run) -> # return jsonError 404, res unless run? # res.json { run } # app.get "#{base}/tracks/:track_id/personalbestrun", loadUrlTrackRuns, (req, res) -> # res.json req.fromUrl.trackRuns app.put "#{base}/tracks/:track_id", editUrlTrack, (req, res) -> track = req.fromUrl.track allowedKeys = [ 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI' ] unless track.published allowedKeys = allowedKeys.concat [ 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI' ] filterAndSaveIfModified track, allowedKeys, req, res app.post "#{base}/tracks/:track_id/drive", loadUrlTrack, (req, res) -> res.send 200 # Now handled by drive socket. # track = req.fromUrl.track # track.save { count_drive: track.count_drive + 1 } app.delete "#{base}/tracks/:track_id", editUrlTrack, (req, res) -> jsonError 403, res if req.fromUrl.track.id is 'v3-base-1' req.fromUrl.track.destroy success: -> res.json {} error: -> jsonError 500, res app.get "#{base}/tracksets/:trackset_id", loadUrlTrackSet, (req, res) -> res.json req.fromUrl.trackSet app.get "#{base}/users/:user_id", loadUrlUser, (req, res) -> user = req.fromUrl.user authenticated = user.id is req.user?.user.pub_id res.json user.toJSON { authenticated } app.put "#{base}/users/:user_id", editUrlUser, (req, res) -> products = req.fromUrl.user.products ? [] maySetPicture = 'ignition' in products or 'mayhem' in products or 'packa' in products return jsonError 403, res if 'picture' of req.body and not maySetPicture allowedKeys = [ 'PI:KEY:<KEY>END_PI' 'name' 'picture' ] filterAndSaveIfModified req.fromUrl.user, allowedKeys, req, res app.get "#{base}/auth/me", (req, res) -> if req.user?.user findUser req.user.user.pub_id, (user) -> return jsonError 404, res unless user? res.json user: user.toJSON { authenticated: yes } else res.json user: null return # Give a JSON 404 response for any unknown path under /v1/. app.get "#{base}/*", (req, res) -> jsonError 404, res return
[ { "context": "cess.env[\"DATABASE_USER\"], \n password: process.env[\"DATABASE_PASS\"], \n database: process.env[\"DAT", "end": 1550, "score": 0.6870337128639221, "start": 1547, "tag": "PASSWORD", "value": "env" }, { "context": "env[\"DATABASE_USER\"], \n password: process.env[\"DATABASE_PASS\"], \n database: process.env[\"DATABASE_DB\"]", "end": 1560, "score": 0.7793542146682739, "start": 1552, "tag": "PASSWORD", "value": "DATABASE" }, { "context": "post '/login', (req,res) ->\n username = req.body.username\n password = SHA256 req.body.password\n dbAuthUse", "end": 8502, "score": 0.954807460308075, "start": 8494, "tag": "USERNAME", "value": "username" }, { "context": "es) ->\n username = req.body.username\n password = SHA256 req.body.password\n dbAuthUser username, password", "end": 8522, "score": 0.9856211543083191, "start": 8516, "tag": "PASSWORD", "value": "SHA256" }, { "context": " username = req.body.username\n password = SHA256 req.body.password\n dbAuthUser username, password.toString()\n .t", "end": 8540, "score": 0.9316975474357605, "start": 8523, "tag": "PASSWORD", "value": "req.body.password" } ]
src/server.coffee
Gnolfo/cgsk
1
express = require("express") http = require('http') # https = require('https') # fs = require('fs') path = require("path") # favicon = require("serve-favicon") logger = require("morgan") cookieParser = require("cookie-parser") bodyParser = require("body-parser") mysql = require('mysql') Q = require('q') SHA256 = require("crypto-js/sha256") session = require("client-sessions") hbs = require('hbs') json = require('hbs-json') express = require('express') exphbs = require('express-handlebars') debug = require("debug")("react-express-template") require("babel/register") dist = path.join(__dirname, '/../dist') assets = path.join(__dirname, '/../assets') app = express() # enable if you have a favicon # app.use favicon("#{dist}/favicon.ico") app.use logger("dev") app.use bodyParser.json() app.use bodyParser.urlencoded(extended: true) app.use cookieParser() app.use express.static(dist) app.use express.static(assets) # 150 day expiration app.use session( cookieName: "session", secret: process.env.SESSION_SALT, duration: 150 * 24 * 60 * 60 * 1000) app.set "port", process.env.PORT or 3000 app.engine 'handlebars', exphbs() app.set 'view engine', 'handlebars' app.set 'views', __dirname hbs.registerHelper 'json', json # # CORS support # # app.all '*', (req, res, next) -> # res.header("Access-Control-Allow-Origin", "*") # res.header("Access-Control-Allow-Headers", "X-Requested-With") # next() pool = mysql.createPool( host: process.env["DATABASE_HOST"], user: process.env["DATABASE_USER"], password: process.env["DATABASE_PASS"], database: process.env["DATABASE_DB"], waitForConnections: true, connectionLimit: 10, timezone: 'utc') closeDB = -> dbConnected = false dbConnection.end() dbQuery = (query, cb) -> debug = false console.log 'running: '+query if debug pool.query query, (err,results) -> console.log 'ran: '+query if debug cb err, results oldDbQuery = (query,cb) -> pool.getConnection (err, conn) -> throw err if err conn.query query, (err, results) -> cb err, results conn.release() dbGetCharacters = () -> deferred = Q.defer() dbQuery "SELECT * FROM characters", deferred.makeNodeResolver() deferred.promise dbGetLists = () -> deferred = Q.defer() dbQuery "SELECT * FROM lists", deferred.makeNodeResolver() deferred.promise dbGetLogs = () -> deferred = Q.defer() dbQuery "SELECT * FROM logs order by timestamp desc LIMIT 75", deferred.makeNodeResolver() deferred.promise dbGetBosses = -> deferred = Q.defer() dbQuery "SELECT * FROM bosses WHERE raid_data_id=12", deferred.makeNodeResolver() deferred.promise dbGetRaidData = -> deferred = Q.defer() dbQuery "SELECT b.id, b.name, b.position, b.avatar_url, i.item_id, i.list_id FROM bosses b JOIN items i on i.boss_id=b.id where b.raid_data_id=12", deferred.makeNodeResolver() deferred.promise # # Auth Queries # dbAuthUser = (username, password) -> deferred = Q.defer() dbQuery "SELECT * FROM users where username = "+mysql.escape(username)+" and password="+mysql.escape(password), deferred.makeNodeResolver() deferred.promise dbCheckUser = (id) -> deferred = Q.defer() dbQuery "SELECT * FROM users where id = "+mysql.escape(id), deferred.makeNodeResolver() deferred.promise # # Raid Queries # dbStartRaid = -> deferred = Q.defer() dbLogStart() dbQuery "INSERT INTO raids (raid_data_id, time_start) VALUES (12,UTC_TIMESTAMP())", deferred.makeNodeResolver() deferred.promise dbGetActives = (raid_id) -> raid_id = mysql.escape raid_id deferred = Q.defer() dbQuery "select * from raids_characters where raid_id=#{raid_id}", deferred.makeNodeResolver() deferred.promise dbEndRaid = (raid_id) -> raid_id = mysql.escape raid_id deferred = Q.defer() dbLogEnd() dbQuery "UPDATE raids set time_end=UTC_TIMESTAMP() where id=#{raid_id}", deferred.makeNodeResolver() deferred.promise dbGetOpenRaid = -> deferred = Q.defer() dbQuery "SELECT * FROM raids where time_end is null order by time_start limit 1", deferred.makeNodeResolver() deferred.promise dbAddRaiders = (raid_id, characters) -> deferred = Q.defer() raid_id = mysql.escape raid_id inserts = characters.map (v) -> dbLogAddRem v, true "(#{raid_id},"+(mysql.escape v)+")" sql = "insert into raids_characters (raid_id, character_id) VALUES "+inserts.join ",\n" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbRemRaiders = (raid_id, characters) -> deferred = Q.defer() raid_id = mysql.escape raid_id list = characters.map (v) -> dbLogAddRem v, false mysql.escape v sql = "delete from raids_characters WHERE raid_id="+raid_id+" and character_id in ("+(inserts.join ",")+")" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbArchiveList = (raid_id) -> deferred = Q.defer() raid_id = mysql.escape raid_id sql = "insert into raids_list_log (raid_id, list_id, character_id, position) select #{raid_id}, list_id, character_id, position from lists" dbQuery sql, deferred.makeNodeResolver() deferred.promise # # Logging Queries # dbLogStart = -> deferred = Q.defer() sql = "insert into logs (action, timestamp) VALUES ('start', UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogEnd = -> deferred = Q.defer() sql = "insert into logs (action, timestamp) VALUES ('end', UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogAddRem = (character_id, add) -> character_id = mysql.escape character_id deferred = Q.defer() action = mysql.escape (if add then 'add' else 'rem') sql = "insert into logs (action, subject_id, timestamp) VALUES ("+action+","+character_id+", UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogBoss = (boss_id) -> boss_id = mysql.escape boss_id deferred = Q.defer() sql = "insert into logs (action, subject_id, timestamp) VALUES ('boss',"+boss_id+", UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogLoot = (raid_id, character_id, item_id) -> raid_id = mysql.escape raid_id character_id = mysql.escape character_id item_id = mysql.escape item_id deferred = Q.defer() sql = "insert into logs (action, subject_id, object_id, timestamp) VALUES ('loot',"+character_id+","+item_id+", UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise # # Tricky query to get all active people (including looter) who will be affected in the lists from a loot suicide # dbGetActivesForSuicide = (raid_id, list_id, character_id) -> raid_id = mysql.escape raid_id list_id = mysql.escape list_id character_id = mysql.escape character_id deferred = Q.defer() sql = "select l.* from lists looter join lists l on l.list_id=#{list_id} and l.position >= looter.position join raids_characters rc on rc.character_id=l.character_id where looter.list_id=#{list_id} and rc.raid_id=#{raid_id} and looter.character_id=#{character_id} order by l.position asc " dbQuery sql, deferred.makeNodeResolver() deferred.promise # # Query to move around character positions in a list # new_ranks is an array of character_id/position pairs that reflect where they should move to # anyone not in new_ranks will keep their position # dbChangeRankings = (list_id, new_ranks) -> list_id = mysql.escape list_id updates = new_ranks.map (v) -> deferred = Q.defer() position = mysql.escape v.position character_id = mysql.escape v.character_id dbQuery "update lists set position=#{position} where list_id=#{list_id} and character_id=#{character_id}", deferred.makeNodeResolver() deferred.promise Q.all updates # # Utility # assembleListsForFrontend = (list_rows) -> list_rows.reduce (pv, cv) -> pv[cv.list_id] = {} unless typeof pv[cv.list_id] is 'object' pv[cv.list_id][cv.position] = cv pv , {} app.use (req,res,next) -> user_id = req.session?.user?.id req.user = req.session.user if user_id? and dbCheckUser user_id next() authRequired = (req,res,next) -> if req.session?.user? next() else res.status(400).send(message: 'You must be logged in!') app.get '/test', (req,res) -> dbGetOpenRaid() .then (raid) -> raid_id = if raid.length > 0 then raid.pop().id else false res.send(raid:raid_id) app.post '/login', (req,res) -> username = req.body.username password = SHA256 req.body.password dbAuthUser username, password.toString() .then (users) -> success = users.length > 0 if success cookie_user = users.shift() delete cookie_user.password req.session = user:cookie_user res.locals = user:cookie_user res.send(success: success) app.post '/logout', (req,res) -> req.session.destroy() if req.session? res.send(success:true) app.post '/loot', authRequired, (req,res) -> list_id = req.body.list_id character_id = req.body.character_id item_id = req.body.item_id raid_id = req.body.raid_id dbGetActivesForSuicide(raid_id, list_id, character_id) .then (old_ranks) -> # The actual suicide logic, first sort the rankings of actives by position (looter should be first thanks to getActivesForSuicide) old_ranks.sort (a,b) -> a.position - b.position # next two lines destructure the looter from the remaining actives and put them at the bottom of actives in transition_ranks # essentially the heart of SK in two lines of code [looter, actives...] = old_ranks transition_ranks = [actives..., looter] # But now we have to stitch the positions back together, essentially charcters draw from transition and position draws from old_ranks # The result is the looter gets the position of the last active, and all actives trade up their position w/ the top active getting the old looter position new_ranks = transition_ranks.map (v,i) -> position: old_ranks[i].position, character_id: v.character_id dbChangeRankings list_id, new_ranks .then -> dbLogLoot raid_id, character_id, item_id dbGetLists() .then (rankings) -> res.send lists: (assembleListsForFrontend rankings) app.post '/start', authRequired, (req,res) -> dbGetOpenRaid() .then (raid) -> if raid.length > 0 res.status(400).send error: 'an open raid already exists' else characters = req.body.characters dbStartRaid() .then (results) -> raid_id = results.insertId dbAddRaiders(raid_id, characters) .then -> res.send(raid_id: results.insertId) app.post '/end', authRequired, (req,res) -> raid_id = req.body.raid_id dbEndRaid raid_id .then -> dbArchiveList raid_id res.send success:true app.post '/boss', authRequired, (req,res) -> boss_id = req.body.boss_id dbLogBoss() .then -> res.send success:true app.post '/add', authRequired, (req,res) -> raid_id = req.body.raid_id characters = req.body.characters dbAddRaiders(raid_id, characters) .then -> res.send success:true app.post '/rem', authRequired, (req,res) -> raid_id = req.body.raid_id characters = req.body.characters dbRemRaiders(raid_id, characters) .then -> res.send success:true app.get '/', (req, res) -> Q.all [dbGetCharacters(), dbGetLists(), dbGetLogs(), dbGetRaidData(), dbGetOpenRaid(), dbGetActives()] .spread (characters, lists, logs, raid_data, open_raid, active_raiders) -> characters = characters.reduce (pv, cv) -> pv[cv.id] = cv pv , {} lists = assembleListsForFrontend lists raid_data = raid_data.reduce (pv,cv) -> pv[cv.id] = (id: cv.id, name: cv.name, avatar_url: cv.avatar_url, items:[], position:cv.position) unless pv[cv.id]? pv[cv.id].items.push(item_id: cv.item_id, list_id: cv.list_id) pv ,{} raid_id = if open_raid.length > 0 then open_raid.pop().id else false if raid_id != false dbGetActives(raid_id) .then (raiders) -> active_raiders = raiders.map (v) -> id: v.character_id, active: true res.render 'index.hbs', (characters:characters, lists: lists, logs: logs, raid_data: raid_data, raid_id: raid_id, active_raiders: active_raiders, logged_in: req.user?) else res.render 'index.hbs', (characters:characters, lists: lists, logs: logs, raid_data: raid_data, raid_id: raid_id, active_raiders: [], logged_in: req.user?) ## catch 404 and forwarding to error handler app.use (req, res, next) -> err = new Error("Not Found") err.status = 404 next err ## error handlers # development error handler # will print stacktrace if app.get("env") is "development" app.use (err, req, res, next) -> res.status err.status or 500 res.send(message: err.message, status: err.status, stack: err.stack) # production error handler # no stacktraces leaked to user app.use (err, req, res, next) -> res.status err.status or 500 res.send(message: err.message) # # HTTPS support # # options = key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') # httpsServer = https.createServer(options, app) # httpsServer.listen app.get("port"), -> # debug "Express https server listening on port " + httpsServer.address().port server = http.createServer(app) server.listen app.get("port"), -> debug "Express server listening on port " + server.address().port
43573
express = require("express") http = require('http') # https = require('https') # fs = require('fs') path = require("path") # favicon = require("serve-favicon") logger = require("morgan") cookieParser = require("cookie-parser") bodyParser = require("body-parser") mysql = require('mysql') Q = require('q') SHA256 = require("crypto-js/sha256") session = require("client-sessions") hbs = require('hbs') json = require('hbs-json') express = require('express') exphbs = require('express-handlebars') debug = require("debug")("react-express-template") require("babel/register") dist = path.join(__dirname, '/../dist') assets = path.join(__dirname, '/../assets') app = express() # enable if you have a favicon # app.use favicon("#{dist}/favicon.ico") app.use logger("dev") app.use bodyParser.json() app.use bodyParser.urlencoded(extended: true) app.use cookieParser() app.use express.static(dist) app.use express.static(assets) # 150 day expiration app.use session( cookieName: "session", secret: process.env.SESSION_SALT, duration: 150 * 24 * 60 * 60 * 1000) app.set "port", process.env.PORT or 3000 app.engine 'handlebars', exphbs() app.set 'view engine', 'handlebars' app.set 'views', __dirname hbs.registerHelper 'json', json # # CORS support # # app.all '*', (req, res, next) -> # res.header("Access-Control-Allow-Origin", "*") # res.header("Access-Control-Allow-Headers", "X-Requested-With") # next() pool = mysql.createPool( host: process.env["DATABASE_HOST"], user: process.env["DATABASE_USER"], password: process.<PASSWORD>["<PASSWORD>_PASS"], database: process.env["DATABASE_DB"], waitForConnections: true, connectionLimit: 10, timezone: 'utc') closeDB = -> dbConnected = false dbConnection.end() dbQuery = (query, cb) -> debug = false console.log 'running: '+query if debug pool.query query, (err,results) -> console.log 'ran: '+query if debug cb err, results oldDbQuery = (query,cb) -> pool.getConnection (err, conn) -> throw err if err conn.query query, (err, results) -> cb err, results conn.release() dbGetCharacters = () -> deferred = Q.defer() dbQuery "SELECT * FROM characters", deferred.makeNodeResolver() deferred.promise dbGetLists = () -> deferred = Q.defer() dbQuery "SELECT * FROM lists", deferred.makeNodeResolver() deferred.promise dbGetLogs = () -> deferred = Q.defer() dbQuery "SELECT * FROM logs order by timestamp desc LIMIT 75", deferred.makeNodeResolver() deferred.promise dbGetBosses = -> deferred = Q.defer() dbQuery "SELECT * FROM bosses WHERE raid_data_id=12", deferred.makeNodeResolver() deferred.promise dbGetRaidData = -> deferred = Q.defer() dbQuery "SELECT b.id, b.name, b.position, b.avatar_url, i.item_id, i.list_id FROM bosses b JOIN items i on i.boss_id=b.id where b.raid_data_id=12", deferred.makeNodeResolver() deferred.promise # # Auth Queries # dbAuthUser = (username, password) -> deferred = Q.defer() dbQuery "SELECT * FROM users where username = "+mysql.escape(username)+" and password="+mysql.escape(password), deferred.makeNodeResolver() deferred.promise dbCheckUser = (id) -> deferred = Q.defer() dbQuery "SELECT * FROM users where id = "+mysql.escape(id), deferred.makeNodeResolver() deferred.promise # # Raid Queries # dbStartRaid = -> deferred = Q.defer() dbLogStart() dbQuery "INSERT INTO raids (raid_data_id, time_start) VALUES (12,UTC_TIMESTAMP())", deferred.makeNodeResolver() deferred.promise dbGetActives = (raid_id) -> raid_id = mysql.escape raid_id deferred = Q.defer() dbQuery "select * from raids_characters where raid_id=#{raid_id}", deferred.makeNodeResolver() deferred.promise dbEndRaid = (raid_id) -> raid_id = mysql.escape raid_id deferred = Q.defer() dbLogEnd() dbQuery "UPDATE raids set time_end=UTC_TIMESTAMP() where id=#{raid_id}", deferred.makeNodeResolver() deferred.promise dbGetOpenRaid = -> deferred = Q.defer() dbQuery "SELECT * FROM raids where time_end is null order by time_start limit 1", deferred.makeNodeResolver() deferred.promise dbAddRaiders = (raid_id, characters) -> deferred = Q.defer() raid_id = mysql.escape raid_id inserts = characters.map (v) -> dbLogAddRem v, true "(#{raid_id},"+(mysql.escape v)+")" sql = "insert into raids_characters (raid_id, character_id) VALUES "+inserts.join ",\n" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbRemRaiders = (raid_id, characters) -> deferred = Q.defer() raid_id = mysql.escape raid_id list = characters.map (v) -> dbLogAddRem v, false mysql.escape v sql = "delete from raids_characters WHERE raid_id="+raid_id+" and character_id in ("+(inserts.join ",")+")" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbArchiveList = (raid_id) -> deferred = Q.defer() raid_id = mysql.escape raid_id sql = "insert into raids_list_log (raid_id, list_id, character_id, position) select #{raid_id}, list_id, character_id, position from lists" dbQuery sql, deferred.makeNodeResolver() deferred.promise # # Logging Queries # dbLogStart = -> deferred = Q.defer() sql = "insert into logs (action, timestamp) VALUES ('start', UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogEnd = -> deferred = Q.defer() sql = "insert into logs (action, timestamp) VALUES ('end', UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogAddRem = (character_id, add) -> character_id = mysql.escape character_id deferred = Q.defer() action = mysql.escape (if add then 'add' else 'rem') sql = "insert into logs (action, subject_id, timestamp) VALUES ("+action+","+character_id+", UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogBoss = (boss_id) -> boss_id = mysql.escape boss_id deferred = Q.defer() sql = "insert into logs (action, subject_id, timestamp) VALUES ('boss',"+boss_id+", UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogLoot = (raid_id, character_id, item_id) -> raid_id = mysql.escape raid_id character_id = mysql.escape character_id item_id = mysql.escape item_id deferred = Q.defer() sql = "insert into logs (action, subject_id, object_id, timestamp) VALUES ('loot',"+character_id+","+item_id+", UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise # # Tricky query to get all active people (including looter) who will be affected in the lists from a loot suicide # dbGetActivesForSuicide = (raid_id, list_id, character_id) -> raid_id = mysql.escape raid_id list_id = mysql.escape list_id character_id = mysql.escape character_id deferred = Q.defer() sql = "select l.* from lists looter join lists l on l.list_id=#{list_id} and l.position >= looter.position join raids_characters rc on rc.character_id=l.character_id where looter.list_id=#{list_id} and rc.raid_id=#{raid_id} and looter.character_id=#{character_id} order by l.position asc " dbQuery sql, deferred.makeNodeResolver() deferred.promise # # Query to move around character positions in a list # new_ranks is an array of character_id/position pairs that reflect where they should move to # anyone not in new_ranks will keep their position # dbChangeRankings = (list_id, new_ranks) -> list_id = mysql.escape list_id updates = new_ranks.map (v) -> deferred = Q.defer() position = mysql.escape v.position character_id = mysql.escape v.character_id dbQuery "update lists set position=#{position} where list_id=#{list_id} and character_id=#{character_id}", deferred.makeNodeResolver() deferred.promise Q.all updates # # Utility # assembleListsForFrontend = (list_rows) -> list_rows.reduce (pv, cv) -> pv[cv.list_id] = {} unless typeof pv[cv.list_id] is 'object' pv[cv.list_id][cv.position] = cv pv , {} app.use (req,res,next) -> user_id = req.session?.user?.id req.user = req.session.user if user_id? and dbCheckUser user_id next() authRequired = (req,res,next) -> if req.session?.user? next() else res.status(400).send(message: 'You must be logged in!') app.get '/test', (req,res) -> dbGetOpenRaid() .then (raid) -> raid_id = if raid.length > 0 then raid.pop().id else false res.send(raid:raid_id) app.post '/login', (req,res) -> username = req.body.username password = <PASSWORD> <PASSWORD> dbAuthUser username, password.toString() .then (users) -> success = users.length > 0 if success cookie_user = users.shift() delete cookie_user.password req.session = user:cookie_user res.locals = user:cookie_user res.send(success: success) app.post '/logout', (req,res) -> req.session.destroy() if req.session? res.send(success:true) app.post '/loot', authRequired, (req,res) -> list_id = req.body.list_id character_id = req.body.character_id item_id = req.body.item_id raid_id = req.body.raid_id dbGetActivesForSuicide(raid_id, list_id, character_id) .then (old_ranks) -> # The actual suicide logic, first sort the rankings of actives by position (looter should be first thanks to getActivesForSuicide) old_ranks.sort (a,b) -> a.position - b.position # next two lines destructure the looter from the remaining actives and put them at the bottom of actives in transition_ranks # essentially the heart of SK in two lines of code [looter, actives...] = old_ranks transition_ranks = [actives..., looter] # But now we have to stitch the positions back together, essentially charcters draw from transition and position draws from old_ranks # The result is the looter gets the position of the last active, and all actives trade up their position w/ the top active getting the old looter position new_ranks = transition_ranks.map (v,i) -> position: old_ranks[i].position, character_id: v.character_id dbChangeRankings list_id, new_ranks .then -> dbLogLoot raid_id, character_id, item_id dbGetLists() .then (rankings) -> res.send lists: (assembleListsForFrontend rankings) app.post '/start', authRequired, (req,res) -> dbGetOpenRaid() .then (raid) -> if raid.length > 0 res.status(400).send error: 'an open raid already exists' else characters = req.body.characters dbStartRaid() .then (results) -> raid_id = results.insertId dbAddRaiders(raid_id, characters) .then -> res.send(raid_id: results.insertId) app.post '/end', authRequired, (req,res) -> raid_id = req.body.raid_id dbEndRaid raid_id .then -> dbArchiveList raid_id res.send success:true app.post '/boss', authRequired, (req,res) -> boss_id = req.body.boss_id dbLogBoss() .then -> res.send success:true app.post '/add', authRequired, (req,res) -> raid_id = req.body.raid_id characters = req.body.characters dbAddRaiders(raid_id, characters) .then -> res.send success:true app.post '/rem', authRequired, (req,res) -> raid_id = req.body.raid_id characters = req.body.characters dbRemRaiders(raid_id, characters) .then -> res.send success:true app.get '/', (req, res) -> Q.all [dbGetCharacters(), dbGetLists(), dbGetLogs(), dbGetRaidData(), dbGetOpenRaid(), dbGetActives()] .spread (characters, lists, logs, raid_data, open_raid, active_raiders) -> characters = characters.reduce (pv, cv) -> pv[cv.id] = cv pv , {} lists = assembleListsForFrontend lists raid_data = raid_data.reduce (pv,cv) -> pv[cv.id] = (id: cv.id, name: cv.name, avatar_url: cv.avatar_url, items:[], position:cv.position) unless pv[cv.id]? pv[cv.id].items.push(item_id: cv.item_id, list_id: cv.list_id) pv ,{} raid_id = if open_raid.length > 0 then open_raid.pop().id else false if raid_id != false dbGetActives(raid_id) .then (raiders) -> active_raiders = raiders.map (v) -> id: v.character_id, active: true res.render 'index.hbs', (characters:characters, lists: lists, logs: logs, raid_data: raid_data, raid_id: raid_id, active_raiders: active_raiders, logged_in: req.user?) else res.render 'index.hbs', (characters:characters, lists: lists, logs: logs, raid_data: raid_data, raid_id: raid_id, active_raiders: [], logged_in: req.user?) ## catch 404 and forwarding to error handler app.use (req, res, next) -> err = new Error("Not Found") err.status = 404 next err ## error handlers # development error handler # will print stacktrace if app.get("env") is "development" app.use (err, req, res, next) -> res.status err.status or 500 res.send(message: err.message, status: err.status, stack: err.stack) # production error handler # no stacktraces leaked to user app.use (err, req, res, next) -> res.status err.status or 500 res.send(message: err.message) # # HTTPS support # # options = key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') # httpsServer = https.createServer(options, app) # httpsServer.listen app.get("port"), -> # debug "Express https server listening on port " + httpsServer.address().port server = http.createServer(app) server.listen app.get("port"), -> debug "Express server listening on port " + server.address().port
true
express = require("express") http = require('http') # https = require('https') # fs = require('fs') path = require("path") # favicon = require("serve-favicon") logger = require("morgan") cookieParser = require("cookie-parser") bodyParser = require("body-parser") mysql = require('mysql') Q = require('q') SHA256 = require("crypto-js/sha256") session = require("client-sessions") hbs = require('hbs') json = require('hbs-json') express = require('express') exphbs = require('express-handlebars') debug = require("debug")("react-express-template") require("babel/register") dist = path.join(__dirname, '/../dist') assets = path.join(__dirname, '/../assets') app = express() # enable if you have a favicon # app.use favicon("#{dist}/favicon.ico") app.use logger("dev") app.use bodyParser.json() app.use bodyParser.urlencoded(extended: true) app.use cookieParser() app.use express.static(dist) app.use express.static(assets) # 150 day expiration app.use session( cookieName: "session", secret: process.env.SESSION_SALT, duration: 150 * 24 * 60 * 60 * 1000) app.set "port", process.env.PORT or 3000 app.engine 'handlebars', exphbs() app.set 'view engine', 'handlebars' app.set 'views', __dirname hbs.registerHelper 'json', json # # CORS support # # app.all '*', (req, res, next) -> # res.header("Access-Control-Allow-Origin", "*") # res.header("Access-Control-Allow-Headers", "X-Requested-With") # next() pool = mysql.createPool( host: process.env["DATABASE_HOST"], user: process.env["DATABASE_USER"], password: process.PI:PASSWORD:<PASSWORD>END_PI["PI:PASSWORD:<PASSWORD>END_PI_PASS"], database: process.env["DATABASE_DB"], waitForConnections: true, connectionLimit: 10, timezone: 'utc') closeDB = -> dbConnected = false dbConnection.end() dbQuery = (query, cb) -> debug = false console.log 'running: '+query if debug pool.query query, (err,results) -> console.log 'ran: '+query if debug cb err, results oldDbQuery = (query,cb) -> pool.getConnection (err, conn) -> throw err if err conn.query query, (err, results) -> cb err, results conn.release() dbGetCharacters = () -> deferred = Q.defer() dbQuery "SELECT * FROM characters", deferred.makeNodeResolver() deferred.promise dbGetLists = () -> deferred = Q.defer() dbQuery "SELECT * FROM lists", deferred.makeNodeResolver() deferred.promise dbGetLogs = () -> deferred = Q.defer() dbQuery "SELECT * FROM logs order by timestamp desc LIMIT 75", deferred.makeNodeResolver() deferred.promise dbGetBosses = -> deferred = Q.defer() dbQuery "SELECT * FROM bosses WHERE raid_data_id=12", deferred.makeNodeResolver() deferred.promise dbGetRaidData = -> deferred = Q.defer() dbQuery "SELECT b.id, b.name, b.position, b.avatar_url, i.item_id, i.list_id FROM bosses b JOIN items i on i.boss_id=b.id where b.raid_data_id=12", deferred.makeNodeResolver() deferred.promise # # Auth Queries # dbAuthUser = (username, password) -> deferred = Q.defer() dbQuery "SELECT * FROM users where username = "+mysql.escape(username)+" and password="+mysql.escape(password), deferred.makeNodeResolver() deferred.promise dbCheckUser = (id) -> deferred = Q.defer() dbQuery "SELECT * FROM users where id = "+mysql.escape(id), deferred.makeNodeResolver() deferred.promise # # Raid Queries # dbStartRaid = -> deferred = Q.defer() dbLogStart() dbQuery "INSERT INTO raids (raid_data_id, time_start) VALUES (12,UTC_TIMESTAMP())", deferred.makeNodeResolver() deferred.promise dbGetActives = (raid_id) -> raid_id = mysql.escape raid_id deferred = Q.defer() dbQuery "select * from raids_characters where raid_id=#{raid_id}", deferred.makeNodeResolver() deferred.promise dbEndRaid = (raid_id) -> raid_id = mysql.escape raid_id deferred = Q.defer() dbLogEnd() dbQuery "UPDATE raids set time_end=UTC_TIMESTAMP() where id=#{raid_id}", deferred.makeNodeResolver() deferred.promise dbGetOpenRaid = -> deferred = Q.defer() dbQuery "SELECT * FROM raids where time_end is null order by time_start limit 1", deferred.makeNodeResolver() deferred.promise dbAddRaiders = (raid_id, characters) -> deferred = Q.defer() raid_id = mysql.escape raid_id inserts = characters.map (v) -> dbLogAddRem v, true "(#{raid_id},"+(mysql.escape v)+")" sql = "insert into raids_characters (raid_id, character_id) VALUES "+inserts.join ",\n" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbRemRaiders = (raid_id, characters) -> deferred = Q.defer() raid_id = mysql.escape raid_id list = characters.map (v) -> dbLogAddRem v, false mysql.escape v sql = "delete from raids_characters WHERE raid_id="+raid_id+" and character_id in ("+(inserts.join ",")+")" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbArchiveList = (raid_id) -> deferred = Q.defer() raid_id = mysql.escape raid_id sql = "insert into raids_list_log (raid_id, list_id, character_id, position) select #{raid_id}, list_id, character_id, position from lists" dbQuery sql, deferred.makeNodeResolver() deferred.promise # # Logging Queries # dbLogStart = -> deferred = Q.defer() sql = "insert into logs (action, timestamp) VALUES ('start', UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogEnd = -> deferred = Q.defer() sql = "insert into logs (action, timestamp) VALUES ('end', UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogAddRem = (character_id, add) -> character_id = mysql.escape character_id deferred = Q.defer() action = mysql.escape (if add then 'add' else 'rem') sql = "insert into logs (action, subject_id, timestamp) VALUES ("+action+","+character_id+", UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogBoss = (boss_id) -> boss_id = mysql.escape boss_id deferred = Q.defer() sql = "insert into logs (action, subject_id, timestamp) VALUES ('boss',"+boss_id+", UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise dbLogLoot = (raid_id, character_id, item_id) -> raid_id = mysql.escape raid_id character_id = mysql.escape character_id item_id = mysql.escape item_id deferred = Q.defer() sql = "insert into logs (action, subject_id, object_id, timestamp) VALUES ('loot',"+character_id+","+item_id+", UTC_TIMESTAMP() )" dbQuery sql, deferred.makeNodeResolver() deferred.promise # # Tricky query to get all active people (including looter) who will be affected in the lists from a loot suicide # dbGetActivesForSuicide = (raid_id, list_id, character_id) -> raid_id = mysql.escape raid_id list_id = mysql.escape list_id character_id = mysql.escape character_id deferred = Q.defer() sql = "select l.* from lists looter join lists l on l.list_id=#{list_id} and l.position >= looter.position join raids_characters rc on rc.character_id=l.character_id where looter.list_id=#{list_id} and rc.raid_id=#{raid_id} and looter.character_id=#{character_id} order by l.position asc " dbQuery sql, deferred.makeNodeResolver() deferred.promise # # Query to move around character positions in a list # new_ranks is an array of character_id/position pairs that reflect where they should move to # anyone not in new_ranks will keep their position # dbChangeRankings = (list_id, new_ranks) -> list_id = mysql.escape list_id updates = new_ranks.map (v) -> deferred = Q.defer() position = mysql.escape v.position character_id = mysql.escape v.character_id dbQuery "update lists set position=#{position} where list_id=#{list_id} and character_id=#{character_id}", deferred.makeNodeResolver() deferred.promise Q.all updates # # Utility # assembleListsForFrontend = (list_rows) -> list_rows.reduce (pv, cv) -> pv[cv.list_id] = {} unless typeof pv[cv.list_id] is 'object' pv[cv.list_id][cv.position] = cv pv , {} app.use (req,res,next) -> user_id = req.session?.user?.id req.user = req.session.user if user_id? and dbCheckUser user_id next() authRequired = (req,res,next) -> if req.session?.user? next() else res.status(400).send(message: 'You must be logged in!') app.get '/test', (req,res) -> dbGetOpenRaid() .then (raid) -> raid_id = if raid.length > 0 then raid.pop().id else false res.send(raid:raid_id) app.post '/login', (req,res) -> username = req.body.username password = PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<PASSWORD>END_PI dbAuthUser username, password.toString() .then (users) -> success = users.length > 0 if success cookie_user = users.shift() delete cookie_user.password req.session = user:cookie_user res.locals = user:cookie_user res.send(success: success) app.post '/logout', (req,res) -> req.session.destroy() if req.session? res.send(success:true) app.post '/loot', authRequired, (req,res) -> list_id = req.body.list_id character_id = req.body.character_id item_id = req.body.item_id raid_id = req.body.raid_id dbGetActivesForSuicide(raid_id, list_id, character_id) .then (old_ranks) -> # The actual suicide logic, first sort the rankings of actives by position (looter should be first thanks to getActivesForSuicide) old_ranks.sort (a,b) -> a.position - b.position # next two lines destructure the looter from the remaining actives and put them at the bottom of actives in transition_ranks # essentially the heart of SK in two lines of code [looter, actives...] = old_ranks transition_ranks = [actives..., looter] # But now we have to stitch the positions back together, essentially charcters draw from transition and position draws from old_ranks # The result is the looter gets the position of the last active, and all actives trade up their position w/ the top active getting the old looter position new_ranks = transition_ranks.map (v,i) -> position: old_ranks[i].position, character_id: v.character_id dbChangeRankings list_id, new_ranks .then -> dbLogLoot raid_id, character_id, item_id dbGetLists() .then (rankings) -> res.send lists: (assembleListsForFrontend rankings) app.post '/start', authRequired, (req,res) -> dbGetOpenRaid() .then (raid) -> if raid.length > 0 res.status(400).send error: 'an open raid already exists' else characters = req.body.characters dbStartRaid() .then (results) -> raid_id = results.insertId dbAddRaiders(raid_id, characters) .then -> res.send(raid_id: results.insertId) app.post '/end', authRequired, (req,res) -> raid_id = req.body.raid_id dbEndRaid raid_id .then -> dbArchiveList raid_id res.send success:true app.post '/boss', authRequired, (req,res) -> boss_id = req.body.boss_id dbLogBoss() .then -> res.send success:true app.post '/add', authRequired, (req,res) -> raid_id = req.body.raid_id characters = req.body.characters dbAddRaiders(raid_id, characters) .then -> res.send success:true app.post '/rem', authRequired, (req,res) -> raid_id = req.body.raid_id characters = req.body.characters dbRemRaiders(raid_id, characters) .then -> res.send success:true app.get '/', (req, res) -> Q.all [dbGetCharacters(), dbGetLists(), dbGetLogs(), dbGetRaidData(), dbGetOpenRaid(), dbGetActives()] .spread (characters, lists, logs, raid_data, open_raid, active_raiders) -> characters = characters.reduce (pv, cv) -> pv[cv.id] = cv pv , {} lists = assembleListsForFrontend lists raid_data = raid_data.reduce (pv,cv) -> pv[cv.id] = (id: cv.id, name: cv.name, avatar_url: cv.avatar_url, items:[], position:cv.position) unless pv[cv.id]? pv[cv.id].items.push(item_id: cv.item_id, list_id: cv.list_id) pv ,{} raid_id = if open_raid.length > 0 then open_raid.pop().id else false if raid_id != false dbGetActives(raid_id) .then (raiders) -> active_raiders = raiders.map (v) -> id: v.character_id, active: true res.render 'index.hbs', (characters:characters, lists: lists, logs: logs, raid_data: raid_data, raid_id: raid_id, active_raiders: active_raiders, logged_in: req.user?) else res.render 'index.hbs', (characters:characters, lists: lists, logs: logs, raid_data: raid_data, raid_id: raid_id, active_raiders: [], logged_in: req.user?) ## catch 404 and forwarding to error handler app.use (req, res, next) -> err = new Error("Not Found") err.status = 404 next err ## error handlers # development error handler # will print stacktrace if app.get("env") is "development" app.use (err, req, res, next) -> res.status err.status or 500 res.send(message: err.message, status: err.status, stack: err.stack) # production error handler # no stacktraces leaked to user app.use (err, req, res, next) -> res.status err.status or 500 res.send(message: err.message) # # HTTPS support # # options = key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') # httpsServer = https.createServer(options, app) # httpsServer.listen app.get("port"), -> # debug "Express https server listening on port " + httpsServer.address().port server = http.createServer(app) server.listen app.get("port"), -> debug "Express server listening on port " + server.address().port
[ { "context": " or in\n # the frontend config (Jyrki Niemi 2014-09-04).\n util.copyCorpusI", "end": 12650, "score": 0.9296979904174805, "start": 12639, "tag": "NAME", "value": "Jyrki Niemi" }, { "context": "to\n # all subfolders and corpora. (Jyrki Niemi 2014-09-08)\n for folder_name of se", "end": 12847, "score": 0.930816650390625, "start": 12836, "tag": "NAME", "value": "Jyrki Niemi" }, { "context": "uld not need to be\n # special-cased here. (Jyrki Niemi 2015-12-04)\n if settings.lemgramService ==", "end": 16156, "score": 0.9996881484985352, "start": 16145, "tag": "NAME", "value": "Jyrki Niemi" }, { "context": " avoid the need to encode long lists of corpora. (Jyrki\n # Niemi 2017-09-29)\n http_", "end": 16529, "score": 0.9985774159431458, "start": 16524, "tag": "NAME", "value": "Jyrki" }, { "context": "encode long lists of corpora. (Jyrki\n # Niemi 2017-09-29)\n http_params =\n ", "end": 16549, "score": 0.997532069683075, "start": 16544, "tag": "NAME", "value": "Niemi" }, { "context": " # Support an alternative lemgram service (Jyrki Niemi\n # 2015-12-04)\n if ", "end": 17256, "score": 0.999157726764679, "start": 17245, "tag": "NAME", "value": "Jyrki Niemi" } ]
app/scripts/services.coffee
CSCfi/Kielipankki-korp-frontend
0
korpApp = angular.module("korpApp") korpApp.factory "utils", ($location) -> valfilter : (attrobj) -> return if attrobj.isStructAttr then "_." + attrobj.value else attrobj.value setupHash : (scope, config) -> onWatch = () -> for obj in config val = $location.search()[obj.key] unless val if obj.default? then val = obj.default else continue val = (obj.val_in or _.identity)(val) if "scope_name" of obj scope[obj.scope_name] = val else if "scope_func" of obj scope[obj.scope_func](val) else scope[obj.key] = val onWatch() scope.$watch ( () -> $location.search() ), -> onWatch() for obj in config watch = obj.expr or obj.scope_name or obj.key scope.$watch watch, do (obj, watch) -> (val) -> val = (obj.val_out or _.identity)(val) if val == obj.default then val = null $location.search obj.key, val or null if obj.key == "page" then c.log "post change", watch, val obj.post_change?(val) korpApp.factory "debounce", ($timeout) -> (func, wait, options) -> args = null inited = null result = null thisArg = null timeoutDeferred = null trailing = true delayed = -> inited = timeoutDeferred = null result = func.apply(thisArg, args) if trailing if options is true leading = true trailing = false else if options and angular.isObject(options) leading = options.leading trailing = (if "trailing" of options then options.trailing else trailing) return () -> args = arguments thisArg = this $timeout.cancel timeoutDeferred if not inited and leading inited = true result = func.apply(thisArg, args) else timeoutDeferred = $timeout(delayed, wait) result korpApp.factory 'backend', ($http, $q, utils, lexicons) -> requestCompare : (cmpObj1, cmpObj2, reduce) -> reduce = _.map reduce, (item) -> item.replace(/^_\./, "") # remove all corpora which do not include all the "reduce"-attributes filterFun = (item) -> settings.corpusListing.corpusHasAttrs item, reduce corpora1 = _.filter cmpObj1.corpora, filterFun corpora2 = _.filter cmpObj2.corpora, filterFun corpusListing = settings.corpusListing.subsetFactory cmpObj1.corpora split = _.filter(reduce, (r) -> settings.corpusListing.getCurrentAttributes()[r]?.type == "set").join(',') attributes = _.extend {}, corpusListing.getCurrentAttributes(), corpusListing.getStructAttrs() reduceIsStructAttr = _.map reduce, (attr) -> attributes[attr]?.isStructAttr rankedReduce = _.filter reduce, (item) -> settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[item]?.ranked top = _.map(rankedReduce, (item) -> return item + ":1").join ',' def = $q.defer() params = command : "loglike" groupby : reduce.join ',' set1_corpus : util.encodeListParam(corpora1).toUpperCase() set1_cqp : cmpObj1.cqp set2_corpus : util.encodeListParam(corpora2).toUpperCase() set2_cqp : cmpObj2.cqp max : 50 split : split top : top conf = url : settings.cgi_script params : util.compressQueryParams params method : "GET" headers : {} _.extend conf.headers, model.getAuthorizationHeader() xhr = $http(conf) xhr.success (data) -> if data.ERROR def.reject() return loglikeValues = data.loglike objs = _.map loglikeValues, (value, key) -> return { value: key loglike: value } tables = _.groupBy objs, (obj) -> if obj.loglike > 0 obj.abs = data.set2[obj.value] return "positive" else obj.abs = data.set1[obj.value] return "negative" groupAndSum = (table, currentMax) -> groups = _.groupBy table, (obj) -> obj.value.replace(/(:.+?)(\/|$| )/g, "$2") res = _.map groups, (value, key) -> # tokenLists = _.map key.split("/"), (tokens) -> # return tokens.split(" ") tokenLists = util.splitCompareKey key, reduce, reduceIsStructAttr # c.log "tokenLists", tokenLists loglike = 0 abs = 0 cqp = [] elems = [] _.map value, (val) -> abs += val.abs loglike += val.loglike elems.push val.value if loglike > currentMax currentMax = loglike { key: key, loglike : loglike, abs : abs, elems : elems, tokenLists: tokenLists } return [res, currentMax] [tables.positive, max] = groupAndSum tables.positive, 0 [tables.negative, max] = groupAndSum tables.negative, max def.resolve [tables, max, cmpObj1, cmpObj2, reduce], xhr return def.promise relatedWordSearch : (lemgram) -> return lexicons.relatedWordSearch(lemgram) requestMapData: (cqp, cqpExprs, within, attribute) -> cqpSubExprs = {} _.map _.keys(cqpExprs), (subCqp, idx) -> cqpSubExprs["subcqp" + idx] = subCqp def = $q.defer() params = command: "count" groupby: attribute.label cqp: cqp corpus: util.encodeListParam attribute.corpora incremental: $.support.ajaxProgress split: attribute.label _.extend params, settings.corpusListing.getWithinParameters() _.extend params, cqpSubExprs conf = url : settings.cgi_script params : util.compressQueryParams params method : "GET" headers : {} _.extend conf.headers, model.getAuthorizationHeader() xhr = $http(conf) xhr.success (data) -> createResult = (subResult, cqp, label) -> points = [] _.map _.keys(subResult.absolute), (hit) -> if (hit.startsWith "|") or (hit.startsWith " ") return [name, countryCode, lat, lng] = hit.split ";" points.push ( abs: subResult.absolute[hit] rel: subResult.relative[hit] name: name countryCode: countryCode lat : parseFloat lat lng : parseFloat lng) return ( label: label cqp: cqp points: points ) if _.isEmpty cqpExprs result = [createResult data.total, cqp, "Σ"] else result = [] for subResult in data.total.slice(1, data.total.length) result.push createResult subResult, subResult.cqp, cqpExprs[subResult.cqp] if data.ERROR def.reject() return def.resolve [{corpora: attribute.corpora, cqp: cqp, within: within, data: result, attribute: attribute}], xhr return def.promise korpApp.factory 'nameEntitySearch', ($rootScope, $q) -> class NameEntities constructor: () -> request: (cqp) -> @def = $q.defer() @promise = @def.promise @proxy = new model.NameProxy() $rootScope.$broadcast 'map_data_available', cqp, settings.corpusListing.stringifySelected(true) @proxy.makeRequest(cqp, @progressCallback).then (data) => @def.resolve data progressCallback: (progress) -> $rootScope.$broadcast 'map_progress', progress return new NameEntities() korpApp.factory 'searches', (utils, $location, $rootScope, $http, $q, nameEntitySearch) -> class Searches constructor : () -> @activeSearch = null def = $q.defer() timedef = $q.defer() @infoDef = def.promise @timeDef = timedef.promise # is resolved when parallel search controller is loaded @langDef = $q.defer() # @modeDef = @getMode() # @modeDef.then () => @getInfoData().then () -> def.resolve() initTimeGraph(timedef) kwicRequest : (cqp, isPaging) -> c.log "kwicRequest", cqp kwicResults.makeRequest(cqp, isPaging) kwicSearch : (cqp, isPaging) -> # simpleSearch.resetView() # kwicResults.@ @kwicRequest cqp, isPaging statsResults.makeRequest cqp @nameEntitySearch cqp if settings.name_classification nameClassificationResults.makeRequest cqp lemgramSearch : (lemgram, searchPrefix, searchSuffix, isPaging) -> #TODO: this is dumb, move the cqp calculations elsewhere cqp = new model.LemgramProxy().lemgramSearch(lemgram, searchPrefix, searchSuffix) statsResults.makeRequest cqp @kwicRequest cqp, isPaging @nameEntitySearch cqp if settings.name_classification nameClassificationResults.makeRequest cqp if settings.wordpicture == false then return # lemgramResults.showPreloader() lemgramResults.makeRequest(lemgram, "lemgram") # def = lemgramProxy.makeRequest(lemgram, "lemgram", $.proxy(lemgramResults.onProgress, lemgramResults)) # c.log "def", def # def.fail (jqXHR, status, errorThrown) -> # c.log "def fail", status # if status == "abort" # safeApply lemgramResults.s, () => # lemgramResults.hidePreloader() nameEntitySearch : (cqp) -> if $location.search().show_map? nameEntitySearch.request cqp getMode : () -> def = $q.defer() mode = $.deparam.querystring().mode if mode? and mode isnt "default" $.getScript("modes/#{mode}_mode.js").done(-> $rootScope.$apply () -> def.resolve() ).fail (args, msg, e) -> $rootScope.$apply () -> def.reject() else def.resolve() return def.promise getInfoData : () -> def = $q.defer() corpora = _(settings.corpusListing.corpora).pluck("id") .invoke("toUpperCase").join "," $http( method : "POST" url : settings.cgi_script data : "command=info&corpus=#{corpora}" headers : 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' ).success (data) -> for corpus in settings.corpusListing.corpora corpus["info"] = data["corpora"][corpus.id.toUpperCase()]["info"] privateStructAttrs = [] for attr in data["corpora"][corpus.id.toUpperCase()].attrs.s if attr.indexOf("__") isnt -1 privateStructAttrs.push attr corpus["private_struct_attributes"] = privateStructAttrs # Copy possible URL and URN information in "info" # to top-level properties, so that it can be # specified in either the backend info file or in # the frontend config (Jyrki Niemi 2014-09-04). util.copyCorpusInfoToConfig corpus # Propagate the properties in corpus folder "info" to # all subfolders and corpora. (Jyrki Niemi 2014-09-08) for folder_name of settings.corporafolders util.propagateCorpusFolderInfo( settings.corporafolders[folder_name], undefined) util.loadCorpora() def.resolve() return def.promise searches = new Searches() oldValues = [] $rootScope.$watchGroup [(() -> $location.search().search), "_loc.search().page"], (newValues) => c.log "searches service watch", $location.search().search searchExpr = $location.search().search unless searchExpr then return [type, value...] = searchExpr?.split("|") value = value.join("|") newValues[1] = Number(newValues[1]) or 0 oldValues[1] = Number(oldValues[1]) or 0 if _.isEqual newValues, oldValues pageChanged = false searchChanged = true else pageChanged = newValues[1] != oldValues[1] searchChanged = newValues[0] != oldValues[0] pageOnly = pageChanged and not searchChanged view.updateSearchHistory value, $location.absUrl() $q.all([searches.infoDef, searches.langDef.promise]).then () -> switch type when "word" searches.activeSearch = type : type val : value page: newValues[1] pageOnly: pageOnly when "lemgram" searches.activeSearch = type : type val : value page: newValues[1] pageOnly: pageOnly when "saldo" extendedSearch.setOneToken "saldo", value when "cqp" if not value then value = $location.search().cqp searches.activeSearch = type : type val : value page: newValues[1] pageOnly: pageOnly searches.kwicSearch value, pageOnly oldValues = [].concat newValues return searches korpApp.service "compareSearches", class CompareSearches constructor : () -> if currentMode != "default" @key = 'saved_searches_' + currentMode else @key = "saved_searches" c.log "key", @key @savedSearches = ($.jStorage.get @key) or [] saveSearch : (searchObj) -> @savedSearches.push searchObj $.jStorage.set @key, @savedSearches flush: () -> @savedSearches[..] = [] $.jStorage.set @key, @savedSearches korpApp.factory "lexicons", ($q, $http) -> karpURL = "https://ws.spraakbanken.gu.se/ws/karp/v2" getLemgrams: (wf, resources, corporaIDs) -> deferred = $q.defer() args = "q" : wf "resource" : if $.isArray(resources) then resources.join(",") else resources # Support an alternative lemgram service. TODO: Make the # service CGI script take the same arguments and return a # similar output as Karp, so that it would not need to be # special-cased here. (Jyrki Niemi 2015-12-04) if settings.lemgramService == "FIN-CLARIN" _.extend args, { wf: wf corpus: corporaIDs.join(",") limit: settings.autocompleteLemgramCount or 10 } # Pass data to FIN-CLARIN lemgram service with POST to # avoid the need to encode long lists of corpora. (Jyrki # Niemi 2017-09-29) http_params = method : "POST" url : settings.lemgrams_cgi_script data : $.param(args) headers : { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } else http_params = method : "GET" url : "#{karpURL}/autocomplete" params : args $http(http_params ).success((data, status, headers, config) -> if data is null deferred.resolve [] else # Support an alternative lemgram service (Jyrki Niemi # 2015-12-04) if settings.lemgramService == "FIN-CLARIN" div = (if $.isPlainObject(data.div) then [data.div] else data.div) karpLemgrams = $.map(div.slice(0, Number(data.count)), (item) -> item.LexicalEntry.lem ) else # Pick the lemgrams. Would be nice if this was done by the backend instead. karpLemgrams = _.map data.hits.hits, (entry) -> entry._source.FormRepresentations[0].lemgram if karpLemgrams.length is 0 deferred.resolve [] return lemgram = karpLemgrams.join(",") corpora = corporaIDs.join(",") $http( method: 'POST' url: settings.cgi_script data : "command=lemgram_count&lemgram=#{lemgram}&count=lemgram&corpus=#{corpora}" headers : { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } ).success (data, status, headers, config) => delete data.time allLemgrams = [] for lemgram, count of data allLemgrams.push {"lemgram" : lemgram, "count" : count} for klemgram in karpLemgrams unless data[klemgram] allLemgrams.push {"lemgram" : klemgram, "count" : 0} deferred.resolve allLemgrams ).error (data, status, headers, config) -> deferred.resolve [] return deferred.promise getSenses: (wf) -> deferred = $q.defer() args = "q" : wf "resource" : "saldom" $http( method: 'GET' url: "#{karpURL}/autocomplete" params : args ).success((data, status, headers, config) => if data is null deferred.resolve [] else karpLemgrams = _.map data.hits.hits, (entry) -> entry._source.FormRepresentations[0].lemgram if karpLemgrams.length is 0 deferred.resolve [] return karpLemgrams = karpLemgrams.slice 0, 100 senseargs = "q" : "extended||and|lemgram|equals|#{karpLemgrams.join('|')}" "resource" : "saldo" "show" : "sense,primary" "size" : 500 $http( method: 'GET' url: "#{karpURL}/minientry" params : senseargs ).success((data, status, headers, config) -> if data.hits.total is 0 deferred.resolve [] return senses = _.map data.hits.hits, (entry) -> { "sense" : entry._source.Sense[0].senseid, "desc" : entry._source.Sense[0].SenseRelations?.primary } deferred.resolve senses ).error (data, status, headers, config) -> deferred.resolve [] ).error (data, status, headers, config) -> deferred.resolve [] return deferred.promise relatedWordSearch : (lemgram) -> def = $q.defer() req = $http( url : "#{karpURL}/minientry" method : "GET" params : q : "extended||and|lemgram|equals|#{lemgram}" show : "sense" resource : "saldo" ).success (data) -> if data.hits.total is 0 def.resolve [] return else senses = _.map data.hits.hits, (entry) -> entry._source.Sense[0].senseid http = $http( url : "#{karpURL}/minientry" method : "GET" params : q : "extended||and|LU|equals|#{senses.join('|')}" show : "LU,sense" resource : "swefn" ).success (data) -> if data.hits.total is 0 def.resolve [] return else eNodes = _.map data.hits.hits, (entry) -> { "label" : entry._source.Sense[0].senseid.replace("swefn--", "") "words" : entry._source.Sense[0].LU } def.resolve eNodes return def.promise
213625
korpApp = angular.module("korpApp") korpApp.factory "utils", ($location) -> valfilter : (attrobj) -> return if attrobj.isStructAttr then "_." + attrobj.value else attrobj.value setupHash : (scope, config) -> onWatch = () -> for obj in config val = $location.search()[obj.key] unless val if obj.default? then val = obj.default else continue val = (obj.val_in or _.identity)(val) if "scope_name" of obj scope[obj.scope_name] = val else if "scope_func" of obj scope[obj.scope_func](val) else scope[obj.key] = val onWatch() scope.$watch ( () -> $location.search() ), -> onWatch() for obj in config watch = obj.expr or obj.scope_name or obj.key scope.$watch watch, do (obj, watch) -> (val) -> val = (obj.val_out or _.identity)(val) if val == obj.default then val = null $location.search obj.key, val or null if obj.key == "page" then c.log "post change", watch, val obj.post_change?(val) korpApp.factory "debounce", ($timeout) -> (func, wait, options) -> args = null inited = null result = null thisArg = null timeoutDeferred = null trailing = true delayed = -> inited = timeoutDeferred = null result = func.apply(thisArg, args) if trailing if options is true leading = true trailing = false else if options and angular.isObject(options) leading = options.leading trailing = (if "trailing" of options then options.trailing else trailing) return () -> args = arguments thisArg = this $timeout.cancel timeoutDeferred if not inited and leading inited = true result = func.apply(thisArg, args) else timeoutDeferred = $timeout(delayed, wait) result korpApp.factory 'backend', ($http, $q, utils, lexicons) -> requestCompare : (cmpObj1, cmpObj2, reduce) -> reduce = _.map reduce, (item) -> item.replace(/^_\./, "") # remove all corpora which do not include all the "reduce"-attributes filterFun = (item) -> settings.corpusListing.corpusHasAttrs item, reduce corpora1 = _.filter cmpObj1.corpora, filterFun corpora2 = _.filter cmpObj2.corpora, filterFun corpusListing = settings.corpusListing.subsetFactory cmpObj1.corpora split = _.filter(reduce, (r) -> settings.corpusListing.getCurrentAttributes()[r]?.type == "set").join(',') attributes = _.extend {}, corpusListing.getCurrentAttributes(), corpusListing.getStructAttrs() reduceIsStructAttr = _.map reduce, (attr) -> attributes[attr]?.isStructAttr rankedReduce = _.filter reduce, (item) -> settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[item]?.ranked top = _.map(rankedReduce, (item) -> return item + ":1").join ',' def = $q.defer() params = command : "loglike" groupby : reduce.join ',' set1_corpus : util.encodeListParam(corpora1).toUpperCase() set1_cqp : cmpObj1.cqp set2_corpus : util.encodeListParam(corpora2).toUpperCase() set2_cqp : cmpObj2.cqp max : 50 split : split top : top conf = url : settings.cgi_script params : util.compressQueryParams params method : "GET" headers : {} _.extend conf.headers, model.getAuthorizationHeader() xhr = $http(conf) xhr.success (data) -> if data.ERROR def.reject() return loglikeValues = data.loglike objs = _.map loglikeValues, (value, key) -> return { value: key loglike: value } tables = _.groupBy objs, (obj) -> if obj.loglike > 0 obj.abs = data.set2[obj.value] return "positive" else obj.abs = data.set1[obj.value] return "negative" groupAndSum = (table, currentMax) -> groups = _.groupBy table, (obj) -> obj.value.replace(/(:.+?)(\/|$| )/g, "$2") res = _.map groups, (value, key) -> # tokenLists = _.map key.split("/"), (tokens) -> # return tokens.split(" ") tokenLists = util.splitCompareKey key, reduce, reduceIsStructAttr # c.log "tokenLists", tokenLists loglike = 0 abs = 0 cqp = [] elems = [] _.map value, (val) -> abs += val.abs loglike += val.loglike elems.push val.value if loglike > currentMax currentMax = loglike { key: key, loglike : loglike, abs : abs, elems : elems, tokenLists: tokenLists } return [res, currentMax] [tables.positive, max] = groupAndSum tables.positive, 0 [tables.negative, max] = groupAndSum tables.negative, max def.resolve [tables, max, cmpObj1, cmpObj2, reduce], xhr return def.promise relatedWordSearch : (lemgram) -> return lexicons.relatedWordSearch(lemgram) requestMapData: (cqp, cqpExprs, within, attribute) -> cqpSubExprs = {} _.map _.keys(cqpExprs), (subCqp, idx) -> cqpSubExprs["subcqp" + idx] = subCqp def = $q.defer() params = command: "count" groupby: attribute.label cqp: cqp corpus: util.encodeListParam attribute.corpora incremental: $.support.ajaxProgress split: attribute.label _.extend params, settings.corpusListing.getWithinParameters() _.extend params, cqpSubExprs conf = url : settings.cgi_script params : util.compressQueryParams params method : "GET" headers : {} _.extend conf.headers, model.getAuthorizationHeader() xhr = $http(conf) xhr.success (data) -> createResult = (subResult, cqp, label) -> points = [] _.map _.keys(subResult.absolute), (hit) -> if (hit.startsWith "|") or (hit.startsWith " ") return [name, countryCode, lat, lng] = hit.split ";" points.push ( abs: subResult.absolute[hit] rel: subResult.relative[hit] name: name countryCode: countryCode lat : parseFloat lat lng : parseFloat lng) return ( label: label cqp: cqp points: points ) if _.isEmpty cqpExprs result = [createResult data.total, cqp, "Σ"] else result = [] for subResult in data.total.slice(1, data.total.length) result.push createResult subResult, subResult.cqp, cqpExprs[subResult.cqp] if data.ERROR def.reject() return def.resolve [{corpora: attribute.corpora, cqp: cqp, within: within, data: result, attribute: attribute}], xhr return def.promise korpApp.factory 'nameEntitySearch', ($rootScope, $q) -> class NameEntities constructor: () -> request: (cqp) -> @def = $q.defer() @promise = @def.promise @proxy = new model.NameProxy() $rootScope.$broadcast 'map_data_available', cqp, settings.corpusListing.stringifySelected(true) @proxy.makeRequest(cqp, @progressCallback).then (data) => @def.resolve data progressCallback: (progress) -> $rootScope.$broadcast 'map_progress', progress return new NameEntities() korpApp.factory 'searches', (utils, $location, $rootScope, $http, $q, nameEntitySearch) -> class Searches constructor : () -> @activeSearch = null def = $q.defer() timedef = $q.defer() @infoDef = def.promise @timeDef = timedef.promise # is resolved when parallel search controller is loaded @langDef = $q.defer() # @modeDef = @getMode() # @modeDef.then () => @getInfoData().then () -> def.resolve() initTimeGraph(timedef) kwicRequest : (cqp, isPaging) -> c.log "kwicRequest", cqp kwicResults.makeRequest(cqp, isPaging) kwicSearch : (cqp, isPaging) -> # simpleSearch.resetView() # kwicResults.@ @kwicRequest cqp, isPaging statsResults.makeRequest cqp @nameEntitySearch cqp if settings.name_classification nameClassificationResults.makeRequest cqp lemgramSearch : (lemgram, searchPrefix, searchSuffix, isPaging) -> #TODO: this is dumb, move the cqp calculations elsewhere cqp = new model.LemgramProxy().lemgramSearch(lemgram, searchPrefix, searchSuffix) statsResults.makeRequest cqp @kwicRequest cqp, isPaging @nameEntitySearch cqp if settings.name_classification nameClassificationResults.makeRequest cqp if settings.wordpicture == false then return # lemgramResults.showPreloader() lemgramResults.makeRequest(lemgram, "lemgram") # def = lemgramProxy.makeRequest(lemgram, "lemgram", $.proxy(lemgramResults.onProgress, lemgramResults)) # c.log "def", def # def.fail (jqXHR, status, errorThrown) -> # c.log "def fail", status # if status == "abort" # safeApply lemgramResults.s, () => # lemgramResults.hidePreloader() nameEntitySearch : (cqp) -> if $location.search().show_map? nameEntitySearch.request cqp getMode : () -> def = $q.defer() mode = $.deparam.querystring().mode if mode? and mode isnt "default" $.getScript("modes/#{mode}_mode.js").done(-> $rootScope.$apply () -> def.resolve() ).fail (args, msg, e) -> $rootScope.$apply () -> def.reject() else def.resolve() return def.promise getInfoData : () -> def = $q.defer() corpora = _(settings.corpusListing.corpora).pluck("id") .invoke("toUpperCase").join "," $http( method : "POST" url : settings.cgi_script data : "command=info&corpus=#{corpora}" headers : 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' ).success (data) -> for corpus in settings.corpusListing.corpora corpus["info"] = data["corpora"][corpus.id.toUpperCase()]["info"] privateStructAttrs = [] for attr in data["corpora"][corpus.id.toUpperCase()].attrs.s if attr.indexOf("__") isnt -1 privateStructAttrs.push attr corpus["private_struct_attributes"] = privateStructAttrs # Copy possible URL and URN information in "info" # to top-level properties, so that it can be # specified in either the backend info file or in # the frontend config (<NAME> 2014-09-04). util.copyCorpusInfoToConfig corpus # Propagate the properties in corpus folder "info" to # all subfolders and corpora. (<NAME> 2014-09-08) for folder_name of settings.corporafolders util.propagateCorpusFolderInfo( settings.corporafolders[folder_name], undefined) util.loadCorpora() def.resolve() return def.promise searches = new Searches() oldValues = [] $rootScope.$watchGroup [(() -> $location.search().search), "_loc.search().page"], (newValues) => c.log "searches service watch", $location.search().search searchExpr = $location.search().search unless searchExpr then return [type, value...] = searchExpr?.split("|") value = value.join("|") newValues[1] = Number(newValues[1]) or 0 oldValues[1] = Number(oldValues[1]) or 0 if _.isEqual newValues, oldValues pageChanged = false searchChanged = true else pageChanged = newValues[1] != oldValues[1] searchChanged = newValues[0] != oldValues[0] pageOnly = pageChanged and not searchChanged view.updateSearchHistory value, $location.absUrl() $q.all([searches.infoDef, searches.langDef.promise]).then () -> switch type when "word" searches.activeSearch = type : type val : value page: newValues[1] pageOnly: pageOnly when "lemgram" searches.activeSearch = type : type val : value page: newValues[1] pageOnly: pageOnly when "saldo" extendedSearch.setOneToken "saldo", value when "cqp" if not value then value = $location.search().cqp searches.activeSearch = type : type val : value page: newValues[1] pageOnly: pageOnly searches.kwicSearch value, pageOnly oldValues = [].concat newValues return searches korpApp.service "compareSearches", class CompareSearches constructor : () -> if currentMode != "default" @key = 'saved_searches_' + currentMode else @key = "saved_searches" c.log "key", @key @savedSearches = ($.jStorage.get @key) or [] saveSearch : (searchObj) -> @savedSearches.push searchObj $.jStorage.set @key, @savedSearches flush: () -> @savedSearches[..] = [] $.jStorage.set @key, @savedSearches korpApp.factory "lexicons", ($q, $http) -> karpURL = "https://ws.spraakbanken.gu.se/ws/karp/v2" getLemgrams: (wf, resources, corporaIDs) -> deferred = $q.defer() args = "q" : wf "resource" : if $.isArray(resources) then resources.join(",") else resources # Support an alternative lemgram service. TODO: Make the # service CGI script take the same arguments and return a # similar output as Karp, so that it would not need to be # special-cased here. (<NAME> 2015-12-04) if settings.lemgramService == "FIN-CLARIN" _.extend args, { wf: wf corpus: corporaIDs.join(",") limit: settings.autocompleteLemgramCount or 10 } # Pass data to FIN-CLARIN lemgram service with POST to # avoid the need to encode long lists of corpora. (<NAME> # <NAME> 2017-09-29) http_params = method : "POST" url : settings.lemgrams_cgi_script data : $.param(args) headers : { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } else http_params = method : "GET" url : "#{karpURL}/autocomplete" params : args $http(http_params ).success((data, status, headers, config) -> if data is null deferred.resolve [] else # Support an alternative lemgram service (<NAME> # 2015-12-04) if settings.lemgramService == "FIN-CLARIN" div = (if $.isPlainObject(data.div) then [data.div] else data.div) karpLemgrams = $.map(div.slice(0, Number(data.count)), (item) -> item.LexicalEntry.lem ) else # Pick the lemgrams. Would be nice if this was done by the backend instead. karpLemgrams = _.map data.hits.hits, (entry) -> entry._source.FormRepresentations[0].lemgram if karpLemgrams.length is 0 deferred.resolve [] return lemgram = karpLemgrams.join(",") corpora = corporaIDs.join(",") $http( method: 'POST' url: settings.cgi_script data : "command=lemgram_count&lemgram=#{lemgram}&count=lemgram&corpus=#{corpora}" headers : { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } ).success (data, status, headers, config) => delete data.time allLemgrams = [] for lemgram, count of data allLemgrams.push {"lemgram" : lemgram, "count" : count} for klemgram in karpLemgrams unless data[klemgram] allLemgrams.push {"lemgram" : klemgram, "count" : 0} deferred.resolve allLemgrams ).error (data, status, headers, config) -> deferred.resolve [] return deferred.promise getSenses: (wf) -> deferred = $q.defer() args = "q" : wf "resource" : "saldom" $http( method: 'GET' url: "#{karpURL}/autocomplete" params : args ).success((data, status, headers, config) => if data is null deferred.resolve [] else karpLemgrams = _.map data.hits.hits, (entry) -> entry._source.FormRepresentations[0].lemgram if karpLemgrams.length is 0 deferred.resolve [] return karpLemgrams = karpLemgrams.slice 0, 100 senseargs = "q" : "extended||and|lemgram|equals|#{karpLemgrams.join('|')}" "resource" : "saldo" "show" : "sense,primary" "size" : 500 $http( method: 'GET' url: "#{karpURL}/minientry" params : senseargs ).success((data, status, headers, config) -> if data.hits.total is 0 deferred.resolve [] return senses = _.map data.hits.hits, (entry) -> { "sense" : entry._source.Sense[0].senseid, "desc" : entry._source.Sense[0].SenseRelations?.primary } deferred.resolve senses ).error (data, status, headers, config) -> deferred.resolve [] ).error (data, status, headers, config) -> deferred.resolve [] return deferred.promise relatedWordSearch : (lemgram) -> def = $q.defer() req = $http( url : "#{karpURL}/minientry" method : "GET" params : q : "extended||and|lemgram|equals|#{lemgram}" show : "sense" resource : "saldo" ).success (data) -> if data.hits.total is 0 def.resolve [] return else senses = _.map data.hits.hits, (entry) -> entry._source.Sense[0].senseid http = $http( url : "#{karpURL}/minientry" method : "GET" params : q : "extended||and|LU|equals|#{senses.join('|')}" show : "LU,sense" resource : "swefn" ).success (data) -> if data.hits.total is 0 def.resolve [] return else eNodes = _.map data.hits.hits, (entry) -> { "label" : entry._source.Sense[0].senseid.replace("swefn--", "") "words" : entry._source.Sense[0].LU } def.resolve eNodes return def.promise
true
korpApp = angular.module("korpApp") korpApp.factory "utils", ($location) -> valfilter : (attrobj) -> return if attrobj.isStructAttr then "_." + attrobj.value else attrobj.value setupHash : (scope, config) -> onWatch = () -> for obj in config val = $location.search()[obj.key] unless val if obj.default? then val = obj.default else continue val = (obj.val_in or _.identity)(val) if "scope_name" of obj scope[obj.scope_name] = val else if "scope_func" of obj scope[obj.scope_func](val) else scope[obj.key] = val onWatch() scope.$watch ( () -> $location.search() ), -> onWatch() for obj in config watch = obj.expr or obj.scope_name or obj.key scope.$watch watch, do (obj, watch) -> (val) -> val = (obj.val_out or _.identity)(val) if val == obj.default then val = null $location.search obj.key, val or null if obj.key == "page" then c.log "post change", watch, val obj.post_change?(val) korpApp.factory "debounce", ($timeout) -> (func, wait, options) -> args = null inited = null result = null thisArg = null timeoutDeferred = null trailing = true delayed = -> inited = timeoutDeferred = null result = func.apply(thisArg, args) if trailing if options is true leading = true trailing = false else if options and angular.isObject(options) leading = options.leading trailing = (if "trailing" of options then options.trailing else trailing) return () -> args = arguments thisArg = this $timeout.cancel timeoutDeferred if not inited and leading inited = true result = func.apply(thisArg, args) else timeoutDeferred = $timeout(delayed, wait) result korpApp.factory 'backend', ($http, $q, utils, lexicons) -> requestCompare : (cmpObj1, cmpObj2, reduce) -> reduce = _.map reduce, (item) -> item.replace(/^_\./, "") # remove all corpora which do not include all the "reduce"-attributes filterFun = (item) -> settings.corpusListing.corpusHasAttrs item, reduce corpora1 = _.filter cmpObj1.corpora, filterFun corpora2 = _.filter cmpObj2.corpora, filterFun corpusListing = settings.corpusListing.subsetFactory cmpObj1.corpora split = _.filter(reduce, (r) -> settings.corpusListing.getCurrentAttributes()[r]?.type == "set").join(',') attributes = _.extend {}, corpusListing.getCurrentAttributes(), corpusListing.getStructAttrs() reduceIsStructAttr = _.map reduce, (attr) -> attributes[attr]?.isStructAttr rankedReduce = _.filter reduce, (item) -> settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[item]?.ranked top = _.map(rankedReduce, (item) -> return item + ":1").join ',' def = $q.defer() params = command : "loglike" groupby : reduce.join ',' set1_corpus : util.encodeListParam(corpora1).toUpperCase() set1_cqp : cmpObj1.cqp set2_corpus : util.encodeListParam(corpora2).toUpperCase() set2_cqp : cmpObj2.cqp max : 50 split : split top : top conf = url : settings.cgi_script params : util.compressQueryParams params method : "GET" headers : {} _.extend conf.headers, model.getAuthorizationHeader() xhr = $http(conf) xhr.success (data) -> if data.ERROR def.reject() return loglikeValues = data.loglike objs = _.map loglikeValues, (value, key) -> return { value: key loglike: value } tables = _.groupBy objs, (obj) -> if obj.loglike > 0 obj.abs = data.set2[obj.value] return "positive" else obj.abs = data.set1[obj.value] return "negative" groupAndSum = (table, currentMax) -> groups = _.groupBy table, (obj) -> obj.value.replace(/(:.+?)(\/|$| )/g, "$2") res = _.map groups, (value, key) -> # tokenLists = _.map key.split("/"), (tokens) -> # return tokens.split(" ") tokenLists = util.splitCompareKey key, reduce, reduceIsStructAttr # c.log "tokenLists", tokenLists loglike = 0 abs = 0 cqp = [] elems = [] _.map value, (val) -> abs += val.abs loglike += val.loglike elems.push val.value if loglike > currentMax currentMax = loglike { key: key, loglike : loglike, abs : abs, elems : elems, tokenLists: tokenLists } return [res, currentMax] [tables.positive, max] = groupAndSum tables.positive, 0 [tables.negative, max] = groupAndSum tables.negative, max def.resolve [tables, max, cmpObj1, cmpObj2, reduce], xhr return def.promise relatedWordSearch : (lemgram) -> return lexicons.relatedWordSearch(lemgram) requestMapData: (cqp, cqpExprs, within, attribute) -> cqpSubExprs = {} _.map _.keys(cqpExprs), (subCqp, idx) -> cqpSubExprs["subcqp" + idx] = subCqp def = $q.defer() params = command: "count" groupby: attribute.label cqp: cqp corpus: util.encodeListParam attribute.corpora incremental: $.support.ajaxProgress split: attribute.label _.extend params, settings.corpusListing.getWithinParameters() _.extend params, cqpSubExprs conf = url : settings.cgi_script params : util.compressQueryParams params method : "GET" headers : {} _.extend conf.headers, model.getAuthorizationHeader() xhr = $http(conf) xhr.success (data) -> createResult = (subResult, cqp, label) -> points = [] _.map _.keys(subResult.absolute), (hit) -> if (hit.startsWith "|") or (hit.startsWith " ") return [name, countryCode, lat, lng] = hit.split ";" points.push ( abs: subResult.absolute[hit] rel: subResult.relative[hit] name: name countryCode: countryCode lat : parseFloat lat lng : parseFloat lng) return ( label: label cqp: cqp points: points ) if _.isEmpty cqpExprs result = [createResult data.total, cqp, "Σ"] else result = [] for subResult in data.total.slice(1, data.total.length) result.push createResult subResult, subResult.cqp, cqpExprs[subResult.cqp] if data.ERROR def.reject() return def.resolve [{corpora: attribute.corpora, cqp: cqp, within: within, data: result, attribute: attribute}], xhr return def.promise korpApp.factory 'nameEntitySearch', ($rootScope, $q) -> class NameEntities constructor: () -> request: (cqp) -> @def = $q.defer() @promise = @def.promise @proxy = new model.NameProxy() $rootScope.$broadcast 'map_data_available', cqp, settings.corpusListing.stringifySelected(true) @proxy.makeRequest(cqp, @progressCallback).then (data) => @def.resolve data progressCallback: (progress) -> $rootScope.$broadcast 'map_progress', progress return new NameEntities() korpApp.factory 'searches', (utils, $location, $rootScope, $http, $q, nameEntitySearch) -> class Searches constructor : () -> @activeSearch = null def = $q.defer() timedef = $q.defer() @infoDef = def.promise @timeDef = timedef.promise # is resolved when parallel search controller is loaded @langDef = $q.defer() # @modeDef = @getMode() # @modeDef.then () => @getInfoData().then () -> def.resolve() initTimeGraph(timedef) kwicRequest : (cqp, isPaging) -> c.log "kwicRequest", cqp kwicResults.makeRequest(cqp, isPaging) kwicSearch : (cqp, isPaging) -> # simpleSearch.resetView() # kwicResults.@ @kwicRequest cqp, isPaging statsResults.makeRequest cqp @nameEntitySearch cqp if settings.name_classification nameClassificationResults.makeRequest cqp lemgramSearch : (lemgram, searchPrefix, searchSuffix, isPaging) -> #TODO: this is dumb, move the cqp calculations elsewhere cqp = new model.LemgramProxy().lemgramSearch(lemgram, searchPrefix, searchSuffix) statsResults.makeRequest cqp @kwicRequest cqp, isPaging @nameEntitySearch cqp if settings.name_classification nameClassificationResults.makeRequest cqp if settings.wordpicture == false then return # lemgramResults.showPreloader() lemgramResults.makeRequest(lemgram, "lemgram") # def = lemgramProxy.makeRequest(lemgram, "lemgram", $.proxy(lemgramResults.onProgress, lemgramResults)) # c.log "def", def # def.fail (jqXHR, status, errorThrown) -> # c.log "def fail", status # if status == "abort" # safeApply lemgramResults.s, () => # lemgramResults.hidePreloader() nameEntitySearch : (cqp) -> if $location.search().show_map? nameEntitySearch.request cqp getMode : () -> def = $q.defer() mode = $.deparam.querystring().mode if mode? and mode isnt "default" $.getScript("modes/#{mode}_mode.js").done(-> $rootScope.$apply () -> def.resolve() ).fail (args, msg, e) -> $rootScope.$apply () -> def.reject() else def.resolve() return def.promise getInfoData : () -> def = $q.defer() corpora = _(settings.corpusListing.corpora).pluck("id") .invoke("toUpperCase").join "," $http( method : "POST" url : settings.cgi_script data : "command=info&corpus=#{corpora}" headers : 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' ).success (data) -> for corpus in settings.corpusListing.corpora corpus["info"] = data["corpora"][corpus.id.toUpperCase()]["info"] privateStructAttrs = [] for attr in data["corpora"][corpus.id.toUpperCase()].attrs.s if attr.indexOf("__") isnt -1 privateStructAttrs.push attr corpus["private_struct_attributes"] = privateStructAttrs # Copy possible URL and URN information in "info" # to top-level properties, so that it can be # specified in either the backend info file or in # the frontend config (PI:NAME:<NAME>END_PI 2014-09-04). util.copyCorpusInfoToConfig corpus # Propagate the properties in corpus folder "info" to # all subfolders and corpora. (PI:NAME:<NAME>END_PI 2014-09-08) for folder_name of settings.corporafolders util.propagateCorpusFolderInfo( settings.corporafolders[folder_name], undefined) util.loadCorpora() def.resolve() return def.promise searches = new Searches() oldValues = [] $rootScope.$watchGroup [(() -> $location.search().search), "_loc.search().page"], (newValues) => c.log "searches service watch", $location.search().search searchExpr = $location.search().search unless searchExpr then return [type, value...] = searchExpr?.split("|") value = value.join("|") newValues[1] = Number(newValues[1]) or 0 oldValues[1] = Number(oldValues[1]) or 0 if _.isEqual newValues, oldValues pageChanged = false searchChanged = true else pageChanged = newValues[1] != oldValues[1] searchChanged = newValues[0] != oldValues[0] pageOnly = pageChanged and not searchChanged view.updateSearchHistory value, $location.absUrl() $q.all([searches.infoDef, searches.langDef.promise]).then () -> switch type when "word" searches.activeSearch = type : type val : value page: newValues[1] pageOnly: pageOnly when "lemgram" searches.activeSearch = type : type val : value page: newValues[1] pageOnly: pageOnly when "saldo" extendedSearch.setOneToken "saldo", value when "cqp" if not value then value = $location.search().cqp searches.activeSearch = type : type val : value page: newValues[1] pageOnly: pageOnly searches.kwicSearch value, pageOnly oldValues = [].concat newValues return searches korpApp.service "compareSearches", class CompareSearches constructor : () -> if currentMode != "default" @key = 'saved_searches_' + currentMode else @key = "saved_searches" c.log "key", @key @savedSearches = ($.jStorage.get @key) or [] saveSearch : (searchObj) -> @savedSearches.push searchObj $.jStorage.set @key, @savedSearches flush: () -> @savedSearches[..] = [] $.jStorage.set @key, @savedSearches korpApp.factory "lexicons", ($q, $http) -> karpURL = "https://ws.spraakbanken.gu.se/ws/karp/v2" getLemgrams: (wf, resources, corporaIDs) -> deferred = $q.defer() args = "q" : wf "resource" : if $.isArray(resources) then resources.join(",") else resources # Support an alternative lemgram service. TODO: Make the # service CGI script take the same arguments and return a # similar output as Karp, so that it would not need to be # special-cased here. (PI:NAME:<NAME>END_PI 2015-12-04) if settings.lemgramService == "FIN-CLARIN" _.extend args, { wf: wf corpus: corporaIDs.join(",") limit: settings.autocompleteLemgramCount or 10 } # Pass data to FIN-CLARIN lemgram service with POST to # avoid the need to encode long lists of corpora. (PI:NAME:<NAME>END_PI # PI:NAME:<NAME>END_PI 2017-09-29) http_params = method : "POST" url : settings.lemgrams_cgi_script data : $.param(args) headers : { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } else http_params = method : "GET" url : "#{karpURL}/autocomplete" params : args $http(http_params ).success((data, status, headers, config) -> if data is null deferred.resolve [] else # Support an alternative lemgram service (PI:NAME:<NAME>END_PI # 2015-12-04) if settings.lemgramService == "FIN-CLARIN" div = (if $.isPlainObject(data.div) then [data.div] else data.div) karpLemgrams = $.map(div.slice(0, Number(data.count)), (item) -> item.LexicalEntry.lem ) else # Pick the lemgrams. Would be nice if this was done by the backend instead. karpLemgrams = _.map data.hits.hits, (entry) -> entry._source.FormRepresentations[0].lemgram if karpLemgrams.length is 0 deferred.resolve [] return lemgram = karpLemgrams.join(",") corpora = corporaIDs.join(",") $http( method: 'POST' url: settings.cgi_script data : "command=lemgram_count&lemgram=#{lemgram}&count=lemgram&corpus=#{corpora}" headers : { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } ).success (data, status, headers, config) => delete data.time allLemgrams = [] for lemgram, count of data allLemgrams.push {"lemgram" : lemgram, "count" : count} for klemgram in karpLemgrams unless data[klemgram] allLemgrams.push {"lemgram" : klemgram, "count" : 0} deferred.resolve allLemgrams ).error (data, status, headers, config) -> deferred.resolve [] return deferred.promise getSenses: (wf) -> deferred = $q.defer() args = "q" : wf "resource" : "saldom" $http( method: 'GET' url: "#{karpURL}/autocomplete" params : args ).success((data, status, headers, config) => if data is null deferred.resolve [] else karpLemgrams = _.map data.hits.hits, (entry) -> entry._source.FormRepresentations[0].lemgram if karpLemgrams.length is 0 deferred.resolve [] return karpLemgrams = karpLemgrams.slice 0, 100 senseargs = "q" : "extended||and|lemgram|equals|#{karpLemgrams.join('|')}" "resource" : "saldo" "show" : "sense,primary" "size" : 500 $http( method: 'GET' url: "#{karpURL}/minientry" params : senseargs ).success((data, status, headers, config) -> if data.hits.total is 0 deferred.resolve [] return senses = _.map data.hits.hits, (entry) -> { "sense" : entry._source.Sense[0].senseid, "desc" : entry._source.Sense[0].SenseRelations?.primary } deferred.resolve senses ).error (data, status, headers, config) -> deferred.resolve [] ).error (data, status, headers, config) -> deferred.resolve [] return deferred.promise relatedWordSearch : (lemgram) -> def = $q.defer() req = $http( url : "#{karpURL}/minientry" method : "GET" params : q : "extended||and|lemgram|equals|#{lemgram}" show : "sense" resource : "saldo" ).success (data) -> if data.hits.total is 0 def.resolve [] return else senses = _.map data.hits.hits, (entry) -> entry._source.Sense[0].senseid http = $http( url : "#{karpURL}/minientry" method : "GET" params : q : "extended||and|LU|equals|#{senses.join('|')}" show : "LU,sense" resource : "swefn" ).success (data) -> if data.hits.total is 0 def.resolve [] return else eNodes = _.map data.hits.hits, (entry) -> { "label" : entry._source.Sense[0].senseid.replace("swefn--", "") "words" : entry._source.Sense[0].LU } def.resolve eNodes return def.promise
[ { "context": "# Mislav Cimpersak\n# 2015\n# mislav.cimpersak@gmail.com\n\n# INSERT YOU", "end": 18, "score": 0.9998645782470703, "start": 2, "tag": "NAME", "value": "Mislav Cimpersak" }, { "context": "# Mislav Cimpersak\n# 2015\n# mislav.cimpersak@gmail.com\n\n# INSERT YOUR NAME AND PASSWORD HERE\nusername = ", "end": 54, "score": 0.9999328255653381, "start": 28, "tag": "EMAIL", "value": "mislav.cimpersak@gmail.com" }, { "context": "ERT YOUR NAME AND PASSWORD HERE\nusername = '' # 'username@domain.com'\npassword = '' # 'password'\n\ncommand: \"python ./", "end": 130, "score": 0.99992436170578, "start": 111, "tag": "EMAIL", "value": "username@domain.com" }, { "context": "e = '' # 'username@domain.com'\npassword = '' # 'password'\n\ncommand: \"python ./anydo.widget/get_anydo.py #{", "end": 158, "score": 0.9988388419151306, "start": 150, "tag": "PASSWORD", "value": "password" } ]
anydo.widget/index.coffee
mislavcimpersak/anydo-widget
2
# Mislav Cimpersak # 2015 # mislav.cimpersak@gmail.com # INSERT YOUR NAME AND PASSWORD HERE username = '' # 'username@domain.com' password = '' # 'password' command: "python ./anydo.widget/get_anydo.py #{username} #{password}" refreshFrequency: 300000 # ms (5 minutes) style: """ width: 100% left: 60px top: 30px color: #000 overflow: hidden max-width: 300px background: rgba(#000, 0.3) border-radius: 5px color: #ddd font-family: 'Roboto Condensed', sans-serif -webkit-font-smoothing: antialiased .tasks list-style-type: none padding: 0 margin: 5 .task list-style: none float: left width: 100% height: auto display: inline-block padding: 10px 20px border-bottom: 1px solid rgba(255, 255, 255, 0.3) .title white-space: nowrap text-overflow: ellipsis overflow: hidden .priority-icon margin-right: 9px .task-checked text-decoration: line-through color: #a3a3a3 .refresh-icon margin-left: 9px font-size: 12px .alert font-weight: 800 font-size: 12px opacity: 0.8 margin-left: 10px margin-top: 5px .alert-icon margin-right: 9px .cf:before, .cf:after content: " "; display: table; .cf:after clear: both """ # Render the output render: -> """ <link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <ul class="tasks cf"> </ul> """ update: (output, domEl) -> dom = $(domEl) # parse the JSON created by the shell script try data = JSON.parse(output) html = "" catch error html = "<li class='task'>" + output + "</li>" data # check if data is empty if data if data.length == 0 html += "<li class='task'>Hooray! No tasks here &nbsp;<i class='fa fa-check'></i></li>" # loop through the services in the JSON. for task in data # start building single task list item html += "<li class='task'>" html += "<div class='title'>" # add high priority icon if task.priority == 'High' html += "<i class='priority-icon fa fa-flash'></i>" if task.status == 'CHECKED' html += "<span class='task-checked'>" html += task.title if task.status == 'CHECKED' html += "</span>" # check if task is repeating if task.repeatingMethod != 'TASK_REPEAT_OFF' html += "<i class='refresh-icon fa fa-recycle'></i>" html += "</div>" # check for alerts if task.hasOwnProperty('alert') alert = task.alert if alert.hasOwnProperty('type') if alert.type == 'OFFSET' html += "<div class='alert'><i class='alert-icon fa fa-bell-o'></i>" if task.alert.repeatStartsOn? html += task.alert.repeatStartsOn else html += task.dueDate html += "</div>" html += "</li>" # end of single task list item # Set our output. $('.tasks').html(html)
28939
# <NAME> # 2015 # <EMAIL> # INSERT YOUR NAME AND PASSWORD HERE username = '' # '<EMAIL>' password = '' # '<PASSWORD>' command: "python ./anydo.widget/get_anydo.py #{username} #{password}" refreshFrequency: 300000 # ms (5 minutes) style: """ width: 100% left: 60px top: 30px color: #000 overflow: hidden max-width: 300px background: rgba(#000, 0.3) border-radius: 5px color: #ddd font-family: 'Roboto Condensed', sans-serif -webkit-font-smoothing: antialiased .tasks list-style-type: none padding: 0 margin: 5 .task list-style: none float: left width: 100% height: auto display: inline-block padding: 10px 20px border-bottom: 1px solid rgba(255, 255, 255, 0.3) .title white-space: nowrap text-overflow: ellipsis overflow: hidden .priority-icon margin-right: 9px .task-checked text-decoration: line-through color: #a3a3a3 .refresh-icon margin-left: 9px font-size: 12px .alert font-weight: 800 font-size: 12px opacity: 0.8 margin-left: 10px margin-top: 5px .alert-icon margin-right: 9px .cf:before, .cf:after content: " "; display: table; .cf:after clear: both """ # Render the output render: -> """ <link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <ul class="tasks cf"> </ul> """ update: (output, domEl) -> dom = $(domEl) # parse the JSON created by the shell script try data = JSON.parse(output) html = "" catch error html = "<li class='task'>" + output + "</li>" data # check if data is empty if data if data.length == 0 html += "<li class='task'>Hooray! No tasks here &nbsp;<i class='fa fa-check'></i></li>" # loop through the services in the JSON. for task in data # start building single task list item html += "<li class='task'>" html += "<div class='title'>" # add high priority icon if task.priority == 'High' html += "<i class='priority-icon fa fa-flash'></i>" if task.status == 'CHECKED' html += "<span class='task-checked'>" html += task.title if task.status == 'CHECKED' html += "</span>" # check if task is repeating if task.repeatingMethod != 'TASK_REPEAT_OFF' html += "<i class='refresh-icon fa fa-recycle'></i>" html += "</div>" # check for alerts if task.hasOwnProperty('alert') alert = task.alert if alert.hasOwnProperty('type') if alert.type == 'OFFSET' html += "<div class='alert'><i class='alert-icon fa fa-bell-o'></i>" if task.alert.repeatStartsOn? html += task.alert.repeatStartsOn else html += task.dueDate html += "</div>" html += "</li>" # end of single task list item # Set our output. $('.tasks').html(html)
true
# PI:NAME:<NAME>END_PI # 2015 # PI:EMAIL:<EMAIL>END_PI # INSERT YOUR NAME AND PASSWORD HERE username = '' # 'PI:EMAIL:<EMAIL>END_PI' password = '' # 'PI:PASSWORD:<PASSWORD>END_PI' command: "python ./anydo.widget/get_anydo.py #{username} #{password}" refreshFrequency: 300000 # ms (5 minutes) style: """ width: 100% left: 60px top: 30px color: #000 overflow: hidden max-width: 300px background: rgba(#000, 0.3) border-radius: 5px color: #ddd font-family: 'Roboto Condensed', sans-serif -webkit-font-smoothing: antialiased .tasks list-style-type: none padding: 0 margin: 5 .task list-style: none float: left width: 100% height: auto display: inline-block padding: 10px 20px border-bottom: 1px solid rgba(255, 255, 255, 0.3) .title white-space: nowrap text-overflow: ellipsis overflow: hidden .priority-icon margin-right: 9px .task-checked text-decoration: line-through color: #a3a3a3 .refresh-icon margin-left: 9px font-size: 12px .alert font-weight: 800 font-size: 12px opacity: 0.8 margin-left: 10px margin-top: 5px .alert-icon margin-right: 9px .cf:before, .cf:after content: " "; display: table; .cf:after clear: both """ # Render the output render: -> """ <link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <ul class="tasks cf"> </ul> """ update: (output, domEl) -> dom = $(domEl) # parse the JSON created by the shell script try data = JSON.parse(output) html = "" catch error html = "<li class='task'>" + output + "</li>" data # check if data is empty if data if data.length == 0 html += "<li class='task'>Hooray! No tasks here &nbsp;<i class='fa fa-check'></i></li>" # loop through the services in the JSON. for task in data # start building single task list item html += "<li class='task'>" html += "<div class='title'>" # add high priority icon if task.priority == 'High' html += "<i class='priority-icon fa fa-flash'></i>" if task.status == 'CHECKED' html += "<span class='task-checked'>" html += task.title if task.status == 'CHECKED' html += "</span>" # check if task is repeating if task.repeatingMethod != 'TASK_REPEAT_OFF' html += "<i class='refresh-icon fa fa-recycle'></i>" html += "</div>" # check for alerts if task.hasOwnProperty('alert') alert = task.alert if alert.hasOwnProperty('type') if alert.type == 'OFFSET' html += "<div class='alert'><i class='alert-icon fa fa-bell-o'></i>" if task.alert.repeatStartsOn? html += task.alert.repeatStartsOn else html += task.dueDate html += "</div>" html += "</li>" # end of single task list item # Set our output. $('.tasks').html(html)
[ { "context": "oordinates[1]\n \n @_id = obj._id\n @_name = 'GritsNode'\n \n if typeof marker != 'undefined' and marke", "end": 770, "score": 0.7218003869056702, "start": 761, "tag": "NAME", "value": "GritsNode" } ]
app/packages/grits-net-mapper/src/grits_node.coffee
billdmcconnell/fliightData
4
# creates an instance of a node # # @param [Object] obj, an object that represents a node, it must contain a # unique _id and a geoJSON 'loc' property # @param [Object] marker, an instance of GritsMarker class GritsNode constructor: (obj, marker) -> if typeof obj == 'undefined' or obj == null throw new Error('A node requires valid input object') return if obj.hasOwnProperty('_id') == false throw new Error('A node requires the "_id" unique identifier property') return if obj.hasOwnProperty('loc') == false throw new Error('A node requires the "loc" geoJSON location property') return longitude = obj.loc.coordinates[0] latitude = obj.loc.coordinates[1] @_id = obj._id @_name = 'GritsNode' if typeof marker != 'undefined' and marker instanceof GritsMarker @marker = marker else @marker = new GritsMarker() @latLng = [latitude, longitude] @incomingThroughput = 0 @outgoingThroughput = 0 @level = 0 @metadata = {} _.extend(@metadata, obj) @eventHandlers = {} return # binds eventHandlers to the node # # @param [Object] eventHandlers, an object containing event handlers setEventHandlers: (eventHandlers) -> for name, method of eventHandlers @eventHandlers[name] = _.bind(method, this)
200897
# creates an instance of a node # # @param [Object] obj, an object that represents a node, it must contain a # unique _id and a geoJSON 'loc' property # @param [Object] marker, an instance of GritsMarker class GritsNode constructor: (obj, marker) -> if typeof obj == 'undefined' or obj == null throw new Error('A node requires valid input object') return if obj.hasOwnProperty('_id') == false throw new Error('A node requires the "_id" unique identifier property') return if obj.hasOwnProperty('loc') == false throw new Error('A node requires the "loc" geoJSON location property') return longitude = obj.loc.coordinates[0] latitude = obj.loc.coordinates[1] @_id = obj._id @_name = '<NAME>' if typeof marker != 'undefined' and marker instanceof GritsMarker @marker = marker else @marker = new GritsMarker() @latLng = [latitude, longitude] @incomingThroughput = 0 @outgoingThroughput = 0 @level = 0 @metadata = {} _.extend(@metadata, obj) @eventHandlers = {} return # binds eventHandlers to the node # # @param [Object] eventHandlers, an object containing event handlers setEventHandlers: (eventHandlers) -> for name, method of eventHandlers @eventHandlers[name] = _.bind(method, this)
true
# creates an instance of a node # # @param [Object] obj, an object that represents a node, it must contain a # unique _id and a geoJSON 'loc' property # @param [Object] marker, an instance of GritsMarker class GritsNode constructor: (obj, marker) -> if typeof obj == 'undefined' or obj == null throw new Error('A node requires valid input object') return if obj.hasOwnProperty('_id') == false throw new Error('A node requires the "_id" unique identifier property') return if obj.hasOwnProperty('loc') == false throw new Error('A node requires the "loc" geoJSON location property') return longitude = obj.loc.coordinates[0] latitude = obj.loc.coordinates[1] @_id = obj._id @_name = 'PI:NAME:<NAME>END_PI' if typeof marker != 'undefined' and marker instanceof GritsMarker @marker = marker else @marker = new GritsMarker() @latLng = [latitude, longitude] @incomingThroughput = 0 @outgoingThroughput = 0 @level = 0 @metadata = {} _.extend(@metadata, obj) @eventHandlers = {} return # binds eventHandlers to the node # # @param [Object] eventHandlers, an object containing event handlers setEventHandlers: (eventHandlers) -> for name, method of eventHandlers @eventHandlers[name] = _.bind(method, this)
[ { "context": "bject spread property over Object.assign\n# @author Sharmila Jesupaul\n# See LICENSE file in root directory for full lic", "end": 98, "score": 0.9998677968978882, "start": 81, "tag": "NAME", "value": "Sharmila Jesupaul" } ]
src/tests/rules/prefer-object-spread.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Prefers object spread property over Object.assign # @author Sharmila Jesupaul # See LICENSE file in root directory for full license. ### 'use strict' rule = require '../../rules/prefer-object-spread' {RuleTester} = require 'eslint' path = require 'path' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'prefer-object-spread', rule, valid: [ 'Object.assign()' 'a = Object.assign(a, b)' 'Object.assign(a, b)' 'a = Object.assign(b, { c: 1 })' 'bar = { ...foo }' 'Object.assign(...foo)' 'Object.assign(foo, { bar: baz })' 'Object.assign({}, ...objects)' "foo({ foo: 'bar' })" ''' Object = {} Object.assign({}, foo) ''' ''' Object = {} Object.assign({}, foo) ''' ''' Object = {} Object.assign foo: 'bar' ''' ''' Object = {} Object.assign { foo: 'bar' } ''' ''' Object = require 'foo' Object.assign({ foo: 'bar' }) ''' ''' import Object from 'foo' Object.assign({ foo: 'bar' }) ''' ''' import { Something as Object } from 'foo' Object.assign({ foo: 'bar' }) ''' ''' import { Object, Array } from 'globals' Object.assign({ foo: 'bar' }) ''' ] invalid: [ code: 'Object.assign({}, foo)' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: 'Object.assign {}, foo' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign {}, foo: 'bar'" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({}, baz, { foo: 'bar' })" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({}, { foo: 'bar', baz: 'foo' })" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({ foo: 'bar' }, baz)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Many args code: "Object.assign({ foo: 'bar' }, cats, dogs, trees, birds)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({ foo: 'bar' }, Object.assign { bar: 'foo' }, baz)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 , messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 31 ] , code: "Object.assign({ foo: 'bar' }, Object.assign({ bar: 'foo' }, Object.assign({}, { superNested: 'butwhy' })))" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 , messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 31 , messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 61 ] , # Mix spread in argument code: "Object.assign({foo: 'bar', ...bar}, baz)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Object shorthand code: 'Object.assign({}, { foo, bar, baz })' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Objects with computed properties code: "Object.assign({}, { [bar]: 'foo' })" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Objects with spread properties code: 'Object.assign({ ...bar }, { ...baz })' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Multiline objects code: ''' Object.assign({ ...bar }, { # this is a bar foo: 'bar' baz: "cats" }) ''' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , ### # This is a special case where Object.assign is called with a single argument # and that argument is an object expression. In this case we warn and display # a message to use an object literal instead. ### code: 'Object.assign({})' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 1 column: 1 ] , code: 'Object.assign({ foo: bar })' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 1 column: 1 ] , code: ''' foo = 'bar' Object.assign({ foo: bar }) ''' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 2 column: 1 ] , code: ''' foo = 'bar' Object.assign({ foo: bar }) ''' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 2 column: 1 ] ]
179855
###* # @fileoverview Prefers object spread property over Object.assign # @author <NAME> # See LICENSE file in root directory for full license. ### 'use strict' rule = require '../../rules/prefer-object-spread' {RuleTester} = require 'eslint' path = require 'path' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'prefer-object-spread', rule, valid: [ 'Object.assign()' 'a = Object.assign(a, b)' 'Object.assign(a, b)' 'a = Object.assign(b, { c: 1 })' 'bar = { ...foo }' 'Object.assign(...foo)' 'Object.assign(foo, { bar: baz })' 'Object.assign({}, ...objects)' "foo({ foo: 'bar' })" ''' Object = {} Object.assign({}, foo) ''' ''' Object = {} Object.assign({}, foo) ''' ''' Object = {} Object.assign foo: 'bar' ''' ''' Object = {} Object.assign { foo: 'bar' } ''' ''' Object = require 'foo' Object.assign({ foo: 'bar' }) ''' ''' import Object from 'foo' Object.assign({ foo: 'bar' }) ''' ''' import { Something as Object } from 'foo' Object.assign({ foo: 'bar' }) ''' ''' import { Object, Array } from 'globals' Object.assign({ foo: 'bar' }) ''' ] invalid: [ code: 'Object.assign({}, foo)' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: 'Object.assign {}, foo' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign {}, foo: 'bar'" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({}, baz, { foo: 'bar' })" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({}, { foo: 'bar', baz: 'foo' })" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({ foo: 'bar' }, baz)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Many args code: "Object.assign({ foo: 'bar' }, cats, dogs, trees, birds)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({ foo: 'bar' }, Object.assign { bar: 'foo' }, baz)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 , messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 31 ] , code: "Object.assign({ foo: 'bar' }, Object.assign({ bar: 'foo' }, Object.assign({}, { superNested: 'butwhy' })))" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 , messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 31 , messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 61 ] , # Mix spread in argument code: "Object.assign({foo: 'bar', ...bar}, baz)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Object shorthand code: 'Object.assign({}, { foo, bar, baz })' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Objects with computed properties code: "Object.assign({}, { [bar]: 'foo' })" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Objects with spread properties code: 'Object.assign({ ...bar }, { ...baz })' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Multiline objects code: ''' Object.assign({ ...bar }, { # this is a bar foo: 'bar' baz: "cats" }) ''' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , ### # This is a special case where Object.assign is called with a single argument # and that argument is an object expression. In this case we warn and display # a message to use an object literal instead. ### code: 'Object.assign({})' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 1 column: 1 ] , code: 'Object.assign({ foo: bar })' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 1 column: 1 ] , code: ''' foo = 'bar' Object.assign({ foo: bar }) ''' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 2 column: 1 ] , code: ''' foo = 'bar' Object.assign({ foo: bar }) ''' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 2 column: 1 ] ]
true
###* # @fileoverview Prefers object spread property over Object.assign # @author PI:NAME:<NAME>END_PI # See LICENSE file in root directory for full license. ### 'use strict' rule = require '../../rules/prefer-object-spread' {RuleTester} = require 'eslint' path = require 'path' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'prefer-object-spread', rule, valid: [ 'Object.assign()' 'a = Object.assign(a, b)' 'Object.assign(a, b)' 'a = Object.assign(b, { c: 1 })' 'bar = { ...foo }' 'Object.assign(...foo)' 'Object.assign(foo, { bar: baz })' 'Object.assign({}, ...objects)' "foo({ foo: 'bar' })" ''' Object = {} Object.assign({}, foo) ''' ''' Object = {} Object.assign({}, foo) ''' ''' Object = {} Object.assign foo: 'bar' ''' ''' Object = {} Object.assign { foo: 'bar' } ''' ''' Object = require 'foo' Object.assign({ foo: 'bar' }) ''' ''' import Object from 'foo' Object.assign({ foo: 'bar' }) ''' ''' import { Something as Object } from 'foo' Object.assign({ foo: 'bar' }) ''' ''' import { Object, Array } from 'globals' Object.assign({ foo: 'bar' }) ''' ] invalid: [ code: 'Object.assign({}, foo)' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: 'Object.assign {}, foo' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign {}, foo: 'bar'" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({}, baz, { foo: 'bar' })" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({}, { foo: 'bar', baz: 'foo' })" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({ foo: 'bar' }, baz)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Many args code: "Object.assign({ foo: 'bar' }, cats, dogs, trees, birds)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , code: "Object.assign({ foo: 'bar' }, Object.assign { bar: 'foo' }, baz)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 , messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 31 ] , code: "Object.assign({ foo: 'bar' }, Object.assign({ bar: 'foo' }, Object.assign({}, { superNested: 'butwhy' })))" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 , messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 31 , messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 61 ] , # Mix spread in argument code: "Object.assign({foo: 'bar', ...bar}, baz)" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Object shorthand code: 'Object.assign({}, { foo, bar, baz })' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Objects with computed properties code: "Object.assign({}, { [bar]: 'foo' })" errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Objects with spread properties code: 'Object.assign({ ...bar }, { ...baz })' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , # Multiline objects code: ''' Object.assign({ ...bar }, { # this is a bar foo: 'bar' baz: "cats" }) ''' errors: [ messageId: 'useSpreadMessage' type: 'CallExpression' line: 1 column: 1 ] , ### # This is a special case where Object.assign is called with a single argument # and that argument is an object expression. In this case we warn and display # a message to use an object literal instead. ### code: 'Object.assign({})' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 1 column: 1 ] , code: 'Object.assign({ foo: bar })' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 1 column: 1 ] , code: ''' foo = 'bar' Object.assign({ foo: bar }) ''' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 2 column: 1 ] , code: ''' foo = 'bar' Object.assign({ foo: bar }) ''' errors: [ messageId: 'useLiteralMessage' type: 'CallExpression' line: 2 column: 1 ] ]
[ { "context": "is is a somewhat hacked up version of filedrop, by Weixi Yen:\r\n# \r\n# Email: [Firstname][Lastname]@gmail.com\r\n", "end": 72, "score": 0.9996782541275024, "start": 63, "tag": "NAME", "value": "Weixi Yen" }, { "context": "ersion of filedrop, by Weixi Yen:\r\n# \r\n# Email: [Firstname][Lastname]@gmail.com\r\n# \r\n# Copyright (c) 2", "end": 95, "score": 0.7502706050872803, "start": 90, "tag": "EMAIL", "value": "First" }, { "context": "iledrop, by Weixi Yen:\r\n# \r\n# Email: [Firstname][Lastname]@gmail.com\r\n# \r\n# Copyright (c) 2010 Resopollution\r\n# \r\n#", "end": 120, "score": 0.8597223162651062, "start": 101, "tag": "EMAIL", "value": "Lastname]@gmail.com" }, { "context": "\n# \r\n# Project home:\r\n# http://www.github.com/weixiyen/jquery-filedrop\r\n# \r\n# Version: 0.1.0\r\n# \r\n# F", "end": 319, "score": 0.808234453201294, "start": 311, "tag": "USERNAME", "value": "weixiyen" } ]
app/assets/javascripts/cropper/filedrop.js.coffee
spanner/cropper
1
# # # This is a somewhat hacked up version of filedrop, by Weixi Yen: # # Email: [Firstname][Lastname]@gmail.com # # Copyright (c) 2010 Resopollution # # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license.php # # Project home: # http://www.github.com/weixiyen/jquery-filedrop # # Version: 0.1.0 # # Features: # Allows sending of extra parameters with file. # Works with Firefox 3.6+ # Future-compliant with HTML5 spec (will work with Webkit browsers and IE9) # Usage: # See README at project homepage Modernizr.addTest 'filereader', -> !!(window.File && window.FileList && window.FileReader) jQuery ($) -> jQuery.event.props.push "dataTransfer" opts = {} errors = [ "BrowserNotSupported", "TooManyFiles", "FileTooLarge" ] doc_leave_timer = undefined stop_loop = false files_count = 0 files = undefined drop = (e) -> e.preventDefault() opts.drop e files = e.dataTransfer.files unless Modernizr.filereader && files? opts.error(errors[0]) return false files_count = files.length upload() false pick = (e, filefield) -> e.preventDefault() files = filefield.files unless Modernizr.filereader && files? opts.error(errors[0]) return false files_count = files.length console.log "pick", files upload() false getBuilder = (filename, filedata, boundary) -> dashdash = "--" crlf = "\r\n" builder = "" $.each opts.data, (i, val) -> val = val() if typeof val is "function" builder += dashdash builder += boundary builder += crlf builder += "Content-Disposition: form-data; name=\"" + i + "\"" builder += crlf builder += crlf builder += val builder += crlf builder += dashdash builder += boundary builder += crlf builder += "Content-Disposition: form-data; name=\"" + opts.paramname + "\"" builder += "; filename=\"" + filename + "\"" builder += crlf builder += "Content-Type: image/jpeg" builder += crlf builder += crlf builder += filedata builder += crlf builder += dashdash builder += boundary builder += dashdash builder += crlf builder progress = (e) -> if e.lengthComputable percentage = Math.round((e.loaded * 100) / e.total) unless @currentProgress is percentage @currentProgress = percentage opts.progressUpdated @index, @file, @currentProgress elapsed = new Date().getTime() diffTime = elapsed - @currentStart if diffTime >= opts.refresh diffData = e.loaded - @startData speed = diffData / diffTime opts.speedUpdated @index, @file, speed @startData = e.loaded @currentStart = elapsed upload = -> send = (e) -> e.target.index = getIndexBySize(e.total) if e.target.index is `undefined` xhr = new XMLHttpRequest() ul = xhr.upload file = files[e.target.index] index = e.target.index start_time = new Date().getTime() boundary = "------multipartformboundary" + (new Date).getTime() builder = undefined newName = rename(file.name) if typeof newName is "string" builder = getBuilder(newName, e.target.result, boundary) else builder = getBuilder(file.name, e.target.result, boundary) ul.index = index ul.file = file ul.downloadStartTime = start_time ul.currentStart = start_time ul.currentProgress = 0 ul.startData = 0 ul.addEventListener "progress", progress, false xhr.open "POST", opts.url, true xhr.setRequestHeader "content-type", "multipart/form-data; boundary=" + boundary xhr.sendAsBinary builder opts.uploadStarted index, file, files_count xhr.onload = -> if xhr.responseText now = new Date().getTime() timeDiff = now - start_time result = opts.uploadFinished(index, file, xhr.responseText, timeDiff) filesDone++ afterAll() if filesDone is files_count - filesRejected stop_loop = true if result is false stop_loop = false unless files opts.error errors[0] return false filesDone = 0 filesRejected = 0 if files_count > opts.maxfiles opts.error errors[1] return false i = 0 while i < files_count return false if stop_loop try unless beforeEach(files[i]) is false return if i is files_count reader = new FileReader() max_file_size = 1048576 * opts.maxfilesize reader.index = i if files[i].size > max_file_size opts.error errors[2], files[i], i filesRejected++ continue reader.onloadend = send reader.readAsBinaryString files[i] else filesRejected++ catch err opts.error errors[0] return false i++ getIndexBySize = (size) -> i = 0 while i < files_count return i if files[i].size is size i++ `undefined` rename = (name) -> opts.rename name beforeEach = (file) -> opts.beforeEach file afterAll = -> opts.afterAll() dragEnter = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.dragEnter e dragOver = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.docOver e opts.dragOver e dragLeave = (e) -> clearTimeout doc_leave_timer opts.dragLeave e e.stopPropagation() docDrop = (e) -> e.preventDefault() opts.docLeave e false docEnter = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.docEnter e false docOver = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.docOver e false docLeave = (e) -> doc_leave_timer = setTimeout(-> opts.docLeave e , 200) empty = -> default_opts = url: "" refresh: 1000 paramname: "userfile" maxfiles: 25 maxfilesize: 1 data: {} drop: empty dragEnter: empty dragOver: empty dragLeave: empty docEnter: empty docOver: empty docLeave: empty beforeEach: empty afterAll: empty rename: empty error: (err, file, i) -> alert err uploadStarted: empty uploadFinished: empty progressUpdated: empty speedUpdated: empty $.fn.filedrop = (options) -> opts = $.extend({}, default_opts, options) @bind("drop", drop).bind("pick", pick).bind("dragenter", dragEnter).bind("dragover", dragOver).bind "dragleave", dragLeave $(document).bind("drop", docDrop).bind("dragenter", docEnter).bind("dragover", docOver).bind "dragleave", docLeave try return if XMLHttpRequest::sendAsBinary XMLHttpRequest::sendAsBinary = (datastr) -> byteValue = (x) -> x.charCodeAt(0) & 0xff ords = Array::map.call(datastr, byteValue) ui8a = new Uint8Array(ords) @send ui8a.buffer
115835
# # # This is a somewhat hacked up version of filedrop, by <NAME>: # # Email: [<EMAIL>name][<EMAIL> # # Copyright (c) 2010 Resopollution # # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license.php # # Project home: # http://www.github.com/weixiyen/jquery-filedrop # # Version: 0.1.0 # # Features: # Allows sending of extra parameters with file. # Works with Firefox 3.6+ # Future-compliant with HTML5 spec (will work with Webkit browsers and IE9) # Usage: # See README at project homepage Modernizr.addTest 'filereader', -> !!(window.File && window.FileList && window.FileReader) jQuery ($) -> jQuery.event.props.push "dataTransfer" opts = {} errors = [ "BrowserNotSupported", "TooManyFiles", "FileTooLarge" ] doc_leave_timer = undefined stop_loop = false files_count = 0 files = undefined drop = (e) -> e.preventDefault() opts.drop e files = e.dataTransfer.files unless Modernizr.filereader && files? opts.error(errors[0]) return false files_count = files.length upload() false pick = (e, filefield) -> e.preventDefault() files = filefield.files unless Modernizr.filereader && files? opts.error(errors[0]) return false files_count = files.length console.log "pick", files upload() false getBuilder = (filename, filedata, boundary) -> dashdash = "--" crlf = "\r\n" builder = "" $.each opts.data, (i, val) -> val = val() if typeof val is "function" builder += dashdash builder += boundary builder += crlf builder += "Content-Disposition: form-data; name=\"" + i + "\"" builder += crlf builder += crlf builder += val builder += crlf builder += dashdash builder += boundary builder += crlf builder += "Content-Disposition: form-data; name=\"" + opts.paramname + "\"" builder += "; filename=\"" + filename + "\"" builder += crlf builder += "Content-Type: image/jpeg" builder += crlf builder += crlf builder += filedata builder += crlf builder += dashdash builder += boundary builder += dashdash builder += crlf builder progress = (e) -> if e.lengthComputable percentage = Math.round((e.loaded * 100) / e.total) unless @currentProgress is percentage @currentProgress = percentage opts.progressUpdated @index, @file, @currentProgress elapsed = new Date().getTime() diffTime = elapsed - @currentStart if diffTime >= opts.refresh diffData = e.loaded - @startData speed = diffData / diffTime opts.speedUpdated @index, @file, speed @startData = e.loaded @currentStart = elapsed upload = -> send = (e) -> e.target.index = getIndexBySize(e.total) if e.target.index is `undefined` xhr = new XMLHttpRequest() ul = xhr.upload file = files[e.target.index] index = e.target.index start_time = new Date().getTime() boundary = "------multipartformboundary" + (new Date).getTime() builder = undefined newName = rename(file.name) if typeof newName is "string" builder = getBuilder(newName, e.target.result, boundary) else builder = getBuilder(file.name, e.target.result, boundary) ul.index = index ul.file = file ul.downloadStartTime = start_time ul.currentStart = start_time ul.currentProgress = 0 ul.startData = 0 ul.addEventListener "progress", progress, false xhr.open "POST", opts.url, true xhr.setRequestHeader "content-type", "multipart/form-data; boundary=" + boundary xhr.sendAsBinary builder opts.uploadStarted index, file, files_count xhr.onload = -> if xhr.responseText now = new Date().getTime() timeDiff = now - start_time result = opts.uploadFinished(index, file, xhr.responseText, timeDiff) filesDone++ afterAll() if filesDone is files_count - filesRejected stop_loop = true if result is false stop_loop = false unless files opts.error errors[0] return false filesDone = 0 filesRejected = 0 if files_count > opts.maxfiles opts.error errors[1] return false i = 0 while i < files_count return false if stop_loop try unless beforeEach(files[i]) is false return if i is files_count reader = new FileReader() max_file_size = 1048576 * opts.maxfilesize reader.index = i if files[i].size > max_file_size opts.error errors[2], files[i], i filesRejected++ continue reader.onloadend = send reader.readAsBinaryString files[i] else filesRejected++ catch err opts.error errors[0] return false i++ getIndexBySize = (size) -> i = 0 while i < files_count return i if files[i].size is size i++ `undefined` rename = (name) -> opts.rename name beforeEach = (file) -> opts.beforeEach file afterAll = -> opts.afterAll() dragEnter = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.dragEnter e dragOver = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.docOver e opts.dragOver e dragLeave = (e) -> clearTimeout doc_leave_timer opts.dragLeave e e.stopPropagation() docDrop = (e) -> e.preventDefault() opts.docLeave e false docEnter = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.docEnter e false docOver = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.docOver e false docLeave = (e) -> doc_leave_timer = setTimeout(-> opts.docLeave e , 200) empty = -> default_opts = url: "" refresh: 1000 paramname: "userfile" maxfiles: 25 maxfilesize: 1 data: {} drop: empty dragEnter: empty dragOver: empty dragLeave: empty docEnter: empty docOver: empty docLeave: empty beforeEach: empty afterAll: empty rename: empty error: (err, file, i) -> alert err uploadStarted: empty uploadFinished: empty progressUpdated: empty speedUpdated: empty $.fn.filedrop = (options) -> opts = $.extend({}, default_opts, options) @bind("drop", drop).bind("pick", pick).bind("dragenter", dragEnter).bind("dragover", dragOver).bind "dragleave", dragLeave $(document).bind("drop", docDrop).bind("dragenter", docEnter).bind("dragover", docOver).bind "dragleave", docLeave try return if XMLHttpRequest::sendAsBinary XMLHttpRequest::sendAsBinary = (datastr) -> byteValue = (x) -> x.charCodeAt(0) & 0xff ords = Array::map.call(datastr, byteValue) ui8a = new Uint8Array(ords) @send ui8a.buffer
true
# # # This is a somewhat hacked up version of filedrop, by PI:NAME:<NAME>END_PI: # # Email: [PI:EMAIL:<EMAIL>END_PIname][PI:EMAIL:<EMAIL>END_PI # # Copyright (c) 2010 Resopollution # # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license.php # # Project home: # http://www.github.com/weixiyen/jquery-filedrop # # Version: 0.1.0 # # Features: # Allows sending of extra parameters with file. # Works with Firefox 3.6+ # Future-compliant with HTML5 spec (will work with Webkit browsers and IE9) # Usage: # See README at project homepage Modernizr.addTest 'filereader', -> !!(window.File && window.FileList && window.FileReader) jQuery ($) -> jQuery.event.props.push "dataTransfer" opts = {} errors = [ "BrowserNotSupported", "TooManyFiles", "FileTooLarge" ] doc_leave_timer = undefined stop_loop = false files_count = 0 files = undefined drop = (e) -> e.preventDefault() opts.drop e files = e.dataTransfer.files unless Modernizr.filereader && files? opts.error(errors[0]) return false files_count = files.length upload() false pick = (e, filefield) -> e.preventDefault() files = filefield.files unless Modernizr.filereader && files? opts.error(errors[0]) return false files_count = files.length console.log "pick", files upload() false getBuilder = (filename, filedata, boundary) -> dashdash = "--" crlf = "\r\n" builder = "" $.each opts.data, (i, val) -> val = val() if typeof val is "function" builder += dashdash builder += boundary builder += crlf builder += "Content-Disposition: form-data; name=\"" + i + "\"" builder += crlf builder += crlf builder += val builder += crlf builder += dashdash builder += boundary builder += crlf builder += "Content-Disposition: form-data; name=\"" + opts.paramname + "\"" builder += "; filename=\"" + filename + "\"" builder += crlf builder += "Content-Type: image/jpeg" builder += crlf builder += crlf builder += filedata builder += crlf builder += dashdash builder += boundary builder += dashdash builder += crlf builder progress = (e) -> if e.lengthComputable percentage = Math.round((e.loaded * 100) / e.total) unless @currentProgress is percentage @currentProgress = percentage opts.progressUpdated @index, @file, @currentProgress elapsed = new Date().getTime() diffTime = elapsed - @currentStart if diffTime >= opts.refresh diffData = e.loaded - @startData speed = diffData / diffTime opts.speedUpdated @index, @file, speed @startData = e.loaded @currentStart = elapsed upload = -> send = (e) -> e.target.index = getIndexBySize(e.total) if e.target.index is `undefined` xhr = new XMLHttpRequest() ul = xhr.upload file = files[e.target.index] index = e.target.index start_time = new Date().getTime() boundary = "------multipartformboundary" + (new Date).getTime() builder = undefined newName = rename(file.name) if typeof newName is "string" builder = getBuilder(newName, e.target.result, boundary) else builder = getBuilder(file.name, e.target.result, boundary) ul.index = index ul.file = file ul.downloadStartTime = start_time ul.currentStart = start_time ul.currentProgress = 0 ul.startData = 0 ul.addEventListener "progress", progress, false xhr.open "POST", opts.url, true xhr.setRequestHeader "content-type", "multipart/form-data; boundary=" + boundary xhr.sendAsBinary builder opts.uploadStarted index, file, files_count xhr.onload = -> if xhr.responseText now = new Date().getTime() timeDiff = now - start_time result = opts.uploadFinished(index, file, xhr.responseText, timeDiff) filesDone++ afterAll() if filesDone is files_count - filesRejected stop_loop = true if result is false stop_loop = false unless files opts.error errors[0] return false filesDone = 0 filesRejected = 0 if files_count > opts.maxfiles opts.error errors[1] return false i = 0 while i < files_count return false if stop_loop try unless beforeEach(files[i]) is false return if i is files_count reader = new FileReader() max_file_size = 1048576 * opts.maxfilesize reader.index = i if files[i].size > max_file_size opts.error errors[2], files[i], i filesRejected++ continue reader.onloadend = send reader.readAsBinaryString files[i] else filesRejected++ catch err opts.error errors[0] return false i++ getIndexBySize = (size) -> i = 0 while i < files_count return i if files[i].size is size i++ `undefined` rename = (name) -> opts.rename name beforeEach = (file) -> opts.beforeEach file afterAll = -> opts.afterAll() dragEnter = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.dragEnter e dragOver = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.docOver e opts.dragOver e dragLeave = (e) -> clearTimeout doc_leave_timer opts.dragLeave e e.stopPropagation() docDrop = (e) -> e.preventDefault() opts.docLeave e false docEnter = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.docEnter e false docOver = (e) -> clearTimeout doc_leave_timer e.preventDefault() opts.docOver e false docLeave = (e) -> doc_leave_timer = setTimeout(-> opts.docLeave e , 200) empty = -> default_opts = url: "" refresh: 1000 paramname: "userfile" maxfiles: 25 maxfilesize: 1 data: {} drop: empty dragEnter: empty dragOver: empty dragLeave: empty docEnter: empty docOver: empty docLeave: empty beforeEach: empty afterAll: empty rename: empty error: (err, file, i) -> alert err uploadStarted: empty uploadFinished: empty progressUpdated: empty speedUpdated: empty $.fn.filedrop = (options) -> opts = $.extend({}, default_opts, options) @bind("drop", drop).bind("pick", pick).bind("dragenter", dragEnter).bind("dragover", dragOver).bind "dragleave", dragLeave $(document).bind("drop", docDrop).bind("dragenter", docEnter).bind("dragover", docOver).bind "dragleave", docLeave try return if XMLHttpRequest::sendAsBinary XMLHttpRequest::sendAsBinary = (datastr) -> byteValue = (x) -> x.charCodeAt(0) & 0xff ords = Array::map.call(datastr, byteValue) ui8a = new Uint8Array(ords) @send ui8a.buffer
[ { "context": "-sign@0.3.0':\n repository: 'https://github.com/mikeal/aws-sign'\n license: 'MIT'\n source: 'index.j", "end": 79, "score": 0.9992480278015137, "start": 73, "tag": "USERNAME", "value": "mikeal" }, { "context": "*!\n * knox - auth\n * Copyright(c) 2010 LearnBoost <dev@learnboost.com>\n * MIT Licensed\n ", "end": 220, "score": 0.9951109886169434, "start": 210, "tag": "USERNAME", "value": "LearnBoost" }, { "context": "nox - auth\n * Copyright(c) 2010 LearnBoost <dev@learnboost.com>\n * MIT Licensed\n */\n <content o", "end": 240, "score": 0.9999262094497681, "start": 222, "tag": "EMAIL", "value": "dev@learnboost.com" }, { "context": "ferjs@2.0.0':\n repository: 'https://github.com/coolaj86/node-bufferjs'\n license: 'MIT'\n source: 'LI", "end": 370, "score": 0.9986150860786438, "start": 362, "tag": "USERNAME", "value": "coolaj86" }, { "context": ".MIT'\n sourceText: \"\"\"\n Copyright (c) 2010 AJ ONeal (and Contributors)\n\n Permission is hereby gr", "end": 484, "score": 0.9998827576637268, "start": 476, "tag": "NAME", "value": "AJ ONeal" }, { "context": "uffers@0.1.1':\n repository: \"http://github.com/substack/node-buffers\"\n license: 'MIT'\n source: 'REA", "end": 1616, "score": 0.9981440901756287, "start": 1608, "tag": "USERNAME", "value": "substack" }, { "context": "erio@0.15.0':\n repository: \"https://github.com/cheeriojs/cheerio\"\n license: 'MIT'\n source: 'https://", "end": 1840, "score": 0.9988206028938293, "start": 1831, "tag": "USERNAME", "value": "cheeriojs" }, { "context": " license: 'MIT'\n source: 'https://github.com/cheeriojs/cheerio/blob/master/package.json'\n 'specificity@", "end": 1910, "score": 0.9990211725234985, "start": 1901, "tag": "USERNAME", "value": "cheeriojs" }, { "context": "icity@0.1.3':\n repository: 'https://github.com/keeganstreet/specificity'\n license: 'MIT'\n sourc", "end": 2008, "score": 0.9991852045059204, "start": 2004, "tag": "USERNAME", "value": "keeg" }, { "context": "\"\"\"\n The ISC License\n\n Copyright (c) Isaac Z. Schlueter\n\n Permission to use, copy, modify, and/or ", "end": 2255, "score": 0.9998889565467834, "start": 2237, "tag": "NAME", "value": "Isaac Z. Schlueter" }, { "context": "itory'\n sourceText: \"\"\"\n Copyright (c) 2014, Gregg Caines, gregg@caines.ca\n\n Permission to use, copy, mo", "end": 3565, "score": 0.9998801350593567, "start": 3553, "tag": "NAME", "value": "Gregg Caines" }, { "context": "rceText: \"\"\"\n Copyright (c) 2014, Gregg Caines, gregg@caines.ca\n\n Permission to use, copy, modify, and/or dist", "end": 3582, "score": 0.9999313354492188, "start": 3567, "tag": "EMAIL", "value": "gregg@caines.ca" }, { "context": "-new)'\n sourceText: \"\"\"\n Copyright (c) 2012, Artur Adib <arturadib@gmail.com>\n All rights reserved.\n\n ", "end": 4459, "score": 0.9999058246612549, "start": 4449, "tag": "NAME", "value": "Artur Adib" }, { "context": "urceText: \"\"\"\n Copyright (c) 2012, Artur Adib <arturadib@gmail.com>\n All rights reserved.\n\n You may use this p", "end": 4480, "score": 0.999932587146759, "start": 4461, "tag": "EMAIL", "value": "arturadib@gmail.com" }, { "context": "th the distribution.\n * Neither the name of Artur Adib nor the\n names of the contributors may b", "end": 5158, "score": 0.9998347759246826, "start": 5148, "tag": "NAME", "value": "Artur Adib" }, { "context": "nacl@0.14.3':\n repository: 'https://github.com/dchest/tweetnacl-js'\n license: 'Public Domain'\n so", "end": 6169, "score": 0.998012363910675, "start": 6163, "tag": "USERNAME", "value": "dchest" }, { "context": ": 'Public Domain'\n source: 'https://github.com/dchest/tweetnacl-js/blob/1042c9c65dc8f1dcb9e981d962d7dbb", "end": 6251, "score": 0.9982511401176453, "start": 6245, "tag": "USERNAME", "value": "dchest" }, { "context": "chema@0.2.2':\n repository: 'https://github.com/kriszyp/json-schema'\n license: 'BSD'\n source: 'READ", "end": 6410, "score": 0.9996808767318726, "start": 6403, "tag": "USERNAME", "value": "kriszyp" }, { "context": " You.\n\n This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights reserved.\n Permission is hereby gr", "end": 18362, "score": 0.9998740553855896, "start": 18345, "tag": "NAME", "value": "Lawrence E. Rosen" }, { "context": "icense: 'MIT'\n repository: 'https://github.com/dfilatov/inherit'\n source: 'LICENSE.md'\n sourceText:", "end": 18670, "score": 0.9993876218795776, "start": 18662, "tag": "USERNAME", "value": "dfilatov" }, { "context": "NSE.md'\n sourceText: \"\"\"\n Copyright (c) 2012 Dmitry Filatov\n\n Permission is hereby granted, free of charge", "end": 18762, "score": 0.9998695254325867, "start": 18748, "tag": "NAME", "value": "Dmitry Filatov" } ]
build/tasks/license-overrides.coffee
Austen-G/BlockBuilder
0
module.exports = 'aws-sign@0.3.0': repository: 'https://github.com/mikeal/aws-sign' license: 'MIT' source: 'index.js' sourceText: """ /*! * knox - auth * Copyright(c) 2010 LearnBoost <dev@learnboost.com> * MIT Licensed */ <content omitted> """ 'bufferjs@2.0.0': repository: 'https://github.com/coolaj86/node-bufferjs' license: 'MIT' source: 'LICENSE.MIT' sourceText: """ Copyright (c) 2010 AJ ONeal (and Contributors) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ 'buffers@0.1.1': repository: "http://github.com/substack/node-buffers" license: 'MIT' source: 'README.markdown' sourceText: """ <content omitted> license ======= MIT/X11 """ 'cheerio@0.15.0': repository: "https://github.com/cheeriojs/cheerio" license: 'MIT' source: 'https://github.com/cheeriojs/cheerio/blob/master/package.json' 'specificity@0.1.3': repository: 'https://github.com/keeganstreet/specificity' license: 'MIT' source: 'package.json in repository' 'promzard@0.2.0': license: 'ISC' source: 'LICENSE in the repository' sourceText: """ The ISC License Copyright (c) Isaac Z. Schlueter Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ 'jschardet@1.1.1': license: 'LGPL' source: 'README.md in the repository' sourceText: """ JsChardet ========= Port of python's chardet (http://chardet.feedparser.org/). License ------- LGPL """ 'core-js@0.4.10': license: 'MIT' source: 'http://rock.mit-license.org linked in source files and bower.json says MIT' 'log-driver@1.2.4': license: 'ISC' source: 'LICENSE file in the repository' sourceText: """ Copyright (c) 2014, Gregg Caines, gregg@caines.ca Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ 'shelljs@0.3.0': license: 'BSD' source: 'LICENSE file in repository - 3-clause BSD (aka BSD-new)' sourceText: """ Copyright (c) 2012, Artur Adib <arturadib@gmail.com> All rights reserved. You may use this project under the terms of the New BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Artur Adib nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARTUR ADIB BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ 'tweetnacl@0.14.3': repository: 'https://github.com/dchest/tweetnacl-js' license: 'Public Domain' source: 'https://github.com/dchest/tweetnacl-js/blob/1042c9c65dc8f1dcb9e981d962d7dbbcf58f1fdc/COPYING.txt says public domain.' 'json-schema@0.2.2': repository: 'https://github.com/kriszyp/json-schema' license: 'BSD' source: 'README links to https://github.com/dojo/dojo/blob/8b6a5e4c42f9cf777dd39eaae8b188e0ebb59a4c/LICENSE' sourceText: """ Dojo is available under *either* the terms of the modified BSD license *or* the Academic Free License version 2.1. As a recipient of Dojo, you may choose which license to receive this code under (except as noted in per-module LICENSE files). Some modules may not be the copyright of the Dojo Foundation. These modules contain explicit declarations of copyright in both the LICENSE files in the directories in which they reside and in the code itself. No external contributions are allowed under licenses which are fundamentally incompatible with the AFL or BSD licenses that Dojo is distributed under. The text of the AFL and BSD licenses is reproduced below. ------------------------------------------------------------------------------- The "New" BSD License: ********************** Copyright (c) 2005-2015, The Dojo Foundation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Dojo Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- The Academic Free License, v. 2.1: ********************************** This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work: Licensed under the Academic Free License version 2.1 1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following: a) to reproduce the Original Work in copies; b) to prepare derivative works ("Derivative Works") based upon the Original Work; c) to distribute copies of the Original Work and Derivative Works to the public; d) to perform the Original Work publicly; and e) to display the Original Work publicly. 2) Grant of Patent License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and Derivative Works. 3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work. 4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. Nothing in this License shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or any other intellectual property of Licensor except as expressly stated herein. No patent license is granted to make, use, sell or offer to sell embodiments of any patent claims other than the licensed claims defined in Section 2. No right is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under different terms from this License any Original Work that Licensor otherwise would have a right to license. 5) This section intentionally omitted. 6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. 7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately proceeding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to Original Work is granted hereunder except under this disclaimer. 8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to any person for any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to liability for death or personal injury resulting from Licensor's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. 9) Acceptance and Termination. If You distribute copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. Nothing else but this License (or another written agreement between Licensor and You) grants You permission to create Derivative Works based upon the Original Work or to exercise any of the rights granted in Section 1 herein, and any attempt to do so except under the terms of this License (or another written agreement between Licensor and You) is expressly prohibited by U.S. copyright law, the equivalent laws of other countries, and by international treaty. Therefore, by exercising any of the rights granted to You in Section 1 herein, You indicate Your acceptance of this License and all of its terms and conditions. 10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. 11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of the U.S. Copyright Act, 17 U.S.C. § 101 et seq., the equivalent laws of other countries, and international treaty. This section shall survive the termination of this License. 12) Attorneys Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. 13) Miscellaneous. This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. 14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner. """ 'inherit@2.2.2': license: 'MIT' repository: 'https://github.com/dfilatov/inherit' source: 'LICENSE.md' sourceText: """ Copyright (c) 2012 Dmitry Filatov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """
69184
module.exports = 'aws-sign@0.3.0': repository: 'https://github.com/mikeal/aws-sign' license: 'MIT' source: 'index.js' sourceText: """ /*! * knox - auth * Copyright(c) 2010 LearnBoost <<EMAIL>> * MIT Licensed */ <content omitted> """ 'bufferjs@2.0.0': repository: 'https://github.com/coolaj86/node-bufferjs' license: 'MIT' source: 'LICENSE.MIT' sourceText: """ Copyright (c) 2010 <NAME> (and Contributors) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ 'buffers@0.1.1': repository: "http://github.com/substack/node-buffers" license: 'MIT' source: 'README.markdown' sourceText: """ <content omitted> license ======= MIT/X11 """ 'cheerio@0.15.0': repository: "https://github.com/cheeriojs/cheerio" license: 'MIT' source: 'https://github.com/cheeriojs/cheerio/blob/master/package.json' 'specificity@0.1.3': repository: 'https://github.com/keeganstreet/specificity' license: 'MIT' source: 'package.json in repository' 'promzard@0.2.0': license: 'ISC' source: 'LICENSE in the repository' sourceText: """ The ISC License Copyright (c) <NAME> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ 'jschardet@1.1.1': license: 'LGPL' source: 'README.md in the repository' sourceText: """ JsChardet ========= Port of python's chardet (http://chardet.feedparser.org/). License ------- LGPL """ 'core-js@0.4.10': license: 'MIT' source: 'http://rock.mit-license.org linked in source files and bower.json says MIT' 'log-driver@1.2.4': license: 'ISC' source: 'LICENSE file in the repository' sourceText: """ Copyright (c) 2014, <NAME>, <EMAIL> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ 'shelljs@0.3.0': license: 'BSD' source: 'LICENSE file in repository - 3-clause BSD (aka BSD-new)' sourceText: """ Copyright (c) 2012, <NAME> <<EMAIL>> All rights reserved. You may use this project under the terms of the New BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of <NAME> nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARTUR ADIB BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ 'tweetnacl@0.14.3': repository: 'https://github.com/dchest/tweetnacl-js' license: 'Public Domain' source: 'https://github.com/dchest/tweetnacl-js/blob/1042c9c65dc8f1dcb9e981d962d7dbbcf58f1fdc/COPYING.txt says public domain.' 'json-schema@0.2.2': repository: 'https://github.com/kriszyp/json-schema' license: 'BSD' source: 'README links to https://github.com/dojo/dojo/blob/8b6a5e4c42f9cf777dd39eaae8b188e0ebb59a4c/LICENSE' sourceText: """ Dojo is available under *either* the terms of the modified BSD license *or* the Academic Free License version 2.1. As a recipient of Dojo, you may choose which license to receive this code under (except as noted in per-module LICENSE files). Some modules may not be the copyright of the Dojo Foundation. These modules contain explicit declarations of copyright in both the LICENSE files in the directories in which they reside and in the code itself. No external contributions are allowed under licenses which are fundamentally incompatible with the AFL or BSD licenses that Dojo is distributed under. The text of the AFL and BSD licenses is reproduced below. ------------------------------------------------------------------------------- The "New" BSD License: ********************** Copyright (c) 2005-2015, The Dojo Foundation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Dojo Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- The Academic Free License, v. 2.1: ********************************** This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work: Licensed under the Academic Free License version 2.1 1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following: a) to reproduce the Original Work in copies; b) to prepare derivative works ("Derivative Works") based upon the Original Work; c) to distribute copies of the Original Work and Derivative Works to the public; d) to perform the Original Work publicly; and e) to display the Original Work publicly. 2) Grant of Patent License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and Derivative Works. 3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work. 4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. Nothing in this License shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or any other intellectual property of Licensor except as expressly stated herein. No patent license is granted to make, use, sell or offer to sell embodiments of any patent claims other than the licensed claims defined in Section 2. No right is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under different terms from this License any Original Work that Licensor otherwise would have a right to license. 5) This section intentionally omitted. 6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. 7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately proceeding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to Original Work is granted hereunder except under this disclaimer. 8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to any person for any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to liability for death or personal injury resulting from Licensor's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. 9) Acceptance and Termination. If You distribute copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. Nothing else but this License (or another written agreement between Licensor and You) grants You permission to create Derivative Works based upon the Original Work or to exercise any of the rights granted in Section 1 herein, and any attempt to do so except under the terms of this License (or another written agreement between Licensor and You) is expressly prohibited by U.S. copyright law, the equivalent laws of other countries, and by international treaty. Therefore, by exercising any of the rights granted to You in Section 1 herein, You indicate Your acceptance of this License and all of its terms and conditions. 10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. 11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of the U.S. Copyright Act, 17 U.S.C. § 101 et seq., the equivalent laws of other countries, and international treaty. This section shall survive the termination of this License. 12) Attorneys Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. 13) Miscellaneous. This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. 14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. This license is Copyright (C) 2003-2004 <NAME>. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner. """ 'inherit@2.2.2': license: 'MIT' repository: 'https://github.com/dfilatov/inherit' source: 'LICENSE.md' sourceText: """ Copyright (c) 2012 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """
true
module.exports = 'aws-sign@0.3.0': repository: 'https://github.com/mikeal/aws-sign' license: 'MIT' source: 'index.js' sourceText: """ /*! * knox - auth * Copyright(c) 2010 LearnBoost <PI:EMAIL:<EMAIL>END_PI> * MIT Licensed */ <content omitted> """ 'bufferjs@2.0.0': repository: 'https://github.com/coolaj86/node-bufferjs' license: 'MIT' source: 'LICENSE.MIT' sourceText: """ Copyright (c) 2010 PI:NAME:<NAME>END_PI (and Contributors) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ 'buffers@0.1.1': repository: "http://github.com/substack/node-buffers" license: 'MIT' source: 'README.markdown' sourceText: """ <content omitted> license ======= MIT/X11 """ 'cheerio@0.15.0': repository: "https://github.com/cheeriojs/cheerio" license: 'MIT' source: 'https://github.com/cheeriojs/cheerio/blob/master/package.json' 'specificity@0.1.3': repository: 'https://github.com/keeganstreet/specificity' license: 'MIT' source: 'package.json in repository' 'promzard@0.2.0': license: 'ISC' source: 'LICENSE in the repository' sourceText: """ The ISC License Copyright (c) PI:NAME:<NAME>END_PI Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ 'jschardet@1.1.1': license: 'LGPL' source: 'README.md in the repository' sourceText: """ JsChardet ========= Port of python's chardet (http://chardet.feedparser.org/). License ------- LGPL """ 'core-js@0.4.10': license: 'MIT' source: 'http://rock.mit-license.org linked in source files and bower.json says MIT' 'log-driver@1.2.4': license: 'ISC' source: 'LICENSE file in the repository' sourceText: """ Copyright (c) 2014, PI:NAME:<NAME>END_PI, PI:EMAIL:<EMAIL>END_PI Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ 'shelljs@0.3.0': license: 'BSD' source: 'LICENSE file in repository - 3-clause BSD (aka BSD-new)' sourceText: """ Copyright (c) 2012, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. You may use this project under the terms of the New BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of PI:NAME:<NAME>END_PI nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARTUR ADIB BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ 'tweetnacl@0.14.3': repository: 'https://github.com/dchest/tweetnacl-js' license: 'Public Domain' source: 'https://github.com/dchest/tweetnacl-js/blob/1042c9c65dc8f1dcb9e981d962d7dbbcf58f1fdc/COPYING.txt says public domain.' 'json-schema@0.2.2': repository: 'https://github.com/kriszyp/json-schema' license: 'BSD' source: 'README links to https://github.com/dojo/dojo/blob/8b6a5e4c42f9cf777dd39eaae8b188e0ebb59a4c/LICENSE' sourceText: """ Dojo is available under *either* the terms of the modified BSD license *or* the Academic Free License version 2.1. As a recipient of Dojo, you may choose which license to receive this code under (except as noted in per-module LICENSE files). Some modules may not be the copyright of the Dojo Foundation. These modules contain explicit declarations of copyright in both the LICENSE files in the directories in which they reside and in the code itself. No external contributions are allowed under licenses which are fundamentally incompatible with the AFL or BSD licenses that Dojo is distributed under. The text of the AFL and BSD licenses is reproduced below. ------------------------------------------------------------------------------- The "New" BSD License: ********************** Copyright (c) 2005-2015, The Dojo Foundation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Dojo Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- The Academic Free License, v. 2.1: ********************************** This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work: Licensed under the Academic Free License version 2.1 1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following: a) to reproduce the Original Work in copies; b) to prepare derivative works ("Derivative Works") based upon the Original Work; c) to distribute copies of the Original Work and Derivative Works to the public; d) to perform the Original Work publicly; and e) to display the Original Work publicly. 2) Grant of Patent License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and Derivative Works. 3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work. 4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. Nothing in this License shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or any other intellectual property of Licensor except as expressly stated herein. No patent license is granted to make, use, sell or offer to sell embodiments of any patent claims other than the licensed claims defined in Section 2. No right is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under different terms from this License any Original Work that Licensor otherwise would have a right to license. 5) This section intentionally omitted. 6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. 7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately proceeding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to Original Work is granted hereunder except under this disclaimer. 8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to any person for any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to liability for death or personal injury resulting from Licensor's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. 9) Acceptance and Termination. If You distribute copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. Nothing else but this License (or another written agreement between Licensor and You) grants You permission to create Derivative Works based upon the Original Work or to exercise any of the rights granted in Section 1 herein, and any attempt to do so except under the terms of this License (or another written agreement between Licensor and You) is expressly prohibited by U.S. copyright law, the equivalent laws of other countries, and by international treaty. Therefore, by exercising any of the rights granted to You in Section 1 herein, You indicate Your acceptance of this License and all of its terms and conditions. 10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. 11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of the U.S. Copyright Act, 17 U.S.C. § 101 et seq., the equivalent laws of other countries, and international treaty. This section shall survive the termination of this License. 12) Attorneys Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. 13) Miscellaneous. This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. 14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. This license is Copyright (C) 2003-2004 PI:NAME:<NAME>END_PI. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner. """ 'inherit@2.2.2': license: 'MIT' repository: 'https://github.com/dfilatov/inherit' source: 'LICENSE.md' sourceText: """ Copyright (c) 2012 PI:NAME:<NAME>END_PI Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """
[ { "context": "\n###\n Author: Nicholas McCready & jfriend00\n AsyncProcessor handles things asy", "end": 34, "score": 0.9998745918273926, "start": 17, "tag": "NAME", "value": "Nicholas McCready" }, { "context": "\n###\n Author: Nicholas McCready & jfriend00\n AsyncProcessor handles things asynchronous-li", "end": 46, "score": 0.999443769454956, "start": 37, "tag": "USERNAME", "value": "jfriend00" } ]
www/lib/js/angular-google-maps/src/coffee/directives/api/utils/async-processor.coffee
neilff/liqbo-cordova
1
### Author: Nicholas McCready & jfriend00 AsyncProcessor handles things asynchronous-like :), to allow the UI to be free'd to do other things Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui ### @ngGmapModule "directives.api.utils", -> @AsyncProcessor = handleLargeArray:(array, callback, pausedCallBack, doneCallBack ,chunk = 100, index = 0) -> if array == undefined or array.length <= 0 doneCallBack() return # set this to whatever number of items you can process at once doChunk = () -> cnt = chunk i = index while cnt-- and i < array.length # process array[index] here callback(array[i]) ++i if i < array.length index = i pausedCallBack() if pausedCallBack? setTimeout(doChunk, 1) else doneCallBack() doChunk()
11601
### Author: <NAME> & jfriend00 AsyncProcessor handles things asynchronous-like :), to allow the UI to be free'd to do other things Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui ### @ngGmapModule "directives.api.utils", -> @AsyncProcessor = handleLargeArray:(array, callback, pausedCallBack, doneCallBack ,chunk = 100, index = 0) -> if array == undefined or array.length <= 0 doneCallBack() return # set this to whatever number of items you can process at once doChunk = () -> cnt = chunk i = index while cnt-- and i < array.length # process array[index] here callback(array[i]) ++i if i < array.length index = i pausedCallBack() if pausedCallBack? setTimeout(doChunk, 1) else doneCallBack() doChunk()
true
### Author: PI:NAME:<NAME>END_PI & jfriend00 AsyncProcessor handles things asynchronous-like :), to allow the UI to be free'd to do other things Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui ### @ngGmapModule "directives.api.utils", -> @AsyncProcessor = handleLargeArray:(array, callback, pausedCallBack, doneCallBack ,chunk = 100, index = 0) -> if array == undefined or array.length <= 0 doneCallBack() return # set this to whatever number of items you can process at once doChunk = () -> cnt = chunk i = index while cnt-- and i < array.length # process array[index] here callback(array[i]) ++i if i < array.length index = i pausedCallBack() if pausedCallBack? setTimeout(doChunk, 1) else doneCallBack() doChunk()
[ { "context": "###\n# controllers/user.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# This module de", "end": 52, "score": 0.9996830821037292, "start": 41, "tag": "NAME", "value": "Dan Nichols" } ]
lib/controllers/users.coffee
dlnichols/h_media
0
### # controllers/user.coffee # # © 2014 Dan Nichols # See LICENSE for more details # # This module defines the basic CRUD actions for the user resource, for use in # our express router. ### 'use strict' # External libs mongoose = require 'mongoose' debug = require('debug') 'hMedia:controllers:user' # Retrieve our model from mongoose User = mongoose.model 'User' ### # User controller # # Define the basic CRUD actions for the user resource ### debug 'Configuring users controller...' module.exports = exports = ### # create ### create: (req, res, next) -> new User() .safeAssign req.body .save (err, user) -> return next(err) if err req.logIn user, (err) -> return next(err) if err res.status 200 .json req.user.userInfo ### # index ### index: (req, res, next) -> res.status 501 .json 501, error: 'User::Index not implemented.' ### # show ### show: (req, res, next) -> if req.params.id res.status 501 .json error: 'User::Show(id) not implemented.' else res.status 200 .json req.user.userInfo ### # update # # Allows for changing user password. ### update: (req, res, next) -> if req.params.id res.status 501 .json error: 'User::Update(id) not implemented.' else req.user.safeAssign req.body req.user.save (err, user) -> return next(err) if err res.status 200 .json req.user.userInfo ### # delete # # Allows a user to delete their account. ### delete: (req, res, next) -> # Check that the user password matches unless req.body.password and req.user.authenticate req.body.password res.status 401 .json error: 'Incorrect password' return # Delete the user from the database req.user.remove (err, user) -> return next(err) if err # Deleted, log them out req.logOut() res.status 200 .json {}
68679
### # controllers/user.coffee # # © 2014 <NAME> # See LICENSE for more details # # This module defines the basic CRUD actions for the user resource, for use in # our express router. ### 'use strict' # External libs mongoose = require 'mongoose' debug = require('debug') 'hMedia:controllers:user' # Retrieve our model from mongoose User = mongoose.model 'User' ### # User controller # # Define the basic CRUD actions for the user resource ### debug 'Configuring users controller...' module.exports = exports = ### # create ### create: (req, res, next) -> new User() .safeAssign req.body .save (err, user) -> return next(err) if err req.logIn user, (err) -> return next(err) if err res.status 200 .json req.user.userInfo ### # index ### index: (req, res, next) -> res.status 501 .json 501, error: 'User::Index not implemented.' ### # show ### show: (req, res, next) -> if req.params.id res.status 501 .json error: 'User::Show(id) not implemented.' else res.status 200 .json req.user.userInfo ### # update # # Allows for changing user password. ### update: (req, res, next) -> if req.params.id res.status 501 .json error: 'User::Update(id) not implemented.' else req.user.safeAssign req.body req.user.save (err, user) -> return next(err) if err res.status 200 .json req.user.userInfo ### # delete # # Allows a user to delete their account. ### delete: (req, res, next) -> # Check that the user password matches unless req.body.password and req.user.authenticate req.body.password res.status 401 .json error: 'Incorrect password' return # Delete the user from the database req.user.remove (err, user) -> return next(err) if err # Deleted, log them out req.logOut() res.status 200 .json {}
true
### # controllers/user.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details # # This module defines the basic CRUD actions for the user resource, for use in # our express router. ### 'use strict' # External libs mongoose = require 'mongoose' debug = require('debug') 'hMedia:controllers:user' # Retrieve our model from mongoose User = mongoose.model 'User' ### # User controller # # Define the basic CRUD actions for the user resource ### debug 'Configuring users controller...' module.exports = exports = ### # create ### create: (req, res, next) -> new User() .safeAssign req.body .save (err, user) -> return next(err) if err req.logIn user, (err) -> return next(err) if err res.status 200 .json req.user.userInfo ### # index ### index: (req, res, next) -> res.status 501 .json 501, error: 'User::Index not implemented.' ### # show ### show: (req, res, next) -> if req.params.id res.status 501 .json error: 'User::Show(id) not implemented.' else res.status 200 .json req.user.userInfo ### # update # # Allows for changing user password. ### update: (req, res, next) -> if req.params.id res.status 501 .json error: 'User::Update(id) not implemented.' else req.user.safeAssign req.body req.user.save (err, user) -> return next(err) if err res.status 200 .json req.user.userInfo ### # delete # # Allows a user to delete their account. ### delete: (req, res, next) -> # Check that the user password matches unless req.body.password and req.user.authenticate req.body.password res.status 401 .json error: 'Incorrect password' return # Delete the user from the database req.user.remove (err, user) -> return next(err) if err # Deleted, log them out req.logOut() res.status 200 .json {}
[ { "context": "uest = require 'supertest'\nagent = request.agent '127.0.0.1:3003'\n\ndescribe 'route /admin/dynamic-indexes::',", "end": 116, "score": 0.9997382760047913, "start": 107, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "n/login'\n .type 'form'\n .send {'alias':'fengfeng2','password':'1234567'}\n .expect 303\n descri", "end": 300, "score": 0.9952865839004517, "start": 291, "tag": "USERNAME", "value": "fengfeng2" }, { "context": "orm'\n .send {'alias':'fengfeng2','password':'1234567'}\n .expect 303\n describe 'route GET /admin/", "end": 321, "score": 0.9992218017578125, "start": 314, "tag": "PASSWORD", "value": "1234567" }, { "context": " describe 'route GET /admin/dynamic-indexes?range=100::',->\n it 'after authentication,agent access thi", "end": 396, "score": 0.9570176601409912, "start": 393, "tag": "IP_ADDRESS", "value": "100" } ]
coffees/test-dynamic-create-tickets-index.coffee
android1and1/tickets
0
assert = require 'assert' cheerio = require 'cheerio' request = require 'supertest' agent = request.agent '127.0.0.1:3003' describe 'route /admin/dynamic-indexes::',-> it 'access successful if authenticate good::',-> agent.post '/admin/login' .type 'form' .send {'alias':'fengfeng2','password':'1234567'} .expect 303 describe 'route GET /admin/dynamic-indexes?range=100::',-> it 'after authentication,agent access this route should be ok::',-> agent.get '/admin/dynamic-indexes' .expect 'Content-Type','text/html; charset=utf-8' .expect 200 .then (res)-> $ = cheerio.load res.text # has head1 text is 'Range List' assert.equal $('h1').text(),'Range List' # because invalid range,server send no list,view display none assert.equal $('.list-group').length,0 describe 'if query is invalidString responses also has waringing:',-> it 'get via query range=invalid should get warning::',-> agent.get '/admin/dynamic-indexes?range=invalid',-> .expect 200 .then (res)-> $ = cheerio.load res.text # has .warning element in this DOM. assert.equal 1,$('.warning').length describe 'route POST /admin/dynamic-indexes::',-> it 'post the form will get response(json)::',-> agent.post '/admin/dynamic-indexes' .type 'form' .send {start:300,end:550} .expect 200 .then (res)-> # this time ,response titles will more than 200 $ = cheerio.load res.text assert.ok $('.list-group-item').length>200
166341
assert = require 'assert' cheerio = require 'cheerio' request = require 'supertest' agent = request.agent '127.0.0.1:3003' describe 'route /admin/dynamic-indexes::',-> it 'access successful if authenticate good::',-> agent.post '/admin/login' .type 'form' .send {'alias':'fengfeng2','password':'<PASSWORD>'} .expect 303 describe 'route GET /admin/dynamic-indexes?range=100::',-> it 'after authentication,agent access this route should be ok::',-> agent.get '/admin/dynamic-indexes' .expect 'Content-Type','text/html; charset=utf-8' .expect 200 .then (res)-> $ = cheerio.load res.text # has head1 text is 'Range List' assert.equal $('h1').text(),'Range List' # because invalid range,server send no list,view display none assert.equal $('.list-group').length,0 describe 'if query is invalidString responses also has waringing:',-> it 'get via query range=invalid should get warning::',-> agent.get '/admin/dynamic-indexes?range=invalid',-> .expect 200 .then (res)-> $ = cheerio.load res.text # has .warning element in this DOM. assert.equal 1,$('.warning').length describe 'route POST /admin/dynamic-indexes::',-> it 'post the form will get response(json)::',-> agent.post '/admin/dynamic-indexes' .type 'form' .send {start:300,end:550} .expect 200 .then (res)-> # this time ,response titles will more than 200 $ = cheerio.load res.text assert.ok $('.list-group-item').length>200
true
assert = require 'assert' cheerio = require 'cheerio' request = require 'supertest' agent = request.agent '127.0.0.1:3003' describe 'route /admin/dynamic-indexes::',-> it 'access successful if authenticate good::',-> agent.post '/admin/login' .type 'form' .send {'alias':'fengfeng2','password':'PI:PASSWORD:<PASSWORD>END_PI'} .expect 303 describe 'route GET /admin/dynamic-indexes?range=100::',-> it 'after authentication,agent access this route should be ok::',-> agent.get '/admin/dynamic-indexes' .expect 'Content-Type','text/html; charset=utf-8' .expect 200 .then (res)-> $ = cheerio.load res.text # has head1 text is 'Range List' assert.equal $('h1').text(),'Range List' # because invalid range,server send no list,view display none assert.equal $('.list-group').length,0 describe 'if query is invalidString responses also has waringing:',-> it 'get via query range=invalid should get warning::',-> agent.get '/admin/dynamic-indexes?range=invalid',-> .expect 200 .then (res)-> $ = cheerio.load res.text # has .warning element in this DOM. assert.equal 1,$('.warning').length describe 'route POST /admin/dynamic-indexes::',-> it 'post the form will get response(json)::',-> agent.post '/admin/dynamic-indexes' .type 'form' .send {start:300,end:550} .expect 200 .then (res)-> # this time ,response titles will more than 200 $ = cheerio.load res.text assert.ok $('.list-group-item').length>200
[ { "context": "lication/json'\n .set 'x-forwarded-email', 'admin@mob.myvnc.com'\n .send prefix: \"/#{app}\", target: \"http:/", "end": 368, "score": 0.9999256134033203, "start": 349, "tag": "EMAIL", "value": "admin@mob.myvnc.com" }, { "context": "tion/json'\n .set 'x-forwarded-email', 'admin@mob.myvnc.com'\n .send \n prefix: \"#{app", "end": 930, "score": 0.9999276399612427, "start": 911, "tag": "EMAIL", "value": "admin@mob.myvnc.com" }, { "context": "tion/json'\n .set 'x-forwarded-email', 'admin@mob.myvnc.com'\n .send prefix: \"/#{app}\"\n ", "end": 1484, "score": 0.9999266862869263, "start": 1465, "tag": "EMAIL", "value": "admin@mob.myvnc.com" } ]
test/unit/controller/UpstreamController.coffee
dorissschoi/sails_proxy_bk
0
_ = require 'lodash' path = require 'path' req = require 'supertest-as-promised' describe 'UpstreamController', -> @timeout 500000 _.each ['app1', 'app2'], (app) -> it "create upstream #{app}", -> req sails.hooks.http.app .post "/upstream" .set 'Content-Type', 'application/json' .set 'x-forwarded-email', 'admin@mob.myvnc.com' .send prefix: "/#{app}", target: "http://#{app}.service.consul:1337" .expect 201 it "get upstream", -> req sails.hooks.http.app .get "/upstream" .expect 200 .then (res) -> sails.log.info res.body it "put upstreams", -> sails.models.upstream .find() .then (apps) -> Promise.all _.map apps, (app) -> req sails.hooks.http.app .put "/upstream/#{app.id}" .set 'Content-Type', 'application/json' .set 'x-forwarded-email', 'admin@mob.myvnc.com' .send prefix: "#{app.prefix}_v2" .expect 200 it "get upstream", -> req sails.hooks.http.app .get "/upstream" .expect 200 .then (res) -> sails.log.info res.body it "delete upstreams", -> sails.models.upstream .find() .then (apps) -> Promise.all _.map apps, (app) -> req sails.hooks.http.app .delete "/upstream/#{app.id}" .set 'Content-Type', 'application/json' .set 'x-forwarded-email', 'admin@mob.myvnc.com' .send prefix: "/#{app}" .expect 200 it "get upstream", -> req sails.hooks.http.app .get "/upstream" .expect 200 .then (res) -> sails.log.info res.body
39451
_ = require 'lodash' path = require 'path' req = require 'supertest-as-promised' describe 'UpstreamController', -> @timeout 500000 _.each ['app1', 'app2'], (app) -> it "create upstream #{app}", -> req sails.hooks.http.app .post "/upstream" .set 'Content-Type', 'application/json' .set 'x-forwarded-email', '<EMAIL>' .send prefix: "/#{app}", target: "http://#{app}.service.consul:1337" .expect 201 it "get upstream", -> req sails.hooks.http.app .get "/upstream" .expect 200 .then (res) -> sails.log.info res.body it "put upstreams", -> sails.models.upstream .find() .then (apps) -> Promise.all _.map apps, (app) -> req sails.hooks.http.app .put "/upstream/#{app.id}" .set 'Content-Type', 'application/json' .set 'x-forwarded-email', '<EMAIL>' .send prefix: "#{app.prefix}_v2" .expect 200 it "get upstream", -> req sails.hooks.http.app .get "/upstream" .expect 200 .then (res) -> sails.log.info res.body it "delete upstreams", -> sails.models.upstream .find() .then (apps) -> Promise.all _.map apps, (app) -> req sails.hooks.http.app .delete "/upstream/#{app.id}" .set 'Content-Type', 'application/json' .set 'x-forwarded-email', '<EMAIL>' .send prefix: "/#{app}" .expect 200 it "get upstream", -> req sails.hooks.http.app .get "/upstream" .expect 200 .then (res) -> sails.log.info res.body
true
_ = require 'lodash' path = require 'path' req = require 'supertest-as-promised' describe 'UpstreamController', -> @timeout 500000 _.each ['app1', 'app2'], (app) -> it "create upstream #{app}", -> req sails.hooks.http.app .post "/upstream" .set 'Content-Type', 'application/json' .set 'x-forwarded-email', 'PI:EMAIL:<EMAIL>END_PI' .send prefix: "/#{app}", target: "http://#{app}.service.consul:1337" .expect 201 it "get upstream", -> req sails.hooks.http.app .get "/upstream" .expect 200 .then (res) -> sails.log.info res.body it "put upstreams", -> sails.models.upstream .find() .then (apps) -> Promise.all _.map apps, (app) -> req sails.hooks.http.app .put "/upstream/#{app.id}" .set 'Content-Type', 'application/json' .set 'x-forwarded-email', 'PI:EMAIL:<EMAIL>END_PI' .send prefix: "#{app.prefix}_v2" .expect 200 it "get upstream", -> req sails.hooks.http.app .get "/upstream" .expect 200 .then (res) -> sails.log.info res.body it "delete upstreams", -> sails.models.upstream .find() .then (apps) -> Promise.all _.map apps, (app) -> req sails.hooks.http.app .delete "/upstream/#{app.id}" .set 'Content-Type', 'application/json' .set 'x-forwarded-email', 'PI:EMAIL:<EMAIL>END_PI' .send prefix: "/#{app}" .expect 200 it "get upstream", -> req sails.hooks.http.app .get "/upstream" .expect 200 .then (res) -> sails.log.info res.body
[ { "context": " =\n\ttitle: \"Extension: Wine Shope Cart\"\n\tauthor: \"Tony Jing (Original: Anadea Inc)\"\n\ttwitter: \"TonyJing\"\n\tdes", "end": 84, "score": 0.9998446106910706, "start": 75, "tag": "NAME", "value": "Tony Jing" }, { "context": "or: \"Tony Jing (Original: Anadea Inc)\"\n\ttwitter: \"TonyJing\"\n\tdescription: \"An another approach for the UX of", "end": 128, "score": 0.9985182285308838, "start": 120, "tag": "USERNAME", "value": "TonyJing" } ]
53cart.framer/framer/backups/backup-2016-08-08 22.34.41.coffee
gremjua-forks/100daysofframer
26
#Project Info Framer.Info = title: "Extension: Wine Shope Cart" author: "Tony Jing (Original: Anadea Inc)" twitter: "TonyJing" description: "An another approach for the UX of Anadea Inc's app. Visual and UI design are from Anadea Inc." #Variables bgColor = "#FBF2E7" purple = "#800363" addedCount = 1 numBottles = 5 allBottles = [] firstClick = true #Layers iphoneBase = new Layer width: Screen.width, height: Screen.height image: "images/iPhone 6 Copy 15@2x.png" bottle = new Layer width: 74, height: 220, x: 64, y: 716 image: "images/bottle.png" for i in [1 .. numBottles] Framer["bottleCopy#{i}"] = bottle.copy() Framer["bottleCopy#{i}"].props = name: "bottleCopy#{i}", opacity: 0 allBottles.push(Framer["bottleCopy#{i}"]) text = new Layer width: 196, y: 733, x: 198 image: "images/bottle_description.png" count = new Layer size: 60, x: 100, y: 738, borderRadius: "50%" backgroundColor: "#000", opacity: 0, html: addedCount style: textAlign: "center", fontSize: "1.6rem", lineHeight: "3.6rem" # bg = new Layer # width: 250, height: 1200, maxX: Screen.width, maxY: Screen.height # backgroundColor: "", style: background: "linear-gradient(to right, rgba(251, 242, 231, 0) 0%, rgba(251, 242, 231, 1) 60%)" # for i in [0...5] Framer["add#{i}"] = new Layer name: "add#{i}", width: 100, height: 60 maxX: Screen.width - 40, y: 200 + i * 272 backgroundColor: "", html: "+ ADD", color: purple borderColor: "", borderWidth: 2, borderRadius: 7 style: fontFamily: "Helvetica Neue", fontSize: "1.5rem" textAlign: "center", lineHeight: "3.5rem" remove = new Layer width: 100, height: 60, opacity: 0 maxX: Screen.width - 40, y: 858, backgroundColor: "" html: "REMOVE", color: purple borderColor: "", borderWidth: 2, borderRadius: 7 style: fontFamily: "Helvetica Neue", fontSize: "1.5rem" textAlign: "center", lineHeight: "3.5rem" smoke = new Layer size: 400, borderRadius: "50%", scale: 0, backgroundColor: "" midX: bottle.midX, midY: bottle.midY + 20 style: background: """radial-gradient(ellipse at center, rgba(225, 205, 205, 1) 30%, rgba(255, 255, 255, 0) 100%)""" smoke.placeBehind(bottle) # States & Animations text.draggable = true text.draggable.vertical = false text.draggable.overdrag = false text.draggable.speedX = 1.5 text.draggable.constraints = x: text.x, width: Screen.width - text.x text.states.add text.states.animationOptions = curve: "spring(150, 18, 0)" count.states.add show: opacity: 1 count.states.animationOptions = time: 0.5 Framer["add2"].states.add selected: borderColor: purple Framer["add2"].states.animationOptions = time: 0.2 remove.states.add selected: opacity: 1 remove.states.animationOptions = time: 0.2 bottleAddPop = new Animation layer: Framer["bottleCopy1"] properties: x: bottle.x + 75, opacity: 1 time: 0.3 bottleAddPop.onAnimationEnd -> Framer["bottleCopy1"].animate properties: x: bottle.x, opacity: 0 time: 0.2 textPop = new Animation layer: text properties: x: text.x + 90 time: 0.3 textPop.onAnimationEnd -> text.animate properties: x: text.x - 90 curve: "spring(130, 12, 0)" puff = new Animation layer: smoke properties: scale: 2, opacity: 0 curve: "ease-out" time: 0.5 countFadeout = new Animation layer: count properties: opacity: 0 time: 0.3 countFadeout.onAnimationEnd -> count.states.switchInstant("default") # Events text.onDragStart -> count.states.switch("show") Framer["add2"].states.switch("selected") Framer["add2"].animate {properties: (opacity: 0), time: 0.5} remove.animate {properties: (opacity: 0), time: 0.5} text.on Events.Drag, (e) -> if parseInt(count.html, 10) == 0 Framer["add2"].states.switch("default") remove.states.switch("default") dragDist = this.x for i in [1..numBottles] if e.velocity.x > 0 and dragDist >= (i * 65 + 225) count.html = addedCount + 1 for b in allBottles b.animate properties: x: bottle.x + i * 60, opacity: 1 time: 0.1 for n in [1..numBottles] if i > n count.html = addedCount + n + 1 Framer["bottleCopy#{n}"].animate properties: x: bottle.x + n * 60, opacity: 1 time: 0.1 if e.velocity.x < 0 levels = Math.floor(Utils.modulate(dragDist, [554, 198], [6, 0])) count.html = addedCount + levels - 1 if i > 1 if Framer["bottleCopy#{i}"].x > (dragDist - 180) Framer["bottleCopy#{i}"].animate properties: x: Framer["bottleCopy#{i-1}"].x opacity: 0 time: 0.1 if Framer["bottleCopy1"].x > (dragDist - 180) Framer["bottleCopy1"].animate properties: x: bottle.x opacity: 0 time: 0.1 text.onDragEnd -> Framer["add2"].animate {properties: (opacity: 1), time: 0.5} remove.animate {properties: (opacity: 1), time: 0.5} this.states.switch("default") for b in allBottles b.animate properties: x: bottle.x time: 0.1 if parseInt(count.html, 10) == 0 Utils.delay 0.3, -> countFadeout.start() if parseInt(count.html, 10) > 0 addedCount = parseInt(count.html, 10) else addedCount = 1 Framer["add2"].onClick -> this.states.switch("selected") remove.states.switch("selected") count.states.switch("show") bottleAddPop.start() textPop.start() if parseInt(count.html, 10) != 1 count.html = parseInt(count.html, 10) + 1 addedCount = parseInt(count.html, 10) if parseInt(count.html, 10) == 1 and firstClick == false count.html = parseInt(count.html, 10) + 1 if parseInt(count.html, 10) == 1 and firstClick == true count.html = 1 firstClick = false remove.onClick -> puff.start() if parseInt(count.html, 10) <= 1 count.html = 0 Utils.delay 0.5, -> countFadeout.start() Framer["add2"].states.switch("default") remove.states.switch("default") else count.html = parseInt(count.html, 10) - 1
110595
#Project Info Framer.Info = title: "Extension: Wine Shope Cart" author: "<NAME> (Original: Anadea Inc)" twitter: "TonyJing" description: "An another approach for the UX of Anadea Inc's app. Visual and UI design are from Anadea Inc." #Variables bgColor = "#FBF2E7" purple = "#800363" addedCount = 1 numBottles = 5 allBottles = [] firstClick = true #Layers iphoneBase = new Layer width: Screen.width, height: Screen.height image: "images/iPhone 6 Copy 15@2x.png" bottle = new Layer width: 74, height: 220, x: 64, y: 716 image: "images/bottle.png" for i in [1 .. numBottles] Framer["bottleCopy#{i}"] = bottle.copy() Framer["bottleCopy#{i}"].props = name: "bottleCopy#{i}", opacity: 0 allBottles.push(Framer["bottleCopy#{i}"]) text = new Layer width: 196, y: 733, x: 198 image: "images/bottle_description.png" count = new Layer size: 60, x: 100, y: 738, borderRadius: "50%" backgroundColor: "#000", opacity: 0, html: addedCount style: textAlign: "center", fontSize: "1.6rem", lineHeight: "3.6rem" # bg = new Layer # width: 250, height: 1200, maxX: Screen.width, maxY: Screen.height # backgroundColor: "", style: background: "linear-gradient(to right, rgba(251, 242, 231, 0) 0%, rgba(251, 242, 231, 1) 60%)" # for i in [0...5] Framer["add#{i}"] = new Layer name: "add#{i}", width: 100, height: 60 maxX: Screen.width - 40, y: 200 + i * 272 backgroundColor: "", html: "+ ADD", color: purple borderColor: "", borderWidth: 2, borderRadius: 7 style: fontFamily: "Helvetica Neue", fontSize: "1.5rem" textAlign: "center", lineHeight: "3.5rem" remove = new Layer width: 100, height: 60, opacity: 0 maxX: Screen.width - 40, y: 858, backgroundColor: "" html: "REMOVE", color: purple borderColor: "", borderWidth: 2, borderRadius: 7 style: fontFamily: "Helvetica Neue", fontSize: "1.5rem" textAlign: "center", lineHeight: "3.5rem" smoke = new Layer size: 400, borderRadius: "50%", scale: 0, backgroundColor: "" midX: bottle.midX, midY: bottle.midY + 20 style: background: """radial-gradient(ellipse at center, rgba(225, 205, 205, 1) 30%, rgba(255, 255, 255, 0) 100%)""" smoke.placeBehind(bottle) # States & Animations text.draggable = true text.draggable.vertical = false text.draggable.overdrag = false text.draggable.speedX = 1.5 text.draggable.constraints = x: text.x, width: Screen.width - text.x text.states.add text.states.animationOptions = curve: "spring(150, 18, 0)" count.states.add show: opacity: 1 count.states.animationOptions = time: 0.5 Framer["add2"].states.add selected: borderColor: purple Framer["add2"].states.animationOptions = time: 0.2 remove.states.add selected: opacity: 1 remove.states.animationOptions = time: 0.2 bottleAddPop = new Animation layer: Framer["bottleCopy1"] properties: x: bottle.x + 75, opacity: 1 time: 0.3 bottleAddPop.onAnimationEnd -> Framer["bottleCopy1"].animate properties: x: bottle.x, opacity: 0 time: 0.2 textPop = new Animation layer: text properties: x: text.x + 90 time: 0.3 textPop.onAnimationEnd -> text.animate properties: x: text.x - 90 curve: "spring(130, 12, 0)" puff = new Animation layer: smoke properties: scale: 2, opacity: 0 curve: "ease-out" time: 0.5 countFadeout = new Animation layer: count properties: opacity: 0 time: 0.3 countFadeout.onAnimationEnd -> count.states.switchInstant("default") # Events text.onDragStart -> count.states.switch("show") Framer["add2"].states.switch("selected") Framer["add2"].animate {properties: (opacity: 0), time: 0.5} remove.animate {properties: (opacity: 0), time: 0.5} text.on Events.Drag, (e) -> if parseInt(count.html, 10) == 0 Framer["add2"].states.switch("default") remove.states.switch("default") dragDist = this.x for i in [1..numBottles] if e.velocity.x > 0 and dragDist >= (i * 65 + 225) count.html = addedCount + 1 for b in allBottles b.animate properties: x: bottle.x + i * 60, opacity: 1 time: 0.1 for n in [1..numBottles] if i > n count.html = addedCount + n + 1 Framer["bottleCopy#{n}"].animate properties: x: bottle.x + n * 60, opacity: 1 time: 0.1 if e.velocity.x < 0 levels = Math.floor(Utils.modulate(dragDist, [554, 198], [6, 0])) count.html = addedCount + levels - 1 if i > 1 if Framer["bottleCopy#{i}"].x > (dragDist - 180) Framer["bottleCopy#{i}"].animate properties: x: Framer["bottleCopy#{i-1}"].x opacity: 0 time: 0.1 if Framer["bottleCopy1"].x > (dragDist - 180) Framer["bottleCopy1"].animate properties: x: bottle.x opacity: 0 time: 0.1 text.onDragEnd -> Framer["add2"].animate {properties: (opacity: 1), time: 0.5} remove.animate {properties: (opacity: 1), time: 0.5} this.states.switch("default") for b in allBottles b.animate properties: x: bottle.x time: 0.1 if parseInt(count.html, 10) == 0 Utils.delay 0.3, -> countFadeout.start() if parseInt(count.html, 10) > 0 addedCount = parseInt(count.html, 10) else addedCount = 1 Framer["add2"].onClick -> this.states.switch("selected") remove.states.switch("selected") count.states.switch("show") bottleAddPop.start() textPop.start() if parseInt(count.html, 10) != 1 count.html = parseInt(count.html, 10) + 1 addedCount = parseInt(count.html, 10) if parseInt(count.html, 10) == 1 and firstClick == false count.html = parseInt(count.html, 10) + 1 if parseInt(count.html, 10) == 1 and firstClick == true count.html = 1 firstClick = false remove.onClick -> puff.start() if parseInt(count.html, 10) <= 1 count.html = 0 Utils.delay 0.5, -> countFadeout.start() Framer["add2"].states.switch("default") remove.states.switch("default") else count.html = parseInt(count.html, 10) - 1
true
#Project Info Framer.Info = title: "Extension: Wine Shope Cart" author: "PI:NAME:<NAME>END_PI (Original: Anadea Inc)" twitter: "TonyJing" description: "An another approach for the UX of Anadea Inc's app. Visual and UI design are from Anadea Inc." #Variables bgColor = "#FBF2E7" purple = "#800363" addedCount = 1 numBottles = 5 allBottles = [] firstClick = true #Layers iphoneBase = new Layer width: Screen.width, height: Screen.height image: "images/iPhone 6 Copy 15@2x.png" bottle = new Layer width: 74, height: 220, x: 64, y: 716 image: "images/bottle.png" for i in [1 .. numBottles] Framer["bottleCopy#{i}"] = bottle.copy() Framer["bottleCopy#{i}"].props = name: "bottleCopy#{i}", opacity: 0 allBottles.push(Framer["bottleCopy#{i}"]) text = new Layer width: 196, y: 733, x: 198 image: "images/bottle_description.png" count = new Layer size: 60, x: 100, y: 738, borderRadius: "50%" backgroundColor: "#000", opacity: 0, html: addedCount style: textAlign: "center", fontSize: "1.6rem", lineHeight: "3.6rem" # bg = new Layer # width: 250, height: 1200, maxX: Screen.width, maxY: Screen.height # backgroundColor: "", style: background: "linear-gradient(to right, rgba(251, 242, 231, 0) 0%, rgba(251, 242, 231, 1) 60%)" # for i in [0...5] Framer["add#{i}"] = new Layer name: "add#{i}", width: 100, height: 60 maxX: Screen.width - 40, y: 200 + i * 272 backgroundColor: "", html: "+ ADD", color: purple borderColor: "", borderWidth: 2, borderRadius: 7 style: fontFamily: "Helvetica Neue", fontSize: "1.5rem" textAlign: "center", lineHeight: "3.5rem" remove = new Layer width: 100, height: 60, opacity: 0 maxX: Screen.width - 40, y: 858, backgroundColor: "" html: "REMOVE", color: purple borderColor: "", borderWidth: 2, borderRadius: 7 style: fontFamily: "Helvetica Neue", fontSize: "1.5rem" textAlign: "center", lineHeight: "3.5rem" smoke = new Layer size: 400, borderRadius: "50%", scale: 0, backgroundColor: "" midX: bottle.midX, midY: bottle.midY + 20 style: background: """radial-gradient(ellipse at center, rgba(225, 205, 205, 1) 30%, rgba(255, 255, 255, 0) 100%)""" smoke.placeBehind(bottle) # States & Animations text.draggable = true text.draggable.vertical = false text.draggable.overdrag = false text.draggable.speedX = 1.5 text.draggable.constraints = x: text.x, width: Screen.width - text.x text.states.add text.states.animationOptions = curve: "spring(150, 18, 0)" count.states.add show: opacity: 1 count.states.animationOptions = time: 0.5 Framer["add2"].states.add selected: borderColor: purple Framer["add2"].states.animationOptions = time: 0.2 remove.states.add selected: opacity: 1 remove.states.animationOptions = time: 0.2 bottleAddPop = new Animation layer: Framer["bottleCopy1"] properties: x: bottle.x + 75, opacity: 1 time: 0.3 bottleAddPop.onAnimationEnd -> Framer["bottleCopy1"].animate properties: x: bottle.x, opacity: 0 time: 0.2 textPop = new Animation layer: text properties: x: text.x + 90 time: 0.3 textPop.onAnimationEnd -> text.animate properties: x: text.x - 90 curve: "spring(130, 12, 0)" puff = new Animation layer: smoke properties: scale: 2, opacity: 0 curve: "ease-out" time: 0.5 countFadeout = new Animation layer: count properties: opacity: 0 time: 0.3 countFadeout.onAnimationEnd -> count.states.switchInstant("default") # Events text.onDragStart -> count.states.switch("show") Framer["add2"].states.switch("selected") Framer["add2"].animate {properties: (opacity: 0), time: 0.5} remove.animate {properties: (opacity: 0), time: 0.5} text.on Events.Drag, (e) -> if parseInt(count.html, 10) == 0 Framer["add2"].states.switch("default") remove.states.switch("default") dragDist = this.x for i in [1..numBottles] if e.velocity.x > 0 and dragDist >= (i * 65 + 225) count.html = addedCount + 1 for b in allBottles b.animate properties: x: bottle.x + i * 60, opacity: 1 time: 0.1 for n in [1..numBottles] if i > n count.html = addedCount + n + 1 Framer["bottleCopy#{n}"].animate properties: x: bottle.x + n * 60, opacity: 1 time: 0.1 if e.velocity.x < 0 levels = Math.floor(Utils.modulate(dragDist, [554, 198], [6, 0])) count.html = addedCount + levels - 1 if i > 1 if Framer["bottleCopy#{i}"].x > (dragDist - 180) Framer["bottleCopy#{i}"].animate properties: x: Framer["bottleCopy#{i-1}"].x opacity: 0 time: 0.1 if Framer["bottleCopy1"].x > (dragDist - 180) Framer["bottleCopy1"].animate properties: x: bottle.x opacity: 0 time: 0.1 text.onDragEnd -> Framer["add2"].animate {properties: (opacity: 1), time: 0.5} remove.animate {properties: (opacity: 1), time: 0.5} this.states.switch("default") for b in allBottles b.animate properties: x: bottle.x time: 0.1 if parseInt(count.html, 10) == 0 Utils.delay 0.3, -> countFadeout.start() if parseInt(count.html, 10) > 0 addedCount = parseInt(count.html, 10) else addedCount = 1 Framer["add2"].onClick -> this.states.switch("selected") remove.states.switch("selected") count.states.switch("show") bottleAddPop.start() textPop.start() if parseInt(count.html, 10) != 1 count.html = parseInt(count.html, 10) + 1 addedCount = parseInt(count.html, 10) if parseInt(count.html, 10) == 1 and firstClick == false count.html = parseInt(count.html, 10) + 1 if parseInt(count.html, 10) == 1 and firstClick == true count.html = 1 firstClick = false remove.onClick -> puff.start() if parseInt(count.html, 10) <= 1 count.html = 0 Utils.delay 0.5, -> countFadeout.start() Framer["add2"].states.switch("default") remove.states.switch("default") else count.html = parseInt(count.html, 10) - 1
[ { "context": "# Copyright © 2013 All rights reserved\n# Author: nhim175@gmail.com\n\nModule = require './module.coffee'\nLogger = requ", "end": 66, "score": 0.9999125003814697, "start": 49, "tag": "EMAIL", "value": "nhim175@gmail.com" } ]
src/lib/scorpion.coffee
nhim175/scorpionsmasher
0
# Copyright © 2013 All rights reserved # Author: nhim175@gmail.com Module = require './module.coffee' Logger = require '../mixins/logger.coffee' Util = require './util/util.coffee' WIDTH = 96 HEIGHT = 108 class Scorpion extends Module @include Logger logPrefix: 'Scorpion' sprite: 'scorpion' health: 1 points: x: [] y: [] pi: 0 speed: 2 bonus: 1 runFrames: Phaser.Animation.generateFrameNames('v', 1, 5, '.png', 0) dieFrames: ['v6.png'] constructor: (game) -> @game = game @me = @game.add.sprite Util.getRandomInt(0, game.width), 0, @sprite @me.animations.add 'run', @runFrames, 24, yes @me.animations.add 'die', @dieFrames, 0, no @me.animations.play 'run' @me.anchor.set(0.5) @sound = new Phaser.Sound @game, 'cockroach', 1 @dieSound = new Phaser.Sound @game, 'die', 1 for i in [0..4] @points.x[i] = game.rnd.between(0, game.width) @points.y[i] = game.height/4*i @plotPath() @sound.play() $(game).on 'GameOverEvent', => @sound.stop() window.plugins?.NativeAudio?.stop 'cockroach' plotPath: -> @path = [] ix = 0 x = @speed/@game.height i = 0 until i > 1 px = @game.math.catmullRomInterpolation @points.x, i py = @game.math.catmullRomInterpolation @points.y, i node = x: px, y: py, angle: 0 node.angle = @game.math.angleBetweenPoints(@path[ix - 1], node) if ix > 0 node.angle += 90 @path.push node ix++ i += x kill: -> if window.plugins?.NativeAudio window.plugins.NativeAudio.play 'die' window.plugins.NativeAudio.stop 'cockroach' else @sound.stop() @dieSound.play() @me.animations.play 'die' @died = true setTimeout => @me.destroy() , 2000 @bonus isKilled: -> @died is true update: -> if @died then return @me.y = @path[@pi].y @me.x = @path[@pi].x @me.rotation = @path[@pi].angle @pi++ if @pi >= @path.length @me.destroy() @died = true module.exports = Scorpion
136680
# Copyright © 2013 All rights reserved # Author: <EMAIL> Module = require './module.coffee' Logger = require '../mixins/logger.coffee' Util = require './util/util.coffee' WIDTH = 96 HEIGHT = 108 class Scorpion extends Module @include Logger logPrefix: 'Scorpion' sprite: 'scorpion' health: 1 points: x: [] y: [] pi: 0 speed: 2 bonus: 1 runFrames: Phaser.Animation.generateFrameNames('v', 1, 5, '.png', 0) dieFrames: ['v6.png'] constructor: (game) -> @game = game @me = @game.add.sprite Util.getRandomInt(0, game.width), 0, @sprite @me.animations.add 'run', @runFrames, 24, yes @me.animations.add 'die', @dieFrames, 0, no @me.animations.play 'run' @me.anchor.set(0.5) @sound = new Phaser.Sound @game, 'cockroach', 1 @dieSound = new Phaser.Sound @game, 'die', 1 for i in [0..4] @points.x[i] = game.rnd.between(0, game.width) @points.y[i] = game.height/4*i @plotPath() @sound.play() $(game).on 'GameOverEvent', => @sound.stop() window.plugins?.NativeAudio?.stop 'cockroach' plotPath: -> @path = [] ix = 0 x = @speed/@game.height i = 0 until i > 1 px = @game.math.catmullRomInterpolation @points.x, i py = @game.math.catmullRomInterpolation @points.y, i node = x: px, y: py, angle: 0 node.angle = @game.math.angleBetweenPoints(@path[ix - 1], node) if ix > 0 node.angle += 90 @path.push node ix++ i += x kill: -> if window.plugins?.NativeAudio window.plugins.NativeAudio.play 'die' window.plugins.NativeAudio.stop 'cockroach' else @sound.stop() @dieSound.play() @me.animations.play 'die' @died = true setTimeout => @me.destroy() , 2000 @bonus isKilled: -> @died is true update: -> if @died then return @me.y = @path[@pi].y @me.x = @path[@pi].x @me.rotation = @path[@pi].angle @pi++ if @pi >= @path.length @me.destroy() @died = true module.exports = Scorpion
true
# Copyright © 2013 All rights reserved # Author: PI:EMAIL:<EMAIL>END_PI Module = require './module.coffee' Logger = require '../mixins/logger.coffee' Util = require './util/util.coffee' WIDTH = 96 HEIGHT = 108 class Scorpion extends Module @include Logger logPrefix: 'Scorpion' sprite: 'scorpion' health: 1 points: x: [] y: [] pi: 0 speed: 2 bonus: 1 runFrames: Phaser.Animation.generateFrameNames('v', 1, 5, '.png', 0) dieFrames: ['v6.png'] constructor: (game) -> @game = game @me = @game.add.sprite Util.getRandomInt(0, game.width), 0, @sprite @me.animations.add 'run', @runFrames, 24, yes @me.animations.add 'die', @dieFrames, 0, no @me.animations.play 'run' @me.anchor.set(0.5) @sound = new Phaser.Sound @game, 'cockroach', 1 @dieSound = new Phaser.Sound @game, 'die', 1 for i in [0..4] @points.x[i] = game.rnd.between(0, game.width) @points.y[i] = game.height/4*i @plotPath() @sound.play() $(game).on 'GameOverEvent', => @sound.stop() window.plugins?.NativeAudio?.stop 'cockroach' plotPath: -> @path = [] ix = 0 x = @speed/@game.height i = 0 until i > 1 px = @game.math.catmullRomInterpolation @points.x, i py = @game.math.catmullRomInterpolation @points.y, i node = x: px, y: py, angle: 0 node.angle = @game.math.angleBetweenPoints(@path[ix - 1], node) if ix > 0 node.angle += 90 @path.push node ix++ i += x kill: -> if window.plugins?.NativeAudio window.plugins.NativeAudio.play 'die' window.plugins.NativeAudio.stop 'cockroach' else @sound.stop() @dieSound.play() @me.animations.play 'die' @died = true setTimeout => @me.destroy() , 2000 @bonus isKilled: -> @died is true update: -> if @died then return @me.y = @path[@pi].y @me.x = @path[@pi].x @me.rotation = @path[@pi].angle @pi++ if @pi >= @path.length @me.destroy() @died = true module.exports = Scorpion
[ { "context": "ng key', ->\n policy = 'Foo'\n settingsKey = 'ScheduleStateDefinedPolicy'\n settings = {}\n settings[settingsKey] = po", "end": 9821, "score": 0.9857760071754456, "start": 9795, "tag": "KEY", "value": "ScheduleStateDefinedPolicy" }, { "context": "etting', ->\n policy = 'Foo'\n settingsKey = 'ScheduleStateDefinedPolicy'\n settings = {}\n settings['DefinedPolicy'] ", "end": 10086, "score": 0.9832806587219238, "start": 10060, "tag": "KEY", "value": "ScheduleStateDefinedPolicy" }, { "context": "oupByRoot\n settingsKey = groupByRoot + \"DefinedPolicy\"\n settings = {}\n settings.groupByField = gr", "end": 10442, "score": 0.9004376530647278, "start": 10436, "tag": "KEY", "value": "Policy" } ]
test/spec/kanban/KanbanAppSpec.coffee
CustomAgile/app-catalog
31
Ext = window.Ext4 || window.Ext Ext.require [ 'Rally.ui.report.StandardReport', 'Rally.apps.kanban.KanbanApp', 'Rally.util.Element', 'Rally.ui.notify.Notifier', 'Rally.app.Context', 'Rally.test.helpers.CardBoard', 'Rally.data.Ranker' ] describe 'Rally.apps.kanban.KanbanApp', -> beforeEach -> @ajax.whenQuerying('artifact').respondWithCount(1, { values: [{ ScheduleState: 'In-Progress' }] createImmediateSubObjects: true }) @projectRef = Rally.environment.getContext().getProject()._ref @projectName = 'Project 1' afterEach -> Rally.test.destroyComponentsOfQuery 'kanbanapp' it 'has the correct default settings', -> @createApp().then => expect(@app.getSetting('groupByField')).toBe 'ScheduleState' expect(@app.getSetting('columns')).toBe Ext.JSON.encode( Defined: wip: '' 'In-Progress': wip: '' Completed: wip: '' Accepted: wip: '' ) expect(@app.getSetting('cardFields')).toBe 'FormattedID,Name,Owner,Discussion,Tasks,Defects' expect(@app.getSetting('showRows')).toBe false it 'should have a default card fields setting', -> @createApp().then => expect(@cardboard.columnConfig.fields).toEqual @app.getSetting('cardFields').split(',') it 'should have use the cardFields setting if available', -> @createApp(cardFields: 'HelloKitty').then => expect(@cardboard.columnConfig.fields).toEqual ['HelloKitty'] it 'should show the field picker', -> @createApp().then => expect(@app.down('#fieldpickerbtn').isVisible()).toBe true it 'does not show add new when user is not a project editor', -> Rally.environment.getContext().getPermissions().userPermissions[0].Role = 'Viewer' @createApp().then => expect(@app.down 'rallyaddnew').toBeNull() it 'shows add new for user who is a project editor', -> @createApp().then => expect(@app.down 'rallyaddnew').toBeDefined() it 'should not schedule a new item in an iteration', -> @createApp().then => editorOpenedStub = @stub(Rally.nav.Manager, 'create') addNewHelper = new Helpers.AddNewHelper this, '.kanban' addNewHelper.addWithDetails('foo').then => expect(editorOpenedStub).toHaveBeenCalledOnce() expect(editorOpenedStub.getCall(0).args[1].iteration).toBe 'u' it 'should set group by field to first column value', -> @createApp().then => editorOpenedStub = @stub(Rally.nav.Manager, 'create') addNewHelper = new Helpers.AddNewHelper this, '.kanban' addNewHelper.addWithDetails('foo').then => expect(editorOpenedStub).toHaveBeenCalledOnce() expect(editorOpenedStub.getCall(0).args[1][@app.getSetting('groupByField')]).toBe @cardboard.getColumns()[0].getValue() it 'should set custom group by field to first column value', -> @createApp( groupByField: 'KanbanState' ).then => editorOpenedStub = @stub(Rally.nav.Manager, 'create') addNewHelper = new Helpers.AddNewHelper this, '.kanban' addNewHelper.addWithDetails('foo').then => expect(editorOpenedStub).toHaveBeenCalledOnce() groupByField = "c_#{@app.getSetting('groupByField')}" expect(editorOpenedStub.getCall(0).args[1][groupByField]).toBe @cardboard.getColumns()[0].getValue() it 'should show correct fields on cards', -> @createApp(cardFields: 'Name,Defects,Project').then => expect(@cardboard.columnConfig.fields).toContain 'Name' expect(@cardboard.columnConfig.fields).toContain 'Defects' expect(@cardboard.columnConfig.fields).toContain 'Project' it 'should show columns with correct wips based on settings', -> columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({columns: Ext.JSON.encode(columnSettings), groupByField: 'ScheduleState'}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].wipLimit).toBe columnSettings.Defined.wip expect(columns[1].wipLimit).toBe columnSettings['In-Progress'].wip it 'should show columns with correct card fields when COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS enabled', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(true) columnSettings = Defined: cardFields: 'Name,Defects,Project' 'In-Progress': cardFields: 'ScheduleState' @createApp({columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].cardConfig.fields).toBeUndefined() expect(columns[0].fields).toEqual columnSettings.Defined.cardFields.split(',') expect(columns[1].fields).toEqual columnSettings['In-Progress'].cardFields.split(',') expect(columns[1].cardConfig.fields).toBeUndefined() it 'should show columns with cardFields when no column.cardFields settings', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(true) columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({cardFields: 'foobar', columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].fields).toEqual ['foobar'] expect(columns[1].fields).toEqual ['foobar'] it 'should show columns with defaultCardFields when no cardFields or column.cardFields settings', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(true) columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].fields).toEqual @app.getSetting('cardFields').split(',') expect(columns[1].fields).toEqual @app.getSetting('cardFields').split(',') it 'should not specify any card fields to show when COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS is off (should let card field picker plugin control it)', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(false) columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 _.each columns, (column) => expect(column.fields).toEqual @app.getSetting('cardFields').split(',') expect(column.cardConfig.fields).toBeUndefined() it 'should contain menu options', -> @createApp().then => options = @app.getOptions() expect(options.length).toBe 3 expect(options[0].text).toBe 'Show Cycle Time Report' expect(options[1].text).toBe 'Show Throughput Report' expect(options[2].text).toBe 'Print' it 'should correctly build report config for non schedule state field stories', -> @createApp().then => @stub(@app, 'getSetting').returns('KanbanState') @stub(@app, '_getWorkItemTypesForChart').returns('G') report_config = @app._buildReportConfig(Rally.ui.report.StandardReport.Reports.CycleLeadTime) expect(report_config.filter_field).toBe @app.groupByField.displayName expect(report_config.work_items).toBe 'G' expect(report_config.report.id).toBe Rally.ui.report.StandardReport.Reports.CycleLeadTime.id it 'should correctly build report config for schedule state field with story and defect types', -> @createApp().then => report_config = @app._buildReportConfig(Rally.ui.report.StandardReport.Reports.Throughput) expect(report_config.filter_field).toBeUndefined() expect(report_config.work_items).toBe 'N' expect(report_config.report.id).toBe Rally.ui.report.StandardReport.Reports.Throughput.id it 'should correctly build standard report component config', -> @createApp().then => report_config = {report: 5} standard_report_config = @app._buildStandardReportConfig(report_config) expect(standard_report_config.project).toBe @app.getContext().getDataContext().project expect(standard_report_config.projectScopeDown).toBe @app.getContext().getDataContext().projectScopeDown expect(standard_report_config.projectScopeUp).toBe @app.getContext().getDataContext().projectScopeUp expect(standard_report_config.reportConfig).toBe report_config it 'should exclude items with a release set in the last column', -> @createApp(hideReleasedCards: true).then => columns = @cardboard.getColumns() _.each columns, (column, index) -> expect(column.hideReleasedCards).toBe index == columns.length - 1 it 'should not exclude items with a release set in the last column', -> @createApp(hideReleasedCards: false).then => _.each @cardboard.getColumns(), (column) -> expect(column.hideReleasedCards).toBe false it 'should show plan estimate when plan estimate field is enabled', -> @createApp(cardFields: "Name,Discussion,Tasks,Defects,PlanEstimate").then => expect(@app.getEl().down('.PlanEstimate')).not.toBeNull() it 'should not show plan estimate when plan estimate field is disabled', -> @createApp(cardFields: "Name,Discussion,Tasks,Defects").then => expect(@app.getEl().down('.rui-card-content')).toBeDefined() expect(@app.getEl().down('.PlanEstimate')).toBeNull() it 'should specify the correct policy preference setting key', -> policy = 'Foo' settingsKey = 'ScheduleStateDefinedPolicy' settings = {} settings[settingsKey] = policy @createApp(settings).then => @assertPolicyCmpConfig(settingsKey, policy) it 'should load legacy non field scoped policy setting', -> policy = 'Foo' settingsKey = 'ScheduleStateDefinedPolicy' settings = {} settings['DefinedPolicy'] = policy @createApp(settings).then => @assertPolicyCmpConfig(settingsKey, policy) it 'should load policy setting when column has WSAPI 2.x c_ prefix', -> policy = 'Foo' groupByRoot = 'SomeCustomField' groupByField = 'c_' + groupByRoot settingsKey = groupByRoot + "DefinedPolicy" settings = {} settings.groupByField = groupByField settings[settingsKey] = policy field = name: groupByField try userstory_model = Rally.test.mock.data.WsapiModelFactory.getUserStoryModel() userstory_model.addField field defect_model = Rally.test.mock.data.WsapiModelFactory.getDefectModel() defect_model.addField field finally @removeField(userstory_model, field) @removeField(defect_model, field) @createApp(settings).then => @assertPolicyCmpConfig('c_' + settingsKey, policy) it 'should be able to scroll forwards', -> @createApp({}, renderTo: Rally.test.helpers.CardBoard.smallContainerForScrolling() ).then => Rally.test.helpers.CardBoard.scrollForwards @cardboard, @ it 'should be able to scroll backwards', -> @createApp({}, renderTo: Rally.test.helpers.CardBoard.smallContainerForScrolling() ).then => Rally.test.helpers.CardBoard.scrollBackwards @cardboard, @ it 'should have correct icons on cards', -> @createApp().then => expect(@app.getEl().query('.rally-card-icon').length).toBe 5 expect(@app.getEl().query('.card-gear-icon').length).toBe 1 expect(@app.getEl().query('.card-plus-icon').length).toBe 1 expect(@app.getEl().query('.card-ready-icon').length).toBe 1 expect(@app.getEl().query('.card-blocked-icon').length).toBe 1 expect(@app.getEl().query('.card-color-icon').length).toBe 1 it 'should include the query filter from settings', -> query = '(Name = "foo")' @createApp(query: query).then => storeConfig = @app.down('rallygridboard').storeConfig expect(storeConfig.filters.length).toBe 1 expect(storeConfig.filters[0].toString()).toBe query it 'should include the filter from timebox scope', -> iteration = @mom.getRecord 'iteration' timeboxScope = Ext.create 'Rally.app.TimeboxScope', record: iteration @createApp({}, {}, timebox: timeboxScope).then => storeConfig = @app.down('rallygridboard').storeConfig expect(storeConfig.filters.length).toBe 1 expect(storeConfig.filters[0].toString()).toBe timeboxScope.getQueryFilter().toString() it 'should include the filters from timebox scope and settings', -> iteration = @mom.getRecord 'iteration' timeboxScope = Ext.create 'Rally.app.TimeboxScope', record: iteration query = '(Name = "foo")' @createApp(query: query, {}, timebox: timeboxScope).then => storeConfig = @app.down('rallygridboard').storeConfig expect(storeConfig.filters.length).toBe 2 expect(storeConfig.filters[0].toString()).toBe query expect(storeConfig.filters[1].toString()).toBe timeboxScope.getQueryFilter().toString() describe 'Swim Lanes', -> it 'should include rows configuration with rowsField when showRows setting is true', -> @createApp(showRows: true, rowsField: 'Owner').then => expect(@cardboard.rowConfig.field).toBe 'Owner' expect(@cardboard.rowConfig.sortDirection).toBe 'ASC' it 'should not include rows configuration when showRows setting is false', -> @createApp(showRows: false, rowsField: 'Owner').then => expect(@cardboard.rowConfig).toBeNull() describe 'Fixed Header', -> it 'should add the fixed header plugin', -> @createApp().then => expect(@getPlugin('rallyfixedheadercardboard', @cardboard)).toBeDefined() it 'should set the initial gridboard height to the app height', -> @createApp().then => expect(@app.down('rallygridboard').getHeight()).toBe @app.getHeight() describe 'plugins', -> describe 'filtering', -> it 'should use rallygridboard custom filter control', -> @createApp().then => plugin = @getPlugin('rallygridboardcustomfiltercontrol') expect(plugin).toBeDefined() expect(plugin.filterChildren).toBe true expect(plugin.filterControlConfig.stateful).toBe true expect(plugin.filterControlConfig.stateId).toBe @app.getContext().getScopedStateId('kanban-custom-filter-button') expect(plugin.filterControlConfig.modelNames).toEqual ['User Story', 'Defect'] expect(plugin.showOwnerFilter).toBe true expect(plugin.ownerFilterControlConfig.stateful).toBe true expect(plugin.ownerFilterControlConfig.stateId).toBe @app.getContext().getScopedStateId('kanban-owner-filter') describe 'field picker', -> it 'should use rallygridboard field picker', -> @createApp().then => plugin = @getPlugin('rallygridboardfieldpicker') expect(plugin).toBeDefined() expect(plugin.headerPosition).toBe 'left' expect(plugin.modelNames).toEqual ['User Story', 'Defect'] expect(@cardboard.columnConfig.fields).toEqual @app.getSetting('cardFields').split(',') helpers createApp: (settings = {}, options = {}, context = {}) -> @app = Ext.create 'Rally.apps.kanban.KanbanApp', context: Ext.create('Rally.app.Context', initialValues: Ext.merge({ project: _ref: @projectRef Name: @projectName workspace: WorkspaceConfiguration: DragDropRankingEnabled: if Ext.isDefined(options.DragDropRankingEnabled) then options.DragDropRankingEnabled else true}, context) ) settings: settings renderTo: options.renderTo || 'testDiv' height: 400 @waitForComponentReady(@app).then => @cardboard = @app.down('rallycardboard') @cardboard.hideMask() assertPolicyCmpConfig: (settingsKey, policy) -> column = @cardboard.getColumns()[0] plugin = _.find(column.plugins, {ptype: 'rallycolumnpolicy'}); prefConfigSettings = plugin.policyCmpConfig.prefConfig.settings expect(Ext.Object.getKeys(prefConfigSettings)[0]).toBe settingsKey expect(prefConfigSettings[settingsKey]).toBe policy expect(plugin.policyCmpConfig.policies).toBe policy removeField: (model, field) -> model.prototype.fields.remove field expect(model.getField(field.name)).toBeUndefined getPlugin: (xtype, cmp = @app.down('rallygridboard')) -> _.find cmp.plugins, (plugin) -> plugin.ptype == xtype
201532
Ext = window.Ext4 || window.Ext Ext.require [ 'Rally.ui.report.StandardReport', 'Rally.apps.kanban.KanbanApp', 'Rally.util.Element', 'Rally.ui.notify.Notifier', 'Rally.app.Context', 'Rally.test.helpers.CardBoard', 'Rally.data.Ranker' ] describe 'Rally.apps.kanban.KanbanApp', -> beforeEach -> @ajax.whenQuerying('artifact').respondWithCount(1, { values: [{ ScheduleState: 'In-Progress' }] createImmediateSubObjects: true }) @projectRef = Rally.environment.getContext().getProject()._ref @projectName = 'Project 1' afterEach -> Rally.test.destroyComponentsOfQuery 'kanbanapp' it 'has the correct default settings', -> @createApp().then => expect(@app.getSetting('groupByField')).toBe 'ScheduleState' expect(@app.getSetting('columns')).toBe Ext.JSON.encode( Defined: wip: '' 'In-Progress': wip: '' Completed: wip: '' Accepted: wip: '' ) expect(@app.getSetting('cardFields')).toBe 'FormattedID,Name,Owner,Discussion,Tasks,Defects' expect(@app.getSetting('showRows')).toBe false it 'should have a default card fields setting', -> @createApp().then => expect(@cardboard.columnConfig.fields).toEqual @app.getSetting('cardFields').split(',') it 'should have use the cardFields setting if available', -> @createApp(cardFields: 'HelloKitty').then => expect(@cardboard.columnConfig.fields).toEqual ['HelloKitty'] it 'should show the field picker', -> @createApp().then => expect(@app.down('#fieldpickerbtn').isVisible()).toBe true it 'does not show add new when user is not a project editor', -> Rally.environment.getContext().getPermissions().userPermissions[0].Role = 'Viewer' @createApp().then => expect(@app.down 'rallyaddnew').toBeNull() it 'shows add new for user who is a project editor', -> @createApp().then => expect(@app.down 'rallyaddnew').toBeDefined() it 'should not schedule a new item in an iteration', -> @createApp().then => editorOpenedStub = @stub(Rally.nav.Manager, 'create') addNewHelper = new Helpers.AddNewHelper this, '.kanban' addNewHelper.addWithDetails('foo').then => expect(editorOpenedStub).toHaveBeenCalledOnce() expect(editorOpenedStub.getCall(0).args[1].iteration).toBe 'u' it 'should set group by field to first column value', -> @createApp().then => editorOpenedStub = @stub(Rally.nav.Manager, 'create') addNewHelper = new Helpers.AddNewHelper this, '.kanban' addNewHelper.addWithDetails('foo').then => expect(editorOpenedStub).toHaveBeenCalledOnce() expect(editorOpenedStub.getCall(0).args[1][@app.getSetting('groupByField')]).toBe @cardboard.getColumns()[0].getValue() it 'should set custom group by field to first column value', -> @createApp( groupByField: 'KanbanState' ).then => editorOpenedStub = @stub(Rally.nav.Manager, 'create') addNewHelper = new Helpers.AddNewHelper this, '.kanban' addNewHelper.addWithDetails('foo').then => expect(editorOpenedStub).toHaveBeenCalledOnce() groupByField = "c_#{@app.getSetting('groupByField')}" expect(editorOpenedStub.getCall(0).args[1][groupByField]).toBe @cardboard.getColumns()[0].getValue() it 'should show correct fields on cards', -> @createApp(cardFields: 'Name,Defects,Project').then => expect(@cardboard.columnConfig.fields).toContain 'Name' expect(@cardboard.columnConfig.fields).toContain 'Defects' expect(@cardboard.columnConfig.fields).toContain 'Project' it 'should show columns with correct wips based on settings', -> columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({columns: Ext.JSON.encode(columnSettings), groupByField: 'ScheduleState'}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].wipLimit).toBe columnSettings.Defined.wip expect(columns[1].wipLimit).toBe columnSettings['In-Progress'].wip it 'should show columns with correct card fields when COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS enabled', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(true) columnSettings = Defined: cardFields: 'Name,Defects,Project' 'In-Progress': cardFields: 'ScheduleState' @createApp({columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].cardConfig.fields).toBeUndefined() expect(columns[0].fields).toEqual columnSettings.Defined.cardFields.split(',') expect(columns[1].fields).toEqual columnSettings['In-Progress'].cardFields.split(',') expect(columns[1].cardConfig.fields).toBeUndefined() it 'should show columns with cardFields when no column.cardFields settings', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(true) columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({cardFields: 'foobar', columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].fields).toEqual ['foobar'] expect(columns[1].fields).toEqual ['foobar'] it 'should show columns with defaultCardFields when no cardFields or column.cardFields settings', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(true) columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].fields).toEqual @app.getSetting('cardFields').split(',') expect(columns[1].fields).toEqual @app.getSetting('cardFields').split(',') it 'should not specify any card fields to show when COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS is off (should let card field picker plugin control it)', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(false) columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 _.each columns, (column) => expect(column.fields).toEqual @app.getSetting('cardFields').split(',') expect(column.cardConfig.fields).toBeUndefined() it 'should contain menu options', -> @createApp().then => options = @app.getOptions() expect(options.length).toBe 3 expect(options[0].text).toBe 'Show Cycle Time Report' expect(options[1].text).toBe 'Show Throughput Report' expect(options[2].text).toBe 'Print' it 'should correctly build report config for non schedule state field stories', -> @createApp().then => @stub(@app, 'getSetting').returns('KanbanState') @stub(@app, '_getWorkItemTypesForChart').returns('G') report_config = @app._buildReportConfig(Rally.ui.report.StandardReport.Reports.CycleLeadTime) expect(report_config.filter_field).toBe @app.groupByField.displayName expect(report_config.work_items).toBe 'G' expect(report_config.report.id).toBe Rally.ui.report.StandardReport.Reports.CycleLeadTime.id it 'should correctly build report config for schedule state field with story and defect types', -> @createApp().then => report_config = @app._buildReportConfig(Rally.ui.report.StandardReport.Reports.Throughput) expect(report_config.filter_field).toBeUndefined() expect(report_config.work_items).toBe 'N' expect(report_config.report.id).toBe Rally.ui.report.StandardReport.Reports.Throughput.id it 'should correctly build standard report component config', -> @createApp().then => report_config = {report: 5} standard_report_config = @app._buildStandardReportConfig(report_config) expect(standard_report_config.project).toBe @app.getContext().getDataContext().project expect(standard_report_config.projectScopeDown).toBe @app.getContext().getDataContext().projectScopeDown expect(standard_report_config.projectScopeUp).toBe @app.getContext().getDataContext().projectScopeUp expect(standard_report_config.reportConfig).toBe report_config it 'should exclude items with a release set in the last column', -> @createApp(hideReleasedCards: true).then => columns = @cardboard.getColumns() _.each columns, (column, index) -> expect(column.hideReleasedCards).toBe index == columns.length - 1 it 'should not exclude items with a release set in the last column', -> @createApp(hideReleasedCards: false).then => _.each @cardboard.getColumns(), (column) -> expect(column.hideReleasedCards).toBe false it 'should show plan estimate when plan estimate field is enabled', -> @createApp(cardFields: "Name,Discussion,Tasks,Defects,PlanEstimate").then => expect(@app.getEl().down('.PlanEstimate')).not.toBeNull() it 'should not show plan estimate when plan estimate field is disabled', -> @createApp(cardFields: "Name,Discussion,Tasks,Defects").then => expect(@app.getEl().down('.rui-card-content')).toBeDefined() expect(@app.getEl().down('.PlanEstimate')).toBeNull() it 'should specify the correct policy preference setting key', -> policy = 'Foo' settingsKey = '<KEY>' settings = {} settings[settingsKey] = policy @createApp(settings).then => @assertPolicyCmpConfig(settingsKey, policy) it 'should load legacy non field scoped policy setting', -> policy = 'Foo' settingsKey = '<KEY>' settings = {} settings['DefinedPolicy'] = policy @createApp(settings).then => @assertPolicyCmpConfig(settingsKey, policy) it 'should load policy setting when column has WSAPI 2.x c_ prefix', -> policy = 'Foo' groupByRoot = 'SomeCustomField' groupByField = 'c_' + groupByRoot settingsKey = groupByRoot + "Defined<KEY>" settings = {} settings.groupByField = groupByField settings[settingsKey] = policy field = name: groupByField try userstory_model = Rally.test.mock.data.WsapiModelFactory.getUserStoryModel() userstory_model.addField field defect_model = Rally.test.mock.data.WsapiModelFactory.getDefectModel() defect_model.addField field finally @removeField(userstory_model, field) @removeField(defect_model, field) @createApp(settings).then => @assertPolicyCmpConfig('c_' + settingsKey, policy) it 'should be able to scroll forwards', -> @createApp({}, renderTo: Rally.test.helpers.CardBoard.smallContainerForScrolling() ).then => Rally.test.helpers.CardBoard.scrollForwards @cardboard, @ it 'should be able to scroll backwards', -> @createApp({}, renderTo: Rally.test.helpers.CardBoard.smallContainerForScrolling() ).then => Rally.test.helpers.CardBoard.scrollBackwards @cardboard, @ it 'should have correct icons on cards', -> @createApp().then => expect(@app.getEl().query('.rally-card-icon').length).toBe 5 expect(@app.getEl().query('.card-gear-icon').length).toBe 1 expect(@app.getEl().query('.card-plus-icon').length).toBe 1 expect(@app.getEl().query('.card-ready-icon').length).toBe 1 expect(@app.getEl().query('.card-blocked-icon').length).toBe 1 expect(@app.getEl().query('.card-color-icon').length).toBe 1 it 'should include the query filter from settings', -> query = '(Name = "foo")' @createApp(query: query).then => storeConfig = @app.down('rallygridboard').storeConfig expect(storeConfig.filters.length).toBe 1 expect(storeConfig.filters[0].toString()).toBe query it 'should include the filter from timebox scope', -> iteration = @mom.getRecord 'iteration' timeboxScope = Ext.create 'Rally.app.TimeboxScope', record: iteration @createApp({}, {}, timebox: timeboxScope).then => storeConfig = @app.down('rallygridboard').storeConfig expect(storeConfig.filters.length).toBe 1 expect(storeConfig.filters[0].toString()).toBe timeboxScope.getQueryFilter().toString() it 'should include the filters from timebox scope and settings', -> iteration = @mom.getRecord 'iteration' timeboxScope = Ext.create 'Rally.app.TimeboxScope', record: iteration query = '(Name = "foo")' @createApp(query: query, {}, timebox: timeboxScope).then => storeConfig = @app.down('rallygridboard').storeConfig expect(storeConfig.filters.length).toBe 2 expect(storeConfig.filters[0].toString()).toBe query expect(storeConfig.filters[1].toString()).toBe timeboxScope.getQueryFilter().toString() describe 'Swim Lanes', -> it 'should include rows configuration with rowsField when showRows setting is true', -> @createApp(showRows: true, rowsField: 'Owner').then => expect(@cardboard.rowConfig.field).toBe 'Owner' expect(@cardboard.rowConfig.sortDirection).toBe 'ASC' it 'should not include rows configuration when showRows setting is false', -> @createApp(showRows: false, rowsField: 'Owner').then => expect(@cardboard.rowConfig).toBeNull() describe 'Fixed Header', -> it 'should add the fixed header plugin', -> @createApp().then => expect(@getPlugin('rallyfixedheadercardboard', @cardboard)).toBeDefined() it 'should set the initial gridboard height to the app height', -> @createApp().then => expect(@app.down('rallygridboard').getHeight()).toBe @app.getHeight() describe 'plugins', -> describe 'filtering', -> it 'should use rallygridboard custom filter control', -> @createApp().then => plugin = @getPlugin('rallygridboardcustomfiltercontrol') expect(plugin).toBeDefined() expect(plugin.filterChildren).toBe true expect(plugin.filterControlConfig.stateful).toBe true expect(plugin.filterControlConfig.stateId).toBe @app.getContext().getScopedStateId('kanban-custom-filter-button') expect(plugin.filterControlConfig.modelNames).toEqual ['User Story', 'Defect'] expect(plugin.showOwnerFilter).toBe true expect(plugin.ownerFilterControlConfig.stateful).toBe true expect(plugin.ownerFilterControlConfig.stateId).toBe @app.getContext().getScopedStateId('kanban-owner-filter') describe 'field picker', -> it 'should use rallygridboard field picker', -> @createApp().then => plugin = @getPlugin('rallygridboardfieldpicker') expect(plugin).toBeDefined() expect(plugin.headerPosition).toBe 'left' expect(plugin.modelNames).toEqual ['User Story', 'Defect'] expect(@cardboard.columnConfig.fields).toEqual @app.getSetting('cardFields').split(',') helpers createApp: (settings = {}, options = {}, context = {}) -> @app = Ext.create 'Rally.apps.kanban.KanbanApp', context: Ext.create('Rally.app.Context', initialValues: Ext.merge({ project: _ref: @projectRef Name: @projectName workspace: WorkspaceConfiguration: DragDropRankingEnabled: if Ext.isDefined(options.DragDropRankingEnabled) then options.DragDropRankingEnabled else true}, context) ) settings: settings renderTo: options.renderTo || 'testDiv' height: 400 @waitForComponentReady(@app).then => @cardboard = @app.down('rallycardboard') @cardboard.hideMask() assertPolicyCmpConfig: (settingsKey, policy) -> column = @cardboard.getColumns()[0] plugin = _.find(column.plugins, {ptype: 'rallycolumnpolicy'}); prefConfigSettings = plugin.policyCmpConfig.prefConfig.settings expect(Ext.Object.getKeys(prefConfigSettings)[0]).toBe settingsKey expect(prefConfigSettings[settingsKey]).toBe policy expect(plugin.policyCmpConfig.policies).toBe policy removeField: (model, field) -> model.prototype.fields.remove field expect(model.getField(field.name)).toBeUndefined getPlugin: (xtype, cmp = @app.down('rallygridboard')) -> _.find cmp.plugins, (plugin) -> plugin.ptype == xtype
true
Ext = window.Ext4 || window.Ext Ext.require [ 'Rally.ui.report.StandardReport', 'Rally.apps.kanban.KanbanApp', 'Rally.util.Element', 'Rally.ui.notify.Notifier', 'Rally.app.Context', 'Rally.test.helpers.CardBoard', 'Rally.data.Ranker' ] describe 'Rally.apps.kanban.KanbanApp', -> beforeEach -> @ajax.whenQuerying('artifact').respondWithCount(1, { values: [{ ScheduleState: 'In-Progress' }] createImmediateSubObjects: true }) @projectRef = Rally.environment.getContext().getProject()._ref @projectName = 'Project 1' afterEach -> Rally.test.destroyComponentsOfQuery 'kanbanapp' it 'has the correct default settings', -> @createApp().then => expect(@app.getSetting('groupByField')).toBe 'ScheduleState' expect(@app.getSetting('columns')).toBe Ext.JSON.encode( Defined: wip: '' 'In-Progress': wip: '' Completed: wip: '' Accepted: wip: '' ) expect(@app.getSetting('cardFields')).toBe 'FormattedID,Name,Owner,Discussion,Tasks,Defects' expect(@app.getSetting('showRows')).toBe false it 'should have a default card fields setting', -> @createApp().then => expect(@cardboard.columnConfig.fields).toEqual @app.getSetting('cardFields').split(',') it 'should have use the cardFields setting if available', -> @createApp(cardFields: 'HelloKitty').then => expect(@cardboard.columnConfig.fields).toEqual ['HelloKitty'] it 'should show the field picker', -> @createApp().then => expect(@app.down('#fieldpickerbtn').isVisible()).toBe true it 'does not show add new when user is not a project editor', -> Rally.environment.getContext().getPermissions().userPermissions[0].Role = 'Viewer' @createApp().then => expect(@app.down 'rallyaddnew').toBeNull() it 'shows add new for user who is a project editor', -> @createApp().then => expect(@app.down 'rallyaddnew').toBeDefined() it 'should not schedule a new item in an iteration', -> @createApp().then => editorOpenedStub = @stub(Rally.nav.Manager, 'create') addNewHelper = new Helpers.AddNewHelper this, '.kanban' addNewHelper.addWithDetails('foo').then => expect(editorOpenedStub).toHaveBeenCalledOnce() expect(editorOpenedStub.getCall(0).args[1].iteration).toBe 'u' it 'should set group by field to first column value', -> @createApp().then => editorOpenedStub = @stub(Rally.nav.Manager, 'create') addNewHelper = new Helpers.AddNewHelper this, '.kanban' addNewHelper.addWithDetails('foo').then => expect(editorOpenedStub).toHaveBeenCalledOnce() expect(editorOpenedStub.getCall(0).args[1][@app.getSetting('groupByField')]).toBe @cardboard.getColumns()[0].getValue() it 'should set custom group by field to first column value', -> @createApp( groupByField: 'KanbanState' ).then => editorOpenedStub = @stub(Rally.nav.Manager, 'create') addNewHelper = new Helpers.AddNewHelper this, '.kanban' addNewHelper.addWithDetails('foo').then => expect(editorOpenedStub).toHaveBeenCalledOnce() groupByField = "c_#{@app.getSetting('groupByField')}" expect(editorOpenedStub.getCall(0).args[1][groupByField]).toBe @cardboard.getColumns()[0].getValue() it 'should show correct fields on cards', -> @createApp(cardFields: 'Name,Defects,Project').then => expect(@cardboard.columnConfig.fields).toContain 'Name' expect(@cardboard.columnConfig.fields).toContain 'Defects' expect(@cardboard.columnConfig.fields).toContain 'Project' it 'should show columns with correct wips based on settings', -> columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({columns: Ext.JSON.encode(columnSettings), groupByField: 'ScheduleState'}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].wipLimit).toBe columnSettings.Defined.wip expect(columns[1].wipLimit).toBe columnSettings['In-Progress'].wip it 'should show columns with correct card fields when COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS enabled', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(true) columnSettings = Defined: cardFields: 'Name,Defects,Project' 'In-Progress': cardFields: 'ScheduleState' @createApp({columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].cardConfig.fields).toBeUndefined() expect(columns[0].fields).toEqual columnSettings.Defined.cardFields.split(',') expect(columns[1].fields).toEqual columnSettings['In-Progress'].cardFields.split(',') expect(columns[1].cardConfig.fields).toBeUndefined() it 'should show columns with cardFields when no column.cardFields settings', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(true) columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({cardFields: 'foobar', columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].fields).toEqual ['foobar'] expect(columns[1].fields).toEqual ['foobar'] it 'should show columns with defaultCardFields when no cardFields or column.cardFields settings', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(true) columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 expect(columns[0].fields).toEqual @app.getSetting('cardFields').split(',') expect(columns[1].fields).toEqual @app.getSetting('cardFields').split(',') it 'should not specify any card fields to show when COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS is off (should let card field picker plugin control it)', -> @stub(Rally.app.Context.prototype, 'isFeatureEnabled').withArgs('COLUMN_LEVEL_FIELD_PICKER_ON_KANBAN_SETTINGS').returns(false) columnSettings = Defined: wip: 1 'In-Progress': wip: 2 @createApp({columns: Ext.JSON.encode(columnSettings)}).then => columns = @cardboard.getColumns() expect(columns.length).toBe 2 _.each columns, (column) => expect(column.fields).toEqual @app.getSetting('cardFields').split(',') expect(column.cardConfig.fields).toBeUndefined() it 'should contain menu options', -> @createApp().then => options = @app.getOptions() expect(options.length).toBe 3 expect(options[0].text).toBe 'Show Cycle Time Report' expect(options[1].text).toBe 'Show Throughput Report' expect(options[2].text).toBe 'Print' it 'should correctly build report config for non schedule state field stories', -> @createApp().then => @stub(@app, 'getSetting').returns('KanbanState') @stub(@app, '_getWorkItemTypesForChart').returns('G') report_config = @app._buildReportConfig(Rally.ui.report.StandardReport.Reports.CycleLeadTime) expect(report_config.filter_field).toBe @app.groupByField.displayName expect(report_config.work_items).toBe 'G' expect(report_config.report.id).toBe Rally.ui.report.StandardReport.Reports.CycleLeadTime.id it 'should correctly build report config for schedule state field with story and defect types', -> @createApp().then => report_config = @app._buildReportConfig(Rally.ui.report.StandardReport.Reports.Throughput) expect(report_config.filter_field).toBeUndefined() expect(report_config.work_items).toBe 'N' expect(report_config.report.id).toBe Rally.ui.report.StandardReport.Reports.Throughput.id it 'should correctly build standard report component config', -> @createApp().then => report_config = {report: 5} standard_report_config = @app._buildStandardReportConfig(report_config) expect(standard_report_config.project).toBe @app.getContext().getDataContext().project expect(standard_report_config.projectScopeDown).toBe @app.getContext().getDataContext().projectScopeDown expect(standard_report_config.projectScopeUp).toBe @app.getContext().getDataContext().projectScopeUp expect(standard_report_config.reportConfig).toBe report_config it 'should exclude items with a release set in the last column', -> @createApp(hideReleasedCards: true).then => columns = @cardboard.getColumns() _.each columns, (column, index) -> expect(column.hideReleasedCards).toBe index == columns.length - 1 it 'should not exclude items with a release set in the last column', -> @createApp(hideReleasedCards: false).then => _.each @cardboard.getColumns(), (column) -> expect(column.hideReleasedCards).toBe false it 'should show plan estimate when plan estimate field is enabled', -> @createApp(cardFields: "Name,Discussion,Tasks,Defects,PlanEstimate").then => expect(@app.getEl().down('.PlanEstimate')).not.toBeNull() it 'should not show plan estimate when plan estimate field is disabled', -> @createApp(cardFields: "Name,Discussion,Tasks,Defects").then => expect(@app.getEl().down('.rui-card-content')).toBeDefined() expect(@app.getEl().down('.PlanEstimate')).toBeNull() it 'should specify the correct policy preference setting key', -> policy = 'Foo' settingsKey = 'PI:KEY:<KEY>END_PI' settings = {} settings[settingsKey] = policy @createApp(settings).then => @assertPolicyCmpConfig(settingsKey, policy) it 'should load legacy non field scoped policy setting', -> policy = 'Foo' settingsKey = 'PI:KEY:<KEY>END_PI' settings = {} settings['DefinedPolicy'] = policy @createApp(settings).then => @assertPolicyCmpConfig(settingsKey, policy) it 'should load policy setting when column has WSAPI 2.x c_ prefix', -> policy = 'Foo' groupByRoot = 'SomeCustomField' groupByField = 'c_' + groupByRoot settingsKey = groupByRoot + "DefinedPI:KEY:<KEY>END_PI" settings = {} settings.groupByField = groupByField settings[settingsKey] = policy field = name: groupByField try userstory_model = Rally.test.mock.data.WsapiModelFactory.getUserStoryModel() userstory_model.addField field defect_model = Rally.test.mock.data.WsapiModelFactory.getDefectModel() defect_model.addField field finally @removeField(userstory_model, field) @removeField(defect_model, field) @createApp(settings).then => @assertPolicyCmpConfig('c_' + settingsKey, policy) it 'should be able to scroll forwards', -> @createApp({}, renderTo: Rally.test.helpers.CardBoard.smallContainerForScrolling() ).then => Rally.test.helpers.CardBoard.scrollForwards @cardboard, @ it 'should be able to scroll backwards', -> @createApp({}, renderTo: Rally.test.helpers.CardBoard.smallContainerForScrolling() ).then => Rally.test.helpers.CardBoard.scrollBackwards @cardboard, @ it 'should have correct icons on cards', -> @createApp().then => expect(@app.getEl().query('.rally-card-icon').length).toBe 5 expect(@app.getEl().query('.card-gear-icon').length).toBe 1 expect(@app.getEl().query('.card-plus-icon').length).toBe 1 expect(@app.getEl().query('.card-ready-icon').length).toBe 1 expect(@app.getEl().query('.card-blocked-icon').length).toBe 1 expect(@app.getEl().query('.card-color-icon').length).toBe 1 it 'should include the query filter from settings', -> query = '(Name = "foo")' @createApp(query: query).then => storeConfig = @app.down('rallygridboard').storeConfig expect(storeConfig.filters.length).toBe 1 expect(storeConfig.filters[0].toString()).toBe query it 'should include the filter from timebox scope', -> iteration = @mom.getRecord 'iteration' timeboxScope = Ext.create 'Rally.app.TimeboxScope', record: iteration @createApp({}, {}, timebox: timeboxScope).then => storeConfig = @app.down('rallygridboard').storeConfig expect(storeConfig.filters.length).toBe 1 expect(storeConfig.filters[0].toString()).toBe timeboxScope.getQueryFilter().toString() it 'should include the filters from timebox scope and settings', -> iteration = @mom.getRecord 'iteration' timeboxScope = Ext.create 'Rally.app.TimeboxScope', record: iteration query = '(Name = "foo")' @createApp(query: query, {}, timebox: timeboxScope).then => storeConfig = @app.down('rallygridboard').storeConfig expect(storeConfig.filters.length).toBe 2 expect(storeConfig.filters[0].toString()).toBe query expect(storeConfig.filters[1].toString()).toBe timeboxScope.getQueryFilter().toString() describe 'Swim Lanes', -> it 'should include rows configuration with rowsField when showRows setting is true', -> @createApp(showRows: true, rowsField: 'Owner').then => expect(@cardboard.rowConfig.field).toBe 'Owner' expect(@cardboard.rowConfig.sortDirection).toBe 'ASC' it 'should not include rows configuration when showRows setting is false', -> @createApp(showRows: false, rowsField: 'Owner').then => expect(@cardboard.rowConfig).toBeNull() describe 'Fixed Header', -> it 'should add the fixed header plugin', -> @createApp().then => expect(@getPlugin('rallyfixedheadercardboard', @cardboard)).toBeDefined() it 'should set the initial gridboard height to the app height', -> @createApp().then => expect(@app.down('rallygridboard').getHeight()).toBe @app.getHeight() describe 'plugins', -> describe 'filtering', -> it 'should use rallygridboard custom filter control', -> @createApp().then => plugin = @getPlugin('rallygridboardcustomfiltercontrol') expect(plugin).toBeDefined() expect(plugin.filterChildren).toBe true expect(plugin.filterControlConfig.stateful).toBe true expect(plugin.filterControlConfig.stateId).toBe @app.getContext().getScopedStateId('kanban-custom-filter-button') expect(plugin.filterControlConfig.modelNames).toEqual ['User Story', 'Defect'] expect(plugin.showOwnerFilter).toBe true expect(plugin.ownerFilterControlConfig.stateful).toBe true expect(plugin.ownerFilterControlConfig.stateId).toBe @app.getContext().getScopedStateId('kanban-owner-filter') describe 'field picker', -> it 'should use rallygridboard field picker', -> @createApp().then => plugin = @getPlugin('rallygridboardfieldpicker') expect(plugin).toBeDefined() expect(plugin.headerPosition).toBe 'left' expect(plugin.modelNames).toEqual ['User Story', 'Defect'] expect(@cardboard.columnConfig.fields).toEqual @app.getSetting('cardFields').split(',') helpers createApp: (settings = {}, options = {}, context = {}) -> @app = Ext.create 'Rally.apps.kanban.KanbanApp', context: Ext.create('Rally.app.Context', initialValues: Ext.merge({ project: _ref: @projectRef Name: @projectName workspace: WorkspaceConfiguration: DragDropRankingEnabled: if Ext.isDefined(options.DragDropRankingEnabled) then options.DragDropRankingEnabled else true}, context) ) settings: settings renderTo: options.renderTo || 'testDiv' height: 400 @waitForComponentReady(@app).then => @cardboard = @app.down('rallycardboard') @cardboard.hideMask() assertPolicyCmpConfig: (settingsKey, policy) -> column = @cardboard.getColumns()[0] plugin = _.find(column.plugins, {ptype: 'rallycolumnpolicy'}); prefConfigSettings = plugin.policyCmpConfig.prefConfig.settings expect(Ext.Object.getKeys(prefConfigSettings)[0]).toBe settingsKey expect(prefConfigSettings[settingsKey]).toBe policy expect(plugin.policyCmpConfig.policies).toBe policy removeField: (model, field) -> model.prototype.fields.remove field expect(model.getField(field.name)).toBeUndefined getPlugin: (xtype, cmp = @app.down('rallygridboard')) -> _.find cmp.plugins, (plugin) -> plugin.ptype == xtype
[ { "context": "->\n manager = new PullRequestManager(token: 'token123')\n assert @authenticate.callCount is 1\n ", "end": 471, "score": 0.8331344723701477, "start": 463, "tag": "PASSWORD", "value": "token123" }, { "context": "(0).args, [\n type: 'oauth'\n token: 'token123'\n ]\n assert typeof manager.create is 'f", "end": 618, "score": 0.8940055966377258, "start": 610, "tag": "PASSWORD", "value": "token123" } ]
test/clients/pull-request-manager-test.coffee
faithcreates/hubot-fgb
1
assert = require 'power-assert' sinon = require 'sinon' GitHub = require 'github' {PullRequestManager} = require '../../src/clients/pull-request-manager' describe 'PullRequestManager', -> beforeEach -> @sinon = sinon.sandbox.create() @authenticate = @sinon.stub GitHub.prototype, 'authenticate', -> # do nothing afterEach -> @sinon.restore() describe '#constructor', -> it 'works', -> manager = new PullRequestManager(token: 'token123') assert @authenticate.callCount is 1 assert.deepEqual @authenticate.getCall(0).args, [ type: 'oauth' token: 'token123' ] assert typeof manager.create is 'function' assert typeof manager.get is 'function' assert typeof manager.list is 'function' assert typeof manager.merge is 'function'
111366
assert = require 'power-assert' sinon = require 'sinon' GitHub = require 'github' {PullRequestManager} = require '../../src/clients/pull-request-manager' describe 'PullRequestManager', -> beforeEach -> @sinon = sinon.sandbox.create() @authenticate = @sinon.stub GitHub.prototype, 'authenticate', -> # do nothing afterEach -> @sinon.restore() describe '#constructor', -> it 'works', -> manager = new PullRequestManager(token: '<PASSWORD>') assert @authenticate.callCount is 1 assert.deepEqual @authenticate.getCall(0).args, [ type: 'oauth' token: '<PASSWORD>' ] assert typeof manager.create is 'function' assert typeof manager.get is 'function' assert typeof manager.list is 'function' assert typeof manager.merge is 'function'
true
assert = require 'power-assert' sinon = require 'sinon' GitHub = require 'github' {PullRequestManager} = require '../../src/clients/pull-request-manager' describe 'PullRequestManager', -> beforeEach -> @sinon = sinon.sandbox.create() @authenticate = @sinon.stub GitHub.prototype, 'authenticate', -> # do nothing afterEach -> @sinon.restore() describe '#constructor', -> it 'works', -> manager = new PullRequestManager(token: 'PI:PASSWORD:<PASSWORD>END_PI') assert @authenticate.callCount is 1 assert.deepEqual @authenticate.getCall(0).args, [ type: 'oauth' token: 'PI:PASSWORD:<PASSWORD>END_PI' ] assert typeof manager.create is 'function' assert typeof manager.get is 'function' assert typeof manager.list is 'function' assert typeof manager.merge is 'function'
[ { "context": "r = null\nadminUser = null\npassword = \"P4thw0rd\"\nsocket = null\ntoken = null\nuserAccess", "end": 830, "score": 0.9992499351501465, "start": 822, "tag": "PASSWORD", "value": "P4thw0rd" }, { "context": " user: (done) ->\n user =\n email: \"user@email.com\"\n password: password\n app.models.", "end": 1094, "score": 0.9999165534973145, "start": 1080, "tag": "EMAIL", "value": "user@email.com" }, { "context": " email: \"user@email.com\"\n password: password\n app.models.User.create user, (err, data) ", "end": 1124, "score": 0.9993566870689392, "start": 1116, "tag": "PASSWORD", "value": "password" }, { "context": ": (done) ->\n adminUser =\n email: \"admin@email.com\"\n password: password\n permissio", "end": 1355, "score": 0.9999212026596069, "start": 1340, "tag": "EMAIL", "value": "admin@email.com" }, { "context": " email: \"admin@email.com\"\n password: password\n permission: app.config.permissionLevels", "end": 1385, "score": 0.9993065595626831, "start": 1377, "tag": "PASSWORD", "value": "password" }, { "context": "t 'should loginWithToken', (done) ->\n token = helpers.createId()\n ttl = 24 * 3600 * 1000 # 24hours\n\n a", "end": 2470, "score": 0.9033541679382324, "start": 2454, "tag": "KEY", "value": "helpers.createId" } ]
test/socket-api.test.coffee
mattstone/StarterApp-Server
0
request = require 'request' should = require('chai').should() async = require 'async' io = require('socket.io-client') helpers = require '../lib/helpers' mongoose = require 'mongoose' arr = (args...) -> args app = {} app.config = require('../config/config.test') app.helpers = require '../lib/helpers.coffee' app.mongoose = require 'mongoose' app.mongoose.promise = global.Promise app.mongoose.connect app.config.mongodb.uri, { useNewUrlParser: true } # load Redis RedisManager = require '../lib/RedisManager' app.r = new RedisManager app # load models app.models = app.helpers.loadModels app # End Setup App appEndPoint = app.config.appEndPoint + ":" + String app.config.port apiEndPoint = app.config.apiEndPoint + ":" + String app.config.port user = null adminUser = null password = "P4thw0rd" socket = null token = null userAccessToken = null adminAccessToken = null describe 'Socket.io API', -> before (done) -> this.timeout = 30000 # create user tasks = user: (done) -> user = email: "user@email.com" password: password app.models.User.create user, (err, data) -> user = data user.confirmUser() workingUser = user done() adminUser: (done) -> adminUser = email: "admin@email.com" password: password permission: app.config.permissionLevels.ADMIN app.models.User.create adminUser, (err, data) -> adminUser = data adminUser.confirmUser() done() async.auto tasks, done after (done) -> this.timeout = 30000 app.mongoose.connection.db.dropDatabase (err) -> done() describe 'Connection', -> it 'should connect', (done) -> #@timeout 30000 socket = io.connect "http://localhost:#{app.config.port}/" return done() if socket.socket?.connected socket.once 'connect', done socket.on 'reconnection', -> console.log 'reconnection', arguments socket.on 'error', -> console.log 'error', arguments socket.on 'event', -> console.log 'event', arguments it 'should return an error for an unknown api method', (done) -> socket.emit 'apiCall', 'startupAppIsGo', (err) -> should.exist err err.should.have.property 'code', 'methodNotFound' done() describe 'Authentication', -> it 'should loginWithToken', (done) -> token = helpers.createId() ttl = 24 * 3600 * 1000 # 24hours app.r.setAccessToken token, user, ttl, (err, result) -> user_id = user.id user_email = user.email socket.emit 'apiCall', 'loginWithToken', token, (err, user) -> should.not.exist err user._id.should.be.equal user_id user.email.should.be.equal user_email done() describe 'User', -> it 'should getUser for a current user', (done) -> socket.emit 'apiCall', 'getUser', (err, userData) -> should.not.exist err userData.should.be.an('object') userData.email.should.be.equal user.email done()
109345
request = require 'request' should = require('chai').should() async = require 'async' io = require('socket.io-client') helpers = require '../lib/helpers' mongoose = require 'mongoose' arr = (args...) -> args app = {} app.config = require('../config/config.test') app.helpers = require '../lib/helpers.coffee' app.mongoose = require 'mongoose' app.mongoose.promise = global.Promise app.mongoose.connect app.config.mongodb.uri, { useNewUrlParser: true } # load Redis RedisManager = require '../lib/RedisManager' app.r = new RedisManager app # load models app.models = app.helpers.loadModels app # End Setup App appEndPoint = app.config.appEndPoint + ":" + String app.config.port apiEndPoint = app.config.apiEndPoint + ":" + String app.config.port user = null adminUser = null password = "<PASSWORD>" socket = null token = null userAccessToken = null adminAccessToken = null describe 'Socket.io API', -> before (done) -> this.timeout = 30000 # create user tasks = user: (done) -> user = email: "<EMAIL>" password: <PASSWORD> app.models.User.create user, (err, data) -> user = data user.confirmUser() workingUser = user done() adminUser: (done) -> adminUser = email: "<EMAIL>" password: <PASSWORD> permission: app.config.permissionLevels.ADMIN app.models.User.create adminUser, (err, data) -> adminUser = data adminUser.confirmUser() done() async.auto tasks, done after (done) -> this.timeout = 30000 app.mongoose.connection.db.dropDatabase (err) -> done() describe 'Connection', -> it 'should connect', (done) -> #@timeout 30000 socket = io.connect "http://localhost:#{app.config.port}/" return done() if socket.socket?.connected socket.once 'connect', done socket.on 'reconnection', -> console.log 'reconnection', arguments socket.on 'error', -> console.log 'error', arguments socket.on 'event', -> console.log 'event', arguments it 'should return an error for an unknown api method', (done) -> socket.emit 'apiCall', 'startupAppIsGo', (err) -> should.exist err err.should.have.property 'code', 'methodNotFound' done() describe 'Authentication', -> it 'should loginWithToken', (done) -> token = <KEY>() ttl = 24 * 3600 * 1000 # 24hours app.r.setAccessToken token, user, ttl, (err, result) -> user_id = user.id user_email = user.email socket.emit 'apiCall', 'loginWithToken', token, (err, user) -> should.not.exist err user._id.should.be.equal user_id user.email.should.be.equal user_email done() describe 'User', -> it 'should getUser for a current user', (done) -> socket.emit 'apiCall', 'getUser', (err, userData) -> should.not.exist err userData.should.be.an('object') userData.email.should.be.equal user.email done()
true
request = require 'request' should = require('chai').should() async = require 'async' io = require('socket.io-client') helpers = require '../lib/helpers' mongoose = require 'mongoose' arr = (args...) -> args app = {} app.config = require('../config/config.test') app.helpers = require '../lib/helpers.coffee' app.mongoose = require 'mongoose' app.mongoose.promise = global.Promise app.mongoose.connect app.config.mongodb.uri, { useNewUrlParser: true } # load Redis RedisManager = require '../lib/RedisManager' app.r = new RedisManager app # load models app.models = app.helpers.loadModels app # End Setup App appEndPoint = app.config.appEndPoint + ":" + String app.config.port apiEndPoint = app.config.apiEndPoint + ":" + String app.config.port user = null adminUser = null password = "PI:PASSWORD:<PASSWORD>END_PI" socket = null token = null userAccessToken = null adminAccessToken = null describe 'Socket.io API', -> before (done) -> this.timeout = 30000 # create user tasks = user: (done) -> user = email: "PI:EMAIL:<EMAIL>END_PI" password: PI:PASSWORD:<PASSWORD>END_PI app.models.User.create user, (err, data) -> user = data user.confirmUser() workingUser = user done() adminUser: (done) -> adminUser = email: "PI:EMAIL:<EMAIL>END_PI" password: PI:PASSWORD:<PASSWORD>END_PI permission: app.config.permissionLevels.ADMIN app.models.User.create adminUser, (err, data) -> adminUser = data adminUser.confirmUser() done() async.auto tasks, done after (done) -> this.timeout = 30000 app.mongoose.connection.db.dropDatabase (err) -> done() describe 'Connection', -> it 'should connect', (done) -> #@timeout 30000 socket = io.connect "http://localhost:#{app.config.port}/" return done() if socket.socket?.connected socket.once 'connect', done socket.on 'reconnection', -> console.log 'reconnection', arguments socket.on 'error', -> console.log 'error', arguments socket.on 'event', -> console.log 'event', arguments it 'should return an error for an unknown api method', (done) -> socket.emit 'apiCall', 'startupAppIsGo', (err) -> should.exist err err.should.have.property 'code', 'methodNotFound' done() describe 'Authentication', -> it 'should loginWithToken', (done) -> token = PI:KEY:<KEY>END_PI() ttl = 24 * 3600 * 1000 # 24hours app.r.setAccessToken token, user, ttl, (err, result) -> user_id = user.id user_email = user.email socket.emit 'apiCall', 'loginWithToken', token, (err, user) -> should.not.exist err user._id.should.be.equal user_id user.email.should.be.equal user_email done() describe 'User', -> it 'should getUser for a current user', (done) -> socket.emit 'apiCall', 'getUser', (err, userData) -> should.not.exist err userData.should.be.an('object') userData.email.should.be.equal user.email done()
[ { "context": " audio.play()\n\nbaseAdmiral = ->\n storageKey = 'base_select_number'\n vue = new Vue\n el: '#search-admiral'\n da", "end": 304, "score": 0.9803589582443237, "start": 286, "tag": "KEY", "value": "base_select_number" } ]
server/app/assets/javascript/index.coffee
Moesugi/MFG
68
$(document).ready -> baseAdmiral() new CommandWatcher([38, 38, 40, 40, 37, 39, 37, 39, 66, 65]).watch -> if localStorage.getItem('sound') != 'false' audio = (new Audio('/rest/v1/sound/random')) audio.volume = 0.3 audio.play() baseAdmiral = -> storageKey = 'base_select_number' vue = new Vue el: '#search-admiral' data: users: [] admiralName: "" methods: getNumber: () -> $('#base_select option:selected')[0].value getUsers: (number, name) -> json = if number == "-1" $.getJSON("/rest/v1/search_user?q=#{name}") else $.getJSON("/rest/v1/search_base_user?base=#{number}&q=#{name}") json.done (data) -> vue.$set('users', data) ready: -> number = localStorage.getItem(storageKey) ? @getNumber() $('#base_select').val(number) @getUsers(number, "") @$watch 'admiralName', => @getUsers(@getNumber(), @admiralName) $('#base_select').change -> number = vue.getNumber() localStorage.setItem(storageKey, number) vue.getUsers(number, vue.admiralName) class CommandWatcher constructor: (commands) -> @keys = [] @length = commands.length @command = commands.join ',' watch: (handler) => watcher = @ $(document).on 'keydown', (event) -> watcher.keys.push event.which # マッチしたら実行後、即return if watcher.keys.length is watcher.length and watcher.keys.join(',') is watcher.command handler() watcher.keys = [] return # マッチしなかったらリセット if watcher.command.indexOf(watcher.keys.join(',')) isnt 0 watcher.keys = [] return
8944
$(document).ready -> baseAdmiral() new CommandWatcher([38, 38, 40, 40, 37, 39, 37, 39, 66, 65]).watch -> if localStorage.getItem('sound') != 'false' audio = (new Audio('/rest/v1/sound/random')) audio.volume = 0.3 audio.play() baseAdmiral = -> storageKey = '<KEY>' vue = new Vue el: '#search-admiral' data: users: [] admiralName: "" methods: getNumber: () -> $('#base_select option:selected')[0].value getUsers: (number, name) -> json = if number == "-1" $.getJSON("/rest/v1/search_user?q=#{name}") else $.getJSON("/rest/v1/search_base_user?base=#{number}&q=#{name}") json.done (data) -> vue.$set('users', data) ready: -> number = localStorage.getItem(storageKey) ? @getNumber() $('#base_select').val(number) @getUsers(number, "") @$watch 'admiralName', => @getUsers(@getNumber(), @admiralName) $('#base_select').change -> number = vue.getNumber() localStorage.setItem(storageKey, number) vue.getUsers(number, vue.admiralName) class CommandWatcher constructor: (commands) -> @keys = [] @length = commands.length @command = commands.join ',' watch: (handler) => watcher = @ $(document).on 'keydown', (event) -> watcher.keys.push event.which # マッチしたら実行後、即return if watcher.keys.length is watcher.length and watcher.keys.join(',') is watcher.command handler() watcher.keys = [] return # マッチしなかったらリセット if watcher.command.indexOf(watcher.keys.join(',')) isnt 0 watcher.keys = [] return
true
$(document).ready -> baseAdmiral() new CommandWatcher([38, 38, 40, 40, 37, 39, 37, 39, 66, 65]).watch -> if localStorage.getItem('sound') != 'false' audio = (new Audio('/rest/v1/sound/random')) audio.volume = 0.3 audio.play() baseAdmiral = -> storageKey = 'PI:KEY:<KEY>END_PI' vue = new Vue el: '#search-admiral' data: users: [] admiralName: "" methods: getNumber: () -> $('#base_select option:selected')[0].value getUsers: (number, name) -> json = if number == "-1" $.getJSON("/rest/v1/search_user?q=#{name}") else $.getJSON("/rest/v1/search_base_user?base=#{number}&q=#{name}") json.done (data) -> vue.$set('users', data) ready: -> number = localStorage.getItem(storageKey) ? @getNumber() $('#base_select').val(number) @getUsers(number, "") @$watch 'admiralName', => @getUsers(@getNumber(), @admiralName) $('#base_select').change -> number = vue.getNumber() localStorage.setItem(storageKey, number) vue.getUsers(number, vue.admiralName) class CommandWatcher constructor: (commands) -> @keys = [] @length = commands.length @command = commands.join ',' watch: (handler) => watcher = @ $(document).on 'keydown', (event) -> watcher.keys.push event.which # マッチしたら実行後、即return if watcher.keys.length is watcher.length and watcher.keys.join(',') is watcher.command handler() watcher.keys = [] return # マッチしなかったらリセット if watcher.command.indexOf(watcher.keys.join(',')) isnt 0 watcher.keys = [] return
[ { "context": ".redirect '/'\n else if passOk\n token = uuid.v4()\n await User.update(id: user.id).set\n ", "end": 2020, "score": 0.6990065574645996, "start": 2016, "tag": "KEY", "value": "uuid" }, { "context": "ect '/'\n else if passOk\n token = uuid.v4()\n await User.update(id: user.id).set\n ", "end": 2023, "score": 0.6202116012573242, "start": 2021, "tag": "KEY", "value": "v4" }, { "context": "fy-account'\n data:\n firstName: user.firstName\n token: token\n\n if this.req.wan", "end": 2369, "score": 0.8001079559326172, "start": 2355, "tag": "USERNAME", "value": "user.firstName" } ]
api/controllers/auth/login.coffee
nkofl/sails-1.0-template
0
uuid = require 'uuid' module.exports = friendlyName: 'Login' description: 'Log in using the provided email and password combination.' inputs: email: description: 'The email to log in as' type: 'string' required: true password: description: 'The unencrypted password to try' type: 'string' required: true rememberMe: description: 'Whether to extend the lifetime of the user\'s session.' type: 'boolean' exits: success: description: 'The user has been successfully logged in.' invalid: description: 'The email and password combo is invalid' responseType: 'unauthorized' redirect: description: 'Login success - redirect' responseType: 'redirect' fn: (inputs, exits) -> fail = => if this.req.wantsJSON || this.req.isSocket exits.invalid() else await sails.helpers.flash this.req, 'Login Failed', 4000, 'error' exits.redirect '/' user = await User.findOne email: inputs.email.toLowerCase() if user passOk = await sails.helpers.checkPassword inputs.password, user.password if passOk && user.emailStatus == 'confirmed' if inputs.rememberMe if this.req.isSocket sails.log.warn 'Received `rememberMe: true` from a virtual request, but it was ignored\n because a browser\'s session cookie cannot be reset over sockets.\n Please use a traditional HTTP request instead.' else this.req.session.cookie.maxAge = sails.config.custom.rememberMeCookieMaxAge this.req.session.user = user if this.req.wantsJSON || this.req.isSocket exits.success() else if this.req.session.returnTo await sails.helpers.flash this.req, 'User logged in' exits.redirect this.req.session.returnTo else await sails.helpers.flash this.req, 'User logged in' exits.redirect '/' else if passOk token = uuid.v4() await User.update(id: user.id).set emailToken: token, emailExpires: new Date(Date.now() + 24*60*60*1000) # 1 day await sails.helpers.sendEmail.with to: inputs.email subject: 'Confirm Email' template: 'email-verify-account' data: firstName: user.firstName token: token if this.req.wantsJSON || this.req.isSocket exits.success 'Must confirm email' else await sails.helpers.flash this.req, 'Email not yet confirmed. Please check your email and click the link to activate your account', 4000 exits.redirect '/' else fail() else fail()
132071
uuid = require 'uuid' module.exports = friendlyName: 'Login' description: 'Log in using the provided email and password combination.' inputs: email: description: 'The email to log in as' type: 'string' required: true password: description: 'The unencrypted password to try' type: 'string' required: true rememberMe: description: 'Whether to extend the lifetime of the user\'s session.' type: 'boolean' exits: success: description: 'The user has been successfully logged in.' invalid: description: 'The email and password combo is invalid' responseType: 'unauthorized' redirect: description: 'Login success - redirect' responseType: 'redirect' fn: (inputs, exits) -> fail = => if this.req.wantsJSON || this.req.isSocket exits.invalid() else await sails.helpers.flash this.req, 'Login Failed', 4000, 'error' exits.redirect '/' user = await User.findOne email: inputs.email.toLowerCase() if user passOk = await sails.helpers.checkPassword inputs.password, user.password if passOk && user.emailStatus == 'confirmed' if inputs.rememberMe if this.req.isSocket sails.log.warn 'Received `rememberMe: true` from a virtual request, but it was ignored\n because a browser\'s session cookie cannot be reset over sockets.\n Please use a traditional HTTP request instead.' else this.req.session.cookie.maxAge = sails.config.custom.rememberMeCookieMaxAge this.req.session.user = user if this.req.wantsJSON || this.req.isSocket exits.success() else if this.req.session.returnTo await sails.helpers.flash this.req, 'User logged in' exits.redirect this.req.session.returnTo else await sails.helpers.flash this.req, 'User logged in' exits.redirect '/' else if passOk token = <KEY>.<KEY>() await User.update(id: user.id).set emailToken: token, emailExpires: new Date(Date.now() + 24*60*60*1000) # 1 day await sails.helpers.sendEmail.with to: inputs.email subject: 'Confirm Email' template: 'email-verify-account' data: firstName: user.firstName token: token if this.req.wantsJSON || this.req.isSocket exits.success 'Must confirm email' else await sails.helpers.flash this.req, 'Email not yet confirmed. Please check your email and click the link to activate your account', 4000 exits.redirect '/' else fail() else fail()
true
uuid = require 'uuid' module.exports = friendlyName: 'Login' description: 'Log in using the provided email and password combination.' inputs: email: description: 'The email to log in as' type: 'string' required: true password: description: 'The unencrypted password to try' type: 'string' required: true rememberMe: description: 'Whether to extend the lifetime of the user\'s session.' type: 'boolean' exits: success: description: 'The user has been successfully logged in.' invalid: description: 'The email and password combo is invalid' responseType: 'unauthorized' redirect: description: 'Login success - redirect' responseType: 'redirect' fn: (inputs, exits) -> fail = => if this.req.wantsJSON || this.req.isSocket exits.invalid() else await sails.helpers.flash this.req, 'Login Failed', 4000, 'error' exits.redirect '/' user = await User.findOne email: inputs.email.toLowerCase() if user passOk = await sails.helpers.checkPassword inputs.password, user.password if passOk && user.emailStatus == 'confirmed' if inputs.rememberMe if this.req.isSocket sails.log.warn 'Received `rememberMe: true` from a virtual request, but it was ignored\n because a browser\'s session cookie cannot be reset over sockets.\n Please use a traditional HTTP request instead.' else this.req.session.cookie.maxAge = sails.config.custom.rememberMeCookieMaxAge this.req.session.user = user if this.req.wantsJSON || this.req.isSocket exits.success() else if this.req.session.returnTo await sails.helpers.flash this.req, 'User logged in' exits.redirect this.req.session.returnTo else await sails.helpers.flash this.req, 'User logged in' exits.redirect '/' else if passOk token = PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI() await User.update(id: user.id).set emailToken: token, emailExpires: new Date(Date.now() + 24*60*60*1000) # 1 day await sails.helpers.sendEmail.with to: inputs.email subject: 'Confirm Email' template: 'email-verify-account' data: firstName: user.firstName token: token if this.req.wantsJSON || this.req.isSocket exits.success 'Must confirm email' else await sails.helpers.flash this.req, 'Email not yet confirmed. Please check your email and click the link to activate your account', 4000 exits.redirect '/' else fail() else fail()
[ { "context": " 'body': '''\n valid_email(${1:'${2:me@example.com}'});\n '''\n", "end": 312, "score": 0.9997886419296265, "start": 298, "tag": "EMAIL", "value": "me@example.com" } ]
snippets/mail_helper.cson
femi-dd/codeigniter-atom
1
'.source.php': 'Codeigniter Send Mail': 'prefix':'cisendemail' 'body': ''' send_email(${1:'${2:recipient}'}, ${3:'${4:subject'}}, ${5:'${6:message}'}); ''' 'Codeigniter Valid Email': 'prefix':'civalidemail' 'body': ''' valid_email(${1:'${2:me@example.com}'}); '''
83755
'.source.php': 'Codeigniter Send Mail': 'prefix':'cisendemail' 'body': ''' send_email(${1:'${2:recipient}'}, ${3:'${4:subject'}}, ${5:'${6:message}'}); ''' 'Codeigniter Valid Email': 'prefix':'civalidemail' 'body': ''' valid_email(${1:'${2:<EMAIL>}'}); '''
true
'.source.php': 'Codeigniter Send Mail': 'prefix':'cisendemail' 'body': ''' send_email(${1:'${2:recipient}'}, ${3:'${4:subject'}}, ${5:'${6:message}'}); ''' 'Codeigniter Valid Email': 'prefix':'civalidemail' 'body': ''' valid_email(${1:'${2:PI:EMAIL:<EMAIL>END_PI}'}); '''
[ { "context": "##\n##\n## Forked from Jeff Mott's CryptoJS\n##\n## https://code.google.com/p/cryp", "end": 30, "score": 0.999871015548706, "start": 21, "tag": "NAME", "value": "Jeff Mott" } ]
node_modules/triplesec/src/wordarray.iced
seekersapp2013/new
151
## ## ## Forked from Jeff Mott's CryptoJS ## ## https://code.google.com/p/crypto-js/ ## util = require './util' #======================================================================= buffer_to_ui8a = (b) -> ret = new Uint8Array b.length for i in [0...b.length] ret[i] = b.readUInt8(i) ret #---------- ui8a_to_buffer = (v) -> ret = new Buffer v.length for i in [0...v.length] ret.writeUInt8(v[i], i) ret #---------- endian_reverse = (x) -> ((x >>> 24) & 0xff) | (((x >>> 16) & 0xff) << 8) | (((x >>> 8) & 0xff) << 16) | ((x & 0xff) << 24) #======================================================================= exports.WordArray = class WordArray # Initializes a newly created word array. # # @param {Array} words (Optional) An array of 32-bit words. # @param {number} sigBytes (Optional) The number of significant bytes in the words. # # @example # # wordArray = new WordArray # wordArray = new WordArray [0x00010203, 0x04050607] # wordArray = new WordArray [0x00010203, 0x04050607], 6 # constructor : (words, sigBytes) -> @words = words || [] @sigBytes = if sigBytes? then sigBytes else @words.length * 4 # # Concatenates a word array to this word array. # # @param {WordArray} wordArray The word array to append. # # @return {WordArray} This word array. # # @example # # wordArray1.concat(wordArray2) # concat : (wordArray) -> # Shortcuts thatWords = wordArray.words; thatSigBytes = wordArray.sigBytes; # Clamp excess bits @clamp() # Concat if @sigBytes % 4 # Copy one byte at a time for i in [0...thatSigBytes] thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff @words[(@sigBytes + i) >>> 2] |= thatByte << (24 - ((@sigBytes + i) % 4) * 8) else @words = @words.concat thatWords @sigBytes += thatSigBytes @ # # Removes insignificant bits. # clamp : -> @words[@sigBytes >>> 2] &= 0xffffffff << (32 - (@sigBytes % 4) * 8); @words.length = Math.ceil(@sigBytes / 4) @ # # Creates a copy of this word array. # # @return {WordArray} The clone. # clone : -> new WordArray @words[0...], @sigBytes #-------------- to_buffer : () -> out = new Buffer @sigBytes p = 0 for w in @words when (@sigBytes - p) >= 4 w = util.fixup_uint32 w out.writeUInt32BE w, p p += 4 while p < @sigBytes ch = (@words[p >>> 2] >>> (24 - (p % 4) * 8)) & 0xff out.writeUInt8 ch, p p++ out #-------------- endian_reverse : () -> for w,i in @words @words[i] = endian_reverse w @ #-------------- # Split the word array into n slices # Don't be too smart about slicing in between words, just puke if we can't make it work. split : (n) -> throw new Error "bad key alignment" unless ((@sigBytes % 4) is 0) and ((@words.length % n) is 0) sz = @words.length / n out = (new WordArray @words[i...(i+sz)] for i in [0...@words.length] by sz) out #-------------- to_utf8 : () -> @to_buffer().toString 'utf8' to_hex : () -> @to_buffer().toString 'hex' to_ui8a : () -> buffer_to_ui8a @to_buffer() #-------------- # Be somewhat flexible. Try either a Buffer or maybe it's already # a word array @alloc : (b) -> if Buffer.isBuffer(b) then WordArray.from_buffer b else if (typeof(b) is 'object') and (b instanceof WordArray) then b else if typeof(b) is 'string' then WordArray.from_hex b else null #-------------- @from_buffer : (b) -> words = [] p = 0 while (b.length - p) >= 4 words.push b.readUInt32BE p p += 4 if p < b.length last = 0 while p < b.length ch = b.readUInt8 p last |= (ch << (24 - (p%4) * 8)) p++ last = util.fixup_uint32 last words.push last new WordArray words, b.length #-------------- @from_buffer_le : (b) -> words = [] p = 0 while (b.length - p) >= 4 words.push b.readUInt32LE p p += 4 if p < b.length last = 0 while p < b.length ch = b.readUInt8 p last |= (ch << ((p%4) * 8)) p++ last = util.fixup_uint32 last words.push last new WordArray words, b.length #-------------- @from_utf8 : (s) -> WordArray.from_buffer new Buffer(s, 'utf8') @from_utf8_le : (s) -> WordArray.from_buffer_le new Buffer(s, 'utf8') @from_hex : (s) -> WordArray.from_buffer new Buffer(s, 'hex') @from_hex_le : (s) -> WordArray.from_buffer_le new Buffer(s, 'hex') @from_ui8a : (v) -> WordArray.from_buffer ui8a_to_buffer(v) @from_i32a : (v) -> new WordArray(Array.apply([], v)) #-------------- # Important! Don't short-circuit since that enables a # forging attack.... equal : (wa) -> ret = true if wa.sigBytes isnt @sigBytes then ret = false else for w,i in @words ret = false unless util.fixup_uint32(w) is util.fixup_uint32(wa.words[i]) ret #-------------- xor : (wa2, { dst_offset, src_offset, n_words } ) -> dst_offset = 0 unless dst_offset src_offset = 0 unless src_offset n_words = wa2.words.length - src_offset unless n_words? if @words.length < dst_offset + n_words throw new Error "dest range exceeded (#{@words.length} < #{dst_offset + n_words})" if wa2.words.length < src_offset + n_words throw new Error "source range exceeded" for i in [0...n_words] tmp = @words[dst_offset + i] ^ wa2.words[src_offset + i] @words[dst_offset+i] = util.fixup_uint32 tmp @ #-------------- truncate : (n_bytes) -> throw new Error "Cannot truncate: #{n_bytes} > #{@sigBytes}" unless n_bytes <= @sigBytes n_words = Math.ceil(n_bytes/4) new WordArray @words[0...n_words], n_bytes #-------------- unshift : (n_words) -> if @words.length >= n_words ret = @words.splice 0, n_words @sigBytes -= n_words*4 new WordArray ret else null #-------------- is_scrubbed : () -> for w in @words when w isnt 0 return false true #-------------- scrub : () -> util.scrub_vec @words # Compare for ordering when both are considered as unsigned big-endian integers. # Return -1 if @ is less than b2. # Return 1 if @ if greater than b2 # Return 0 if equal # Assumes two clamped buffers cmp_ule : (wa2) -> util.buffer_cmp_ule @to_buffer(), wa2.to_buffer() #-------------- # @param{number} low The low word to include in the output slice # @param{number} hi The hi word to include in the output slice (exclusive) slice : (low, hi) -> n = @words.length unless (low < hi) and (hi <= n) throw new Error "Bad WordArray slice [#{low},#{hi})] when only #{n} avail" sb = (hi - low)*4 if hi is n then sb -= (n*4 - @sigBytes) new WordArray @words[low...hi], sb #======================================================================= exports.X64Word = class X64Word constructor : (@high, @low) -> clone : -> new X64Word @high, @low #======================================================================= # An array of 64-bit words # @property {Array} words The array of CryptoJS.x64.Word objects. # @property {number} sigBytes The number of significant bytes in this word array. exports.X64WordArray = class X64WordArray # # @param {array} words (optional) an array of X64Word objects. # @param {number} sigbytes (optional) the number of significant bytes in the words. # # @example # # wordarray = new X64WordArray() # # wordarray = new X64WordArray([ # new X64Word(0x00010203, 0x04050607), # new X64Word (0x18191a1b, 0x1c1d1e1f) # ]) # wordarray = new X64WordArray([ # new X64Word(0x00010203, 0x04050607), # new X64Word (0x18191a1b, 0x1c1d1e1f) # ],10) # # constructor : (words, @sigBytes) -> @words = words or [] @sigBytes = @words.length * 8 unless @sigBytes # # Converts this 64-bit word array to a 32-bit word array. # # @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. # toX32 : -> v = [] for w in @words v.push w.high v.push w.low new WordArray v, @sigBytes clone : -> new X64WordArray (w.clone() for w in @words), @sigBytes #======================================================================= exports.buffer_to_ui8a = buffer_to_ui8a exports.ui8a_to_buffer = ui8a_to_buffer exports.endian_reverse = endian_reverse #=======================================================================
179080
## ## ## Forked from <NAME>'s CryptoJS ## ## https://code.google.com/p/crypto-js/ ## util = require './util' #======================================================================= buffer_to_ui8a = (b) -> ret = new Uint8Array b.length for i in [0...b.length] ret[i] = b.readUInt8(i) ret #---------- ui8a_to_buffer = (v) -> ret = new Buffer v.length for i in [0...v.length] ret.writeUInt8(v[i], i) ret #---------- endian_reverse = (x) -> ((x >>> 24) & 0xff) | (((x >>> 16) & 0xff) << 8) | (((x >>> 8) & 0xff) << 16) | ((x & 0xff) << 24) #======================================================================= exports.WordArray = class WordArray # Initializes a newly created word array. # # @param {Array} words (Optional) An array of 32-bit words. # @param {number} sigBytes (Optional) The number of significant bytes in the words. # # @example # # wordArray = new WordArray # wordArray = new WordArray [0x00010203, 0x04050607] # wordArray = new WordArray [0x00010203, 0x04050607], 6 # constructor : (words, sigBytes) -> @words = words || [] @sigBytes = if sigBytes? then sigBytes else @words.length * 4 # # Concatenates a word array to this word array. # # @param {WordArray} wordArray The word array to append. # # @return {WordArray} This word array. # # @example # # wordArray1.concat(wordArray2) # concat : (wordArray) -> # Shortcuts thatWords = wordArray.words; thatSigBytes = wordArray.sigBytes; # Clamp excess bits @clamp() # Concat if @sigBytes % 4 # Copy one byte at a time for i in [0...thatSigBytes] thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff @words[(@sigBytes + i) >>> 2] |= thatByte << (24 - ((@sigBytes + i) % 4) * 8) else @words = @words.concat thatWords @sigBytes += thatSigBytes @ # # Removes insignificant bits. # clamp : -> @words[@sigBytes >>> 2] &= 0xffffffff << (32 - (@sigBytes % 4) * 8); @words.length = Math.ceil(@sigBytes / 4) @ # # Creates a copy of this word array. # # @return {WordArray} The clone. # clone : -> new WordArray @words[0...], @sigBytes #-------------- to_buffer : () -> out = new Buffer @sigBytes p = 0 for w in @words when (@sigBytes - p) >= 4 w = util.fixup_uint32 w out.writeUInt32BE w, p p += 4 while p < @sigBytes ch = (@words[p >>> 2] >>> (24 - (p % 4) * 8)) & 0xff out.writeUInt8 ch, p p++ out #-------------- endian_reverse : () -> for w,i in @words @words[i] = endian_reverse w @ #-------------- # Split the word array into n slices # Don't be too smart about slicing in between words, just puke if we can't make it work. split : (n) -> throw new Error "bad key alignment" unless ((@sigBytes % 4) is 0) and ((@words.length % n) is 0) sz = @words.length / n out = (new WordArray @words[i...(i+sz)] for i in [0...@words.length] by sz) out #-------------- to_utf8 : () -> @to_buffer().toString 'utf8' to_hex : () -> @to_buffer().toString 'hex' to_ui8a : () -> buffer_to_ui8a @to_buffer() #-------------- # Be somewhat flexible. Try either a Buffer or maybe it's already # a word array @alloc : (b) -> if Buffer.isBuffer(b) then WordArray.from_buffer b else if (typeof(b) is 'object') and (b instanceof WordArray) then b else if typeof(b) is 'string' then WordArray.from_hex b else null #-------------- @from_buffer : (b) -> words = [] p = 0 while (b.length - p) >= 4 words.push b.readUInt32BE p p += 4 if p < b.length last = 0 while p < b.length ch = b.readUInt8 p last |= (ch << (24 - (p%4) * 8)) p++ last = util.fixup_uint32 last words.push last new WordArray words, b.length #-------------- @from_buffer_le : (b) -> words = [] p = 0 while (b.length - p) >= 4 words.push b.readUInt32LE p p += 4 if p < b.length last = 0 while p < b.length ch = b.readUInt8 p last |= (ch << ((p%4) * 8)) p++ last = util.fixup_uint32 last words.push last new WordArray words, b.length #-------------- @from_utf8 : (s) -> WordArray.from_buffer new Buffer(s, 'utf8') @from_utf8_le : (s) -> WordArray.from_buffer_le new Buffer(s, 'utf8') @from_hex : (s) -> WordArray.from_buffer new Buffer(s, 'hex') @from_hex_le : (s) -> WordArray.from_buffer_le new Buffer(s, 'hex') @from_ui8a : (v) -> WordArray.from_buffer ui8a_to_buffer(v) @from_i32a : (v) -> new WordArray(Array.apply([], v)) #-------------- # Important! Don't short-circuit since that enables a # forging attack.... equal : (wa) -> ret = true if wa.sigBytes isnt @sigBytes then ret = false else for w,i in @words ret = false unless util.fixup_uint32(w) is util.fixup_uint32(wa.words[i]) ret #-------------- xor : (wa2, { dst_offset, src_offset, n_words } ) -> dst_offset = 0 unless dst_offset src_offset = 0 unless src_offset n_words = wa2.words.length - src_offset unless n_words? if @words.length < dst_offset + n_words throw new Error "dest range exceeded (#{@words.length} < #{dst_offset + n_words})" if wa2.words.length < src_offset + n_words throw new Error "source range exceeded" for i in [0...n_words] tmp = @words[dst_offset + i] ^ wa2.words[src_offset + i] @words[dst_offset+i] = util.fixup_uint32 tmp @ #-------------- truncate : (n_bytes) -> throw new Error "Cannot truncate: #{n_bytes} > #{@sigBytes}" unless n_bytes <= @sigBytes n_words = Math.ceil(n_bytes/4) new WordArray @words[0...n_words], n_bytes #-------------- unshift : (n_words) -> if @words.length >= n_words ret = @words.splice 0, n_words @sigBytes -= n_words*4 new WordArray ret else null #-------------- is_scrubbed : () -> for w in @words when w isnt 0 return false true #-------------- scrub : () -> util.scrub_vec @words # Compare for ordering when both are considered as unsigned big-endian integers. # Return -1 if @ is less than b2. # Return 1 if @ if greater than b2 # Return 0 if equal # Assumes two clamped buffers cmp_ule : (wa2) -> util.buffer_cmp_ule @to_buffer(), wa2.to_buffer() #-------------- # @param{number} low The low word to include in the output slice # @param{number} hi The hi word to include in the output slice (exclusive) slice : (low, hi) -> n = @words.length unless (low < hi) and (hi <= n) throw new Error "Bad WordArray slice [#{low},#{hi})] when only #{n} avail" sb = (hi - low)*4 if hi is n then sb -= (n*4 - @sigBytes) new WordArray @words[low...hi], sb #======================================================================= exports.X64Word = class X64Word constructor : (@high, @low) -> clone : -> new X64Word @high, @low #======================================================================= # An array of 64-bit words # @property {Array} words The array of CryptoJS.x64.Word objects. # @property {number} sigBytes The number of significant bytes in this word array. exports.X64WordArray = class X64WordArray # # @param {array} words (optional) an array of X64Word objects. # @param {number} sigbytes (optional) the number of significant bytes in the words. # # @example # # wordarray = new X64WordArray() # # wordarray = new X64WordArray([ # new X64Word(0x00010203, 0x04050607), # new X64Word (0x18191a1b, 0x1c1d1e1f) # ]) # wordarray = new X64WordArray([ # new X64Word(0x00010203, 0x04050607), # new X64Word (0x18191a1b, 0x1c1d1e1f) # ],10) # # constructor : (words, @sigBytes) -> @words = words or [] @sigBytes = @words.length * 8 unless @sigBytes # # Converts this 64-bit word array to a 32-bit word array. # # @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. # toX32 : -> v = [] for w in @words v.push w.high v.push w.low new WordArray v, @sigBytes clone : -> new X64WordArray (w.clone() for w in @words), @sigBytes #======================================================================= exports.buffer_to_ui8a = buffer_to_ui8a exports.ui8a_to_buffer = ui8a_to_buffer exports.endian_reverse = endian_reverse #=======================================================================
true
## ## ## Forked from PI:NAME:<NAME>END_PI's CryptoJS ## ## https://code.google.com/p/crypto-js/ ## util = require './util' #======================================================================= buffer_to_ui8a = (b) -> ret = new Uint8Array b.length for i in [0...b.length] ret[i] = b.readUInt8(i) ret #---------- ui8a_to_buffer = (v) -> ret = new Buffer v.length for i in [0...v.length] ret.writeUInt8(v[i], i) ret #---------- endian_reverse = (x) -> ((x >>> 24) & 0xff) | (((x >>> 16) & 0xff) << 8) | (((x >>> 8) & 0xff) << 16) | ((x & 0xff) << 24) #======================================================================= exports.WordArray = class WordArray # Initializes a newly created word array. # # @param {Array} words (Optional) An array of 32-bit words. # @param {number} sigBytes (Optional) The number of significant bytes in the words. # # @example # # wordArray = new WordArray # wordArray = new WordArray [0x00010203, 0x04050607] # wordArray = new WordArray [0x00010203, 0x04050607], 6 # constructor : (words, sigBytes) -> @words = words || [] @sigBytes = if sigBytes? then sigBytes else @words.length * 4 # # Concatenates a word array to this word array. # # @param {WordArray} wordArray The word array to append. # # @return {WordArray} This word array. # # @example # # wordArray1.concat(wordArray2) # concat : (wordArray) -> # Shortcuts thatWords = wordArray.words; thatSigBytes = wordArray.sigBytes; # Clamp excess bits @clamp() # Concat if @sigBytes % 4 # Copy one byte at a time for i in [0...thatSigBytes] thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff @words[(@sigBytes + i) >>> 2] |= thatByte << (24 - ((@sigBytes + i) % 4) * 8) else @words = @words.concat thatWords @sigBytes += thatSigBytes @ # # Removes insignificant bits. # clamp : -> @words[@sigBytes >>> 2] &= 0xffffffff << (32 - (@sigBytes % 4) * 8); @words.length = Math.ceil(@sigBytes / 4) @ # # Creates a copy of this word array. # # @return {WordArray} The clone. # clone : -> new WordArray @words[0...], @sigBytes #-------------- to_buffer : () -> out = new Buffer @sigBytes p = 0 for w in @words when (@sigBytes - p) >= 4 w = util.fixup_uint32 w out.writeUInt32BE w, p p += 4 while p < @sigBytes ch = (@words[p >>> 2] >>> (24 - (p % 4) * 8)) & 0xff out.writeUInt8 ch, p p++ out #-------------- endian_reverse : () -> for w,i in @words @words[i] = endian_reverse w @ #-------------- # Split the word array into n slices # Don't be too smart about slicing in between words, just puke if we can't make it work. split : (n) -> throw new Error "bad key alignment" unless ((@sigBytes % 4) is 0) and ((@words.length % n) is 0) sz = @words.length / n out = (new WordArray @words[i...(i+sz)] for i in [0...@words.length] by sz) out #-------------- to_utf8 : () -> @to_buffer().toString 'utf8' to_hex : () -> @to_buffer().toString 'hex' to_ui8a : () -> buffer_to_ui8a @to_buffer() #-------------- # Be somewhat flexible. Try either a Buffer or maybe it's already # a word array @alloc : (b) -> if Buffer.isBuffer(b) then WordArray.from_buffer b else if (typeof(b) is 'object') and (b instanceof WordArray) then b else if typeof(b) is 'string' then WordArray.from_hex b else null #-------------- @from_buffer : (b) -> words = [] p = 0 while (b.length - p) >= 4 words.push b.readUInt32BE p p += 4 if p < b.length last = 0 while p < b.length ch = b.readUInt8 p last |= (ch << (24 - (p%4) * 8)) p++ last = util.fixup_uint32 last words.push last new WordArray words, b.length #-------------- @from_buffer_le : (b) -> words = [] p = 0 while (b.length - p) >= 4 words.push b.readUInt32LE p p += 4 if p < b.length last = 0 while p < b.length ch = b.readUInt8 p last |= (ch << ((p%4) * 8)) p++ last = util.fixup_uint32 last words.push last new WordArray words, b.length #-------------- @from_utf8 : (s) -> WordArray.from_buffer new Buffer(s, 'utf8') @from_utf8_le : (s) -> WordArray.from_buffer_le new Buffer(s, 'utf8') @from_hex : (s) -> WordArray.from_buffer new Buffer(s, 'hex') @from_hex_le : (s) -> WordArray.from_buffer_le new Buffer(s, 'hex') @from_ui8a : (v) -> WordArray.from_buffer ui8a_to_buffer(v) @from_i32a : (v) -> new WordArray(Array.apply([], v)) #-------------- # Important! Don't short-circuit since that enables a # forging attack.... equal : (wa) -> ret = true if wa.sigBytes isnt @sigBytes then ret = false else for w,i in @words ret = false unless util.fixup_uint32(w) is util.fixup_uint32(wa.words[i]) ret #-------------- xor : (wa2, { dst_offset, src_offset, n_words } ) -> dst_offset = 0 unless dst_offset src_offset = 0 unless src_offset n_words = wa2.words.length - src_offset unless n_words? if @words.length < dst_offset + n_words throw new Error "dest range exceeded (#{@words.length} < #{dst_offset + n_words})" if wa2.words.length < src_offset + n_words throw new Error "source range exceeded" for i in [0...n_words] tmp = @words[dst_offset + i] ^ wa2.words[src_offset + i] @words[dst_offset+i] = util.fixup_uint32 tmp @ #-------------- truncate : (n_bytes) -> throw new Error "Cannot truncate: #{n_bytes} > #{@sigBytes}" unless n_bytes <= @sigBytes n_words = Math.ceil(n_bytes/4) new WordArray @words[0...n_words], n_bytes #-------------- unshift : (n_words) -> if @words.length >= n_words ret = @words.splice 0, n_words @sigBytes -= n_words*4 new WordArray ret else null #-------------- is_scrubbed : () -> for w in @words when w isnt 0 return false true #-------------- scrub : () -> util.scrub_vec @words # Compare for ordering when both are considered as unsigned big-endian integers. # Return -1 if @ is less than b2. # Return 1 if @ if greater than b2 # Return 0 if equal # Assumes two clamped buffers cmp_ule : (wa2) -> util.buffer_cmp_ule @to_buffer(), wa2.to_buffer() #-------------- # @param{number} low The low word to include in the output slice # @param{number} hi The hi word to include in the output slice (exclusive) slice : (low, hi) -> n = @words.length unless (low < hi) and (hi <= n) throw new Error "Bad WordArray slice [#{low},#{hi})] when only #{n} avail" sb = (hi - low)*4 if hi is n then sb -= (n*4 - @sigBytes) new WordArray @words[low...hi], sb #======================================================================= exports.X64Word = class X64Word constructor : (@high, @low) -> clone : -> new X64Word @high, @low #======================================================================= # An array of 64-bit words # @property {Array} words The array of CryptoJS.x64.Word objects. # @property {number} sigBytes The number of significant bytes in this word array. exports.X64WordArray = class X64WordArray # # @param {array} words (optional) an array of X64Word objects. # @param {number} sigbytes (optional) the number of significant bytes in the words. # # @example # # wordarray = new X64WordArray() # # wordarray = new X64WordArray([ # new X64Word(0x00010203, 0x04050607), # new X64Word (0x18191a1b, 0x1c1d1e1f) # ]) # wordarray = new X64WordArray([ # new X64Word(0x00010203, 0x04050607), # new X64Word (0x18191a1b, 0x1c1d1e1f) # ],10) # # constructor : (words, @sigBytes) -> @words = words or [] @sigBytes = @words.length * 8 unless @sigBytes # # Converts this 64-bit word array to a 32-bit word array. # # @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. # toX32 : -> v = [] for w in @words v.push w.high v.push w.low new WordArray v, @sigBytes clone : -> new X64WordArray (w.clone() for w in @words), @sigBytes #======================================================================= exports.buffer_to_ui8a = buffer_to_ui8a exports.ui8a_to_buffer = ui8a_to_buffer exports.endian_reverse = endian_reverse #=======================================================================
[ { "context": ".DesignerNews extends Columns.FeedColumn\n name: \"DesignerNews\"\n width: 1\n thumb: \"img/column-designernews.png", "end": 75, "score": 0.807325541973114, "start": 63, "tag": "NAME", "value": "DesignerNews" } ]
src/columns/designernews/DesignerNews.coffee
jariz/hackertab
548
class Columns.DesignerNews extends Columns.FeedColumn name: "DesignerNews" width: 1 thumb: "img/column-designernews.png" link: "https://www.designernews.co/" url: "https://api.designernews.co/api/v2/stories/" element: "dn-item" dataPath: "stories" tabbie.register "DesignerNews"
194703
class Columns.DesignerNews extends Columns.FeedColumn name: "<NAME>" width: 1 thumb: "img/column-designernews.png" link: "https://www.designernews.co/" url: "https://api.designernews.co/api/v2/stories/" element: "dn-item" dataPath: "stories" tabbie.register "DesignerNews"
true
class Columns.DesignerNews extends Columns.FeedColumn name: "PI:NAME:<NAME>END_PI" width: 1 thumb: "img/column-designernews.png" link: "https://www.designernews.co/" url: "https://api.designernews.co/api/v2/stories/" element: "dn-item" dataPath: "stories" tabbie.register "DesignerNews"
[ { "context": "# @author mr.doob / http://mrdoob.com/\n# @author kile / http://kile", "end": 17, "score": 0.9616553783416748, "start": 10, "tag": "NAME", "value": "mr.doob" }, { "context": "# @author mr.doob / http://mrdoob.com/\n# @author kile / http://kile.stravaganza.org/\n# @author philogb ", "end": 53, "score": 0.951265275478363, "start": 49, "tag": "USERNAME", "value": "kile" }, { "context": "thor kile / http://kile.stravaganza.org/\n# @author philogb / http://blog.thejit.org/\n# @author mikael emting", "end": 102, "score": 0.9977617859840393, "start": 95, "tag": "USERNAME", "value": "philogb" }, { "context": "author philogb / http://blog.thejit.org/\n# @author mikael emtinger / http://gomo.se/\n# @author egraether / http://eg", "end": 154, "score": 0.9998525977134705, "start": 139, "tag": "NAME", "value": "mikael emtinger" }, { "context": "author mikael emtinger / http://gomo.se/\n# @author egraether / http://egraether.com/\n# @author aladjev.andrew@", "end": 192, "score": 0.9967466592788696, "start": 183, "tag": "USERNAME", "value": "egraether" }, { "context": "author egraether / http://egraether.com/\n# @author aladjev.andrew@gmail.com\n\nclass Vector3\n constructor: (x, y, z) ->\n @x", "end": 251, "score": 0.9999174475669861, "start": 227, "tag": "EMAIL", "value": "aladjev.andrew@gmail.com" } ]
source/javascripts/new_src/core/vector_3.coffee
andrew-aladev/three.js
0
# @author mr.doob / http://mrdoob.com/ # @author kile / http://kile.stravaganza.org/ # @author philogb / http://blog.thejit.org/ # @author mikael emtinger / http://gomo.se/ # @author egraether / http://egraether.com/ # @author aladjev.andrew@gmail.com class Vector3 constructor: (x, y, z) -> @x = x or 0 @y = y or 0 @z = z or 0 set: (x, y, z) -> @x = x @y = y @z = z this setX: (x) -> @x = x this setY: (y) -> @y = y this setZ: (z) -> @z = z this copy: (v) -> @x = v.x @y = v.y @z = v.z this add: (a, b) -> @x = a.x + b.x @y = a.y + b.y @z = a.z + b.z this addSelf: (v) -> @x += v.x @y += v.y @z += v.z this addScalar: (s) -> @x += s @y += s @z += s this sub: (a, b) -> @x = a.x - b.x @y = a.y - b.y @z = a.z - b.z this subSelf: (v) -> @x -= v.x @y -= v.y @z -= v.z this multiply: (a, b) -> @x = a.x * b.x @y = a.y * b.y @z = a.z * b.z this multiplySelf: (v) -> @x *= v.x @y *= v.y @z *= v.z this multiplyScalar: (s) -> @x *= s @y *= s @z *= s this divideSelf: (v) -> @x /= v.x @y /= v.y @z /= v.z this divideScalar: (s) -> if s @x /= s @y /= s @z /= s else @x = 0 @y = 0 @z = 0 this negate: -> @multiplyScalar -1 dot: (v) -> @x * v.x + @y * v.y + @z * v.z lengthSq: -> @x * @x + @y * @y + @z * @z length: -> Math.sqrt @lengthSq() lengthManhattan: -> Math.abs(@x) + Math.abs(@y) + Math.abs(@z) normalize: -> @divideScalar @length() setLength: (l) -> @normalize().multiplyScalar l lerpSelf: (v, alpha) -> @x += (v.x - @x) * alpha @y += (v.y - @y) * alpha @z += (v.z - @z) * alpha this cross: (a, b) -> @x = a.y * b.z - a.z * b.y @y = a.z * b.x - a.x * b.z @z = a.x * b.y - a.y * b.x this crossSelf: (v) -> x = @x y = @y z = @z @x = y * v.z - z * v.y @y = z * v.x - x * v.z @z = x * v.y - y * v.x this distanceTo: (v) -> Math.sqrt @distanceToSquared(v) distanceToSquared: (v) -> new Vector3().sub(this, v).lengthSq() getPositionFromMatrix: (m) -> @x = m.elements[12] @y = m.elements[13] @z = m.elements[14] this getRotationFromMatrix: (m, scale) -> sx = (if scale then scale.x else 1) sy = (if scale then scale.y else 1) sz = (if scale then scale.z else 1) m11 = m.elements[0] / sx m12 = m.elements[4] / sy m13 = m.elements[8] / sz m21 = m.elements[1] / sx m22 = m.elements[5] / sy m23 = m.elements[9] / sz m33 = m.elements[10] / sz @y = Math.asin(m13) cosY = Math.cos(@y) if Math.abs(cosY) > 0.00001 @x = Math.atan2(-m23 / cosY, m33 / cosY) @z = Math.atan2(-m12 / cosY, m11 / cosY) else @x = 0 @z = Math.atan2(m21, m22) this getScaleFromMatrix: (m) -> sx = @set(m.elements[0], m.elements[1], m.elements[2]).length() sy = @set(m.elements[4], m.elements[5], m.elements[6]).length() sz = @set(m.elements[8], m.elements[9], m.elements[10]).length() @x = sx @y = sy @z = sz equals: (v) -> (v.x is @x) and (v.y is @y) and (v.z is @z) isZero: -> @lengthSq() < 0.0001 # almostZero clone: -> new Vector3 @x, @y, @z namespace "THREE", (exports) -> exports.Vector3 = Vector3
164517
# @author <NAME> / http://mrdoob.com/ # @author kile / http://kile.stravaganza.org/ # @author philogb / http://blog.thejit.org/ # @author <NAME> / http://gomo.se/ # @author egraether / http://egraether.com/ # @author <EMAIL> class Vector3 constructor: (x, y, z) -> @x = x or 0 @y = y or 0 @z = z or 0 set: (x, y, z) -> @x = x @y = y @z = z this setX: (x) -> @x = x this setY: (y) -> @y = y this setZ: (z) -> @z = z this copy: (v) -> @x = v.x @y = v.y @z = v.z this add: (a, b) -> @x = a.x + b.x @y = a.y + b.y @z = a.z + b.z this addSelf: (v) -> @x += v.x @y += v.y @z += v.z this addScalar: (s) -> @x += s @y += s @z += s this sub: (a, b) -> @x = a.x - b.x @y = a.y - b.y @z = a.z - b.z this subSelf: (v) -> @x -= v.x @y -= v.y @z -= v.z this multiply: (a, b) -> @x = a.x * b.x @y = a.y * b.y @z = a.z * b.z this multiplySelf: (v) -> @x *= v.x @y *= v.y @z *= v.z this multiplyScalar: (s) -> @x *= s @y *= s @z *= s this divideSelf: (v) -> @x /= v.x @y /= v.y @z /= v.z this divideScalar: (s) -> if s @x /= s @y /= s @z /= s else @x = 0 @y = 0 @z = 0 this negate: -> @multiplyScalar -1 dot: (v) -> @x * v.x + @y * v.y + @z * v.z lengthSq: -> @x * @x + @y * @y + @z * @z length: -> Math.sqrt @lengthSq() lengthManhattan: -> Math.abs(@x) + Math.abs(@y) + Math.abs(@z) normalize: -> @divideScalar @length() setLength: (l) -> @normalize().multiplyScalar l lerpSelf: (v, alpha) -> @x += (v.x - @x) * alpha @y += (v.y - @y) * alpha @z += (v.z - @z) * alpha this cross: (a, b) -> @x = a.y * b.z - a.z * b.y @y = a.z * b.x - a.x * b.z @z = a.x * b.y - a.y * b.x this crossSelf: (v) -> x = @x y = @y z = @z @x = y * v.z - z * v.y @y = z * v.x - x * v.z @z = x * v.y - y * v.x this distanceTo: (v) -> Math.sqrt @distanceToSquared(v) distanceToSquared: (v) -> new Vector3().sub(this, v).lengthSq() getPositionFromMatrix: (m) -> @x = m.elements[12] @y = m.elements[13] @z = m.elements[14] this getRotationFromMatrix: (m, scale) -> sx = (if scale then scale.x else 1) sy = (if scale then scale.y else 1) sz = (if scale then scale.z else 1) m11 = m.elements[0] / sx m12 = m.elements[4] / sy m13 = m.elements[8] / sz m21 = m.elements[1] / sx m22 = m.elements[5] / sy m23 = m.elements[9] / sz m33 = m.elements[10] / sz @y = Math.asin(m13) cosY = Math.cos(@y) if Math.abs(cosY) > 0.00001 @x = Math.atan2(-m23 / cosY, m33 / cosY) @z = Math.atan2(-m12 / cosY, m11 / cosY) else @x = 0 @z = Math.atan2(m21, m22) this getScaleFromMatrix: (m) -> sx = @set(m.elements[0], m.elements[1], m.elements[2]).length() sy = @set(m.elements[4], m.elements[5], m.elements[6]).length() sz = @set(m.elements[8], m.elements[9], m.elements[10]).length() @x = sx @y = sy @z = sz equals: (v) -> (v.x is @x) and (v.y is @y) and (v.z is @z) isZero: -> @lengthSq() < 0.0001 # almostZero clone: -> new Vector3 @x, @y, @z namespace "THREE", (exports) -> exports.Vector3 = Vector3
true
# @author PI:NAME:<NAME>END_PI / http://mrdoob.com/ # @author kile / http://kile.stravaganza.org/ # @author philogb / http://blog.thejit.org/ # @author PI:NAME:<NAME>END_PI / http://gomo.se/ # @author egraether / http://egraether.com/ # @author PI:EMAIL:<EMAIL>END_PI class Vector3 constructor: (x, y, z) -> @x = x or 0 @y = y or 0 @z = z or 0 set: (x, y, z) -> @x = x @y = y @z = z this setX: (x) -> @x = x this setY: (y) -> @y = y this setZ: (z) -> @z = z this copy: (v) -> @x = v.x @y = v.y @z = v.z this add: (a, b) -> @x = a.x + b.x @y = a.y + b.y @z = a.z + b.z this addSelf: (v) -> @x += v.x @y += v.y @z += v.z this addScalar: (s) -> @x += s @y += s @z += s this sub: (a, b) -> @x = a.x - b.x @y = a.y - b.y @z = a.z - b.z this subSelf: (v) -> @x -= v.x @y -= v.y @z -= v.z this multiply: (a, b) -> @x = a.x * b.x @y = a.y * b.y @z = a.z * b.z this multiplySelf: (v) -> @x *= v.x @y *= v.y @z *= v.z this multiplyScalar: (s) -> @x *= s @y *= s @z *= s this divideSelf: (v) -> @x /= v.x @y /= v.y @z /= v.z this divideScalar: (s) -> if s @x /= s @y /= s @z /= s else @x = 0 @y = 0 @z = 0 this negate: -> @multiplyScalar -1 dot: (v) -> @x * v.x + @y * v.y + @z * v.z lengthSq: -> @x * @x + @y * @y + @z * @z length: -> Math.sqrt @lengthSq() lengthManhattan: -> Math.abs(@x) + Math.abs(@y) + Math.abs(@z) normalize: -> @divideScalar @length() setLength: (l) -> @normalize().multiplyScalar l lerpSelf: (v, alpha) -> @x += (v.x - @x) * alpha @y += (v.y - @y) * alpha @z += (v.z - @z) * alpha this cross: (a, b) -> @x = a.y * b.z - a.z * b.y @y = a.z * b.x - a.x * b.z @z = a.x * b.y - a.y * b.x this crossSelf: (v) -> x = @x y = @y z = @z @x = y * v.z - z * v.y @y = z * v.x - x * v.z @z = x * v.y - y * v.x this distanceTo: (v) -> Math.sqrt @distanceToSquared(v) distanceToSquared: (v) -> new Vector3().sub(this, v).lengthSq() getPositionFromMatrix: (m) -> @x = m.elements[12] @y = m.elements[13] @z = m.elements[14] this getRotationFromMatrix: (m, scale) -> sx = (if scale then scale.x else 1) sy = (if scale then scale.y else 1) sz = (if scale then scale.z else 1) m11 = m.elements[0] / sx m12 = m.elements[4] / sy m13 = m.elements[8] / sz m21 = m.elements[1] / sx m22 = m.elements[5] / sy m23 = m.elements[9] / sz m33 = m.elements[10] / sz @y = Math.asin(m13) cosY = Math.cos(@y) if Math.abs(cosY) > 0.00001 @x = Math.atan2(-m23 / cosY, m33 / cosY) @z = Math.atan2(-m12 / cosY, m11 / cosY) else @x = 0 @z = Math.atan2(m21, m22) this getScaleFromMatrix: (m) -> sx = @set(m.elements[0], m.elements[1], m.elements[2]).length() sy = @set(m.elements[4], m.elements[5], m.elements[6]).length() sz = @set(m.elements[8], m.elements[9], m.elements[10]).length() @x = sx @y = sy @z = sz equals: (v) -> (v.x is @x) and (v.y is @y) and (v.z is @z) isZero: -> @lengthSq() < 0.0001 # almostZero clone: -> new Vector3 @x, @y, @z namespace "THREE", (exports) -> exports.Vector3 = Vector3
[ { "context": "# Paul Rudd isn't a douchebag\n#\n# load up celery man please\n#", "end": 11, "score": 0.9998610615730286, "start": 2, "tag": "NAME", "value": "Paul Rudd" } ]
scripts/celery-man.coffee
RiotGamesMinions/lefay
7
# Paul Rudd isn't a douchebag # # load up celery man please # can i get a printout of oyster smiling? # do we have any new sequences? # can i see a flarhgunnstow? module.exports = (robot) -> robot.respond /load up celery man please/i, (msg) -> msg.send "http://www.simpleindustries.com/wp-content/uploads/2010/05/paul_sequence1.png" robot.respond /.*printout of oyster smiling.*/i, (msg) -> msg.send "http://30.media.tumblr.com/tumblr_lkg4w5D1Gi1qc39ego1_500.jpg" robot.hear /new sequences/i, (msg) -> msg.send "I have a BETA sequence I've been working on. Would you like to see it?" robot.respond /.*hat wobble.*/i, (msg) -> msg.send "Yes.\nhttp://i.imgur.com/4asZA.gif" robot.respond /.*flarhgunnstow.*/i, (msg) -> msg.send "Yes.\nhttp://29.media.tumblr.com/tumblr_l2e4bbhrzl1qzad9ao1_400.gif"
25497
# <NAME> isn't a douchebag # # load up celery man please # can i get a printout of oyster smiling? # do we have any new sequences? # can i see a flarhgunnstow? module.exports = (robot) -> robot.respond /load up celery man please/i, (msg) -> msg.send "http://www.simpleindustries.com/wp-content/uploads/2010/05/paul_sequence1.png" robot.respond /.*printout of oyster smiling.*/i, (msg) -> msg.send "http://30.media.tumblr.com/tumblr_lkg4w5D1Gi1qc39ego1_500.jpg" robot.hear /new sequences/i, (msg) -> msg.send "I have a BETA sequence I've been working on. Would you like to see it?" robot.respond /.*hat wobble.*/i, (msg) -> msg.send "Yes.\nhttp://i.imgur.com/4asZA.gif" robot.respond /.*flarhgunnstow.*/i, (msg) -> msg.send "Yes.\nhttp://29.media.tumblr.com/tumblr_l2e4bbhrzl1qzad9ao1_400.gif"
true
# PI:NAME:<NAME>END_PI isn't a douchebag # # load up celery man please # can i get a printout of oyster smiling? # do we have any new sequences? # can i see a flarhgunnstow? module.exports = (robot) -> robot.respond /load up celery man please/i, (msg) -> msg.send "http://www.simpleindustries.com/wp-content/uploads/2010/05/paul_sequence1.png" robot.respond /.*printout of oyster smiling.*/i, (msg) -> msg.send "http://30.media.tumblr.com/tumblr_lkg4w5D1Gi1qc39ego1_500.jpg" robot.hear /new sequences/i, (msg) -> msg.send "I have a BETA sequence I've been working on. Would you like to see it?" robot.respond /.*hat wobble.*/i, (msg) -> msg.send "Yes.\nhttp://i.imgur.com/4asZA.gif" robot.respond /.*flarhgunnstow.*/i, (msg) -> msg.send "Yes.\nhttp://29.media.tumblr.com/tumblr_l2e4bbhrzl1qzad9ao1_400.gif"
[ { "context": "estore?()\n\n setup = =>\n createUser()\n .then (@currentUser)=>\n createUser\n slackUsername: \"Bob\"\n", "end": 816, "score": 0.9960333108901978, "start": 803, "tag": "USERNAME", "value": "(@currentUser" }, { "context": "tUser)=>\n createUser\n slackUsername: \"Bob\"\n .then (@recipient)=>\n createProject()\n ", "end": 864, "score": 0.997384250164032, "start": 861, "tag": "USERNAME", "value": "Bob" }, { "context": " createUser\n slackUsername: \"Bob\"\n .then (@recipient)=>\n createProject()\n .then (@project)=>\n ", "end": 887, "score": 0.9778760671615601, "start": 876, "tag": "USERNAME", "value": "(@recipient" }, { "context": "ect)\n .then (@rewardType)=>\n currentUser = @currentUser\n recipient = @recipient\n msg = message(", "end": 1052, "score": 0.9958033561706543, "start": 1040, "tag": "USERNAME", "value": "@currentUser" }, { "context": " currentUser = @currentUser\n recipient = @recipient\n msg = message('', {@currentUser})\n con", "end": 1081, "score": 0.9513974189758301, "start": 1071, "tag": "USERNAME", "value": "@recipient" }, { "context": "ageRoom.should.have.been.calledWith(\n \"Bob\",\n \"Congratulations! You have received", "end": 1608, "score": 0.8147484064102173, "start": 1605, "tag": "NAME", "value": "Bob" }, { "context": ".text.should.eq \"Error awarding 'random reward' to Bob. Unable to complete the transaction.\"\n", "end": 2240, "score": 0.98981112241745, "start": 2237, "tag": "NAME", "value": "Bob" } ]
test/controllers/rewards-state-controller-tests.coffee
citizencode/swarmbot
21
{ createUser, createProject, createRewardType, message } = require '../helpers/test-helper' { p, json } = require 'lightsaber' sinon = require 'sinon' RewardsStateController = require '../../src/controllers/rewards-state-controller' User = require '../../src/models/user' Project = require '../../src/models/project' RewardType = require '../../src/models/reward-type' swarmbot = require '../../src/models/swarmbot' describe 'RewardsStateController', -> controller = null currentUser = null recipient = null project = null msg = null rewardType = null beforeEach -> sinon.spy(App, 'pmReply') App.robot = messageRoom: sinon.spy() adapter: { customMessage: sinon.spy() } afterEach -> App.pmReply.restore?() setup = => createUser() .then (@currentUser)=> createUser slackUsername: "Bob" .then (@recipient)=> createProject() .then (@project)=> project = @project createRewardType(@project) .then (@rewardType)=> currentUser = @currentUser recipient = @recipient msg = message('', {@currentUser}) controller = new RewardsStateController(msg) rewardType = @rewardType describe "#sendReward", -> describe "when colu is up", -> it "sends a message to the user and to the room about the transaction", -> setup() .then => controller.sendReward(recipient, rewardType, 111) .then => App.pmReply.getCall(0).args[1].text.should.eq "Reward sent!" App.robot.messageRoom.should.have.been.calledWith( "Bob", "Congratulations! You have received 111 project coins\nhttp://coloredcoins.org/explorer/tx/1234" ) describe "when colu is down", -> beforeEach -> swarmbot.colu.restore?() sinon.stub(swarmbot, 'colu').returns Promise.resolve on: -> init: -> sendAsset: (x, cb)-> throw new Error("bang") issueAsset: -> it "sends error message", -> setup() .then => controller.sendReward(recipient, rewardType, 111) .then => App.pmReply.getCall(0).args[1].text.should.eq "Error awarding 'random reward' to Bob. Unable to complete the transaction."
132925
{ createUser, createProject, createRewardType, message } = require '../helpers/test-helper' { p, json } = require 'lightsaber' sinon = require 'sinon' RewardsStateController = require '../../src/controllers/rewards-state-controller' User = require '../../src/models/user' Project = require '../../src/models/project' RewardType = require '../../src/models/reward-type' swarmbot = require '../../src/models/swarmbot' describe 'RewardsStateController', -> controller = null currentUser = null recipient = null project = null msg = null rewardType = null beforeEach -> sinon.spy(App, 'pmReply') App.robot = messageRoom: sinon.spy() adapter: { customMessage: sinon.spy() } afterEach -> App.pmReply.restore?() setup = => createUser() .then (@currentUser)=> createUser slackUsername: "Bob" .then (@recipient)=> createProject() .then (@project)=> project = @project createRewardType(@project) .then (@rewardType)=> currentUser = @currentUser recipient = @recipient msg = message('', {@currentUser}) controller = new RewardsStateController(msg) rewardType = @rewardType describe "#sendReward", -> describe "when colu is up", -> it "sends a message to the user and to the room about the transaction", -> setup() .then => controller.sendReward(recipient, rewardType, 111) .then => App.pmReply.getCall(0).args[1].text.should.eq "Reward sent!" App.robot.messageRoom.should.have.been.calledWith( "<NAME>", "Congratulations! You have received 111 project coins\nhttp://coloredcoins.org/explorer/tx/1234" ) describe "when colu is down", -> beforeEach -> swarmbot.colu.restore?() sinon.stub(swarmbot, 'colu').returns Promise.resolve on: -> init: -> sendAsset: (x, cb)-> throw new Error("bang") issueAsset: -> it "sends error message", -> setup() .then => controller.sendReward(recipient, rewardType, 111) .then => App.pmReply.getCall(0).args[1].text.should.eq "Error awarding 'random reward' to <NAME>. Unable to complete the transaction."
true
{ createUser, createProject, createRewardType, message } = require '../helpers/test-helper' { p, json } = require 'lightsaber' sinon = require 'sinon' RewardsStateController = require '../../src/controllers/rewards-state-controller' User = require '../../src/models/user' Project = require '../../src/models/project' RewardType = require '../../src/models/reward-type' swarmbot = require '../../src/models/swarmbot' describe 'RewardsStateController', -> controller = null currentUser = null recipient = null project = null msg = null rewardType = null beforeEach -> sinon.spy(App, 'pmReply') App.robot = messageRoom: sinon.spy() adapter: { customMessage: sinon.spy() } afterEach -> App.pmReply.restore?() setup = => createUser() .then (@currentUser)=> createUser slackUsername: "Bob" .then (@recipient)=> createProject() .then (@project)=> project = @project createRewardType(@project) .then (@rewardType)=> currentUser = @currentUser recipient = @recipient msg = message('', {@currentUser}) controller = new RewardsStateController(msg) rewardType = @rewardType describe "#sendReward", -> describe "when colu is up", -> it "sends a message to the user and to the room about the transaction", -> setup() .then => controller.sendReward(recipient, rewardType, 111) .then => App.pmReply.getCall(0).args[1].text.should.eq "Reward sent!" App.robot.messageRoom.should.have.been.calledWith( "PI:NAME:<NAME>END_PI", "Congratulations! You have received 111 project coins\nhttp://coloredcoins.org/explorer/tx/1234" ) describe "when colu is down", -> beforeEach -> swarmbot.colu.restore?() sinon.stub(swarmbot, 'colu').returns Promise.resolve on: -> init: -> sendAsset: (x, cb)-> throw new Error("bang") issueAsset: -> it "sends error message", -> setup() .then => controller.sendReward(recipient, rewardType, 111) .then => App.pmReply.getCall(0).args[1].text.should.eq "Error awarding 'random reward' to PI:NAME:<NAME>END_PI. Unable to complete the transaction."
[ { "context": "counts()\n messaging.accounts.create = (username, password, companyname, phone, address, city, sta", "end": 19178, "score": 0.8256922364234924, "start": 19170, "tag": "USERNAME", "value": "username" }, { "context": "_create._call(messaging, {}, _.defaults({username:username, password:password, companyname:companyname, phon", "end": 19452, "score": 0.9994131326675415, "start": 19444, "tag": "USERNAME", "value": "username" }, { "context": "ging, {}, _.defaults({username:username, password:password, companyname:companyname, phone:phone, address:ad", "end": 19471, "score": 0.9995673298835754, "start": 19463, "tag": "PASSWORD", "value": "password" }, { "context": "Messages\n messaging.accounts.destroy = (username) -> callWithError messaging.accounts._dest", "end": 20202, "score": 0.9084095358848572, "start": 20194, "tag": "USERNAME", "value": "username" }, { "context": "destroy._call(messaging, {}, _.defaults({username:username}, {apikey:messaging.defaults.apikey})), \"accounts", "end": 20306, "score": 0.9981822967529297, "start": 20298, "tag": "USERNAME", "value": "username" } ]
src/dyn-js.coffee
dyninc/dyn-js
6
'use strict' _ = require 'underscore' q = require 'q' https = require 'https' log = require 'npmlog' qs = require 'querystring' _.templateSettings = { interpolate: /\{\{(.+?)\}\}/g } _request_q = (dyn, method, path, body, isTraffic) -> log.verbose 'dyn', "invoking via https : #{method} #{path}" defer = q.defer() cc = (a, b, c) -> log.verbose 'dyn', "invocation returned : #{method} #{path}" if (a != null) return defer.reject.call {}, [a] return defer.resolve.call {}, [a, b, c] host = dyn.defaults.host port = dyn.defaults.port path = dyn.defaults.prefix + path headers = _.clone dyn.defaults.headers if body && typeof(body) != 'string' body = JSON.stringify(body) headers['Content-Length'] = body.length else if body headers['Content-Length'] = body.length else headers['Content-Length'] = 0 if isTraffic unless ((path.indexOf("/REST/Session/") == 0) && (method == 'POST')) if (dyn.defaults.token == null) throw new Error('must open a session first') headers['Auth-Token'] = dyn.defaults.token opts = {hostname:host,port:port,method:method,path:path,headers:headers} log.silly 'dyn', "request : #{JSON.stringify(opts)}" req = https.request opts, (res) -> # log.silly 'dynres', arguments data = '' res.on 'readable', -> # log.silly 'dynres', arguments chunk = res.read() # log.silly 'dyn', "partial : #{chunk}" data += chunk.toString('ascii') res.on 'end', -> log.silly 'dyn', "response : #{data}" response = JSON.parse(data) cc(null, response, res) req.on 'error', (e) -> log.warn 'dyn', "error : #{JSON.stringify(e)}" cc(e) req.write body if body req.end() return defer.promise crudTraffic = (path, custom) -> custom ||= {} methods = {_list:'GET',_create:'POST',_get:'GET',_update:'PUT',_destroy:'DELETE'} _.reduce _.keys(methods), (a, x) -> a[x] ||= {} a[x]._path = (dyn, data) -> cpath = custom?[x]?.path || path _.template(cpath)(data) a[x]._call = (dyn, pathData, bodyData) -> log.silly 'dyn', "api call : #{x} -> #{path}" _request_q dyn, custom?.method || methods[x], a[x]._path(dyn, pathData), bodyData, true a , {} crudMessaging = (path, custom) -> custom ||= {} methods = {_list:'GET',_create:'POST',_get:'GET',_update:'POST',_destroy:'POST'} allKeys = _.uniq _.keys(custom).concat(_.keys(methods)) _.reduce allKeys, (a, x) -> a[x] ||= {} a[x]._path = (dyn, data) -> cpath = custom?[x]?.path || path data.e = escape _.template(cpath)(data) a[x]._call = (dyn, pathData, bodyData) -> log.silly 'dyn', "api call : #{x} -> #{path}" method = custom?[x]?.method || methods[x] if method == 'GET' _request_q dyn, method, a[x]._path(dyn, pathData) + "?" + qs.stringify(bodyData) else _request_q dyn, method, a[x]._path(dyn, pathData), qs.stringify(bodyData) a , {} crudRecord = (type) -> crudTraffic "/#{type}Record/", _list: {path:"/#{type}Record/{{zone}}/{{fqdn}}"} _create: {path:"/#{type}Record/{{zone}}/{{fqdn}}/"} _get: {path:"/#{type}Record/{{zone}}/{{fqdn}}/{{id}}"} _update: {path:"/#{type}Record/{{zone}}/{{fqdn}}/{{id}}"} _destroy: {path:"/#{type}Record/{{zone}}/{{fqdn}}/{{id}}"} crudZone = -> crudTraffic "/Zone/", _list: {path:"/Zone/"} _create: {path:"/Zone/{{zone}}/"} _get: {path:"/Zone/{{zone}}/"} _update: {path:"/Zone/{{zone}}/"} _destroy: {path:"/Zone/{{zone}}/"} crudHttpRedirect = -> crudTraffic "/HTTPRedirect/", _get: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} _update: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} _create: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} _destroy: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} crudGslb = -> crudTraffic "/GSLB/", _list: {path:"/GSLB/{{zone}}"} _create: {path:"/GSLB/{{zone}}/{{fqdn}}"} _get: {path:"/GSLB/{{zone}}/{{fqdn}}"} _update: {path:"/GSLB/{{zone}}/{{fqdn}}"} _destroy: {path:"/GSLB/{{zone}}/{{fqdn}}"} crudGslbRegion = -> crudTraffic "/GSLBRegion/", _list: {path:"/GSLBRegion/{{zone}}"} _create: {path:"/GSLBRegion/{{zone}}/{{fqdn}}"} _get: {path:"/GSLBRegion/{{zone}}/{{fqdn}}"} _update: {path:"/GSLBRegion/{{zone}}/{{fqdn}}/{{region_code}}"} _destroy: {path:"/GSLBRegion/{{zone}}/{{fqdn}}"} crudSenders = (type) -> crudMessaging "/senders", _list: {path:"/senders"} _create: {path:"/senders"} _update: {path:"/senders"} _details: {path:"/senders/details", method:"GET"} _status: {path:"/senders/status", method:"GET"} _dkim: {path:"/senders/dkim", method:"POST"} _destroy: {path:"/senders/delete"} crudAccounts = (type) -> crudMessaging "/accounts", _list: {path:"/accounts"} _create: {path:"/accounts"} _destroy: {path:"/accounts/delete"} _list_xheaders: {path:"/accounts/xheaders", method:"GET"} _update_xheaders: {path:"/accounts/xheaders", method:"POST"} crudRecipients = (type) -> crudMessaging "/recipients", _activate: {path:"/recipients/activate", method:"POST"} _status: {path:"/recipients/status", method: "GET"} crudSendMail = (type) -> crudMessaging "/send/", _create: {path:"/send"} crudSuppressions = (type) -> crudMessaging "/suppressions", _list: {path:"/suppressions"} _create: {path:"/suppressions"} _activate: {path:"/suppressions/activate", method: "POST"} _count: {path:"/suppressions/count", method:"GET"} crudReportsSentMail = (type) -> crudMessaging "/reports", _list: {path:"/reports/sent"} _count: {path:"/reports/sent/count", method:"GET"} crudReportsDelivered = (type) -> crudMessaging "/reports", _list: {path:"/reports/delivered"} _count: {path:"/reports/delivered/count", method:"GET"} crudReportsBounces = (type) -> crudMessaging "/reports", _list: {path:"/reports/bounces"} _count: {path:"/reports/bounces/count", method:"GET"} crudReportsComplaints = (type) -> crudMessaging "/reports", _list: {path:"/reports/complaints"} _count: {path:"/reports/complaints/count", method:"GET"} crudReportsIssues = (type) -> crudMessaging "/reports", _list: {path:"/reports/issues"} _count: {path:"/reports/issues/count", method:"GET"} crudReportsOpens = (type) -> crudMessaging "/reports", _list: {path:"/reports/opens"} _count: {path:"/reports/opens/count", method:"GET"} _unique: {path:"/reports/opens/unique", method:"GET"} _unique_count: {path:"/reports/opens/count/unique", method:"GET"} crudReportsClicks = (type) -> crudMessaging "/reports", _list: {path:"/reports/clicks"} _count: {path:"/reports/clicks/count", method:"GET"} _unique: {path:"/reports/clicks/unique", method:"GET"} _unique_count: {path:"/reports/clicks/count/unique", method:"GET"} makePromise = (val) -> r = q.defer() r.resolve(val) r.promise callWithError = (funProm, description, successFilter, successCase, errorCase) -> funProm.then (x) -> makePromise if successFilter(x[1]) log.silly 'dyn', "api call returned successfully : #{JSON.stringify(x[1])}" successCase(x[1]) else log.info 'dyn', "api call returned error : #{JSON.stringify(x[1])}" errorCase x[1] , (x) -> log.warn 'dyn', "unexpected error : #{JSON.stringify(x[1])}" errorCase x isOk = (x) -> x && (x.status == 'success') identity = (x) -> x extract = (key) -> (x) -> x?[key] extractData = extract 'data' extractMsgs = extract 'msgs' msgIsOk = (x) -> x && x.response && (x.response.status == 200) extractMsgData = (x) -> x?.response?.data okBool = -> true failBool = -> false extractRecords = (x) -> return [] unless x && x.data _(x.data).map (r) -> v = r.split("/") {type:v[2].replace(/Record$/, ""),zone:v[3],fqdn:v[4],id:v[5]} extractZones = (x) -> return [] unless x && x.data _(x.data).map (r) -> v = r.split("/") {zone:v[3]} throwMessages = (x) -> throw (x.msgs || "unknown exception when calling api") throwMsgMessages = (x) -> throw (x?.response?.message || "unknown exception when calling api") Dyn = (opts) -> traffic_defaults = _.defaults opts?.traffic || {}, { host: 'api2.dynect.net' port: 443 prefix:'/REST' headers:{ 'Content-Type':'application/json' 'User-Agent':'dyn-js v1.0.3' } token:null } messaging_defaults = _.defaults opts?.messaging || {}, { host: 'emailapi.dynect.net' port: 443 prefix:'/rest/json' headers:{ 'Content-Type':'application/x-www-form-urlencoded' 'User-Agent':'dyn-js v1.0.3' } apikey:null } dyn = {} dyn.traffic = {} traffic = dyn.traffic dyn.log = log dyn.log.level = "info" traffic.defaults = _.clone traffic_defaults traffic.withZone = (zone) -> traffic.defaults.zone = zone traffic traffic.zone = crudZone() traffic.zone.list = () -> callWithError traffic.zone._list._call(traffic, {}, {}), "zone.list", isOk, extractZones, throwMessages traffic.zone.create = (args) -> callWithError traffic.zone._create._call(traffic, {zone:traffic.defaults.zone}, args), "zone.create", isOk, extractData, throwMessages traffic.zone.get = -> callWithError traffic.zone._list._call(traffic, {zone:traffic.defaults.zone}, {}), "zone.get", isOk, extractData, throwMessages traffic.zone.destroy = -> callWithError traffic.zone._destroy._call(traffic, {zone:traffic.defaults.zone}, {}), "zone.destroy", isOk, extractMsgs, throwMessages traffic.zone.publish = -> callWithError traffic.zone._update._call(traffic, {zone:traffic.defaults.zone}, {publish:true}), "zone.publish", isOk, extractData, throwMessages traffic.zone.freeze = -> callWithError traffic.zone._update._call(traffic, {zone:traffic.defaults.zone}, {freeze:true}), "zone.freeze", isOk, extractData, throwMessages traffic.zone.thaw = -> callWithError traffic.zone._update._call(traffic, {zone:traffic.defaults.zone}, {thaw:true}), "zone.thaw", isOk, extractData, throwMessages traffic.session = crudTraffic "/Session/" traffic.session.create = -> callWithError(traffic.session._create._call(traffic, {}, _.pick(traffic.defaults, 'customer_name', 'user_name', 'password')), "session.create", isOk, (x) -> traffic.defaults.token = x.data.token makePromise x , throwMessages) traffic.session.destroy = -> callWithError(traffic.session._destroy._call(traffic, {}, {}), "session.destroy", isOk, (x) -> traffic.defaults.token = null makePromise x , throwMessages) recordTypes = ['All','ANY','A','AAAA','CERT','CNAME','DHCID','DNAME','DNSKEY','DS','IPSECKEY','KEY','KX','LOC','MX','NAPTR','NS','NSAP','PTR','PX','RP','SOA','SPF','SRV','SSHFP','TXT'] whiteList = {'All':'list','ANY':'list','SOA':{'list':true,'get':true,'update':true}} allow = (x, op) -> !whiteList[x] || ( _.isString(whiteList[x]) && whiteList[x] == op) || ( _.isObject(whiteList[x]) && whiteList[x][op] ) traffic.record = _.reduce recordTypes, (a, x) -> type = "_#{x}" a[type] = crudRecord(x) a[type].list = ( (fqdn) -> callWithError traffic.record[type]._list._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn||''}, {}), "record._#{type}.list", isOk, extractRecords, throwMessages ) if allow(x, 'list') a[type].create = ( (fqdn, record) -> callWithError traffic.record[type]._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, record), "record._#{type}.create", isOk, extractData, throwMessages ) if allow(x, 'create') a[type].destroy = ( (fqdn, opt_id) -> callWithError traffic.record[type]._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:opt_id||''}, {}), "record._#{type}.destroy", isOk, extractMsgs, throwMessages ) if allow(x, 'destroy') a[type].get = ( (fqdn, id) -> callWithError traffic.record[type]._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:id}, {}), "record._#{type}.get", isOk, extractRecords, throwMessages ) if allow(x, 'get') a[type].update = ( (fqdn, id, record) -> callWithError traffic.record[type]._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:id}, record), "record._#{type}.update", isOk, extractData, throwMessages ) if allow(x, 'update') a[type].replace = ( (fqdn, records) -> arg = {} arg["#{x}Records"] = records callWithError traffic.record[type]._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:''}, arg), "record._#{type}.replace", isOk, extractData, throwMessages ) if allow(x, 'replace') a , {} traffic.http_redirect = crudHttpRedirect() traffic.http_redirect.list = (fqdn) -> callWithError traffic.http_redirect._list._call(traffic, {zone:traffic.defaults.zone}, {}), "http_redirect.list", isOk, extractData, throwMessages traffic.http_redirect.get = (fqdn, detail) -> callWithError traffic.http_redirect._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {detail:detail||'N'}), "http_redirect.get", isOk, extractData, throwMessages traffic.http_redirect.create = (fqdn, code, keep_uri, url) -> callWithError traffic.http_redirect._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {code:code, keep_uri:keep_uri, url:url}), "http_redirect.create", isOk, extractData, throwMessages traffic.http_redirect.update = (fqdn, code, keep_uri, url) -> callWithError traffic.http_redirect._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {code:code, keep_uri:keep_uri, url:url}), "http_redirect.update", isOk, extractData, throwMessages traffic.http_redirect.destroy = (fqdn) -> callWithError traffic.http_redirect._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "http_redirect.destroy", isOk, extractData, throwMessages traffic.gslb = crudGslb() traffic.gslb.list = (detail) -> callWithError traffic.gslb._list._call(traffic, {zone:traffic.defaults.zone}, {detail:detail||'N'}), "gslb.list", isOk, extractData, throwMessages traffic.gslb.get = (fqdn) -> callWithError traffic.gslb._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslb.get", isOk, extractData, throwMessages traffic.gslb.create = (fqdn, opts) -> callWithError traffic.gslb._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslb.create", isOk, extractData, throwMessages traffic.gslb.destroy = (fqdn) -> callWithError traffic.gslb._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslb.destroy", isOk, extractData, throwMessages traffic.gslb.update = (fqdn, opts) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslb.update", isOk, extractData, throwMessages traffic.gslb.activate = (fqdn) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {activate:true}), "gslb.activate", isOk, extractData, throwMessages traffic.gslb.deactivate = (fqdn) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {deactivate:true}), "gslb.deactivate", isOk, extractData, throwMessages traffic.gslb.recover = (fqdn) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {recover:true}), "gslb.recover", isOk, extractData, throwMessages traffic.gslb.recoverip = (fqdn, opts) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslb.recoverip", isOk, extractData, throwMessages traffic.gslbRegion = crudGslbRegion() traffic.gslbRegion.list = (detail) -> callWithError traffic.gslbRegion._list._call(traffic, {zone:traffic.defaults.zone}, {detail:detail||'N'}), "gslbRegion.list", isOk, extractData, throwMessages traffic.gslbRegion.get = (fqdn) -> callWithError traffic.gslbRegion._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslbRegion.get", isOk, extractData, throwMessages traffic.gslbRegion.create = (fqdn, opts) -> callWithError traffic.gslbRegion._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslbRegion.create", isOk, extractData, throwMessages traffic.gslbRegion.destroy = (fqdn) -> callWithError traffic.gslbRegion._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslbRegion.destroy", isOk, extractData, throwMessages traffic.gslbRegion.update = (fqdn, region_code, opts) -> callWithError traffic.gslbRegion._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,region_code:region_code}, opts), "gslbRegion.update", isOk, extractData, throwMessages dyn.messaging = {} messaging = dyn.messaging messaging.defaults = _.clone messaging_defaults messaging.senders = crudSenders() messaging.senders.list = (startindex) -> callWithError messaging.senders._list._call(messaging, {}, _.defaults({startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "senders.list", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.create = (email, seeding) -> callWithError messaging.senders._create._call(messaging, {}, _.defaults({emailaddress:email,seeding:seeding||'0'}, {apikey:messaging.defaults.apikey})), "senders.create", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.update = (email, seeding) -> callWithError messaging.senders._update._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.update", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.details = (email) -> callWithError messaging.senders._details._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.details", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.status = (email) -> callWithError messaging.senders._status._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.status", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.dkim = (email, dkim) -> callWithError messaging.senders._dkim._call(messaging, {}, _.defaults({emailaddress:email,dkim:dkim}, {apikey:messaging.defaults.apikey})), "senders.dkim", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.destroy = (email) -> callWithError messaging.senders._destroy._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.destroy", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts = crudAccounts() messaging.accounts.create = (username, password, companyname, phone, address, city, state, zipcode, country, timezone, bounceurl, spamurl, unsubscribeurl, trackopens, tracelinks, trackunsubscribes, generatenewapikey) -> callWithError messaging.accounts._create._call(messaging, {}, _.defaults({username:username, password:password, companyname:companyname, phone:phone, address:address, city:city, state:state, zipcode:zipcode, country:country, timezone:timezone, bounceurl:bounceurl, spamurl:spamurl, unsubscribeurl:unsubscribeurl, trackopens:trackopens, tracelinks:tracelinks, trackunsubscribes:trackunsubscribes, generatenewapikey:generatenewapikey}, {apikey:messaging.defaults.apikey})), "accounts.create", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.list = (startindex) -> callWithError messaging.accounts._list._call(messaging, {}, _.defaults({startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "accounts.list", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.destroy = (username) -> callWithError messaging.accounts._destroy._call(messaging, {}, _.defaults({username:username}, {apikey:messaging.defaults.apikey})), "accounts.destroy", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.list_xheaders = -> callWithError messaging.accounts._list_xheaders._call(messaging, {}, _.defaults({}, {apikey:messaging.defaults.apikey})), "accounts.list_xheaders", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.update_xheaders = (xh1,xh2,xh3,xh4) -> callWithError messaging.accounts._update_xheaders._call(messaging, {}, _.defaults({xheader1:xh1,xheader2:xh2,xheader3:xh3,xheader4:xh4}, {apikey:messaging.defaults.apikey})), "accounts.update_xheaders", msgIsOk, extractMsgData, throwMsgMessages messaging.recipients = crudRecipients() messaging.recipients.status = (email) -> callWithError messaging.recipients._status._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "recipients.status", msgIsOk, extractMsgData, throwMsgMessages messaging.recipients.activate = (email) -> callWithError messaging.recipients._activate._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "recipients.activate", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions = crudSuppressions() messaging.suppressions.count = (startdate, enddate) -> callWithError messaging.suppressions._count._call(messaging, {}, _.defaults({}, {apikey:messaging.defaults.apikey})), "suppressions.count", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions.list = (startdate, enddate, startindex) -> callWithError messaging.suppressions._list._call(messaging, {}, _.defaults({startdate:startdate, enddate:enddate, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "suppressions.list", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions.create = (email) -> callWithError messaging.suppressions._create._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "suppressions.create", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions.activate = (email) -> callWithError messaging.suppressions._activate._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "suppressions.activate", msgIsOk, extractMsgData, throwMsgMessages messaging.delivery = crudReportsDelivered() messaging.delivery.count = (starttime, endtime) -> callWithError messaging.delivery._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "delivery.count", msgIsOk, extractMsgData, throwMsgMessages messaging.delivery.list = (starttime, endtime, startindex) -> callWithError messaging.delivery._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "delivery.list", msgIsOk, extractMsgData, throwMsgMessages messaging.sent_mail = crudReportsSentMail() messaging.sent_mail.count = (starttime, endtime) -> callWithError messaging.sent_mail._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "sent_mail.count", msgIsOk, extractMsgData, throwMsgMessages messaging.sent_mail.list = (starttime, endtime, startindex) -> callWithError messaging.sent_mail._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "sent_mail.list", msgIsOk, extractMsgData, throwMsgMessages messaging.bounces = crudReportsBounces() messaging.bounces.count = (starttime, endtime) -> callWithError messaging.bounces._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "bounces.count", msgIsOk, extractMsgData, throwMsgMessages messaging.bounces.list = (starttime, endtime, startindex) -> callWithError messaging.bounces._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "bounces.list", msgIsOk, extractMsgData, throwMsgMessages messaging.complaints = crudReportsComplaints() messaging.complaints.count = (starttime, endtime) -> callWithError messaging.complaints._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "complaints.count", msgIsOk, extractMsgData, throwMsgMessages messaging.complaints.list = (starttime, endtime, startindex) -> callWithError messaging.complaints._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "complaints.list", msgIsOk, extractMsgData, throwMsgMessages messaging.issues = crudReportsIssues() messaging.issues.count = (starttime, endtime) -> callWithError messaging.issues._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "issues.count", msgIsOk, extractMsgData, throwMsgMessages messaging.issues.list = (starttime, endtime, startindex) -> callWithError messaging.issues._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "issues.list", msgIsOk, extractMsgData, throwMsgMessages messaging.opens = crudReportsOpens() messaging.opens.count = (starttime, endtime) -> callWithError messaging.opens._count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.count", msgIsOk, extractMsgData, throwMsgMessages messaging.opens.list = (starttime, endtime, startindex) -> callWithError messaging.opens._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.list", msgIsOk, extractMsgData, throwMsgMessages messaging.opens.unique = (starttime, endtime, startindex) -> callWithError messaging.opens._unique._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.unqiue", msgIsOk, extractMsgData, throwMsgMessages messaging.opens.unique_count = (starttime, endtime) -> callWithError messaging.opens._unique_count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.unique_count", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks = crudReportsClicks() messaging.clicks.count = (starttime, endtime) -> callWithError messaging.clicks._count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.count", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks.list = (starttime, endtime, startindex) -> callWithError messaging.clicks._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.list", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks.unique = (starttime, endtime, startindex) -> callWithError messaging.clicks._unique._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.unique", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks.unique_count = (starttime, endtime) -> callWithError messaging.clicks._unique_count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.unique_count", msgIsOk, extractMsgData, throwMsgMessages messaging.send_mail = crudSendMail() messaging.send_mail.create = (from, to, subject, bodytext, bodyhmtl, cc, replyto, xheaders) -> callWithError messaging.send_mail._create._call(messaging, {}, _.defaults({from:from, to:to, subject:subject, bodytext:bodytext, bodyhtml:bodyhmtl, cc:cc, replyto:replyto, xheaders:xheaders}, {apikey:messaging.defaults.apikey})), "send_mail.create", msgIsOk, extractMsgData, throwMsgMessages dyn module.exports = Dyn
117820
'use strict' _ = require 'underscore' q = require 'q' https = require 'https' log = require 'npmlog' qs = require 'querystring' _.templateSettings = { interpolate: /\{\{(.+?)\}\}/g } _request_q = (dyn, method, path, body, isTraffic) -> log.verbose 'dyn', "invoking via https : #{method} #{path}" defer = q.defer() cc = (a, b, c) -> log.verbose 'dyn', "invocation returned : #{method} #{path}" if (a != null) return defer.reject.call {}, [a] return defer.resolve.call {}, [a, b, c] host = dyn.defaults.host port = dyn.defaults.port path = dyn.defaults.prefix + path headers = _.clone dyn.defaults.headers if body && typeof(body) != 'string' body = JSON.stringify(body) headers['Content-Length'] = body.length else if body headers['Content-Length'] = body.length else headers['Content-Length'] = 0 if isTraffic unless ((path.indexOf("/REST/Session/") == 0) && (method == 'POST')) if (dyn.defaults.token == null) throw new Error('must open a session first') headers['Auth-Token'] = dyn.defaults.token opts = {hostname:host,port:port,method:method,path:path,headers:headers} log.silly 'dyn', "request : #{JSON.stringify(opts)}" req = https.request opts, (res) -> # log.silly 'dynres', arguments data = '' res.on 'readable', -> # log.silly 'dynres', arguments chunk = res.read() # log.silly 'dyn', "partial : #{chunk}" data += chunk.toString('ascii') res.on 'end', -> log.silly 'dyn', "response : #{data}" response = JSON.parse(data) cc(null, response, res) req.on 'error', (e) -> log.warn 'dyn', "error : #{JSON.stringify(e)}" cc(e) req.write body if body req.end() return defer.promise crudTraffic = (path, custom) -> custom ||= {} methods = {_list:'GET',_create:'POST',_get:'GET',_update:'PUT',_destroy:'DELETE'} _.reduce _.keys(methods), (a, x) -> a[x] ||= {} a[x]._path = (dyn, data) -> cpath = custom?[x]?.path || path _.template(cpath)(data) a[x]._call = (dyn, pathData, bodyData) -> log.silly 'dyn', "api call : #{x} -> #{path}" _request_q dyn, custom?.method || methods[x], a[x]._path(dyn, pathData), bodyData, true a , {} crudMessaging = (path, custom) -> custom ||= {} methods = {_list:'GET',_create:'POST',_get:'GET',_update:'POST',_destroy:'POST'} allKeys = _.uniq _.keys(custom).concat(_.keys(methods)) _.reduce allKeys, (a, x) -> a[x] ||= {} a[x]._path = (dyn, data) -> cpath = custom?[x]?.path || path data.e = escape _.template(cpath)(data) a[x]._call = (dyn, pathData, bodyData) -> log.silly 'dyn', "api call : #{x} -> #{path}" method = custom?[x]?.method || methods[x] if method == 'GET' _request_q dyn, method, a[x]._path(dyn, pathData) + "?" + qs.stringify(bodyData) else _request_q dyn, method, a[x]._path(dyn, pathData), qs.stringify(bodyData) a , {} crudRecord = (type) -> crudTraffic "/#{type}Record/", _list: {path:"/#{type}Record/{{zone}}/{{fqdn}}"} _create: {path:"/#{type}Record/{{zone}}/{{fqdn}}/"} _get: {path:"/#{type}Record/{{zone}}/{{fqdn}}/{{id}}"} _update: {path:"/#{type}Record/{{zone}}/{{fqdn}}/{{id}}"} _destroy: {path:"/#{type}Record/{{zone}}/{{fqdn}}/{{id}}"} crudZone = -> crudTraffic "/Zone/", _list: {path:"/Zone/"} _create: {path:"/Zone/{{zone}}/"} _get: {path:"/Zone/{{zone}}/"} _update: {path:"/Zone/{{zone}}/"} _destroy: {path:"/Zone/{{zone}}/"} crudHttpRedirect = -> crudTraffic "/HTTPRedirect/", _get: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} _update: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} _create: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} _destroy: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} crudGslb = -> crudTraffic "/GSLB/", _list: {path:"/GSLB/{{zone}}"} _create: {path:"/GSLB/{{zone}}/{{fqdn}}"} _get: {path:"/GSLB/{{zone}}/{{fqdn}}"} _update: {path:"/GSLB/{{zone}}/{{fqdn}}"} _destroy: {path:"/GSLB/{{zone}}/{{fqdn}}"} crudGslbRegion = -> crudTraffic "/GSLBRegion/", _list: {path:"/GSLBRegion/{{zone}}"} _create: {path:"/GSLBRegion/{{zone}}/{{fqdn}}"} _get: {path:"/GSLBRegion/{{zone}}/{{fqdn}}"} _update: {path:"/GSLBRegion/{{zone}}/{{fqdn}}/{{region_code}}"} _destroy: {path:"/GSLBRegion/{{zone}}/{{fqdn}}"} crudSenders = (type) -> crudMessaging "/senders", _list: {path:"/senders"} _create: {path:"/senders"} _update: {path:"/senders"} _details: {path:"/senders/details", method:"GET"} _status: {path:"/senders/status", method:"GET"} _dkim: {path:"/senders/dkim", method:"POST"} _destroy: {path:"/senders/delete"} crudAccounts = (type) -> crudMessaging "/accounts", _list: {path:"/accounts"} _create: {path:"/accounts"} _destroy: {path:"/accounts/delete"} _list_xheaders: {path:"/accounts/xheaders", method:"GET"} _update_xheaders: {path:"/accounts/xheaders", method:"POST"} crudRecipients = (type) -> crudMessaging "/recipients", _activate: {path:"/recipients/activate", method:"POST"} _status: {path:"/recipients/status", method: "GET"} crudSendMail = (type) -> crudMessaging "/send/", _create: {path:"/send"} crudSuppressions = (type) -> crudMessaging "/suppressions", _list: {path:"/suppressions"} _create: {path:"/suppressions"} _activate: {path:"/suppressions/activate", method: "POST"} _count: {path:"/suppressions/count", method:"GET"} crudReportsSentMail = (type) -> crudMessaging "/reports", _list: {path:"/reports/sent"} _count: {path:"/reports/sent/count", method:"GET"} crudReportsDelivered = (type) -> crudMessaging "/reports", _list: {path:"/reports/delivered"} _count: {path:"/reports/delivered/count", method:"GET"} crudReportsBounces = (type) -> crudMessaging "/reports", _list: {path:"/reports/bounces"} _count: {path:"/reports/bounces/count", method:"GET"} crudReportsComplaints = (type) -> crudMessaging "/reports", _list: {path:"/reports/complaints"} _count: {path:"/reports/complaints/count", method:"GET"} crudReportsIssues = (type) -> crudMessaging "/reports", _list: {path:"/reports/issues"} _count: {path:"/reports/issues/count", method:"GET"} crudReportsOpens = (type) -> crudMessaging "/reports", _list: {path:"/reports/opens"} _count: {path:"/reports/opens/count", method:"GET"} _unique: {path:"/reports/opens/unique", method:"GET"} _unique_count: {path:"/reports/opens/count/unique", method:"GET"} crudReportsClicks = (type) -> crudMessaging "/reports", _list: {path:"/reports/clicks"} _count: {path:"/reports/clicks/count", method:"GET"} _unique: {path:"/reports/clicks/unique", method:"GET"} _unique_count: {path:"/reports/clicks/count/unique", method:"GET"} makePromise = (val) -> r = q.defer() r.resolve(val) r.promise callWithError = (funProm, description, successFilter, successCase, errorCase) -> funProm.then (x) -> makePromise if successFilter(x[1]) log.silly 'dyn', "api call returned successfully : #{JSON.stringify(x[1])}" successCase(x[1]) else log.info 'dyn', "api call returned error : #{JSON.stringify(x[1])}" errorCase x[1] , (x) -> log.warn 'dyn', "unexpected error : #{JSON.stringify(x[1])}" errorCase x isOk = (x) -> x && (x.status == 'success') identity = (x) -> x extract = (key) -> (x) -> x?[key] extractData = extract 'data' extractMsgs = extract 'msgs' msgIsOk = (x) -> x && x.response && (x.response.status == 200) extractMsgData = (x) -> x?.response?.data okBool = -> true failBool = -> false extractRecords = (x) -> return [] unless x && x.data _(x.data).map (r) -> v = r.split("/") {type:v[2].replace(/Record$/, ""),zone:v[3],fqdn:v[4],id:v[5]} extractZones = (x) -> return [] unless x && x.data _(x.data).map (r) -> v = r.split("/") {zone:v[3]} throwMessages = (x) -> throw (x.msgs || "unknown exception when calling api") throwMsgMessages = (x) -> throw (x?.response?.message || "unknown exception when calling api") Dyn = (opts) -> traffic_defaults = _.defaults opts?.traffic || {}, { host: 'api2.dynect.net' port: 443 prefix:'/REST' headers:{ 'Content-Type':'application/json' 'User-Agent':'dyn-js v1.0.3' } token:null } messaging_defaults = _.defaults opts?.messaging || {}, { host: 'emailapi.dynect.net' port: 443 prefix:'/rest/json' headers:{ 'Content-Type':'application/x-www-form-urlencoded' 'User-Agent':'dyn-js v1.0.3' } apikey:null } dyn = {} dyn.traffic = {} traffic = dyn.traffic dyn.log = log dyn.log.level = "info" traffic.defaults = _.clone traffic_defaults traffic.withZone = (zone) -> traffic.defaults.zone = zone traffic traffic.zone = crudZone() traffic.zone.list = () -> callWithError traffic.zone._list._call(traffic, {}, {}), "zone.list", isOk, extractZones, throwMessages traffic.zone.create = (args) -> callWithError traffic.zone._create._call(traffic, {zone:traffic.defaults.zone}, args), "zone.create", isOk, extractData, throwMessages traffic.zone.get = -> callWithError traffic.zone._list._call(traffic, {zone:traffic.defaults.zone}, {}), "zone.get", isOk, extractData, throwMessages traffic.zone.destroy = -> callWithError traffic.zone._destroy._call(traffic, {zone:traffic.defaults.zone}, {}), "zone.destroy", isOk, extractMsgs, throwMessages traffic.zone.publish = -> callWithError traffic.zone._update._call(traffic, {zone:traffic.defaults.zone}, {publish:true}), "zone.publish", isOk, extractData, throwMessages traffic.zone.freeze = -> callWithError traffic.zone._update._call(traffic, {zone:traffic.defaults.zone}, {freeze:true}), "zone.freeze", isOk, extractData, throwMessages traffic.zone.thaw = -> callWithError traffic.zone._update._call(traffic, {zone:traffic.defaults.zone}, {thaw:true}), "zone.thaw", isOk, extractData, throwMessages traffic.session = crudTraffic "/Session/" traffic.session.create = -> callWithError(traffic.session._create._call(traffic, {}, _.pick(traffic.defaults, 'customer_name', 'user_name', 'password')), "session.create", isOk, (x) -> traffic.defaults.token = x.data.token makePromise x , throwMessages) traffic.session.destroy = -> callWithError(traffic.session._destroy._call(traffic, {}, {}), "session.destroy", isOk, (x) -> traffic.defaults.token = null makePromise x , throwMessages) recordTypes = ['All','ANY','A','AAAA','CERT','CNAME','DHCID','DNAME','DNSKEY','DS','IPSECKEY','KEY','KX','LOC','MX','NAPTR','NS','NSAP','PTR','PX','RP','SOA','SPF','SRV','SSHFP','TXT'] whiteList = {'All':'list','ANY':'list','SOA':{'list':true,'get':true,'update':true}} allow = (x, op) -> !whiteList[x] || ( _.isString(whiteList[x]) && whiteList[x] == op) || ( _.isObject(whiteList[x]) && whiteList[x][op] ) traffic.record = _.reduce recordTypes, (a, x) -> type = "_#{x}" a[type] = crudRecord(x) a[type].list = ( (fqdn) -> callWithError traffic.record[type]._list._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn||''}, {}), "record._#{type}.list", isOk, extractRecords, throwMessages ) if allow(x, 'list') a[type].create = ( (fqdn, record) -> callWithError traffic.record[type]._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, record), "record._#{type}.create", isOk, extractData, throwMessages ) if allow(x, 'create') a[type].destroy = ( (fqdn, opt_id) -> callWithError traffic.record[type]._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:opt_id||''}, {}), "record._#{type}.destroy", isOk, extractMsgs, throwMessages ) if allow(x, 'destroy') a[type].get = ( (fqdn, id) -> callWithError traffic.record[type]._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:id}, {}), "record._#{type}.get", isOk, extractRecords, throwMessages ) if allow(x, 'get') a[type].update = ( (fqdn, id, record) -> callWithError traffic.record[type]._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:id}, record), "record._#{type}.update", isOk, extractData, throwMessages ) if allow(x, 'update') a[type].replace = ( (fqdn, records) -> arg = {} arg["#{x}Records"] = records callWithError traffic.record[type]._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:''}, arg), "record._#{type}.replace", isOk, extractData, throwMessages ) if allow(x, 'replace') a , {} traffic.http_redirect = crudHttpRedirect() traffic.http_redirect.list = (fqdn) -> callWithError traffic.http_redirect._list._call(traffic, {zone:traffic.defaults.zone}, {}), "http_redirect.list", isOk, extractData, throwMessages traffic.http_redirect.get = (fqdn, detail) -> callWithError traffic.http_redirect._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {detail:detail||'N'}), "http_redirect.get", isOk, extractData, throwMessages traffic.http_redirect.create = (fqdn, code, keep_uri, url) -> callWithError traffic.http_redirect._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {code:code, keep_uri:keep_uri, url:url}), "http_redirect.create", isOk, extractData, throwMessages traffic.http_redirect.update = (fqdn, code, keep_uri, url) -> callWithError traffic.http_redirect._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {code:code, keep_uri:keep_uri, url:url}), "http_redirect.update", isOk, extractData, throwMessages traffic.http_redirect.destroy = (fqdn) -> callWithError traffic.http_redirect._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "http_redirect.destroy", isOk, extractData, throwMessages traffic.gslb = crudGslb() traffic.gslb.list = (detail) -> callWithError traffic.gslb._list._call(traffic, {zone:traffic.defaults.zone}, {detail:detail||'N'}), "gslb.list", isOk, extractData, throwMessages traffic.gslb.get = (fqdn) -> callWithError traffic.gslb._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslb.get", isOk, extractData, throwMessages traffic.gslb.create = (fqdn, opts) -> callWithError traffic.gslb._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslb.create", isOk, extractData, throwMessages traffic.gslb.destroy = (fqdn) -> callWithError traffic.gslb._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslb.destroy", isOk, extractData, throwMessages traffic.gslb.update = (fqdn, opts) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslb.update", isOk, extractData, throwMessages traffic.gslb.activate = (fqdn) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {activate:true}), "gslb.activate", isOk, extractData, throwMessages traffic.gslb.deactivate = (fqdn) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {deactivate:true}), "gslb.deactivate", isOk, extractData, throwMessages traffic.gslb.recover = (fqdn) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {recover:true}), "gslb.recover", isOk, extractData, throwMessages traffic.gslb.recoverip = (fqdn, opts) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslb.recoverip", isOk, extractData, throwMessages traffic.gslbRegion = crudGslbRegion() traffic.gslbRegion.list = (detail) -> callWithError traffic.gslbRegion._list._call(traffic, {zone:traffic.defaults.zone}, {detail:detail||'N'}), "gslbRegion.list", isOk, extractData, throwMessages traffic.gslbRegion.get = (fqdn) -> callWithError traffic.gslbRegion._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslbRegion.get", isOk, extractData, throwMessages traffic.gslbRegion.create = (fqdn, opts) -> callWithError traffic.gslbRegion._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslbRegion.create", isOk, extractData, throwMessages traffic.gslbRegion.destroy = (fqdn) -> callWithError traffic.gslbRegion._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslbRegion.destroy", isOk, extractData, throwMessages traffic.gslbRegion.update = (fqdn, region_code, opts) -> callWithError traffic.gslbRegion._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,region_code:region_code}, opts), "gslbRegion.update", isOk, extractData, throwMessages dyn.messaging = {} messaging = dyn.messaging messaging.defaults = _.clone messaging_defaults messaging.senders = crudSenders() messaging.senders.list = (startindex) -> callWithError messaging.senders._list._call(messaging, {}, _.defaults({startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "senders.list", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.create = (email, seeding) -> callWithError messaging.senders._create._call(messaging, {}, _.defaults({emailaddress:email,seeding:seeding||'0'}, {apikey:messaging.defaults.apikey})), "senders.create", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.update = (email, seeding) -> callWithError messaging.senders._update._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.update", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.details = (email) -> callWithError messaging.senders._details._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.details", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.status = (email) -> callWithError messaging.senders._status._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.status", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.dkim = (email, dkim) -> callWithError messaging.senders._dkim._call(messaging, {}, _.defaults({emailaddress:email,dkim:dkim}, {apikey:messaging.defaults.apikey})), "senders.dkim", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.destroy = (email) -> callWithError messaging.senders._destroy._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.destroy", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts = crudAccounts() messaging.accounts.create = (username, password, companyname, phone, address, city, state, zipcode, country, timezone, bounceurl, spamurl, unsubscribeurl, trackopens, tracelinks, trackunsubscribes, generatenewapikey) -> callWithError messaging.accounts._create._call(messaging, {}, _.defaults({username:username, password:<PASSWORD>, companyname:companyname, phone:phone, address:address, city:city, state:state, zipcode:zipcode, country:country, timezone:timezone, bounceurl:bounceurl, spamurl:spamurl, unsubscribeurl:unsubscribeurl, trackopens:trackopens, tracelinks:tracelinks, trackunsubscribes:trackunsubscribes, generatenewapikey:generatenewapikey}, {apikey:messaging.defaults.apikey})), "accounts.create", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.list = (startindex) -> callWithError messaging.accounts._list._call(messaging, {}, _.defaults({startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "accounts.list", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.destroy = (username) -> callWithError messaging.accounts._destroy._call(messaging, {}, _.defaults({username:username}, {apikey:messaging.defaults.apikey})), "accounts.destroy", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.list_xheaders = -> callWithError messaging.accounts._list_xheaders._call(messaging, {}, _.defaults({}, {apikey:messaging.defaults.apikey})), "accounts.list_xheaders", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.update_xheaders = (xh1,xh2,xh3,xh4) -> callWithError messaging.accounts._update_xheaders._call(messaging, {}, _.defaults({xheader1:xh1,xheader2:xh2,xheader3:xh3,xheader4:xh4}, {apikey:messaging.defaults.apikey})), "accounts.update_xheaders", msgIsOk, extractMsgData, throwMsgMessages messaging.recipients = crudRecipients() messaging.recipients.status = (email) -> callWithError messaging.recipients._status._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "recipients.status", msgIsOk, extractMsgData, throwMsgMessages messaging.recipients.activate = (email) -> callWithError messaging.recipients._activate._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "recipients.activate", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions = crudSuppressions() messaging.suppressions.count = (startdate, enddate) -> callWithError messaging.suppressions._count._call(messaging, {}, _.defaults({}, {apikey:messaging.defaults.apikey})), "suppressions.count", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions.list = (startdate, enddate, startindex) -> callWithError messaging.suppressions._list._call(messaging, {}, _.defaults({startdate:startdate, enddate:enddate, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "suppressions.list", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions.create = (email) -> callWithError messaging.suppressions._create._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "suppressions.create", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions.activate = (email) -> callWithError messaging.suppressions._activate._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "suppressions.activate", msgIsOk, extractMsgData, throwMsgMessages messaging.delivery = crudReportsDelivered() messaging.delivery.count = (starttime, endtime) -> callWithError messaging.delivery._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "delivery.count", msgIsOk, extractMsgData, throwMsgMessages messaging.delivery.list = (starttime, endtime, startindex) -> callWithError messaging.delivery._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "delivery.list", msgIsOk, extractMsgData, throwMsgMessages messaging.sent_mail = crudReportsSentMail() messaging.sent_mail.count = (starttime, endtime) -> callWithError messaging.sent_mail._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "sent_mail.count", msgIsOk, extractMsgData, throwMsgMessages messaging.sent_mail.list = (starttime, endtime, startindex) -> callWithError messaging.sent_mail._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "sent_mail.list", msgIsOk, extractMsgData, throwMsgMessages messaging.bounces = crudReportsBounces() messaging.bounces.count = (starttime, endtime) -> callWithError messaging.bounces._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "bounces.count", msgIsOk, extractMsgData, throwMsgMessages messaging.bounces.list = (starttime, endtime, startindex) -> callWithError messaging.bounces._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "bounces.list", msgIsOk, extractMsgData, throwMsgMessages messaging.complaints = crudReportsComplaints() messaging.complaints.count = (starttime, endtime) -> callWithError messaging.complaints._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "complaints.count", msgIsOk, extractMsgData, throwMsgMessages messaging.complaints.list = (starttime, endtime, startindex) -> callWithError messaging.complaints._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "complaints.list", msgIsOk, extractMsgData, throwMsgMessages messaging.issues = crudReportsIssues() messaging.issues.count = (starttime, endtime) -> callWithError messaging.issues._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "issues.count", msgIsOk, extractMsgData, throwMsgMessages messaging.issues.list = (starttime, endtime, startindex) -> callWithError messaging.issues._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "issues.list", msgIsOk, extractMsgData, throwMsgMessages messaging.opens = crudReportsOpens() messaging.opens.count = (starttime, endtime) -> callWithError messaging.opens._count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.count", msgIsOk, extractMsgData, throwMsgMessages messaging.opens.list = (starttime, endtime, startindex) -> callWithError messaging.opens._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.list", msgIsOk, extractMsgData, throwMsgMessages messaging.opens.unique = (starttime, endtime, startindex) -> callWithError messaging.opens._unique._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.unqiue", msgIsOk, extractMsgData, throwMsgMessages messaging.opens.unique_count = (starttime, endtime) -> callWithError messaging.opens._unique_count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.unique_count", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks = crudReportsClicks() messaging.clicks.count = (starttime, endtime) -> callWithError messaging.clicks._count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.count", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks.list = (starttime, endtime, startindex) -> callWithError messaging.clicks._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.list", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks.unique = (starttime, endtime, startindex) -> callWithError messaging.clicks._unique._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.unique", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks.unique_count = (starttime, endtime) -> callWithError messaging.clicks._unique_count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.unique_count", msgIsOk, extractMsgData, throwMsgMessages messaging.send_mail = crudSendMail() messaging.send_mail.create = (from, to, subject, bodytext, bodyhmtl, cc, replyto, xheaders) -> callWithError messaging.send_mail._create._call(messaging, {}, _.defaults({from:from, to:to, subject:subject, bodytext:bodytext, bodyhtml:bodyhmtl, cc:cc, replyto:replyto, xheaders:xheaders}, {apikey:messaging.defaults.apikey})), "send_mail.create", msgIsOk, extractMsgData, throwMsgMessages dyn module.exports = Dyn
true
'use strict' _ = require 'underscore' q = require 'q' https = require 'https' log = require 'npmlog' qs = require 'querystring' _.templateSettings = { interpolate: /\{\{(.+?)\}\}/g } _request_q = (dyn, method, path, body, isTraffic) -> log.verbose 'dyn', "invoking via https : #{method} #{path}" defer = q.defer() cc = (a, b, c) -> log.verbose 'dyn', "invocation returned : #{method} #{path}" if (a != null) return defer.reject.call {}, [a] return defer.resolve.call {}, [a, b, c] host = dyn.defaults.host port = dyn.defaults.port path = dyn.defaults.prefix + path headers = _.clone dyn.defaults.headers if body && typeof(body) != 'string' body = JSON.stringify(body) headers['Content-Length'] = body.length else if body headers['Content-Length'] = body.length else headers['Content-Length'] = 0 if isTraffic unless ((path.indexOf("/REST/Session/") == 0) && (method == 'POST')) if (dyn.defaults.token == null) throw new Error('must open a session first') headers['Auth-Token'] = dyn.defaults.token opts = {hostname:host,port:port,method:method,path:path,headers:headers} log.silly 'dyn', "request : #{JSON.stringify(opts)}" req = https.request opts, (res) -> # log.silly 'dynres', arguments data = '' res.on 'readable', -> # log.silly 'dynres', arguments chunk = res.read() # log.silly 'dyn', "partial : #{chunk}" data += chunk.toString('ascii') res.on 'end', -> log.silly 'dyn', "response : #{data}" response = JSON.parse(data) cc(null, response, res) req.on 'error', (e) -> log.warn 'dyn', "error : #{JSON.stringify(e)}" cc(e) req.write body if body req.end() return defer.promise crudTraffic = (path, custom) -> custom ||= {} methods = {_list:'GET',_create:'POST',_get:'GET',_update:'PUT',_destroy:'DELETE'} _.reduce _.keys(methods), (a, x) -> a[x] ||= {} a[x]._path = (dyn, data) -> cpath = custom?[x]?.path || path _.template(cpath)(data) a[x]._call = (dyn, pathData, bodyData) -> log.silly 'dyn', "api call : #{x} -> #{path}" _request_q dyn, custom?.method || methods[x], a[x]._path(dyn, pathData), bodyData, true a , {} crudMessaging = (path, custom) -> custom ||= {} methods = {_list:'GET',_create:'POST',_get:'GET',_update:'POST',_destroy:'POST'} allKeys = _.uniq _.keys(custom).concat(_.keys(methods)) _.reduce allKeys, (a, x) -> a[x] ||= {} a[x]._path = (dyn, data) -> cpath = custom?[x]?.path || path data.e = escape _.template(cpath)(data) a[x]._call = (dyn, pathData, bodyData) -> log.silly 'dyn', "api call : #{x} -> #{path}" method = custom?[x]?.method || methods[x] if method == 'GET' _request_q dyn, method, a[x]._path(dyn, pathData) + "?" + qs.stringify(bodyData) else _request_q dyn, method, a[x]._path(dyn, pathData), qs.stringify(bodyData) a , {} crudRecord = (type) -> crudTraffic "/#{type}Record/", _list: {path:"/#{type}Record/{{zone}}/{{fqdn}}"} _create: {path:"/#{type}Record/{{zone}}/{{fqdn}}/"} _get: {path:"/#{type}Record/{{zone}}/{{fqdn}}/{{id}}"} _update: {path:"/#{type}Record/{{zone}}/{{fqdn}}/{{id}}"} _destroy: {path:"/#{type}Record/{{zone}}/{{fqdn}}/{{id}}"} crudZone = -> crudTraffic "/Zone/", _list: {path:"/Zone/"} _create: {path:"/Zone/{{zone}}/"} _get: {path:"/Zone/{{zone}}/"} _update: {path:"/Zone/{{zone}}/"} _destroy: {path:"/Zone/{{zone}}/"} crudHttpRedirect = -> crudTraffic "/HTTPRedirect/", _get: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} _update: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} _create: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} _destroy: {path:"/HTTPRedirect/{{zone}}/{{fqdn}}"} crudGslb = -> crudTraffic "/GSLB/", _list: {path:"/GSLB/{{zone}}"} _create: {path:"/GSLB/{{zone}}/{{fqdn}}"} _get: {path:"/GSLB/{{zone}}/{{fqdn}}"} _update: {path:"/GSLB/{{zone}}/{{fqdn}}"} _destroy: {path:"/GSLB/{{zone}}/{{fqdn}}"} crudGslbRegion = -> crudTraffic "/GSLBRegion/", _list: {path:"/GSLBRegion/{{zone}}"} _create: {path:"/GSLBRegion/{{zone}}/{{fqdn}}"} _get: {path:"/GSLBRegion/{{zone}}/{{fqdn}}"} _update: {path:"/GSLBRegion/{{zone}}/{{fqdn}}/{{region_code}}"} _destroy: {path:"/GSLBRegion/{{zone}}/{{fqdn}}"} crudSenders = (type) -> crudMessaging "/senders", _list: {path:"/senders"} _create: {path:"/senders"} _update: {path:"/senders"} _details: {path:"/senders/details", method:"GET"} _status: {path:"/senders/status", method:"GET"} _dkim: {path:"/senders/dkim", method:"POST"} _destroy: {path:"/senders/delete"} crudAccounts = (type) -> crudMessaging "/accounts", _list: {path:"/accounts"} _create: {path:"/accounts"} _destroy: {path:"/accounts/delete"} _list_xheaders: {path:"/accounts/xheaders", method:"GET"} _update_xheaders: {path:"/accounts/xheaders", method:"POST"} crudRecipients = (type) -> crudMessaging "/recipients", _activate: {path:"/recipients/activate", method:"POST"} _status: {path:"/recipients/status", method: "GET"} crudSendMail = (type) -> crudMessaging "/send/", _create: {path:"/send"} crudSuppressions = (type) -> crudMessaging "/suppressions", _list: {path:"/suppressions"} _create: {path:"/suppressions"} _activate: {path:"/suppressions/activate", method: "POST"} _count: {path:"/suppressions/count", method:"GET"} crudReportsSentMail = (type) -> crudMessaging "/reports", _list: {path:"/reports/sent"} _count: {path:"/reports/sent/count", method:"GET"} crudReportsDelivered = (type) -> crudMessaging "/reports", _list: {path:"/reports/delivered"} _count: {path:"/reports/delivered/count", method:"GET"} crudReportsBounces = (type) -> crudMessaging "/reports", _list: {path:"/reports/bounces"} _count: {path:"/reports/bounces/count", method:"GET"} crudReportsComplaints = (type) -> crudMessaging "/reports", _list: {path:"/reports/complaints"} _count: {path:"/reports/complaints/count", method:"GET"} crudReportsIssues = (type) -> crudMessaging "/reports", _list: {path:"/reports/issues"} _count: {path:"/reports/issues/count", method:"GET"} crudReportsOpens = (type) -> crudMessaging "/reports", _list: {path:"/reports/opens"} _count: {path:"/reports/opens/count", method:"GET"} _unique: {path:"/reports/opens/unique", method:"GET"} _unique_count: {path:"/reports/opens/count/unique", method:"GET"} crudReportsClicks = (type) -> crudMessaging "/reports", _list: {path:"/reports/clicks"} _count: {path:"/reports/clicks/count", method:"GET"} _unique: {path:"/reports/clicks/unique", method:"GET"} _unique_count: {path:"/reports/clicks/count/unique", method:"GET"} makePromise = (val) -> r = q.defer() r.resolve(val) r.promise callWithError = (funProm, description, successFilter, successCase, errorCase) -> funProm.then (x) -> makePromise if successFilter(x[1]) log.silly 'dyn', "api call returned successfully : #{JSON.stringify(x[1])}" successCase(x[1]) else log.info 'dyn', "api call returned error : #{JSON.stringify(x[1])}" errorCase x[1] , (x) -> log.warn 'dyn', "unexpected error : #{JSON.stringify(x[1])}" errorCase x isOk = (x) -> x && (x.status == 'success') identity = (x) -> x extract = (key) -> (x) -> x?[key] extractData = extract 'data' extractMsgs = extract 'msgs' msgIsOk = (x) -> x && x.response && (x.response.status == 200) extractMsgData = (x) -> x?.response?.data okBool = -> true failBool = -> false extractRecords = (x) -> return [] unless x && x.data _(x.data).map (r) -> v = r.split("/") {type:v[2].replace(/Record$/, ""),zone:v[3],fqdn:v[4],id:v[5]} extractZones = (x) -> return [] unless x && x.data _(x.data).map (r) -> v = r.split("/") {zone:v[3]} throwMessages = (x) -> throw (x.msgs || "unknown exception when calling api") throwMsgMessages = (x) -> throw (x?.response?.message || "unknown exception when calling api") Dyn = (opts) -> traffic_defaults = _.defaults opts?.traffic || {}, { host: 'api2.dynect.net' port: 443 prefix:'/REST' headers:{ 'Content-Type':'application/json' 'User-Agent':'dyn-js v1.0.3' } token:null } messaging_defaults = _.defaults opts?.messaging || {}, { host: 'emailapi.dynect.net' port: 443 prefix:'/rest/json' headers:{ 'Content-Type':'application/x-www-form-urlencoded' 'User-Agent':'dyn-js v1.0.3' } apikey:null } dyn = {} dyn.traffic = {} traffic = dyn.traffic dyn.log = log dyn.log.level = "info" traffic.defaults = _.clone traffic_defaults traffic.withZone = (zone) -> traffic.defaults.zone = zone traffic traffic.zone = crudZone() traffic.zone.list = () -> callWithError traffic.zone._list._call(traffic, {}, {}), "zone.list", isOk, extractZones, throwMessages traffic.zone.create = (args) -> callWithError traffic.zone._create._call(traffic, {zone:traffic.defaults.zone}, args), "zone.create", isOk, extractData, throwMessages traffic.zone.get = -> callWithError traffic.zone._list._call(traffic, {zone:traffic.defaults.zone}, {}), "zone.get", isOk, extractData, throwMessages traffic.zone.destroy = -> callWithError traffic.zone._destroy._call(traffic, {zone:traffic.defaults.zone}, {}), "zone.destroy", isOk, extractMsgs, throwMessages traffic.zone.publish = -> callWithError traffic.zone._update._call(traffic, {zone:traffic.defaults.zone}, {publish:true}), "zone.publish", isOk, extractData, throwMessages traffic.zone.freeze = -> callWithError traffic.zone._update._call(traffic, {zone:traffic.defaults.zone}, {freeze:true}), "zone.freeze", isOk, extractData, throwMessages traffic.zone.thaw = -> callWithError traffic.zone._update._call(traffic, {zone:traffic.defaults.zone}, {thaw:true}), "zone.thaw", isOk, extractData, throwMessages traffic.session = crudTraffic "/Session/" traffic.session.create = -> callWithError(traffic.session._create._call(traffic, {}, _.pick(traffic.defaults, 'customer_name', 'user_name', 'password')), "session.create", isOk, (x) -> traffic.defaults.token = x.data.token makePromise x , throwMessages) traffic.session.destroy = -> callWithError(traffic.session._destroy._call(traffic, {}, {}), "session.destroy", isOk, (x) -> traffic.defaults.token = null makePromise x , throwMessages) recordTypes = ['All','ANY','A','AAAA','CERT','CNAME','DHCID','DNAME','DNSKEY','DS','IPSECKEY','KEY','KX','LOC','MX','NAPTR','NS','NSAP','PTR','PX','RP','SOA','SPF','SRV','SSHFP','TXT'] whiteList = {'All':'list','ANY':'list','SOA':{'list':true,'get':true,'update':true}} allow = (x, op) -> !whiteList[x] || ( _.isString(whiteList[x]) && whiteList[x] == op) || ( _.isObject(whiteList[x]) && whiteList[x][op] ) traffic.record = _.reduce recordTypes, (a, x) -> type = "_#{x}" a[type] = crudRecord(x) a[type].list = ( (fqdn) -> callWithError traffic.record[type]._list._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn||''}, {}), "record._#{type}.list", isOk, extractRecords, throwMessages ) if allow(x, 'list') a[type].create = ( (fqdn, record) -> callWithError traffic.record[type]._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, record), "record._#{type}.create", isOk, extractData, throwMessages ) if allow(x, 'create') a[type].destroy = ( (fqdn, opt_id) -> callWithError traffic.record[type]._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:opt_id||''}, {}), "record._#{type}.destroy", isOk, extractMsgs, throwMessages ) if allow(x, 'destroy') a[type].get = ( (fqdn, id) -> callWithError traffic.record[type]._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:id}, {}), "record._#{type}.get", isOk, extractRecords, throwMessages ) if allow(x, 'get') a[type].update = ( (fqdn, id, record) -> callWithError traffic.record[type]._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:id}, record), "record._#{type}.update", isOk, extractData, throwMessages ) if allow(x, 'update') a[type].replace = ( (fqdn, records) -> arg = {} arg["#{x}Records"] = records callWithError traffic.record[type]._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,id:''}, arg), "record._#{type}.replace", isOk, extractData, throwMessages ) if allow(x, 'replace') a , {} traffic.http_redirect = crudHttpRedirect() traffic.http_redirect.list = (fqdn) -> callWithError traffic.http_redirect._list._call(traffic, {zone:traffic.defaults.zone}, {}), "http_redirect.list", isOk, extractData, throwMessages traffic.http_redirect.get = (fqdn, detail) -> callWithError traffic.http_redirect._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {detail:detail||'N'}), "http_redirect.get", isOk, extractData, throwMessages traffic.http_redirect.create = (fqdn, code, keep_uri, url) -> callWithError traffic.http_redirect._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {code:code, keep_uri:keep_uri, url:url}), "http_redirect.create", isOk, extractData, throwMessages traffic.http_redirect.update = (fqdn, code, keep_uri, url) -> callWithError traffic.http_redirect._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {code:code, keep_uri:keep_uri, url:url}), "http_redirect.update", isOk, extractData, throwMessages traffic.http_redirect.destroy = (fqdn) -> callWithError traffic.http_redirect._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "http_redirect.destroy", isOk, extractData, throwMessages traffic.gslb = crudGslb() traffic.gslb.list = (detail) -> callWithError traffic.gslb._list._call(traffic, {zone:traffic.defaults.zone}, {detail:detail||'N'}), "gslb.list", isOk, extractData, throwMessages traffic.gslb.get = (fqdn) -> callWithError traffic.gslb._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslb.get", isOk, extractData, throwMessages traffic.gslb.create = (fqdn, opts) -> callWithError traffic.gslb._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslb.create", isOk, extractData, throwMessages traffic.gslb.destroy = (fqdn) -> callWithError traffic.gslb._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslb.destroy", isOk, extractData, throwMessages traffic.gslb.update = (fqdn, opts) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslb.update", isOk, extractData, throwMessages traffic.gslb.activate = (fqdn) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {activate:true}), "gslb.activate", isOk, extractData, throwMessages traffic.gslb.deactivate = (fqdn) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {deactivate:true}), "gslb.deactivate", isOk, extractData, throwMessages traffic.gslb.recover = (fqdn) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {recover:true}), "gslb.recover", isOk, extractData, throwMessages traffic.gslb.recoverip = (fqdn, opts) -> callWithError traffic.gslb._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslb.recoverip", isOk, extractData, throwMessages traffic.gslbRegion = crudGslbRegion() traffic.gslbRegion.list = (detail) -> callWithError traffic.gslbRegion._list._call(traffic, {zone:traffic.defaults.zone}, {detail:detail||'N'}), "gslbRegion.list", isOk, extractData, throwMessages traffic.gslbRegion.get = (fqdn) -> callWithError traffic.gslbRegion._get._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslbRegion.get", isOk, extractData, throwMessages traffic.gslbRegion.create = (fqdn, opts) -> callWithError traffic.gslbRegion._create._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, opts), "gslbRegion.create", isOk, extractData, throwMessages traffic.gslbRegion.destroy = (fqdn) -> callWithError traffic.gslbRegion._destroy._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn}, {}), "gslbRegion.destroy", isOk, extractData, throwMessages traffic.gslbRegion.update = (fqdn, region_code, opts) -> callWithError traffic.gslbRegion._update._call(traffic, {zone:traffic.defaults.zone,fqdn:fqdn,region_code:region_code}, opts), "gslbRegion.update", isOk, extractData, throwMessages dyn.messaging = {} messaging = dyn.messaging messaging.defaults = _.clone messaging_defaults messaging.senders = crudSenders() messaging.senders.list = (startindex) -> callWithError messaging.senders._list._call(messaging, {}, _.defaults({startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "senders.list", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.create = (email, seeding) -> callWithError messaging.senders._create._call(messaging, {}, _.defaults({emailaddress:email,seeding:seeding||'0'}, {apikey:messaging.defaults.apikey})), "senders.create", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.update = (email, seeding) -> callWithError messaging.senders._update._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.update", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.details = (email) -> callWithError messaging.senders._details._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.details", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.status = (email) -> callWithError messaging.senders._status._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.status", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.dkim = (email, dkim) -> callWithError messaging.senders._dkim._call(messaging, {}, _.defaults({emailaddress:email,dkim:dkim}, {apikey:messaging.defaults.apikey})), "senders.dkim", msgIsOk, extractMsgData, throwMsgMessages messaging.senders.destroy = (email) -> callWithError messaging.senders._destroy._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "senders.destroy", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts = crudAccounts() messaging.accounts.create = (username, password, companyname, phone, address, city, state, zipcode, country, timezone, bounceurl, spamurl, unsubscribeurl, trackopens, tracelinks, trackunsubscribes, generatenewapikey) -> callWithError messaging.accounts._create._call(messaging, {}, _.defaults({username:username, password:PI:PASSWORD:<PASSWORD>END_PI, companyname:companyname, phone:phone, address:address, city:city, state:state, zipcode:zipcode, country:country, timezone:timezone, bounceurl:bounceurl, spamurl:spamurl, unsubscribeurl:unsubscribeurl, trackopens:trackopens, tracelinks:tracelinks, trackunsubscribes:trackunsubscribes, generatenewapikey:generatenewapikey}, {apikey:messaging.defaults.apikey})), "accounts.create", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.list = (startindex) -> callWithError messaging.accounts._list._call(messaging, {}, _.defaults({startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "accounts.list", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.destroy = (username) -> callWithError messaging.accounts._destroy._call(messaging, {}, _.defaults({username:username}, {apikey:messaging.defaults.apikey})), "accounts.destroy", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.list_xheaders = -> callWithError messaging.accounts._list_xheaders._call(messaging, {}, _.defaults({}, {apikey:messaging.defaults.apikey})), "accounts.list_xheaders", msgIsOk, extractMsgData, throwMsgMessages messaging.accounts.update_xheaders = (xh1,xh2,xh3,xh4) -> callWithError messaging.accounts._update_xheaders._call(messaging, {}, _.defaults({xheader1:xh1,xheader2:xh2,xheader3:xh3,xheader4:xh4}, {apikey:messaging.defaults.apikey})), "accounts.update_xheaders", msgIsOk, extractMsgData, throwMsgMessages messaging.recipients = crudRecipients() messaging.recipients.status = (email) -> callWithError messaging.recipients._status._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "recipients.status", msgIsOk, extractMsgData, throwMsgMessages messaging.recipients.activate = (email) -> callWithError messaging.recipients._activate._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "recipients.activate", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions = crudSuppressions() messaging.suppressions.count = (startdate, enddate) -> callWithError messaging.suppressions._count._call(messaging, {}, _.defaults({}, {apikey:messaging.defaults.apikey})), "suppressions.count", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions.list = (startdate, enddate, startindex) -> callWithError messaging.suppressions._list._call(messaging, {}, _.defaults({startdate:startdate, enddate:enddate, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "suppressions.list", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions.create = (email) -> callWithError messaging.suppressions._create._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "suppressions.create", msgIsOk, extractMsgData, throwMsgMessages messaging.suppressions.activate = (email) -> callWithError messaging.suppressions._activate._call(messaging, {}, _.defaults({emailaddress:email}, {apikey:messaging.defaults.apikey})), "suppressions.activate", msgIsOk, extractMsgData, throwMsgMessages messaging.delivery = crudReportsDelivered() messaging.delivery.count = (starttime, endtime) -> callWithError messaging.delivery._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "delivery.count", msgIsOk, extractMsgData, throwMsgMessages messaging.delivery.list = (starttime, endtime, startindex) -> callWithError messaging.delivery._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "delivery.list", msgIsOk, extractMsgData, throwMsgMessages messaging.sent_mail = crudReportsSentMail() messaging.sent_mail.count = (starttime, endtime) -> callWithError messaging.sent_mail._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "sent_mail.count", msgIsOk, extractMsgData, throwMsgMessages messaging.sent_mail.list = (starttime, endtime, startindex) -> callWithError messaging.sent_mail._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "sent_mail.list", msgIsOk, extractMsgData, throwMsgMessages messaging.bounces = crudReportsBounces() messaging.bounces.count = (starttime, endtime) -> callWithError messaging.bounces._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "bounces.count", msgIsOk, extractMsgData, throwMsgMessages messaging.bounces.list = (starttime, endtime, startindex) -> callWithError messaging.bounces._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "bounces.list", msgIsOk, extractMsgData, throwMsgMessages messaging.complaints = crudReportsComplaints() messaging.complaints.count = (starttime, endtime) -> callWithError messaging.complaints._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "complaints.count", msgIsOk, extractMsgData, throwMsgMessages messaging.complaints.list = (starttime, endtime, startindex) -> callWithError messaging.complaints._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "complaints.list", msgIsOk, extractMsgData, throwMsgMessages messaging.issues = crudReportsIssues() messaging.issues.count = (starttime, endtime) -> callWithError messaging.issues._count._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "issues.count", msgIsOk, extractMsgData, throwMsgMessages messaging.issues.list = (starttime, endtime, startindex) -> callWithError messaging.issues._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime, startindex:startindex||'0'}, {apikey:messaging.defaults.apikey})), "issues.list", msgIsOk, extractMsgData, throwMsgMessages messaging.opens = crudReportsOpens() messaging.opens.count = (starttime, endtime) -> callWithError messaging.opens._count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.count", msgIsOk, extractMsgData, throwMsgMessages messaging.opens.list = (starttime, endtime, startindex) -> callWithError messaging.opens._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.list", msgIsOk, extractMsgData, throwMsgMessages messaging.opens.unique = (starttime, endtime, startindex) -> callWithError messaging.opens._unique._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.unqiue", msgIsOk, extractMsgData, throwMsgMessages messaging.opens.unique_count = (starttime, endtime) -> callWithError messaging.opens._unique_count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "opens.unique_count", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks = crudReportsClicks() messaging.clicks.count = (starttime, endtime) -> callWithError messaging.clicks._count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.count", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks.list = (starttime, endtime, startindex) -> callWithError messaging.clicks._list._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.list", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks.unique = (starttime, endtime, startindex) -> callWithError messaging.clicks._unique._call(messaging, {}, _.defaults({starttime:starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.unique", msgIsOk, extractMsgData, throwMsgMessages messaging.clicks.unique_count = (starttime, endtime) -> callWithError messaging.clicks._unique_count._call(messaging, {}, _.defaults({starttime, endtime:endtime}, {apikey:messaging.defaults.apikey})), "clicks.unique_count", msgIsOk, extractMsgData, throwMsgMessages messaging.send_mail = crudSendMail() messaging.send_mail.create = (from, to, subject, bodytext, bodyhmtl, cc, replyto, xheaders) -> callWithError messaging.send_mail._create._call(messaging, {}, _.defaults({from:from, to:to, subject:subject, bodytext:bodytext, bodyhtml:bodyhmtl, cc:cc, replyto:replyto, xheaders:xheaders}, {apikey:messaging.defaults.apikey})), "send_mail.create", msgIsOk, extractMsgData, throwMsgMessages dyn module.exports = Dyn
[ { "context": " : $scope.email\n password : $scope.password\n callback : (err, success)", "end": 1941, "score": 0.5138763785362244, "start": 1941, "tag": "PASSWORD", "value": "" }, { "context": "il = null\n $scope.password = null\n $scope.vpassword = null\n $scope.ema", "end": 3178, "score": 0.6973081827163696, "start": 3174, "tag": "PASSWORD", "value": "null" }, { "context": " emailID : $scope.email\n password : $scope.password\n callback : (err) ->\n $", "end": 4485, "score": 0.9240902066230774, "start": 4471, "tag": "PASSWORD", "value": "scope.password" } ]
src/server/applications/authentication_interface/js/controller.coffee
bladepan/cloudbrowser
0
CBAuthentication = angular.module("CBAuthentication", []) # API Objects curBrowser = cloudbrowser.currentBrowser auth = cloudbrowser.auth appConfig = cloudbrowser.parentAppConfig googleStrategy = auth.getGoogleStrategy() localStrategy = auth.getLocalStrategy() # Status Strings AUTH_FAIL = "Invalid credentials" EMAIL_EMPTY = "Please provide the Email ID" EMAIL_IN_USE = "Account with this Email ID already exists" EMAIL_INVALID = "Please provide a valid email ID" RESET_SUCCESS = "A password reset link has been sent to your email ID" PASSWORD_EMPTY = "Please provide the password" # Regular expressions EMAIL_RE = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/ CBAuthentication.controller "LoginCtrl", ($scope) -> $scope.safeApply = (fn) -> phase = this.$root.$$phase if phase is '$apply' or phase is '$digest' if fn then fn() else this.$apply(fn) # Initialization $scope.email = null $scope.password = null $scope.emailError = null $scope.passwordError = null $scope.loginError = null $scope.resetSuccessMsg = null $scope.isDisabled = false $scope.showEmailButton = false # Watches $scope.$watch "email + password", () -> $scope.loginError = null $scope.isDisabled = false $scope.resetSuccessMsg = null $scope.$watch "email", () -> $scope.emailError = null $scope.$watch "password", () -> $scope.passwordError = null # Methods on angular scope $scope.googleLogin = () -> googleStrategy.login() $scope.login = () -> if not $scope.email then $scope.emailError = EMAIL_EMPTY else if not $scope.password then $scope.passwordError = PASSWORD_EMPTY else $scope.isDisabled = true localStrategy.login emailID : $scope.email password : $scope.password callback : (err, success) -> $scope.safeApply -> if err then $scope.loginError = err.message else if not success then $scope.loginError = AUTH_FAIL # We redirect on success and kill this VB # so there's no need to display a success message $scope.isDisabled = false $scope.sendResetLink = () -> if not ($scope.email and EMAIL_RE.test($scope.email.toUpperCase())) $scope.emailError = EMAIL_INVALID else $scope.resetDisabled = true auth.sendResetLink $scope.email, (err, success) -> $scope.safeApply -> if err then $scope.emailError = err.message else $scope.resetSuccessMsg = RESET_SUCCESS $scope.resetDisabled = false CBAuthentication.controller "SignupCtrl", ($scope) -> $scope.safeApply = (fn) -> phase = this.$root.$$phase if phase is '$apply' or phase is '$digest' if fn then fn() else this.$apply(fn) # Initialization $scope.email = null $scope.password = null $scope.vpassword = null $scope.emailError = null $scope.signupError = null $scope.passwordError = null $scope.successMessage = false $scope.isDisabled = false # Watches $scope.$watch "email", (nval, oval) -> $scope.emailError = null $scope.signupError = null $scope.isDisabled = false $scope.successMessage = false appConfig.isLocalUser $scope.email, (err, exists) -> $scope.safeApply () -> if err then return ($scope.emailError = err.message) else if not exists then return $scope.emailError = EMAIL_IN_USE $scope.isDisabled = true $scope.$watch "password+vpassword", -> if not $scope.emailError then $scope.isDisabled = false $scope.signupError = null $scope.passwordError = null # Methods on the angular scope $scope.signup = () -> $scope.isDisabled = true if not ($scope.email and EMAIL_RE.test($scope.email.toUpperCase())) $scope.emailError = EMAIL_INVALID else if not $scope.password then $scope.passwordError = PASSWORD_EMPTY else localStrategy.signup emailID : $scope.email password : $scope.password callback : (err) -> $scope.safeApply -> if err then $scope.signupError = err.message else $scope.successMessage = true
178369
CBAuthentication = angular.module("CBAuthentication", []) # API Objects curBrowser = cloudbrowser.currentBrowser auth = cloudbrowser.auth appConfig = cloudbrowser.parentAppConfig googleStrategy = auth.getGoogleStrategy() localStrategy = auth.getLocalStrategy() # Status Strings AUTH_FAIL = "Invalid credentials" EMAIL_EMPTY = "Please provide the Email ID" EMAIL_IN_USE = "Account with this Email ID already exists" EMAIL_INVALID = "Please provide a valid email ID" RESET_SUCCESS = "A password reset link has been sent to your email ID" PASSWORD_EMPTY = "Please provide the password" # Regular expressions EMAIL_RE = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/ CBAuthentication.controller "LoginCtrl", ($scope) -> $scope.safeApply = (fn) -> phase = this.$root.$$phase if phase is '$apply' or phase is '$digest' if fn then fn() else this.$apply(fn) # Initialization $scope.email = null $scope.password = null $scope.emailError = null $scope.passwordError = null $scope.loginError = null $scope.resetSuccessMsg = null $scope.isDisabled = false $scope.showEmailButton = false # Watches $scope.$watch "email + password", () -> $scope.loginError = null $scope.isDisabled = false $scope.resetSuccessMsg = null $scope.$watch "email", () -> $scope.emailError = null $scope.$watch "password", () -> $scope.passwordError = null # Methods on angular scope $scope.googleLogin = () -> googleStrategy.login() $scope.login = () -> if not $scope.email then $scope.emailError = EMAIL_EMPTY else if not $scope.password then $scope.passwordError = PASSWORD_EMPTY else $scope.isDisabled = true localStrategy.login emailID : $scope.email password : $scope<PASSWORD>.password callback : (err, success) -> $scope.safeApply -> if err then $scope.loginError = err.message else if not success then $scope.loginError = AUTH_FAIL # We redirect on success and kill this VB # so there's no need to display a success message $scope.isDisabled = false $scope.sendResetLink = () -> if not ($scope.email and EMAIL_RE.test($scope.email.toUpperCase())) $scope.emailError = EMAIL_INVALID else $scope.resetDisabled = true auth.sendResetLink $scope.email, (err, success) -> $scope.safeApply -> if err then $scope.emailError = err.message else $scope.resetSuccessMsg = RESET_SUCCESS $scope.resetDisabled = false CBAuthentication.controller "SignupCtrl", ($scope) -> $scope.safeApply = (fn) -> phase = this.$root.$$phase if phase is '$apply' or phase is '$digest' if fn then fn() else this.$apply(fn) # Initialization $scope.email = null $scope.password = <PASSWORD> $scope.vpassword = null $scope.emailError = null $scope.signupError = null $scope.passwordError = null $scope.successMessage = false $scope.isDisabled = false # Watches $scope.$watch "email", (nval, oval) -> $scope.emailError = null $scope.signupError = null $scope.isDisabled = false $scope.successMessage = false appConfig.isLocalUser $scope.email, (err, exists) -> $scope.safeApply () -> if err then return ($scope.emailError = err.message) else if not exists then return $scope.emailError = EMAIL_IN_USE $scope.isDisabled = true $scope.$watch "password+vpassword", -> if not $scope.emailError then $scope.isDisabled = false $scope.signupError = null $scope.passwordError = null # Methods on the angular scope $scope.signup = () -> $scope.isDisabled = true if not ($scope.email and EMAIL_RE.test($scope.email.toUpperCase())) $scope.emailError = EMAIL_INVALID else if not $scope.password then $scope.passwordError = PASSWORD_EMPTY else localStrategy.signup emailID : $scope.email password : $<PASSWORD> callback : (err) -> $scope.safeApply -> if err then $scope.signupError = err.message else $scope.successMessage = true
true
CBAuthentication = angular.module("CBAuthentication", []) # API Objects curBrowser = cloudbrowser.currentBrowser auth = cloudbrowser.auth appConfig = cloudbrowser.parentAppConfig googleStrategy = auth.getGoogleStrategy() localStrategy = auth.getLocalStrategy() # Status Strings AUTH_FAIL = "Invalid credentials" EMAIL_EMPTY = "Please provide the Email ID" EMAIL_IN_USE = "Account with this Email ID already exists" EMAIL_INVALID = "Please provide a valid email ID" RESET_SUCCESS = "A password reset link has been sent to your email ID" PASSWORD_EMPTY = "Please provide the password" # Regular expressions EMAIL_RE = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/ CBAuthentication.controller "LoginCtrl", ($scope) -> $scope.safeApply = (fn) -> phase = this.$root.$$phase if phase is '$apply' or phase is '$digest' if fn then fn() else this.$apply(fn) # Initialization $scope.email = null $scope.password = null $scope.emailError = null $scope.passwordError = null $scope.loginError = null $scope.resetSuccessMsg = null $scope.isDisabled = false $scope.showEmailButton = false # Watches $scope.$watch "email + password", () -> $scope.loginError = null $scope.isDisabled = false $scope.resetSuccessMsg = null $scope.$watch "email", () -> $scope.emailError = null $scope.$watch "password", () -> $scope.passwordError = null # Methods on angular scope $scope.googleLogin = () -> googleStrategy.login() $scope.login = () -> if not $scope.email then $scope.emailError = EMAIL_EMPTY else if not $scope.password then $scope.passwordError = PASSWORD_EMPTY else $scope.isDisabled = true localStrategy.login emailID : $scope.email password : $scopePI:PASSWORD:<PASSWORD>END_PI.password callback : (err, success) -> $scope.safeApply -> if err then $scope.loginError = err.message else if not success then $scope.loginError = AUTH_FAIL # We redirect on success and kill this VB # so there's no need to display a success message $scope.isDisabled = false $scope.sendResetLink = () -> if not ($scope.email and EMAIL_RE.test($scope.email.toUpperCase())) $scope.emailError = EMAIL_INVALID else $scope.resetDisabled = true auth.sendResetLink $scope.email, (err, success) -> $scope.safeApply -> if err then $scope.emailError = err.message else $scope.resetSuccessMsg = RESET_SUCCESS $scope.resetDisabled = false CBAuthentication.controller "SignupCtrl", ($scope) -> $scope.safeApply = (fn) -> phase = this.$root.$$phase if phase is '$apply' or phase is '$digest' if fn then fn() else this.$apply(fn) # Initialization $scope.email = null $scope.password = PI:PASSWORD:<PASSWORD>END_PI $scope.vpassword = null $scope.emailError = null $scope.signupError = null $scope.passwordError = null $scope.successMessage = false $scope.isDisabled = false # Watches $scope.$watch "email", (nval, oval) -> $scope.emailError = null $scope.signupError = null $scope.isDisabled = false $scope.successMessage = false appConfig.isLocalUser $scope.email, (err, exists) -> $scope.safeApply () -> if err then return ($scope.emailError = err.message) else if not exists then return $scope.emailError = EMAIL_IN_USE $scope.isDisabled = true $scope.$watch "password+vpassword", -> if not $scope.emailError then $scope.isDisabled = false $scope.signupError = null $scope.passwordError = null # Methods on the angular scope $scope.signup = () -> $scope.isDisabled = true if not ($scope.email and EMAIL_RE.test($scope.email.toUpperCase())) $scope.emailError = EMAIL_INVALID else if not $scope.password then $scope.passwordError = PASSWORD_EMPTY else localStrategy.signup emailID : $scope.email password : $PI:PASSWORD:<PASSWORD>END_PI callback : (err) -> $scope.safeApply -> if err then $scope.signupError = err.message else $scope.successMessage = true
[ { "context": "as URLs\", ->\n {tokens} = grammar.tokenizeLine(\"John Smith <johnSmith@example.com>\")\n expect(tokens[0]).t", "end": 2097, "score": 0.9998739361763, "start": 2087, "tag": "NAME", "value": "John Smith" }, { "context": "\n {tokens} = grammar.tokenizeLine(\"John Smith <johnSmith@example.com>\")\n expect(tokens[0]).toEqual value: \"John Smi", "end": 2120, "score": 0.9999265074729919, "start": 2099, "tag": "EMAIL", "value": "johnSmith@example.com" }, { "context": "mple.com>\")\n expect(tokens[0]).toEqual value: \"John Smith <johnSmith@example.com>\", scopes: [\"source.asciid", "end": 2172, "score": 0.9998732805252075, "start": 2162, "tag": "NAME", "value": "John Smith" }, { "context": " expect(tokens[0]).toEqual value: \"John Smith <johnSmith@example.com>\", scopes: [\"source.asciidoc\"]\n\n it \"tokenizes i", "end": 2195, "score": 0.9999251961708069, "start": 2174, "tag": "EMAIL", "value": "johnSmith@example.com" }, { "context": "\", ->\n {tokens} = grammar.tokenizeLine(\"[verse, Homer Simpson]\\n\")\n expect(tokens[1]).toEqual value: \"verse\"", "end": 10578, "score": 0.9153040647506714, "start": 10565, "tag": "NAME", "value": "Homer Simpson" }, { "context": ".asciidoc\"]\n expect(tokens[3]).toEqual value: \"Homer Simpson\", scopes: [\"source.asciidoc\", \"markup.quote.attri", "end": 10746, "score": 0.9998601078987122, "start": 10733, "tag": "NAME", "value": "Homer Simpson" }, { "context": "\", ->\n {tokens} = grammar.tokenizeLine(\"[quote, Erwin Schrödinger, Sorry]\\n\")\n expect(tokens[1]).toEqual value: ", "end": 10947, "score": 0.9996442794799805, "start": 10930, "tag": "NAME", "value": "Erwin Schrödinger" }, { "context": ".asciidoc\"]\n expect(tokens[3]).toEqual value: \"Erwin Schrödinger\", scopes: [\"source.asciidoc\", \"markup.quote.attri", "end": 11126, "score": 0.9997535943984985, "start": 11109, "tag": "NAME", "value": "Erwin Schrödinger" } ]
.atom/.atom/packages/language-asciidoc/spec/asciidoc-spec.coffee
thepieuvre/dotfiles
0
describe "AsciiDoc grammar", -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage("language-asciidoc") runs -> grammar = atom.grammars.grammarForScopeName("source.asciidoc") # convenience function during development debug = (tokens) -> console.log(JSON.stringify(tokens, null, '\t')) it "parses the grammar", -> expect(grammar).toBeDefined() expect(grammar.scopeName).toBe "source.asciidoc" it "tokenizes *bold* text", -> {tokens} = grammar.tokenizeLine("this is *bold* text") expect(tokens[0]).toEqual value: "this is ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "*bold*", scopes: ["source.asciidoc", "markup.bold.asciidoc"] expect(tokens[2]).toEqual value: " text", scopes: ["source.asciidoc"] it "tokenizes _italic_ text", -> {tokens} = grammar.tokenizeLine("this is _italic_ text") expect(tokens[0]).toEqual value: "this is ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "_italic_", scopes: ["source.asciidoc", "markup.italic.asciidoc"] expect(tokens[2]).toEqual value: " text", scopes: ["source.asciidoc"] it "tokenizes HTML elements", -> {tokens} = grammar.tokenizeLine("Dungeons &amp; Dragons") expect(tokens[0]).toEqual value: "Dungeons ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "&", scopes: ["source.asciidoc", "markup.htmlentity.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "amp", scopes: ["source.asciidoc", "markup.htmlentity.asciidoc"] expect(tokens[3]).toEqual value: ";", scopes: ["source.asciidoc", "markup.htmlentity.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " Dragons", scopes: ["source.asciidoc"] it "tokenizes URLs", -> {tokens} = grammar.tokenizeLine("http://www.docbook.org is great") expect(tokens[0]).toEqual value: "http://www.docbook.org", scopes: ["source.asciidoc", "markup.underline.link.asciidoc"] it "does not tokenizes email addresses as URLs", -> {tokens} = grammar.tokenizeLine("John Smith <johnSmith@example.com>") expect(tokens[0]).toEqual value: "John Smith <johnSmith@example.com>", scopes: ["source.asciidoc"] it "tokenizes inline macros", -> {tokens} = grammar.tokenizeLine("http://www.docbook.org/[DocBook.org]") expect(tokens[0]).toEqual value: "http:", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc", "support.constant.asciidoc"] expect(tokens[1]).toEqual value: "//www.docbook.org/", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc"] expect(tokens[2]).toEqual value: "[", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc", "support.constant.asciidoc"] expect(tokens[3]).toEqual value: "DocBook.org", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc"] expect(tokens[4]).toEqual value: "]", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc", "support.constant.asciidoc"] it "tokenizes block macros", -> {tokens} = grammar.tokenizeLine("image::tiger.png[Tyger tyger]") expect(tokens[0]).toEqual value: "image::", scopes: ["source.asciidoc", "markup.macro.block.asciidoc", "support.constant.asciidoc"] expect(tokens[1]).toEqual value: "tiger.png", scopes: ["source.asciidoc", "markup.macro.block.asciidoc"] expect(tokens[2]).toEqual value: "[", scopes: ["source.asciidoc", "markup.macro.block.asciidoc", "support.constant.asciidoc"] expect(tokens[3]).toEqual value: "Tyger tyger", scopes: ["source.asciidoc", "markup.macro.block.asciidoc"] expect(tokens[4]).toEqual value: "]", scopes: ["source.asciidoc", "markup.macro.block.asciidoc", "support.constant.asciidoc"] it "tokenizes [[blockId]] elements", -> {tokens} = grammar.tokenizeLine("this is a [[blockId]] element") expect(tokens[0]).toEqual value: "this is a ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "[[", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "blockId", scopes: ["source.asciidoc", "markup.blockid.asciidoc"] expect(tokens[3]).toEqual value: "]]", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " element", scopes: ["source.asciidoc"] it "tokenizes [[[bib-ref]]] bibliography references", -> {tokens} = grammar.tokenizeLine("this is a [[[bib-ref]]] element") expect(tokens[0]).toEqual value: "this is a ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "[[[", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "bib-ref", scopes: ["source.asciidoc", "markup.biblioref.asciidoc"] expect(tokens[3]).toEqual value: "]]]", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " element", scopes: ["source.asciidoc"] it "tokenizes <<reference>> elements", -> {tokens} = grammar.tokenizeLine("this is a <<reference>> element") expect(tokens[0]).toEqual value: "this is a ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "<<", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "reference", scopes: ["source.asciidoc", "markup.reference.asciidoc"] expect(tokens[3]).toEqual value: ">>", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " element", scopes: ["source.asciidoc"] testAsciidocHeaders = (level) -> equalsSigns = level + 1 marker = Array(equalsSigns + 1).join('=') {tokens} = grammar.tokenizeLine("#{marker} Heading #{level}") expect(tokens[0]).toEqual value: "#{marker} ", scopes: ["source.asciidoc", "markup.heading.asciidoc"] expect(tokens[1]).toEqual value: "Heading #{level}", scopes: ["source.asciidoc", "markup.heading.asciidoc"] it "tokenizes AsciiDoc-style headings", -> testAsciidocHeaders(level) for level in [0..5] it "tokenizes block titles", -> {tokens} = grammar.tokenizeLine(""" .An example example ========= Example ========= """) expect(tokens[1]).toEqual value: "An example example", scopes: ["source.asciidoc", "markup.heading.blocktitle.asciidoc"] expect(tokens[3]).toEqual value: "=========", scopes: ["source.asciidoc", "markup.block.example.asciidoc"] it "tokenizes list bullets with the length up to 5 symbols", -> {tokens} = grammar.tokenizeLine(""" . Level 1 .. Level 2 *** Level 3 **** Level 4 ***** Level 5 """) expect(tokens[0]).toEqual value: ".", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[3]).toEqual value: "..", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[6]).toEqual value: "***", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[9]).toEqual value: "****", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[12]).toEqual value: "*****", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] it "tokenizes table delimited block", -> {tokens} = grammar.tokenizeLine("|===\n|===") expect(tokens[0]).toEqual value: "|===", scopes: ["source.asciidoc", "support.table.asciidoc"] expect(tokens[2]).toEqual value: "|===", scopes: ["source.asciidoc", "support.table.asciidoc"] it "ignores table delimited block with less than 3 equal signs", -> {tokens} = grammar.tokenizeLine("|==\n|==") expect(tokens[0]).toEqual value: "|==\n|==", scopes: ["source.asciidoc"] it "tokenizes cell delimiters within table block", -> {tokens} = grammar.tokenizeLine("|===\n|Name h|Purpose\n|===") expect(tokens[2]).toEqual value: "|", scopes: ["source.asciidoc", "support.table.asciidoc"] expect(tokens[6]).toEqual value: "|", scopes: ["source.asciidoc", "support.table.asciidoc"] it "tokenizes cell specs within table block", -> {tokens} = grammar.tokenizeLine("|===\n^|1 2.2+^.^|2 .3+<.>m|3\n|===") expect(tokens[2]).toEqual value: "^", scopes: ["source.asciidoc", "support.table.spec.asciidoc"] expect(tokens[6]).toEqual value: "2.2+^.^", scopes: ["source.asciidoc", "support.table.spec.asciidoc"] expect(tokens[10]).toEqual value: ".3+<.>m", scopes: ["source.asciidoc", "support.table.spec.asciidoc"] it "tokenizes admonition", -> {tokens} = grammar.tokenizeLine("NOTE: This is a note") expect(tokens[0]).toEqual value: "NOTE:", scopes: ["source.asciidoc", "markup.admonition.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "This is a note", scopes: ["source.asciidoc", "markup.admonition.asciidoc"] it "tokenizes explicit paragraph styles", -> {tokens} = grammar.tokenizeLine("[NOTE]\n====\n") expect(tokens[1]).toEqual value: "NOTE", scopes: ["source.asciidoc", "markup.explicit.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: "====", scopes: ["source.asciidoc", "markup.block.example.asciidoc"] it "tokenizes section templates", -> {tokens} = grammar.tokenizeLine("[sect1]\nThis is an section.\n") expect(tokens[1]).toEqual value: "sect1", scopes: ["source.asciidoc", "markup.section.asciidoc", "support.constant.asciidoc"] expect(tokens[3]).toEqual value: "\nThis is an section.\n", scopes: ["source.asciidoc"] it "tokenizes quote blocks", -> {tokens} = grammar.tokenizeLine(""" [quote] ____ D'oh! ____ """) expect(tokens[1]).toEqual value: "quote", scopes: ["source.asciidoc", "markup.quote.declaration.asciidoc"] expect(tokens[4]).toEqual value: "____", scopes: ["source.asciidoc", "markup.quote.block.asciidoc"] expect(tokens[5]).toEqual value: "\nD'oh!\n", scopes: ["source.asciidoc", "markup.quote.block.asciidoc"] expect(tokens[6]).toEqual value: "____", scopes: ["source.asciidoc", "markup.quote.block.asciidoc"] it "tokenizes quote declarations with attribution", -> {tokens} = grammar.tokenizeLine("[verse, Homer Simpson]\n") expect(tokens[1]).toEqual value: "verse", scopes: ["source.asciidoc", "markup.quote.declaration.asciidoc"] expect(tokens[3]).toEqual value: "Homer Simpson", scopes: ["source.asciidoc", "markup.quote.attribution.asciidoc"] it "tokenizes quote declarations with attribution and citation", -> {tokens} = grammar.tokenizeLine("[quote, Erwin Schrödinger, Sorry]\n") expect(tokens[1]).toEqual value: "quote", scopes: ["source.asciidoc", "markup.quote.declaration.asciidoc"] expect(tokens[3]).toEqual value: "Erwin Schrödinger", scopes: ["source.asciidoc", "markup.quote.attribution.asciidoc"] expect(tokens[5]).toEqual value: "Sorry", scopes: ["source.asciidoc", "markup.quote.citation.asciidoc"] testBlock = (delimiter,type) -> marker = Array(5).join(delimiter) {tokens} = grammar.tokenizeLine("#{marker}\ncontent\n#{marker}") expect(tokens[0]).toEqual value: marker, scopes: ["source.asciidoc", type] expect(tokens[2]).toEqual value: marker, scopes: ["source.asciidoc", type] it "tokenizes comment block", -> testBlock "/", "comment.block.asciidoc" it "tokenizes example block", -> testBlock "=", "markup.block.example.asciidoc" it "tokenizes sidebar block", -> testBlock "*", "markup.block.sidebar.asciidoc" it "tokenizes literal block", -> testBlock ".", "markup.block.literal.asciidoc" it "tokenizes passthrough block", -> testBlock "+", "markup.block.passthrough.asciidoc"
22559
describe "AsciiDoc grammar", -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage("language-asciidoc") runs -> grammar = atom.grammars.grammarForScopeName("source.asciidoc") # convenience function during development debug = (tokens) -> console.log(JSON.stringify(tokens, null, '\t')) it "parses the grammar", -> expect(grammar).toBeDefined() expect(grammar.scopeName).toBe "source.asciidoc" it "tokenizes *bold* text", -> {tokens} = grammar.tokenizeLine("this is *bold* text") expect(tokens[0]).toEqual value: "this is ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "*bold*", scopes: ["source.asciidoc", "markup.bold.asciidoc"] expect(tokens[2]).toEqual value: " text", scopes: ["source.asciidoc"] it "tokenizes _italic_ text", -> {tokens} = grammar.tokenizeLine("this is _italic_ text") expect(tokens[0]).toEqual value: "this is ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "_italic_", scopes: ["source.asciidoc", "markup.italic.asciidoc"] expect(tokens[2]).toEqual value: " text", scopes: ["source.asciidoc"] it "tokenizes HTML elements", -> {tokens} = grammar.tokenizeLine("Dungeons &amp; Dragons") expect(tokens[0]).toEqual value: "Dungeons ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "&", scopes: ["source.asciidoc", "markup.htmlentity.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "amp", scopes: ["source.asciidoc", "markup.htmlentity.asciidoc"] expect(tokens[3]).toEqual value: ";", scopes: ["source.asciidoc", "markup.htmlentity.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " Dragons", scopes: ["source.asciidoc"] it "tokenizes URLs", -> {tokens} = grammar.tokenizeLine("http://www.docbook.org is great") expect(tokens[0]).toEqual value: "http://www.docbook.org", scopes: ["source.asciidoc", "markup.underline.link.asciidoc"] it "does not tokenizes email addresses as URLs", -> {tokens} = grammar.tokenizeLine("<NAME> <<EMAIL>>") expect(tokens[0]).toEqual value: "<NAME> <<EMAIL>>", scopes: ["source.asciidoc"] it "tokenizes inline macros", -> {tokens} = grammar.tokenizeLine("http://www.docbook.org/[DocBook.org]") expect(tokens[0]).toEqual value: "http:", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc", "support.constant.asciidoc"] expect(tokens[1]).toEqual value: "//www.docbook.org/", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc"] expect(tokens[2]).toEqual value: "[", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc", "support.constant.asciidoc"] expect(tokens[3]).toEqual value: "DocBook.org", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc"] expect(tokens[4]).toEqual value: "]", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc", "support.constant.asciidoc"] it "tokenizes block macros", -> {tokens} = grammar.tokenizeLine("image::tiger.png[Tyger tyger]") expect(tokens[0]).toEqual value: "image::", scopes: ["source.asciidoc", "markup.macro.block.asciidoc", "support.constant.asciidoc"] expect(tokens[1]).toEqual value: "tiger.png", scopes: ["source.asciidoc", "markup.macro.block.asciidoc"] expect(tokens[2]).toEqual value: "[", scopes: ["source.asciidoc", "markup.macro.block.asciidoc", "support.constant.asciidoc"] expect(tokens[3]).toEqual value: "Tyger tyger", scopes: ["source.asciidoc", "markup.macro.block.asciidoc"] expect(tokens[4]).toEqual value: "]", scopes: ["source.asciidoc", "markup.macro.block.asciidoc", "support.constant.asciidoc"] it "tokenizes [[blockId]] elements", -> {tokens} = grammar.tokenizeLine("this is a [[blockId]] element") expect(tokens[0]).toEqual value: "this is a ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "[[", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "blockId", scopes: ["source.asciidoc", "markup.blockid.asciidoc"] expect(tokens[3]).toEqual value: "]]", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " element", scopes: ["source.asciidoc"] it "tokenizes [[[bib-ref]]] bibliography references", -> {tokens} = grammar.tokenizeLine("this is a [[[bib-ref]]] element") expect(tokens[0]).toEqual value: "this is a ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "[[[", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "bib-ref", scopes: ["source.asciidoc", "markup.biblioref.asciidoc"] expect(tokens[3]).toEqual value: "]]]", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " element", scopes: ["source.asciidoc"] it "tokenizes <<reference>> elements", -> {tokens} = grammar.tokenizeLine("this is a <<reference>> element") expect(tokens[0]).toEqual value: "this is a ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "<<", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "reference", scopes: ["source.asciidoc", "markup.reference.asciidoc"] expect(tokens[3]).toEqual value: ">>", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " element", scopes: ["source.asciidoc"] testAsciidocHeaders = (level) -> equalsSigns = level + 1 marker = Array(equalsSigns + 1).join('=') {tokens} = grammar.tokenizeLine("#{marker} Heading #{level}") expect(tokens[0]).toEqual value: "#{marker} ", scopes: ["source.asciidoc", "markup.heading.asciidoc"] expect(tokens[1]).toEqual value: "Heading #{level}", scopes: ["source.asciidoc", "markup.heading.asciidoc"] it "tokenizes AsciiDoc-style headings", -> testAsciidocHeaders(level) for level in [0..5] it "tokenizes block titles", -> {tokens} = grammar.tokenizeLine(""" .An example example ========= Example ========= """) expect(tokens[1]).toEqual value: "An example example", scopes: ["source.asciidoc", "markup.heading.blocktitle.asciidoc"] expect(tokens[3]).toEqual value: "=========", scopes: ["source.asciidoc", "markup.block.example.asciidoc"] it "tokenizes list bullets with the length up to 5 symbols", -> {tokens} = grammar.tokenizeLine(""" . Level 1 .. Level 2 *** Level 3 **** Level 4 ***** Level 5 """) expect(tokens[0]).toEqual value: ".", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[3]).toEqual value: "..", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[6]).toEqual value: "***", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[9]).toEqual value: "****", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[12]).toEqual value: "*****", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] it "tokenizes table delimited block", -> {tokens} = grammar.tokenizeLine("|===\n|===") expect(tokens[0]).toEqual value: "|===", scopes: ["source.asciidoc", "support.table.asciidoc"] expect(tokens[2]).toEqual value: "|===", scopes: ["source.asciidoc", "support.table.asciidoc"] it "ignores table delimited block with less than 3 equal signs", -> {tokens} = grammar.tokenizeLine("|==\n|==") expect(tokens[0]).toEqual value: "|==\n|==", scopes: ["source.asciidoc"] it "tokenizes cell delimiters within table block", -> {tokens} = grammar.tokenizeLine("|===\n|Name h|Purpose\n|===") expect(tokens[2]).toEqual value: "|", scopes: ["source.asciidoc", "support.table.asciidoc"] expect(tokens[6]).toEqual value: "|", scopes: ["source.asciidoc", "support.table.asciidoc"] it "tokenizes cell specs within table block", -> {tokens} = grammar.tokenizeLine("|===\n^|1 2.2+^.^|2 .3+<.>m|3\n|===") expect(tokens[2]).toEqual value: "^", scopes: ["source.asciidoc", "support.table.spec.asciidoc"] expect(tokens[6]).toEqual value: "2.2+^.^", scopes: ["source.asciidoc", "support.table.spec.asciidoc"] expect(tokens[10]).toEqual value: ".3+<.>m", scopes: ["source.asciidoc", "support.table.spec.asciidoc"] it "tokenizes admonition", -> {tokens} = grammar.tokenizeLine("NOTE: This is a note") expect(tokens[0]).toEqual value: "NOTE:", scopes: ["source.asciidoc", "markup.admonition.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "This is a note", scopes: ["source.asciidoc", "markup.admonition.asciidoc"] it "tokenizes explicit paragraph styles", -> {tokens} = grammar.tokenizeLine("[NOTE]\n====\n") expect(tokens[1]).toEqual value: "NOTE", scopes: ["source.asciidoc", "markup.explicit.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: "====", scopes: ["source.asciidoc", "markup.block.example.asciidoc"] it "tokenizes section templates", -> {tokens} = grammar.tokenizeLine("[sect1]\nThis is an section.\n") expect(tokens[1]).toEqual value: "sect1", scopes: ["source.asciidoc", "markup.section.asciidoc", "support.constant.asciidoc"] expect(tokens[3]).toEqual value: "\nThis is an section.\n", scopes: ["source.asciidoc"] it "tokenizes quote blocks", -> {tokens} = grammar.tokenizeLine(""" [quote] ____ D'oh! ____ """) expect(tokens[1]).toEqual value: "quote", scopes: ["source.asciidoc", "markup.quote.declaration.asciidoc"] expect(tokens[4]).toEqual value: "____", scopes: ["source.asciidoc", "markup.quote.block.asciidoc"] expect(tokens[5]).toEqual value: "\nD'oh!\n", scopes: ["source.asciidoc", "markup.quote.block.asciidoc"] expect(tokens[6]).toEqual value: "____", scopes: ["source.asciidoc", "markup.quote.block.asciidoc"] it "tokenizes quote declarations with attribution", -> {tokens} = grammar.tokenizeLine("[verse, <NAME>]\n") expect(tokens[1]).toEqual value: "verse", scopes: ["source.asciidoc", "markup.quote.declaration.asciidoc"] expect(tokens[3]).toEqual value: "<NAME>", scopes: ["source.asciidoc", "markup.quote.attribution.asciidoc"] it "tokenizes quote declarations with attribution and citation", -> {tokens} = grammar.tokenizeLine("[quote, <NAME>, Sorry]\n") expect(tokens[1]).toEqual value: "quote", scopes: ["source.asciidoc", "markup.quote.declaration.asciidoc"] expect(tokens[3]).toEqual value: "<NAME>", scopes: ["source.asciidoc", "markup.quote.attribution.asciidoc"] expect(tokens[5]).toEqual value: "Sorry", scopes: ["source.asciidoc", "markup.quote.citation.asciidoc"] testBlock = (delimiter,type) -> marker = Array(5).join(delimiter) {tokens} = grammar.tokenizeLine("#{marker}\ncontent\n#{marker}") expect(tokens[0]).toEqual value: marker, scopes: ["source.asciidoc", type] expect(tokens[2]).toEqual value: marker, scopes: ["source.asciidoc", type] it "tokenizes comment block", -> testBlock "/", "comment.block.asciidoc" it "tokenizes example block", -> testBlock "=", "markup.block.example.asciidoc" it "tokenizes sidebar block", -> testBlock "*", "markup.block.sidebar.asciidoc" it "tokenizes literal block", -> testBlock ".", "markup.block.literal.asciidoc" it "tokenizes passthrough block", -> testBlock "+", "markup.block.passthrough.asciidoc"
true
describe "AsciiDoc grammar", -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage("language-asciidoc") runs -> grammar = atom.grammars.grammarForScopeName("source.asciidoc") # convenience function during development debug = (tokens) -> console.log(JSON.stringify(tokens, null, '\t')) it "parses the grammar", -> expect(grammar).toBeDefined() expect(grammar.scopeName).toBe "source.asciidoc" it "tokenizes *bold* text", -> {tokens} = grammar.tokenizeLine("this is *bold* text") expect(tokens[0]).toEqual value: "this is ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "*bold*", scopes: ["source.asciidoc", "markup.bold.asciidoc"] expect(tokens[2]).toEqual value: " text", scopes: ["source.asciidoc"] it "tokenizes _italic_ text", -> {tokens} = grammar.tokenizeLine("this is _italic_ text") expect(tokens[0]).toEqual value: "this is ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "_italic_", scopes: ["source.asciidoc", "markup.italic.asciidoc"] expect(tokens[2]).toEqual value: " text", scopes: ["source.asciidoc"] it "tokenizes HTML elements", -> {tokens} = grammar.tokenizeLine("Dungeons &amp; Dragons") expect(tokens[0]).toEqual value: "Dungeons ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "&", scopes: ["source.asciidoc", "markup.htmlentity.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "amp", scopes: ["source.asciidoc", "markup.htmlentity.asciidoc"] expect(tokens[3]).toEqual value: ";", scopes: ["source.asciidoc", "markup.htmlentity.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " Dragons", scopes: ["source.asciidoc"] it "tokenizes URLs", -> {tokens} = grammar.tokenizeLine("http://www.docbook.org is great") expect(tokens[0]).toEqual value: "http://www.docbook.org", scopes: ["source.asciidoc", "markup.underline.link.asciidoc"] it "does not tokenizes email addresses as URLs", -> {tokens} = grammar.tokenizeLine("PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>") expect(tokens[0]).toEqual value: "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>", scopes: ["source.asciidoc"] it "tokenizes inline macros", -> {tokens} = grammar.tokenizeLine("http://www.docbook.org/[DocBook.org]") expect(tokens[0]).toEqual value: "http:", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc", "support.constant.asciidoc"] expect(tokens[1]).toEqual value: "//www.docbook.org/", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc"] expect(tokens[2]).toEqual value: "[", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc", "support.constant.asciidoc"] expect(tokens[3]).toEqual value: "DocBook.org", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc"] expect(tokens[4]).toEqual value: "]", scopes: ["source.asciidoc", "markup.macro.inline.asciidoc", "support.constant.asciidoc"] it "tokenizes block macros", -> {tokens} = grammar.tokenizeLine("image::tiger.png[Tyger tyger]") expect(tokens[0]).toEqual value: "image::", scopes: ["source.asciidoc", "markup.macro.block.asciidoc", "support.constant.asciidoc"] expect(tokens[1]).toEqual value: "tiger.png", scopes: ["source.asciidoc", "markup.macro.block.asciidoc"] expect(tokens[2]).toEqual value: "[", scopes: ["source.asciidoc", "markup.macro.block.asciidoc", "support.constant.asciidoc"] expect(tokens[3]).toEqual value: "Tyger tyger", scopes: ["source.asciidoc", "markup.macro.block.asciidoc"] expect(tokens[4]).toEqual value: "]", scopes: ["source.asciidoc", "markup.macro.block.asciidoc", "support.constant.asciidoc"] it "tokenizes [[blockId]] elements", -> {tokens} = grammar.tokenizeLine("this is a [[blockId]] element") expect(tokens[0]).toEqual value: "this is a ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "[[", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "blockId", scopes: ["source.asciidoc", "markup.blockid.asciidoc"] expect(tokens[3]).toEqual value: "]]", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " element", scopes: ["source.asciidoc"] it "tokenizes [[[bib-ref]]] bibliography references", -> {tokens} = grammar.tokenizeLine("this is a [[[bib-ref]]] element") expect(tokens[0]).toEqual value: "this is a ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "[[[", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "bib-ref", scopes: ["source.asciidoc", "markup.biblioref.asciidoc"] expect(tokens[3]).toEqual value: "]]]", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " element", scopes: ["source.asciidoc"] it "tokenizes <<reference>> elements", -> {tokens} = grammar.tokenizeLine("this is a <<reference>> element") expect(tokens[0]).toEqual value: "this is a ", scopes: ["source.asciidoc"] expect(tokens[1]).toEqual value: "<<", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "reference", scopes: ["source.asciidoc", "markup.reference.asciidoc"] expect(tokens[3]).toEqual value: ">>", scopes: ["source.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: " element", scopes: ["source.asciidoc"] testAsciidocHeaders = (level) -> equalsSigns = level + 1 marker = Array(equalsSigns + 1).join('=') {tokens} = grammar.tokenizeLine("#{marker} Heading #{level}") expect(tokens[0]).toEqual value: "#{marker} ", scopes: ["source.asciidoc", "markup.heading.asciidoc"] expect(tokens[1]).toEqual value: "Heading #{level}", scopes: ["source.asciidoc", "markup.heading.asciidoc"] it "tokenizes AsciiDoc-style headings", -> testAsciidocHeaders(level) for level in [0..5] it "tokenizes block titles", -> {tokens} = grammar.tokenizeLine(""" .An example example ========= Example ========= """) expect(tokens[1]).toEqual value: "An example example", scopes: ["source.asciidoc", "markup.heading.blocktitle.asciidoc"] expect(tokens[3]).toEqual value: "=========", scopes: ["source.asciidoc", "markup.block.example.asciidoc"] it "tokenizes list bullets with the length up to 5 symbols", -> {tokens} = grammar.tokenizeLine(""" . Level 1 .. Level 2 *** Level 3 **** Level 4 ***** Level 5 """) expect(tokens[0]).toEqual value: ".", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[3]).toEqual value: "..", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[6]).toEqual value: "***", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[9]).toEqual value: "****", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] expect(tokens[12]).toEqual value: "*****", scopes: ["source.asciidoc", "markup.list.asciidoc", "markup.list.bullet.asciidoc"] it "tokenizes table delimited block", -> {tokens} = grammar.tokenizeLine("|===\n|===") expect(tokens[0]).toEqual value: "|===", scopes: ["source.asciidoc", "support.table.asciidoc"] expect(tokens[2]).toEqual value: "|===", scopes: ["source.asciidoc", "support.table.asciidoc"] it "ignores table delimited block with less than 3 equal signs", -> {tokens} = grammar.tokenizeLine("|==\n|==") expect(tokens[0]).toEqual value: "|==\n|==", scopes: ["source.asciidoc"] it "tokenizes cell delimiters within table block", -> {tokens} = grammar.tokenizeLine("|===\n|Name h|Purpose\n|===") expect(tokens[2]).toEqual value: "|", scopes: ["source.asciidoc", "support.table.asciidoc"] expect(tokens[6]).toEqual value: "|", scopes: ["source.asciidoc", "support.table.asciidoc"] it "tokenizes cell specs within table block", -> {tokens} = grammar.tokenizeLine("|===\n^|1 2.2+^.^|2 .3+<.>m|3\n|===") expect(tokens[2]).toEqual value: "^", scopes: ["source.asciidoc", "support.table.spec.asciidoc"] expect(tokens[6]).toEqual value: "2.2+^.^", scopes: ["source.asciidoc", "support.table.spec.asciidoc"] expect(tokens[10]).toEqual value: ".3+<.>m", scopes: ["source.asciidoc", "support.table.spec.asciidoc"] it "tokenizes admonition", -> {tokens} = grammar.tokenizeLine("NOTE: This is a note") expect(tokens[0]).toEqual value: "NOTE:", scopes: ["source.asciidoc", "markup.admonition.asciidoc", "support.constant.asciidoc"] expect(tokens[2]).toEqual value: "This is a note", scopes: ["source.asciidoc", "markup.admonition.asciidoc"] it "tokenizes explicit paragraph styles", -> {tokens} = grammar.tokenizeLine("[NOTE]\n====\n") expect(tokens[1]).toEqual value: "NOTE", scopes: ["source.asciidoc", "markup.explicit.asciidoc", "support.constant.asciidoc"] expect(tokens[4]).toEqual value: "====", scopes: ["source.asciidoc", "markup.block.example.asciidoc"] it "tokenizes section templates", -> {tokens} = grammar.tokenizeLine("[sect1]\nThis is an section.\n") expect(tokens[1]).toEqual value: "sect1", scopes: ["source.asciidoc", "markup.section.asciidoc", "support.constant.asciidoc"] expect(tokens[3]).toEqual value: "\nThis is an section.\n", scopes: ["source.asciidoc"] it "tokenizes quote blocks", -> {tokens} = grammar.tokenizeLine(""" [quote] ____ D'oh! ____ """) expect(tokens[1]).toEqual value: "quote", scopes: ["source.asciidoc", "markup.quote.declaration.asciidoc"] expect(tokens[4]).toEqual value: "____", scopes: ["source.asciidoc", "markup.quote.block.asciidoc"] expect(tokens[5]).toEqual value: "\nD'oh!\n", scopes: ["source.asciidoc", "markup.quote.block.asciidoc"] expect(tokens[6]).toEqual value: "____", scopes: ["source.asciidoc", "markup.quote.block.asciidoc"] it "tokenizes quote declarations with attribution", -> {tokens} = grammar.tokenizeLine("[verse, PI:NAME:<NAME>END_PI]\n") expect(tokens[1]).toEqual value: "verse", scopes: ["source.asciidoc", "markup.quote.declaration.asciidoc"] expect(tokens[3]).toEqual value: "PI:NAME:<NAME>END_PI", scopes: ["source.asciidoc", "markup.quote.attribution.asciidoc"] it "tokenizes quote declarations with attribution and citation", -> {tokens} = grammar.tokenizeLine("[quote, PI:NAME:<NAME>END_PI, Sorry]\n") expect(tokens[1]).toEqual value: "quote", scopes: ["source.asciidoc", "markup.quote.declaration.asciidoc"] expect(tokens[3]).toEqual value: "PI:NAME:<NAME>END_PI", scopes: ["source.asciidoc", "markup.quote.attribution.asciidoc"] expect(tokens[5]).toEqual value: "Sorry", scopes: ["source.asciidoc", "markup.quote.citation.asciidoc"] testBlock = (delimiter,type) -> marker = Array(5).join(delimiter) {tokens} = grammar.tokenizeLine("#{marker}\ncontent\n#{marker}") expect(tokens[0]).toEqual value: marker, scopes: ["source.asciidoc", type] expect(tokens[2]).toEqual value: marker, scopes: ["source.asciidoc", type] it "tokenizes comment block", -> testBlock "/", "comment.block.asciidoc" it "tokenizes example block", -> testBlock "=", "markup.block.example.asciidoc" it "tokenizes sidebar block", -> testBlock "*", "markup.block.sidebar.asciidoc" it "tokenizes literal block", -> testBlock ".", "markup.block.literal.asciidoc" it "tokenizes passthrough block", -> testBlock "+", "markup.block.passthrough.asciidoc"
[ { "context": "api/sign_up', { sign_up: { email: email, password: password } })\n .success((data) ->\n console.l", "end": 1623, "score": 0.9984756112098694, "start": 1615, "tag": "PASSWORD", "value": "password" }, { "context": "api/sign_in', { session: { email: email, password: password } })\n .success((data) ->\n console.log", "end": 2207, "score": 0.9977308511734009, "start": 2199, "tag": "PASSWORD", "value": "password" } ]
webapp/app/scripts/app.coffee
ntaoo/angularwithrails
0
'use strict' app = angular.module('app', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]) app.config(["$locationProvider", ($locationProvider) -> $locationProvider.html5Mode(true) ]) app.config(["$routeProvider", ($routeProvider) -> $routeProvider .when '/', templateUrl: 'views/main.html' controller: 'MainCtrl' .when '/sign_in', templateUrl: 'views/sign_in.html' controller: 'SignInCtrl' .when '/sign_up', templateUrl: 'views/sign_up.html' controller: 'SignUpCtrl' .when '/articles', templateUrl: 'views/articles.html' controller: 'ArticlesCtrl', resolve: { checkCurrentUser: ["Authentication", (Authentication) -> Authentication.checkCurrentUser()] } .otherwise redirectTo: '/' ]) app.config(["$httpProvider", ($httpProvider) -> interceptor = ['$rootScope', '$location', '$q', ($rootScope, $location, $q) -> success = (response) -> response error = (response) -> if response.status == 401 console.log ' catch 401' $rootScope.$broadcast('event:signInRequired') $q.reject(response) else if response.status == 422 console.log 'catch 422' $q.reject(response) else $q.reject(response) return (promise) -> promise.then(success, error) ] $httpProvider.responseInterceptors.push(interceptor) ]) app.service('Authentication', ["$rootScope", "$http", "$q", "$location", "currentUser", ($rootScope, $http, $q, $location, currentUser) -> signUp: (email, password) -> deferred = $q.defer() $http.post('/api/sign_up', { sign_up: { email: email, password: password } }) .success((data) -> console.log 'signed up and signed in' currentUser.set(data.currentUser) $rootScope.$broadcast('event:signedIn') deferred.resolve() ) .error((data, status) -> if status == 422 console.log 'status code: 422' deferred.reject(data, status) else deferred.reject(data, status) ) return deferred.promise signIn: (email, password) -> deferred = $q.defer() $http.post('/api/sign_in', { session: { email: email, password: password } }) .success((data) -> console.log 'signed in' currentUser.set(data.currentUser) $rootScope.$broadcast('event:signedIn') deferred.resolve() ) .error((data, status) -> if status == 422 console.log 'status code: 422' deferred.reject(data, status) else deferred.reject(data, status) ) return deferred.promise checkCurrentUser: () -> if !(currentUser.isExisting()) $rootScope.$broadcast('event:signInRequired') clearCurrentUser: () -> currentUser.clear() ]) app.service('currentUser', ["$http", "$q", ($http, $q) -> id = null email = null _clear = () -> id = null email = null isExisting: () -> id != null && email != null signOut: () -> deferred = $q.defer() $http.delete('/api/sign_out') .success(() -> _clear() deferred.resolve() ) .error((data, status) -> if status == 422 console.log 'status code: 422' deferred.reject(data, status) else deferred.reject(data, status) ) set: (user) -> id = user.id email = user.email clear: () -> _clear() ]) app.run(["$rootScope", "$http", "$location", "Authentication", ($rootScope, $http, $location, Authentication) -> $rootScope.$on('event:signInRequired', (_) -> Authentication.clearCurrentUser() $location.path('/sign_in') ) ])
107882
'use strict' app = angular.module('app', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]) app.config(["$locationProvider", ($locationProvider) -> $locationProvider.html5Mode(true) ]) app.config(["$routeProvider", ($routeProvider) -> $routeProvider .when '/', templateUrl: 'views/main.html' controller: 'MainCtrl' .when '/sign_in', templateUrl: 'views/sign_in.html' controller: 'SignInCtrl' .when '/sign_up', templateUrl: 'views/sign_up.html' controller: 'SignUpCtrl' .when '/articles', templateUrl: 'views/articles.html' controller: 'ArticlesCtrl', resolve: { checkCurrentUser: ["Authentication", (Authentication) -> Authentication.checkCurrentUser()] } .otherwise redirectTo: '/' ]) app.config(["$httpProvider", ($httpProvider) -> interceptor = ['$rootScope', '$location', '$q', ($rootScope, $location, $q) -> success = (response) -> response error = (response) -> if response.status == 401 console.log ' catch 401' $rootScope.$broadcast('event:signInRequired') $q.reject(response) else if response.status == 422 console.log 'catch 422' $q.reject(response) else $q.reject(response) return (promise) -> promise.then(success, error) ] $httpProvider.responseInterceptors.push(interceptor) ]) app.service('Authentication', ["$rootScope", "$http", "$q", "$location", "currentUser", ($rootScope, $http, $q, $location, currentUser) -> signUp: (email, password) -> deferred = $q.defer() $http.post('/api/sign_up', { sign_up: { email: email, password: <PASSWORD> } }) .success((data) -> console.log 'signed up and signed in' currentUser.set(data.currentUser) $rootScope.$broadcast('event:signedIn') deferred.resolve() ) .error((data, status) -> if status == 422 console.log 'status code: 422' deferred.reject(data, status) else deferred.reject(data, status) ) return deferred.promise signIn: (email, password) -> deferred = $q.defer() $http.post('/api/sign_in', { session: { email: email, password: <PASSWORD> } }) .success((data) -> console.log 'signed in' currentUser.set(data.currentUser) $rootScope.$broadcast('event:signedIn') deferred.resolve() ) .error((data, status) -> if status == 422 console.log 'status code: 422' deferred.reject(data, status) else deferred.reject(data, status) ) return deferred.promise checkCurrentUser: () -> if !(currentUser.isExisting()) $rootScope.$broadcast('event:signInRequired') clearCurrentUser: () -> currentUser.clear() ]) app.service('currentUser', ["$http", "$q", ($http, $q) -> id = null email = null _clear = () -> id = null email = null isExisting: () -> id != null && email != null signOut: () -> deferred = $q.defer() $http.delete('/api/sign_out') .success(() -> _clear() deferred.resolve() ) .error((data, status) -> if status == 422 console.log 'status code: 422' deferred.reject(data, status) else deferred.reject(data, status) ) set: (user) -> id = user.id email = user.email clear: () -> _clear() ]) app.run(["$rootScope", "$http", "$location", "Authentication", ($rootScope, $http, $location, Authentication) -> $rootScope.$on('event:signInRequired', (_) -> Authentication.clearCurrentUser() $location.path('/sign_in') ) ])
true
'use strict' app = angular.module('app', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]) app.config(["$locationProvider", ($locationProvider) -> $locationProvider.html5Mode(true) ]) app.config(["$routeProvider", ($routeProvider) -> $routeProvider .when '/', templateUrl: 'views/main.html' controller: 'MainCtrl' .when '/sign_in', templateUrl: 'views/sign_in.html' controller: 'SignInCtrl' .when '/sign_up', templateUrl: 'views/sign_up.html' controller: 'SignUpCtrl' .when '/articles', templateUrl: 'views/articles.html' controller: 'ArticlesCtrl', resolve: { checkCurrentUser: ["Authentication", (Authentication) -> Authentication.checkCurrentUser()] } .otherwise redirectTo: '/' ]) app.config(["$httpProvider", ($httpProvider) -> interceptor = ['$rootScope', '$location', '$q', ($rootScope, $location, $q) -> success = (response) -> response error = (response) -> if response.status == 401 console.log ' catch 401' $rootScope.$broadcast('event:signInRequired') $q.reject(response) else if response.status == 422 console.log 'catch 422' $q.reject(response) else $q.reject(response) return (promise) -> promise.then(success, error) ] $httpProvider.responseInterceptors.push(interceptor) ]) app.service('Authentication', ["$rootScope", "$http", "$q", "$location", "currentUser", ($rootScope, $http, $q, $location, currentUser) -> signUp: (email, password) -> deferred = $q.defer() $http.post('/api/sign_up', { sign_up: { email: email, password: PI:PASSWORD:<PASSWORD>END_PI } }) .success((data) -> console.log 'signed up and signed in' currentUser.set(data.currentUser) $rootScope.$broadcast('event:signedIn') deferred.resolve() ) .error((data, status) -> if status == 422 console.log 'status code: 422' deferred.reject(data, status) else deferred.reject(data, status) ) return deferred.promise signIn: (email, password) -> deferred = $q.defer() $http.post('/api/sign_in', { session: { email: email, password: PI:PASSWORD:<PASSWORD>END_PI } }) .success((data) -> console.log 'signed in' currentUser.set(data.currentUser) $rootScope.$broadcast('event:signedIn') deferred.resolve() ) .error((data, status) -> if status == 422 console.log 'status code: 422' deferred.reject(data, status) else deferred.reject(data, status) ) return deferred.promise checkCurrentUser: () -> if !(currentUser.isExisting()) $rootScope.$broadcast('event:signInRequired') clearCurrentUser: () -> currentUser.clear() ]) app.service('currentUser', ["$http", "$q", ($http, $q) -> id = null email = null _clear = () -> id = null email = null isExisting: () -> id != null && email != null signOut: () -> deferred = $q.defer() $http.delete('/api/sign_out') .success(() -> _clear() deferred.resolve() ) .error((data, status) -> if status == 422 console.log 'status code: 422' deferred.reject(data, status) else deferred.reject(data, status) ) set: (user) -> id = user.id email = user.email clear: () -> _clear() ]) app.run(["$rootScope", "$http", "$location", "Authentication", ($rootScope, $http, $location, Authentication) -> $rootScope.$on('event:signInRequired', (_) -> Authentication.clearCurrentUser() $location.path('/sign_in') ) ])
[ { "context": "nterest = new Backbone.Model id: 'foobar', name: 'Foo Bar'\n @view.resultsList.trigger 'add', interest\n", "end": 770, "score": 0.9946351051330566, "start": 763, "tag": "NAME", "value": "Foo Bar" }, { "context": "'foobar'\n interest: id: 'foobar', name: 'Foo Bar'\n category: 'collected_before'\n\n Ba", "end": 1205, "score": 0.9905663132667542, "start": 1198, "tag": "NAME", "value": "Foo Bar" }, { "context": "nterest = new Backbone.Model id: 'foobar', name: 'Foo Bar'\n @view.collection.addInterest @interest\n\n ", "end": 1498, "score": 0.994091808795929, "start": 1491, "tag": "NAME", "value": "Foo Bar" } ]
src/desktop/components/user_interests/test/view.coffee
kanaabe/force
1
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' UserInterestsView = null describe 'UserInterestsView', -> before (done) -> benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') UserInterestsView = rewire '../view' UserInterestsView.__set__ 'CURRENT_USER', 'existy' UserInterestsView.__set__ 'ResultsListView', Backbone.View Backbone.$ = $ done() after -> benv.teardown() beforeEach -> sinon.stub Backbone, 'sync' @view = new UserInterestsView afterEach -> Backbone.sync.restore() describe '#interested', -> beforeEach -> interest = new Backbone.Model id: 'foobar', name: 'Foo Bar' @view.resultsList.trigger 'add', interest it 'when a result is added; the view syncs it as an inteerest', -> Backbone.sync.callCount.should.equal 2 Backbone.sync.args[0][1].url() .should.containEql '/api/v1/me/user_interest' Backbone.sync.args[0][1].attributes .should.eql interest_type: 'Artist' interest_id: 'foobar' interest: id: 'foobar', name: 'Foo Bar' category: 'collected_before' Backbone.sync.args[1][1].url() .should.containEql '/api/v1/me/follow/artist' @view.following.length.should.equal 1 describe '#uninterested', -> beforeEach -> @interest = new Backbone.Model id: 'foobar', name: 'Foo Bar' @view.collection.addInterest @interest it 'removes the interest from the collection', -> @view.collection.length.should.equal 1 @view.resultsList.trigger 'remove', @interest @view.collection.length.should.equal 0 it 'destroys the interest', -> sinon.spy @view.collection.model::, 'destroy' @view.resultsList.trigger 'remove', @interest @view.collection.model::destroy.called.should.be.true()
157972
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' UserInterestsView = null describe 'UserInterestsView', -> before (done) -> benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') UserInterestsView = rewire '../view' UserInterestsView.__set__ 'CURRENT_USER', 'existy' UserInterestsView.__set__ 'ResultsListView', Backbone.View Backbone.$ = $ done() after -> benv.teardown() beforeEach -> sinon.stub Backbone, 'sync' @view = new UserInterestsView afterEach -> Backbone.sync.restore() describe '#interested', -> beforeEach -> interest = new Backbone.Model id: 'foobar', name: '<NAME>' @view.resultsList.trigger 'add', interest it 'when a result is added; the view syncs it as an inteerest', -> Backbone.sync.callCount.should.equal 2 Backbone.sync.args[0][1].url() .should.containEql '/api/v1/me/user_interest' Backbone.sync.args[0][1].attributes .should.eql interest_type: 'Artist' interest_id: 'foobar' interest: id: 'foobar', name: '<NAME>' category: 'collected_before' Backbone.sync.args[1][1].url() .should.containEql '/api/v1/me/follow/artist' @view.following.length.should.equal 1 describe '#uninterested', -> beforeEach -> @interest = new Backbone.Model id: 'foobar', name: '<NAME>' @view.collection.addInterest @interest it 'removes the interest from the collection', -> @view.collection.length.should.equal 1 @view.resultsList.trigger 'remove', @interest @view.collection.length.should.equal 0 it 'destroys the interest', -> sinon.spy @view.collection.model::, 'destroy' @view.resultsList.trigger 'remove', @interest @view.collection.model::destroy.called.should.be.true()
true
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' UserInterestsView = null describe 'UserInterestsView', -> before (done) -> benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') UserInterestsView = rewire '../view' UserInterestsView.__set__ 'CURRENT_USER', 'existy' UserInterestsView.__set__ 'ResultsListView', Backbone.View Backbone.$ = $ done() after -> benv.teardown() beforeEach -> sinon.stub Backbone, 'sync' @view = new UserInterestsView afterEach -> Backbone.sync.restore() describe '#interested', -> beforeEach -> interest = new Backbone.Model id: 'foobar', name: 'PI:NAME:<NAME>END_PI' @view.resultsList.trigger 'add', interest it 'when a result is added; the view syncs it as an inteerest', -> Backbone.sync.callCount.should.equal 2 Backbone.sync.args[0][1].url() .should.containEql '/api/v1/me/user_interest' Backbone.sync.args[0][1].attributes .should.eql interest_type: 'Artist' interest_id: 'foobar' interest: id: 'foobar', name: 'PI:NAME:<NAME>END_PI' category: 'collected_before' Backbone.sync.args[1][1].url() .should.containEql '/api/v1/me/follow/artist' @view.following.length.should.equal 1 describe '#uninterested', -> beforeEach -> @interest = new Backbone.Model id: 'foobar', name: 'PI:NAME:<NAME>END_PI' @view.collection.addInterest @interest it 'removes the interest from the collection', -> @view.collection.length.should.equal 1 @view.resultsList.trigger 'remove', @interest @view.collection.length.should.equal 0 it 'destroys the interest', -> sinon.spy @view.collection.model::, 'destroy' @view.resultsList.trigger 'remove', @interest @view.collection.model::destroy.called.should.be.true()
[ { "context": "given registration.\n *\n * The key is 'Realigned' if there is exactly one registration,\n * o", "end": 3103, "score": 0.748318076133728, "start": 3094, "tag": "KEY", "value": "Realigned" }, { "context": "Values)\n bolusDataSeries =\n key: 'Bolus Arrival'\n type: 'bar'\n yAxis: 1\n ", "end": 4959, "score": 0.999554455280304, "start": 4946, "tag": "NAME", "value": "Bolus Arrival" } ]
app/javascripts/intensityChart.coffee
ohsu-qin/qiprofile
0
define ['angular', 'chart'], (ng) -> intensityChart = ng.module 'qiprofile.intensitychart', [] intensityChart.factory 'IntensityChart', -> ###* * The Y axis value formatter function. If the given intensity * value is integral, then this function returns the integer. * Otherwise, the value is truncated to two decimal places. * * nvd3 unfortunately uses this function to format both the tick * values and the tooltip y values. Therefore, this function * formats the integral tick values as an integer and the float * y values as floats. Thus, both the y tick values and the * tooltip are more readable. * * @method formatIntensity * @param value the intensity value * @return the chart display value ### formatIntensity = (value) -> # ~~ is the obscure Javascript idiom for correctly converting # a float to an int. Math.floor does not correctly truncate # negative floats. intValue = ~~value if value == intValue intValue else value.toFixed(2) ###* * Makes the D3 intensity chart configuration for the given session. * * The result includes the T1 scan data series and each registration * data series. The chart x-axis labels are the one-based series * indexes, e.g. ['1', '2', ..., '12'] for 12 series. * * @method configure * @param session the session object * @param element the chart Angular jqLite element * @return the ngnvd3 chart configuration ### configure: (scan, element) -> # The scan data series and volume select color. This value must match # the .qi-scan-vol-btn-group basic color. SCAN_COLOR = 'Indigo' # The registration data series and volume select button colors. If # there are more than four registrations per scan, which is highly # unlikely, then the colors are reused. These values must match # the .qi-reg-vol-btn-group basic colors. REG_COLORS = ['LightGreen', 'LightYellow', 'LightCyan', 'LemonChiffon'] ###* * @method coordinate * @param image the scan or registration volume image * @param index the zero-based volume index * @return the intensity chart {x, y} coordinate ### coordinate = (image, index) -> {x: index + 1, y: image.averageIntensity} ###* * @method coordinates * @param images the scan or registration volume images * @return the intensity chart [{x, y}, ...] coordinates ### coordinates = (images) -> (coordinate(image, i) for image, i in images) ###* * @method dataSeriesKey * @return 'Realigned', followed by the one-based registration * number if there is more than one ### dataSeriesKey = (index) -> if scan.registrations.length == 1 'Realigned' else "Realigned #{ index + 1 }" ###* * Makes the data series {key, color} format object for the * given registration. * * The key is 'Realigned' if there is exactly one registration, * otherwise 'Realigned' followed by the one-based registration * number, e.g. 'Reg 1'. * * @method registrationDataSeries * @param registration the registration object * @param index the index of the registration in the registrations * array * @return the data series {key, color, values} format object ### registrationDataSeries = (registration, index) -> # Return the data series format object. key: dataSeriesKey(index) type: 'line' yAxis: 1 color: REG_COLORS[index % REG_COLORS.length] values: coordinates(registration.volumes.images) # The scan data series configuration. scanDataSeries = key: 'Scan' type: 'line' yAxis: 1 color: SCAN_COLOR values: coordinates(scan.volumes.images) # The registration data series. regDataSeries = (registrationDataSeries(reg, i) for reg, i in scan.registrations) # Combine the scan and registration data series. data = [scanDataSeries].concat(regDataSeries) # Add the bolus arrival bar. bolusArvNdx = scan.bolusArrivalIndex if bolusArvNdx? # Extend the bar from the axis to the top. dsIntensities = (_.map(dataSeries.values, 'y') for dataSeries in data) dsMaxIntensities = (_.max(values) for values in dsIntensities) maxIntensity = _.max(dsMaxIntensities) yValues = new Array(scan.volumes.images.length) if Array.prototype.fill? yValues.fill(0) else # Polyfill IE. for i in [0...yValues.length] yValues[i] = 0 yValues[bolusArvNdx] = maxIntensity values = ({x: i + 1, y: y} for y, i in yValues) bolusDataSeries = key: 'Bolus Arrival' type: 'bar' yAxis: 1 color: 'SandyBrown' values: values showMaxMin: false data.push(bolusDataSeries) # Return the chart configuration. options: chart: type: 'multiChart' forceY: [0] yAxis: tickFormat: formatIntensity showMaxMin: false xAxis: axisLabel: 'Time Point' ticks: scan.volumes.images.length tooltip: headerFormatter: (volumeNumber) -> "Volume #{ volumeNumber }" # Note: due to a svd3 but, valueFormatter doesn't work on a # multichart, although headerFormatter does. #valueFormatter: d3.format('.2f') data: data
34105
define ['angular', 'chart'], (ng) -> intensityChart = ng.module 'qiprofile.intensitychart', [] intensityChart.factory 'IntensityChart', -> ###* * The Y axis value formatter function. If the given intensity * value is integral, then this function returns the integer. * Otherwise, the value is truncated to two decimal places. * * nvd3 unfortunately uses this function to format both the tick * values and the tooltip y values. Therefore, this function * formats the integral tick values as an integer and the float * y values as floats. Thus, both the y tick values and the * tooltip are more readable. * * @method formatIntensity * @param value the intensity value * @return the chart display value ### formatIntensity = (value) -> # ~~ is the obscure Javascript idiom for correctly converting # a float to an int. Math.floor does not correctly truncate # negative floats. intValue = ~~value if value == intValue intValue else value.toFixed(2) ###* * Makes the D3 intensity chart configuration for the given session. * * The result includes the T1 scan data series and each registration * data series. The chart x-axis labels are the one-based series * indexes, e.g. ['1', '2', ..., '12'] for 12 series. * * @method configure * @param session the session object * @param element the chart Angular jqLite element * @return the ngnvd3 chart configuration ### configure: (scan, element) -> # The scan data series and volume select color. This value must match # the .qi-scan-vol-btn-group basic color. SCAN_COLOR = 'Indigo' # The registration data series and volume select button colors. If # there are more than four registrations per scan, which is highly # unlikely, then the colors are reused. These values must match # the .qi-reg-vol-btn-group basic colors. REG_COLORS = ['LightGreen', 'LightYellow', 'LightCyan', 'LemonChiffon'] ###* * @method coordinate * @param image the scan or registration volume image * @param index the zero-based volume index * @return the intensity chart {x, y} coordinate ### coordinate = (image, index) -> {x: index + 1, y: image.averageIntensity} ###* * @method coordinates * @param images the scan or registration volume images * @return the intensity chart [{x, y}, ...] coordinates ### coordinates = (images) -> (coordinate(image, i) for image, i in images) ###* * @method dataSeriesKey * @return 'Realigned', followed by the one-based registration * number if there is more than one ### dataSeriesKey = (index) -> if scan.registrations.length == 1 'Realigned' else "Realigned #{ index + 1 }" ###* * Makes the data series {key, color} format object for the * given registration. * * The key is '<KEY>' if there is exactly one registration, * otherwise 'Realigned' followed by the one-based registration * number, e.g. 'Reg 1'. * * @method registrationDataSeries * @param registration the registration object * @param index the index of the registration in the registrations * array * @return the data series {key, color, values} format object ### registrationDataSeries = (registration, index) -> # Return the data series format object. key: dataSeriesKey(index) type: 'line' yAxis: 1 color: REG_COLORS[index % REG_COLORS.length] values: coordinates(registration.volumes.images) # The scan data series configuration. scanDataSeries = key: 'Scan' type: 'line' yAxis: 1 color: SCAN_COLOR values: coordinates(scan.volumes.images) # The registration data series. regDataSeries = (registrationDataSeries(reg, i) for reg, i in scan.registrations) # Combine the scan and registration data series. data = [scanDataSeries].concat(regDataSeries) # Add the bolus arrival bar. bolusArvNdx = scan.bolusArrivalIndex if bolusArvNdx? # Extend the bar from the axis to the top. dsIntensities = (_.map(dataSeries.values, 'y') for dataSeries in data) dsMaxIntensities = (_.max(values) for values in dsIntensities) maxIntensity = _.max(dsMaxIntensities) yValues = new Array(scan.volumes.images.length) if Array.prototype.fill? yValues.fill(0) else # Polyfill IE. for i in [0...yValues.length] yValues[i] = 0 yValues[bolusArvNdx] = maxIntensity values = ({x: i + 1, y: y} for y, i in yValues) bolusDataSeries = key: '<NAME>' type: 'bar' yAxis: 1 color: 'SandyBrown' values: values showMaxMin: false data.push(bolusDataSeries) # Return the chart configuration. options: chart: type: 'multiChart' forceY: [0] yAxis: tickFormat: formatIntensity showMaxMin: false xAxis: axisLabel: 'Time Point' ticks: scan.volumes.images.length tooltip: headerFormatter: (volumeNumber) -> "Volume #{ volumeNumber }" # Note: due to a svd3 but, valueFormatter doesn't work on a # multichart, although headerFormatter does. #valueFormatter: d3.format('.2f') data: data
true
define ['angular', 'chart'], (ng) -> intensityChart = ng.module 'qiprofile.intensitychart', [] intensityChart.factory 'IntensityChart', -> ###* * The Y axis value formatter function. If the given intensity * value is integral, then this function returns the integer. * Otherwise, the value is truncated to two decimal places. * * nvd3 unfortunately uses this function to format both the tick * values and the tooltip y values. Therefore, this function * formats the integral tick values as an integer and the float * y values as floats. Thus, both the y tick values and the * tooltip are more readable. * * @method formatIntensity * @param value the intensity value * @return the chart display value ### formatIntensity = (value) -> # ~~ is the obscure Javascript idiom for correctly converting # a float to an int. Math.floor does not correctly truncate # negative floats. intValue = ~~value if value == intValue intValue else value.toFixed(2) ###* * Makes the D3 intensity chart configuration for the given session. * * The result includes the T1 scan data series and each registration * data series. The chart x-axis labels are the one-based series * indexes, e.g. ['1', '2', ..., '12'] for 12 series. * * @method configure * @param session the session object * @param element the chart Angular jqLite element * @return the ngnvd3 chart configuration ### configure: (scan, element) -> # The scan data series and volume select color. This value must match # the .qi-scan-vol-btn-group basic color. SCAN_COLOR = 'Indigo' # The registration data series and volume select button colors. If # there are more than four registrations per scan, which is highly # unlikely, then the colors are reused. These values must match # the .qi-reg-vol-btn-group basic colors. REG_COLORS = ['LightGreen', 'LightYellow', 'LightCyan', 'LemonChiffon'] ###* * @method coordinate * @param image the scan or registration volume image * @param index the zero-based volume index * @return the intensity chart {x, y} coordinate ### coordinate = (image, index) -> {x: index + 1, y: image.averageIntensity} ###* * @method coordinates * @param images the scan or registration volume images * @return the intensity chart [{x, y}, ...] coordinates ### coordinates = (images) -> (coordinate(image, i) for image, i in images) ###* * @method dataSeriesKey * @return 'Realigned', followed by the one-based registration * number if there is more than one ### dataSeriesKey = (index) -> if scan.registrations.length == 1 'Realigned' else "Realigned #{ index + 1 }" ###* * Makes the data series {key, color} format object for the * given registration. * * The key is 'PI:KEY:<KEY>END_PI' if there is exactly one registration, * otherwise 'Realigned' followed by the one-based registration * number, e.g. 'Reg 1'. * * @method registrationDataSeries * @param registration the registration object * @param index the index of the registration in the registrations * array * @return the data series {key, color, values} format object ### registrationDataSeries = (registration, index) -> # Return the data series format object. key: dataSeriesKey(index) type: 'line' yAxis: 1 color: REG_COLORS[index % REG_COLORS.length] values: coordinates(registration.volumes.images) # The scan data series configuration. scanDataSeries = key: 'Scan' type: 'line' yAxis: 1 color: SCAN_COLOR values: coordinates(scan.volumes.images) # The registration data series. regDataSeries = (registrationDataSeries(reg, i) for reg, i in scan.registrations) # Combine the scan and registration data series. data = [scanDataSeries].concat(regDataSeries) # Add the bolus arrival bar. bolusArvNdx = scan.bolusArrivalIndex if bolusArvNdx? # Extend the bar from the axis to the top. dsIntensities = (_.map(dataSeries.values, 'y') for dataSeries in data) dsMaxIntensities = (_.max(values) for values in dsIntensities) maxIntensity = _.max(dsMaxIntensities) yValues = new Array(scan.volumes.images.length) if Array.prototype.fill? yValues.fill(0) else # Polyfill IE. for i in [0...yValues.length] yValues[i] = 0 yValues[bolusArvNdx] = maxIntensity values = ({x: i + 1, y: y} for y, i in yValues) bolusDataSeries = key: 'PI:NAME:<NAME>END_PI' type: 'bar' yAxis: 1 color: 'SandyBrown' values: values showMaxMin: false data.push(bolusDataSeries) # Return the chart configuration. options: chart: type: 'multiChart' forceY: [0] yAxis: tickFormat: formatIntensity showMaxMin: false xAxis: axisLabel: 'Time Point' ticks: scan.volumes.images.length tooltip: headerFormatter: (volumeNumber) -> "Volume #{ volumeNumber }" # Note: due to a svd3 but, valueFormatter doesn't work on a # multichart, although headerFormatter does. #valueFormatter: d3.format('.2f') data: data
[ { "context": "v_key, salesforce: { user_name: \"one\", password: \"two\", key: \"thre\" } } )\n .fail (error) => \n ", "end": 855, "score": 0.9993171691894531, "start": 852, "tag": "PASSWORD", "value": "two" }, { "context": "rl: \"https://na99.salesforce.com\", access_token: \"abcdefg\", id: \"https://na15.salesforce.com/abcdefg/abcdef", "end": 1143, "score": 0.8933755159378052, "start": 1136, "tag": "PASSWORD", "value": "abcdefg" } ]
tests/integration/action_salesforce.coffee
3vot/3vot-cli
0
Setup = require("../../app/actions/salesforce_setup") should = require("should") nock = require("nock") rimraf = require("rimraf"); Path = require("path"); sinon = require("sinon") #nock.recorder.rec(); describe '3VOT Salesforce', -> before (done) -> projectPath = Path.join( process.cwd() , "3vot_cli_2_test" ); console.info("Changing current directory in profile before to " + projectPath) process.chdir( projectPath ); done() after () -> projectPath = Path.join( process.cwd(), ".." ); console.info("Restoring current directory in profile after to"); process.chdir( projectPath ); it 'should setup salesforce', (done) -> @timeout(20000) server = sinon.fakeServer.create(); Setup( { user_name: "cli_2_test", public_dev_key: process.env.public_dev_key, salesforce: { user_name: "one", password: "two", key: "thre" } } ) .fail (error) => error.should.equal(""); .done -> done() server.requests[0].respond( 200, { "Content-Type": "application/json" }, JSON.stringify([{ instance_url: "https://na99.salesforce.com", access_token: "abcdefg", id: "https://na15.salesforce.com/abcdefg/abcdeff" }]) );
37452
Setup = require("../../app/actions/salesforce_setup") should = require("should") nock = require("nock") rimraf = require("rimraf"); Path = require("path"); sinon = require("sinon") #nock.recorder.rec(); describe '3VOT Salesforce', -> before (done) -> projectPath = Path.join( process.cwd() , "3vot_cli_2_test" ); console.info("Changing current directory in profile before to " + projectPath) process.chdir( projectPath ); done() after () -> projectPath = Path.join( process.cwd(), ".." ); console.info("Restoring current directory in profile after to"); process.chdir( projectPath ); it 'should setup salesforce', (done) -> @timeout(20000) server = sinon.fakeServer.create(); Setup( { user_name: "cli_2_test", public_dev_key: process.env.public_dev_key, salesforce: { user_name: "one", password: "<PASSWORD>", key: "thre" } } ) .fail (error) => error.should.equal(""); .done -> done() server.requests[0].respond( 200, { "Content-Type": "application/json" }, JSON.stringify([{ instance_url: "https://na99.salesforce.com", access_token: "<PASSWORD>", id: "https://na15.salesforce.com/abcdefg/abcdeff" }]) );
true
Setup = require("../../app/actions/salesforce_setup") should = require("should") nock = require("nock") rimraf = require("rimraf"); Path = require("path"); sinon = require("sinon") #nock.recorder.rec(); describe '3VOT Salesforce', -> before (done) -> projectPath = Path.join( process.cwd() , "3vot_cli_2_test" ); console.info("Changing current directory in profile before to " + projectPath) process.chdir( projectPath ); done() after () -> projectPath = Path.join( process.cwd(), ".." ); console.info("Restoring current directory in profile after to"); process.chdir( projectPath ); it 'should setup salesforce', (done) -> @timeout(20000) server = sinon.fakeServer.create(); Setup( { user_name: "cli_2_test", public_dev_key: process.env.public_dev_key, salesforce: { user_name: "one", password: "PI:PASSWORD:<PASSWORD>END_PI", key: "thre" } } ) .fail (error) => error.should.equal(""); .done -> done() server.requests[0].respond( 200, { "Content-Type": "application/json" }, JSON.stringify([{ instance_url: "https://na99.salesforce.com", access_token: "PI:PASSWORD:<PASSWORD>END_PI", id: "https://na15.salesforce.com/abcdefg/abcdeff" }]) );
[ { "context": "name: \"VimL\"\nscopeName: \"source.viml\"\ninjectionSelector: \"", "end": 8, "score": 0.5525156259536743, "start": 7, "tag": "NAME", "value": "V" } ]
grammars/viml.cson
Alhadis/atom-vimL
15
name: "VimL" scopeName: "source.viml" injectionSelector: "source.gfm source.embedded.viml" fileTypes: [ "vim" "vimrc" "gvimrc" "nvimrc" "_vimrc" "exrc" "nexrc" "vmb" ] firstLineMatch: """(?x) # Vimball (?:^|\\n)UseVimball\\b | # Hashbang ^\\#!.*(?:\\s|\\/|(?<=!)\\b) (?:vim|nvim) (?:$|\\s) | # Modeline (?: # Vim/Vi modeline, accounting for all possible variations (?:(?:^|[ \\t])(?:vi|Vi(?=m))(?:m[<=>]?[0-9]+|m)?|[ \\t]ex)(?=:(?=[ \\t]*set?[ \\t][^\\r\\n:]+:)|:(?![ \\t]*set?[ \\t])) (?:(?:[ \\t]*:[ \\t]*|[ \\t])\\w*(?:[ \\t]*=(?:[^\\\\\\s]|\\\\.)*)?)*[ \\t:] (?:filetype|ft|syntax)[ \\t]*= (?i:vim) (?=$|\\s|:) | # Emacs modeline, assuming a major mode for VimScript even exists -\\*-(?i:[ \\t]*(?=[^:;\\s]+[ \\t]*-\\*-)|(?:.*?[ \\t;]|(?<=-\\*-))[ \\t]*mode[ \\t]*:[ \\t]*) (?i:Vim|VimL|VimScript) (?=[ \\t;]|(?<![-*])-\\*-).*?-\\*- ) """ foldingStartMarker: "^(?:if|while|for|fu|function|augroup|aug)" foldingStopMarker: "(?:endif|endwhile|endfor|endf|endfunction|augroup\\.END|aug\\.END)$" limitLineLength: no patterns: [{ # VimBall archive name: "meta.file-archive.vimball" begin: '\\A(?=" Vimball Archiver)' end: "(?=A)B" patterns: [{ # Help file name: "meta.file-record.help-file.vimball" begin: "^(.*?\\S.*?\\.txt)(\\t)(\\[{3}1)(?=$)" end: "(?!\\G)(?=^.*?\\S.*?\\t\\[{3}1$)" beginCaptures: 0: name: "markup.heading.1.vimball" 1: name: "entity.name.file.path.vimball" 2: name: "punctuation.whitespace.tab.separator.vimball" 3: name: "punctuation.definition.header.vimball" contentName: "text.embedded.vim-help" patterns: [{ # Line count begin: "\\G" end: "^(\\d+$)?" endCaptures: 0: name: "comment.ignored.line-count.viml" 1: name: "sublimelinter.gutter-mark" }, include: "text.vim-help"] },{ # Vim script file name: "meta.file-record.vimball.viml" begin: "^(.*?\\S.*?[ \\t]*?)(\\t)(\\[{3}1)(?=$)" end: "(?!\\G)(?=^.*?\\S.*?\\t\\[{3}1$)" beginCaptures: 0: name: "markup.heading.1.vimball" 1: name: "entity.name.file.path.vimball" 2: name: "punctuation.whitespace.tab.separator.vimball" 3: name: "punctuation.definition.header.vimball" patterns: [{ # Line count begin: "\\G" end: "^(\\d+$)?" endCaptures: 0: name: "comment.ignored.line-count.viml" 1: name: "sublimelinter.gutter-mark" }, include: "#main"] }, include: "#main"] }, include: "#main"] repository: main: patterns: [ {include: "#vimTodo"} {include: "#comments"} {include: "#modelines"} {include: "#pathname"} {include: "#escape"} {include: "#strings"} {include: "#hashbang"} {include: "#numbers"} {include: "#syntax"} {include: "#highlightLink"} {include: "#funcDef"} {include: "#auCmd"} {include: "#auGroup"} {include: "#parameter"} {include: "#assignment"} {include: "#expr"} {include: "#keyword"} {include: "#register"} {include: "#filetype"} {include: "#variable"} {include: "#supportType"} {include: "#supportVariable"} {include: "#extraVimOptions"} {include: "#extraVimFunc"} {include: "#keywordLists"} ] strings: patterns: [{ name: "string.quoted.double.empty.viml" match: '(")(")' captures: 1: name: "punctuation.definition.string.begin.viml" 2: name: "punctuation.definition.string.end.viml" },{ name: "string.quoted.single.empty.viml" match: "(')(')" captures: 1: name: "punctuation.definition.string.begin.viml" 2: name: "punctuation.definition.string.end.viml" },{ name: "string.quoted.double.viml" match: '(")((?:[^\\\\"]|\\\\.)*)(")' captures: 1: name: "punctuation.definition.string.begin.viml" 2: patterns: [include: "#escape"] 3: name: "punctuation.definition.string.end.viml" },{ name: "string.quoted.single.viml" match: "(')((?:[^']|'')*)(')" captures: 1: name: "punctuation.definition.string.begin.viml" 2: patterns: [{ name: "constant.character.escape.quotes.viml" match: "''" }] 3: name: "punctuation.definition.string.end.viml" },{ name: "string.regexp.interpolated.viml" match: "(/)(?:\\\\\\\\|\\\\/|[^\\n/])*(/)" captures: 1: name: "punctuation.section.regexp.begin.viml" 2: name: "punctuation.section.regexp.end.viml" }] # Something prefixed with a backslash escape: patterns: [ {include: "#escapedCodePoint"} {include: "#escapedKey"} {match: "(\\\\)b", name: "constant.character.escape.backspace.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)e", name: "constant.character.escape.escape.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)f", name: "constant.character.escape.form-feed.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)n", name: "constant.character.escape.newline.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)r", name: "constant.character.escape.return.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)t", name: "constant.character.escape.tab.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)\\1",name: "constant.character.escape.backslash.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: '(\\\\)"', name: "constant.character.escape.quote.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\).", name: "constant.character.escape.other.viml", captures: 1: name: "punctuation.definition.escape.viml"} ] # Characters specified by codepoint escapedCodePoint: patterns: [{ # Hexadecimal, short: \x20 name: "constant.character.escape.codepoint.hex.short.viml" match: "(\\\\)[xX][0-9A-Fa-f]{1,2}" captures: 1: name: "punctuation.definition.escape.backslash.viml" },{ # Codepoint, long: \u0020 \u00000020 name: "constant.character.escape.codepoint.hex.long.viml" match: "(\\\\)(?:u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8})" captures: 1: name: "punctuation.definition.escape.backslash.viml" },{ # Codepoint, octal: \040 name: "constant.character.escape.codepoint.octal.viml" match: "(\\\\)([0-7]{1,3})" captures: 1: name: "punctuation.definition.escape.backslash.viml" }] escapedKey: name: "constant.character.escape.keymapping.viml" match: '(\\\\<\\*?)(?:[^">\\\\]|\\\\.)+(>)' captures: 1: name: "punctuation.definition.escape.key.begin.viml" 2: name: "punctuation.definition.escape.key.end.viml" # This only exists to stop stuff like ~/.vim/ being highlighted like a regex pathname: name: "constant.pathname.viml" begin: "~/" end: "(?=\\s)" comments: patterns: [{ # Fully-commented line with a leading field-name name: "comment.line.quotes.viml" begin: '^\\s*(")(?=(\\s*[A-Z]\\w+)+:)' end: "((:))(.*)$" contentName: "support.constant.field.viml" beginCaptures: 1: name: "punctuation.definition.comment.viml" endCaptures: 1: name: "support.constant.field.viml" 2: name: "punctuation.separator.key-value.colon.viml" 3: patterns: [include: "#commentInnards"] },{ # Fully-commented line name: "comment.line.quotes.viml" begin: '^\\s*(")' end: '$' beginCaptures: 1: name: "punctuation.definition.comment.viml" patterns: [include: "#commentInnards"] },{ # Trailing comment, no closing quote name: "comment.inline.quotes.viml" patterns: [include: "#commentInnards"] begin: '(?<!^)\\s*(")(?=[^\\n"]*$)' end: "$" beginCaptures: 1: name: "punctuation.definition.comment.viml" }] commentInnards: patterns: [ {include: "#modelines"} {include: "#todo"} ] # Vim modelines modelines: patterns: [{ # Using "vim:set" name: "string.other.modeline.viml" patterns: [include: "#main"] begin: "(?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|[\\t\\x20]ex):\\s*(?=set?\\s)" end: ":|$" },{ name: "string.other.modeline.viml" patterns: [include: "#main"] begin: "(?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|[\\t\\x20]ex):" end: "$" }] # Embedded interpreter directive hashbang: name: "comment.line.shebang.viml" begin: "\\A#!" end: "$" beginCaptures: 0: name: "punctuation.definition.comment.shebang.viml" numbers: patterns: [{ name: "constant.numeric.hex.short.viml" match: "0[xX][0-9A-Fa-f]+" },{ name: "constant.numeric.hex.long.viml" match: "0[zZ][0-9A-Fa-f]+" },{ name: "constant.numeric.float.exponential.viml" match: "(?<!\\w)-?\\d+\\.\\d+[eE][-+]?\\d+" },{ name: "constant.numeric.float.viml" match: "(?<!\\w)-?\\d+\\.\\d+" },{ name: "constant.numeric.integer.viml" match: "(?<!\\w)-?\\d+" }] funcDef: patterns: [{ name: "storage.function.viml" match: "\\b(fu(nc?|nction)?|end(f|fu|func?|function)?)\\b" },{ name: "entity.name.function.viml" match: "(?:([sSgGbBwWtTlL]?(:))?[\\w#]+)(?=\\()" captures: 1: name: "storage.modifier.scope.viml" 2: name: "punctuation.definition.scope.key-value.viml" },{ name: "storage.modifier.$1.function.viml" match: "(?<=\\)|\\s)(abort|dict|closure|range)(?=\\s|$)" }] auCmd: name: "meta.autocmd.viml" match: "\\b(autocmd|au)(!)?\\b\\s+(?!\\*)(\\S+)\\s+(\\S+)(?:\\s+(\\+\\+(nested|once)))?" captures: 1: name: "storage.type.autocmd.viml" 2: name: "storage.modifier.force.viml" 3: name: "meta.events-list.viml", patterns: [include: "#main"] 4: name: "string.unquoted.autocmd-suffix-list.viml" 5: name: "storage.modifier.$6.viml" auGroup: patterns: [ name: "meta.augroup.viml" begin: "\\b(augroup|aug)(!)?\\b\\s*([\\w#]+)" end: "\\b(\\1)\\s+(END)\\b" patterns: [include: "#main"] beginCaptures: 1: name: "storage.type.function.viml" 2: name: "storage.modifier.force.viml" 3: name: "entity.name.function.viml" endCaptures: 1: name: "storage.type.augroup.viml" 2: name: "keyword.control.end" ] parameter: name: "meta.parameter.viml" match: "(-)(\\w+)(=)" captures: 1: name: "punctuation.definition.parameter.viml" 2: name: "entity.name.parameter.viml" 3: name: "punctuation.assignment.parameter.viml" assignment: patterns: [{ name: "keyword.operator.assignment.compound.viml" match: "[-+.]=" },{ name: "keyword.operator.assignment.viml" match: "=" }] expr: patterns: [ name: "keyword.operator.logical.viml" match: "[&|=]{2}[?#]?|[!><]=[#?]?|[=!]~(?!\\/)[#?]?|[><][#?*]|\\b(?:isnot|is)\\b|\\\\|[-+%*]" {match: "\\s[><]\\s",name: "keyword.operator.logical.viml"} {match: "(?<=\\S)!", name: "storage.modifier.force.viml"} {match: "!(?=\\S)", name: "keyword.operator.logical.not.viml"} {match: "{", name: "punctuation.expression.bracket.curly.begin.viml"} {match: "}", name: "punctuation.expression.bracket.curly.end.viml"} {match: "\\[", name: "punctuation.expression.bracket.square.begin.viml"} {match: "\\]", name: "punctuation.expression.bracket.square.end.viml"} {match: "\\(", name: "punctuation.expression.bracket.round.begin.viml"} {match: "\\)", name: "punctuation.expression.bracket.round.end.viml"} {match: "\\|", name: "punctuation.separator.statement.viml"} {match: ",", name: "punctuation.separator.comma.viml"} {match: ":", name: "punctuation.separator.colon.viml"} {match: "\\.{3}", name: "keyword.operator.rest.viml"} {match: "\\.", name: "punctuation.delimiter.property.dot.viml"} {match: "&(?=\\w+)", name: "punctuation.definition.option.viml"} ] keyword: patterns: [{ name: "keyword.control.$1.viml" match: "\\b(if|while|for|return|try|catch|finally|finish|end(if|for|while|try)?|else(if)?|do|in|:)\\b" },{ name: "keyword.operator.$1.viml" match: "\\b(unlet)\\b" },{ name: "storage.type.let.viml" match: "\\blet\\b" },{ name: "support.constant.vimball.use.viml" match: "(?<=^|\\n)UseVimball(?=\\s*$)" }] register: name: "variable.other.register.viml" match: "(@)([-\"A-Za-z\\d:.%#=*+~_/])" captures: 1: name: "punctuation.definition.register.viml" variable: patterns: [{ name: "variable.language.self.viml" match: "\\b(self)\\b" },{ name: "support.variable.environment.viml" match: "(\\$)\\w+" captures: 1: name: "punctuation.definition.variable.viml" },{ name: "variable.other.viml" match: "(&?)(?:([sSgGbBwWlLaAvV](:))|[@$]|&(?!&))\\w*" captures: 1: name: "punctuation.definition.reference.viml" 2: name: "storage.modifier.scope.viml" 3: name: "punctuation.definition.scope.key-value.viml" }] supportType: name: "entity.tag.name.viml" match: "(<).*?(>)" captures: 1: name: "punctuation.definition.bracket.angle.begin.viml" 2: name: "punctuation.definition.bracket.angle.end.viml" supportVariable: name: "support.variable.viml" match: "\\b(?:am(?:enu)?|(?:hl|inc)?search|[Bb]uf(?:[Nn]ew[Ff]ile|[Rr]ead)?|[Ff]ile[Tt]ype)\\b" # Highlighting link, used heavily in syntax-definition files highlightLink: match: "(?x)^\\s* (:)? \\s* (?# 1: punctuation.separator.key-value.colon.viml) (hi|highlight) (?# 2: support.function.highlight.viml) (!)? (?# 3: storage.modifier.force.viml) (?:\\s+(def|default))? (?# 4: support.function.highlight-default.viml) (?:\\s+(link)) (?# 5: support.function.highlight-link.viml) (?:\\s+([-\\w]+)) (?# 6: variable.parameter.group-name.viml) (?:\\s+(?:(NONE)|([-\\w]+)))?" captures: 1: name: "punctuation.separator.key-value.colon.viml" 2: name: "support.function.highlight.viml" 3: name: "storage.modifier.force.viml" 4: name: "support.function.highlight-default.viml" 5: name: "support.function.highlight-link.viml" 6: name: "variable.parameter.group-name.viml" 7: name: "support.constant.highlighting.viml" 8: name: "variable.parameter.group-name.viml" # Filetype assignment filetype: match: "\\b(?:(setf|setfiletype)(?:\\s+(FALLBACK))?\\s+|(ft|filetype)\\s*(=))([.\\w]+)" captures: 1: name: "support.function.command.viml" 2: name: "support.variable.option.viml" 3: name: "storage.modifier.fallback.viml" 4: name: "keyword.operator.assignment.viml" 5: name: "variable.parameter.function.filetype.viml" # Syntax highlighting definitions syntax: name: "meta.syntax-item.viml" begin: "^\\s*(:)?(?:(VimFold\\w)\\s+)?\\s*(syntax|syn?)(?=\\s|$)" end: "$" beginCaptures: 1: name: "punctuation.separator.key-value.colon.viml" 2: name: "support.function.fold-command.viml" 3: name: "storage.type.syntax-item.viml" patterns: [{ # Case-matching match: "\\G\\s+(case)(?:\\s+(match|ignore))?(?=\\s|$)" captures: 1: name: "support.function.syntax-case.viml" 2: name: "support.constant.$2-case.viml" },{ # Spell-checking match: "\\G\\s+(spell)(?:\\s+(toplevel|notoplevel|default))?(?=\\s|$)" captures: 1: name: "support.function.syntax-spellcheck.viml" 2: name: "support.constant.$2-checking.viml" },{ # Keyword lists begin: "\\G\\s+(keyword)(?:\\s+([-\\w]+))?" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-keywords.viml" 2: name: "variable.parameter.group-name.viml" contentName: "keyword.other.syntax-definition.viml" patterns: [ {include: "#syntaxOptions"} {include: "#assignment"} {include: "#expr"} ] },{ # Pattern-based match begin: "\\G\\s+(match)(?:\\s+([-\\w]+))?\\s*" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-match.viml" 2: name: "variable.parameter.group-name.viml" patterns: [include: "#syntaxRegex"] },{ # Multiline pattern-based match begin: "\\G\\s+(region)(?:\\s+([-\\w]+))?" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-region.viml" 2: name: "variable.parameter.group-name.viml" patterns: [ {include: "#syntaxOptions"} {include: "#main"} ] },{ # Group cluster begin: "\\G\\s+(cluster)(?:\\s+([-\\w]+))?(?=\\s|$)" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-cluster.viml" 2: name: "variable.parameter.group-name.viml" patterns: [ {include: "#syntaxOptions"} {include: "#main"} ] },{ # Concealment match: "\\G\\s+(conceal)(?:\\s+(on|off)(?=\\s|$))?" captures: 1: name: "support.function.syntax-conceal.viml" 2: name: "support.constant.boolean.$2.viml" },{ # Inclusion match: "\\G\\s+(include)(?:\\s+((@)?[-\\w]+))?(?:\\s+(\\S+))?" captures: 1: name: "support.function.syntax-include.viml" 2: name: "variable.parameter.group-name.viml" 3: name: "punctuation.definition.group-reference.viml" 4: name: "string.unquoted.filename.viml", patterns: [include: "#supportType"] },{ # Sync/Redrawing mode begin: "\\G\\s+(sync)(?=\\s|$)" end: "$" beginCaptures: 1: name: "support.function.syntax-sync.viml" patterns: [{ match: "\\G\\s+(fromstart)(?=\\s|$)" captures: 1: name: "support.constant.sync-$1.viml" },{ match: "\\G\\s+(ccomment|clear)(?:\\s+(?![-\\w]+\\s*=)([-\\w]+))?" captures: 1: name: "support.constant.sync-$1.viml" 2: name: "variable.parameter.group-name.viml" },{ match: "\\G\\s+(minlines|lines)\\s*(=)(\\d*)" captures: 1: name: "support.constant.sync-mode.viml" 2: name: "punctuation.assignment.parameter.viml" 3: name: "constant.numeric.integer.viml" },{ match: "(?x)\\G\\s+(match|region)(?:\\s+(?![-\\w]+\\s*=)([-\\w]+))?" captures: 1: name: "support.constant.sync-mode.viml" 2: name: "variable.parameter.group-name.viml" 3: name: "support.constant.sync-mode-location.viml" },{ begin: "(?<=\\s)(groupt?here|linecont)(?:\\s+(?![-\\w]+\\s*=)([-\\w]+))?(?=\\s|$)" end: "(?=$)" beginCaptures: 1: name: "support.constant.sync-match.viml" 2: name: "variable.parameter.group-name.viml" patterns: [include: "#syntaxRegex"] }, include: "#syntaxOptions"] }, include: "#main"] # Syntax item arguments, as described in :syn-arguments syntaxOptions: patterns: [{ # Options that take a regex name: "meta.syntax-item.pattern-argument.viml" begin: "(?<=\\s)(start|skip|end)(?:\\s*(=))" end: "(?=$|\\s)" beginCaptures: 1: name: "support.constant.$1-pattern.viml" 2: name: "punctuation.assignment.parameter.viml" patterns: [include: "#regex"] },{ # Everything else name: "meta.syntax-item.argument.viml" match: """(?x)(?<=\\s) ((?:matchgroup|contains|containedin|nextgroup|add|remove|minlines|linebreaks|maxlines)(?=\\s*=) |(?:cchar|conceal|concealends|contained|display|excludenl|extend|fold|keepend|oneline|skipempty|skipnl|skipwhite|transparent)) (?:(?=$|\\s)|\\s*(=)(\\S*)?)""" captures: 1: name: "support.constant.syntax-$1.viml" 2: name: "punctuation.assignment.parameter.viml" 3: name: "string.unquoted.syntax-option.viml", patterns: [ {include: "#numbers"} {match: ",", name: "punctuation.separator.comma.viml"} {match: "@", name: "punctuation.definition.group-reference.viml"} ] }] # Body of any syntax-item option which uses an unlabelled regex syntaxRegex: patterns: [ {include: "#syntaxOptions"} # Ensure only one regex is matched name: "string.regexp.viml" begin: "(?<=\\s)(\\S)" end: "(?:(\\1)(\\S*)(.*))?$" patterns: [include: "#regexInnards"] beginCaptures: 1: name: "punctuation.definition.string.begin.viml" endCaptures: 1: name: "punctuation.definition.string.end.viml" 2: patterns: [include: "#regexOffset"] 3: patterns: [include: "#syntaxOptions", {include: "#main"}] ] # Regular expression regex: name: "string.regexp.viml" begin: "(?<=\\s|=)(\\S)" end: "$|(\\1)(\\S*)" patterns: [include: "#regexInnards"] beginCaptures: 1: name: "punctuation.definition.string.begin.viml" endCaptures: 1: name: "punctuation.definition.string.end.viml" 2: patterns: [include: "#regexOffset"] # Pattern offset regexOffset: name: "meta.pattern-offset.viml" match: "(ms|me|hs|he|rs|re|lc)(=)(?:(\\d+)|([se])(?:([-+])(\\d+))?)(,)?" captures: 1: name: "constant.language.pattern-offset.viml" 2: name: "punctuation.assignment.parameter.viml" 3: name: "constant.numeric.integer.viml" 4: name: "constant.language.pattern-position.viml" 5: name: "keyword.operator.arithmetic.viml" 6: name: "constant.numeric.integer.viml" 7: name: "punctuation.separator.comma.viml" regexInnards: patterns: [{ # Character class begin: "\\[" end: "\\]|$" beginCaptures: 0: name: "punctuation.definition.character-class.begin.viml" endCaptures: 0: name: "punctuation.definition.character-class.end.viml" patterns: [include: "#regexInnards"] },{ # Escaped character name: "constant.character.escape.viml" match: "(\\\\)." captures: 1: name: "punctuation.definition.backslash.escape.viml" }] # Extra functions not picked up by keyword parser extraVimFunc: name: "support.function.viml" match: """(?x)\\b ((?:echo(?:hl?)?)|exe(?:c(?:ute)?)?|[lxvn]?noremap|smapc(?:lear)?|mapmode|xmap|(?:[xs]un|snore)map |Plugin|autocmd|[cinvo]?(?:un|nore)?(?:map|menu)|(?:range)?go(?:to)?|(?:count)?(?:pop?|tag?|tn(?:ext)?|tp(?:revious)?|tr(?:ewind)?) |(?:range)?(?:s(?:ubstitute)?|ret(?:ab)?|g(?:lobal)?)|unm(?:ap)?|map_l|mapc(?:lear)?|N?buffer|N?bnext|N?bNext|N?bprevious|N?bmod |ab(?:breviate)?|norea(?:bbrev)?|[ic](?:un|nore)?ab|split_f|rangefold|[ic](?:un|nore)?ab|[ic]abbrev|edit_f|next_f|[vcoxli]u |(?:range)?(?:w(?:rite)?|up(?:date)?)|sar|cno|[vl]n|[io]?no|[xn]n|snor|lm(?:ap)?|lunmap|lear|[vnx]m|om|[ci]m|ap|nun|sunm) \\b""" # Extra options not picked up by keyword parser extraVimOptions: name: "support.variable.option.viml" match: """(?x)\\b (no)? (altwerase|bf|escapetime|extended|filec|iclower|keytime|leftright|li|lock|noprint|octal|recdir|searchincr |shellmeta|ttywerase|windowname|wl|wraplen) \\b""" # The following lists are auto-extracted from Vim's syntax file. # Run `bin/update` to repopulate them. keywordLists: patterns: [ {include: "#vimTodo"} {include: "#vimAugroupKey"} {include: "#vimAutoEvent"} {include: "#vimBehaveModel"} {include: "#vimCommand"} {include: "#vimFTCmd"} {include: "#vimFTOption"} {include: "#vimFgBgAttrib"} {include: "#vimFuncKey"} {include: "#vimFuncName"} {include: "#vimGroup"} {include: "#vimGroupSpecial"} {include: "#vimHLGroup"} {include: "#vimHiAttrib"} {include: "#vimHiClear"} {include: "#vimHiCtermColor"} {include: "#vimMapModKey"} {include: "#vimOption"} {include: "#vimPattern"} {include: "#vimStdPlugin"} {include: "#vimSynCase"} {include: "#vimSynType"} {include: "#vimSyncC"} {include: "#vimSyncLinecont"} {include: "#vimSyncMatch"} {include: "#vimSyncNone"} {include: "#vimSyncRegion"} {include: "#vimUserAttrbCmplt"} {include: "#vimUserAttrbKey"} {include: "#vimUserCommand"} {include: "#vimErrSetting"} ] vimTodo: name: "support.constant.${1:/downcase}.viml" match: """(?x) \\b ( COMBAK | FIXME | TODO | XXX ) \\b """ vimAugroupKey: name: "support.function.vimAugroupKey.viml" match: """(?x) \\b ( aug | augroup ) \\b """ vimAutoEvent: name: "support.function.auto-event.viml" match: """(?xi) \\b ( BufAdd | BufCreate | BufDelete | BufEnter | BufFilePost | BufFilePre | BufHidden | BufLeave | BufNewFile | BufNew | BufReadCmd | BufReadPost | BufReadPre | BufRead | BufUnload | BufWinEnter | BufWinLeave | BufWipeout | BufWriteCmd | BufWritePost | BufWritePre | BufWrite | CmdUndefined | CmdlineChanged | CmdlineEnter | CmdlineLeave | CmdwinEnter | CmdwinLeave | ColorSchemePre | ColorScheme | CompleteChanged | CompleteDonePre | CompleteDone | CursorHoldI | CursorHold | CursorMovedI | CursorMoved | DiffUpdated | DirChanged | EncodingChanged | ExitPre | FileAppendCmd | FileAppendPost | FileAppendPre | FileChangedRO | FileChangedShellPost | FileChangedShell | FileEncoding | FileReadCmd | FileReadPost | FileReadPre | FileType | FileWriteCmd | FileWritePost | FileWritePre | FilterReadPost | FilterReadPre | FilterWritePost | FilterWritePre | FocusGained | FocusLost | FuncUndefined | GUIEnter | GUIFailed | InsertChange | InsertCharPre | InsertEnter | InsertLeavePre | InsertLeave | MenuPopup | OptionSet | QuickFixCmdPost | QuickFixCmdPre | QuitPre | RemoteReply | SafeStateAgain | SafeState | SessionLoadPost | ShellCmdPost | ShellFilterPost | SigUSR1 | SourceCmd | SourcePost | SourcePre | SpellFileMissing | StdinReadPost | StdinReadPre | SwapExists | Syntax | TabClosed | TabEnter | TabLeave | TabNew | TermChanged | TermResponse | TerminalOpen | TerminalWinOpen | TextChangedI | TextChangedP | TextChanged | TextYankPost | User | VimEnter | VimLeavePre | VimLeave | VimResized | VimResume | VimSuspend | WinEnter | WinLeave | WinNew ) \\b """ vimBehaveModel: name: "support.function.vimBehaveModel.viml" match: """(?x) \\b ( mswin | xterm ) \\b """ vimCommand: name: "support.function.command.viml" match: """(?x) \\b ( abc | abclear | abo | aboveleft | ab | addd | all? | ar | args | arga | argadd | argd | argdelete | argdo | arge | argedit | argg | argglobal | argl | arglocal | argu | argument | as | ascii | au | a | bN | bNext | b | buffer | ba | ball | badd? | balt | bd | bdelete | bel | belowright | bf | bfirst | bl | blast | bm | bmodified | bn | bnext | bo | botright | bp | bprevious | br | brewind | break? | breaka | breakadd | breakd | breakdel | breakl | breaklist | bro | browse | bufdo | buffers | bun | bunload | bw | bwipeout | cN | cNext | cNf | cNfile | c | change | cabc | cabclear | cabo | cabove | cad | caddbuffer | cadde | caddexpr | caddf | caddfile | caf | cafter | call? | cat | catch | ca | cb | cbuffer | cbe | cbefore | cbel | cbelow | cbo | cbottom | ccl | cclose | cc | cdo | cd | ce | center | cex | cexpr | cf | cfile | cfdo | cfir | cfirst | cg | cgetfile | cgetb | cgetbuffer | cgete | cgetexpr | changes | chd | chdir | che | checkpath | checkt | checktime | chi | chistory | cl | clist | cla | clast | class | cle | clearjumps | clo | close | cmapc | cmapclear | cn | cnext | cnew | cnewer | cnf | cnfile | cnor | co | copy | col | colder | colo | colorscheme | comc | comclear | comp | compiler | com | con | continue | conf | confirm | const? | copen? | cp | cprevious | cpf | cpfile | cq | cquit | cr | crewind | cscope | cstag | cs | cuna | cunabbrev | cun | cw | cwindow | d | delete | debugg | debuggreedy | debug | defc | defcompile | def | delc | delcommand | delel | delep | deletel | deletep | deletl | deletp | delf | delfunction | dell | delm | delmarks | delp | dep | di | display | dif | diffupdate | diffg | diffget | diffo | diffoff | diffp | diffpatch | diffput? | diffs | diffsplit | difft | diffthis | dig | digraphs | dir | disa | disassemble | dj | djump | dli | dlist | dl | doaut | doau | do | dp | dr | drop | ds | dsearch | dsp | dsplit | e | edit | earlier | ea | echoc | echoconsole | echoe | echoerr | echom | echomsg | echon | ec | el | else | elseif? | em | emenu | en | endif | enddef | endf | endfunction | endfor? | endt | endtry | endw | endwhile | enew? | eval | exit? | export | exp | exu | exusage | ex | f | file | files | filetype | filet | filt | filter | find? | fina | finally | fini | finish | fir | first | fix | fixdel | fo | fold | foldc | foldclose | foldd | folddoopen | folddoc | folddoclosed | foldo | foldopen | for | fu | function | go | goto | gr | grep | grepa | grepadd | gui | gvim | g | h | help | ha | hardcopy | helpc | helpclose | helpf | helpfind | helpg | helpgrep | helpt | helptags | hide? | his | history | hi | iabc | iabclear | ia | if | ij | ijump | il | ilist | imapc | imapclear | import | imp | inor | interface | intro | in | is | isearch | isp | isplit | iuna | iunabbrev | i | j | join | ju | jumps | kee | keepmarks | keepalt | keepa | keepj | keepjumps | keepp | keeppatterns | k | lN | lNext | lNf | lNfile | l | list | la | last | lab | labove | lad | laddexpr | laddb | laddbuffer | laddf | laddfile | laf | lafter | lan | language | later | lat | lb | lbuffer | lbe | lbefore | lbel | lbelow | lbo | lbottom | lcd? | lch | lchdir | lcl | lclose | lcscope | lcs | ldo? | le | left | lefta | leftabove | leg | legacy | lex | lexpr | lf | lfile | lfdo | lfir | lfirst | lg | lgetfile | lgetb | lgetbuffer | lgete | lgetexpr | lgr | lgrep | lgrepa | lgrepadd | lh | lhelpgrep | lhi | lhistory | lla | llast | lli | llist | ll | lmake? | lmapc | lmapclear | lma | lne | lnext | lnew | lnewer | lnf | lnfile | lo | loadview | loadkeymap | loadk | loc | lockmarks | lockv | lockvar | lol | lolder | lop | lopen | lp | lprevious | lpf | lpfile | lr | lrewind | ls | lt | ltag | luado | luafile | lua | lv | lvimgrep | lvimgrepa | lvimgrepadd | lw | lwindow | m | move | ma | mark | make? | marks | mat | match | menut | menutranslate | mes | messages | mk | mkexrc | mks | mksession | mksp | mkspell | mkv | mkvimrc | mkview? | mode? | mz | mzscheme | mzf | mzfile | n | next | nb | nbkey | nbc | nbclose | nbs | nbstart | new | nmapc | nmapclear | noautocmd | noa | noh | nohlsearch | nore | nor | nos | noswapfile | nu | number | o | open | ol | oldfiles | omapc | omapclear | on | only | opt | options | ownsyntax | p | print | pa | packadd | packl | packloadall | pc | pclose | pe | perl | ped | pedit | perldo? | pop? | popup? | pp | ppop | pre | preserve | prev | previous | prof | profile | profd | profdel | promptf | promptfind | promptr | promptrepl | pro | ps | psearch | ptN | ptNext | ptag? | ptf | ptfirst | ptj | ptjump | ptl | ptlast | ptn | ptnext | ptp | ptprevious | ptr | ptrewind | pts | ptselect | put? | pwd? | py3do | py3f | py3file | py3 | py | python | pydo | pyf | pyfile | python3 | pythonx | pyxdo | pyxfile | pyx | q | quit | qa | qall | quita | quitall | r | read | rec | recover | redo? | redir? | redr | redraw | redraws | redrawstatus | redrawt | redrawtabline | reg | registers | res | resize | ret | retab | retu | return | rew | rewind | ri | right | rightb | rightbelow | ru | runtime | ruby? | rubydo? | rubyf | rubyfile | rundo | rv | rviminfo | sIc | sIe | sIg | sIl | sIn | sIp | sIr | sI | sN | sNext | sa | sargument | sall? | san | sandbox | sav | saveas | sbN | sbNext | sb | sbuffer | sba | sball | sbf | sbfirst | sbl | sblast | sbm | sbmodified | sbn | sbnext | sbp | sbprevious | sbr | sbrewind | scI | sce | scg | sci | scl | scp | scr | scriptnames | scripte | scriptencoding | scriptv | scriptversion | scscope | scs | sc | set? | setf | setfiletype | setg | setglobal | setl | setlocal | sf | sfind | sfir | sfirst | sgI | sgc | sge | sgi | sgl | sgn | sgp | sgr | sg | sh | shell | sic | sie | sign | sig | sil | silent | sim | simalt | sin | sip | sir | si | sl | sleep | sla | slast | sm | smagic | sm | smap | smenu | sme | smile | sn | snext | sno | snomagic | snoremenu | snoreme | so | source | sort? | sp | split | spe | spellgood | spelld | spelldump | spelli | spellinfo | spellr | spellrare | spellr | spellrepall | spellr | spellrrare | spellu | spellundo | spellw | spellwrong | spr | sprevious | srI | src | sre | srewind | srg | sri | srl | srn | srp | sr | st | stop | stag? | star | startinsert | startg | startgreplace | startr | startreplace | stj | stjump | stopi | stopinsert | sts | stselect | substitutepattern | substituterepeat | sun | sunhide | sunmenu | sunme | sus | suspend | sv | sview | sw | swapname | syncbind | sync | syntime | syn | sy | tN | tNext | tag? | tabN | tabNext | tabc | tabclose | tabdo? | tabe | tabedit | tabf | tabfind | tabfir | tabfirst | tabl | tablast | tabm | tabmove | tabn | tabnext | tabnew | tabo | tabonly | tabp | tabprevious | tabr | tabrewind | tabs | tab | tags | tcl? | tcd | tch | tchdir | tcldo? | tclf | tclfile | te | tearoff | ter | terminal | tf | tfirst | th | throw | tj | tjump | tl | tlast | tlmenu | tlm | tlnoremenu | tln | tlunmenu | tlu | tm | tmenu | tmap? | tmapc | tmapclear | tn | tnext | tno | tnoremap | to | topleft | tp | tprevious | tr | trewind | try | ts | tselect | tu | tunmenu | tunmap? | type | t | u | undo | una | unabbreviate | undoj | undojoin | undol | undolist | unh | unhide | unlo | unlockvar | unl | uns | unsilent | up | update | var | ve | version | verb | verbose | vert | vertical | vi | visual | view? | vim9 | vim9cmd | vim9s | vim9script | vim | vimgrep | vimgrepa | vimgrepadd | viu | viusage | vmapc | vmapclear | vnew? | vs | vsplit | v | wN | wNext | w | write | wa | wall | wh | while | win | winsize | winc | wincmd | windo | winp | winpos | wn | wnext | wp | wprevious | wqa | wqall | wq | wundo | wv | wviminfo | x | xit | xa | xall | xmapc | xmapclear | xmenu | xme | xnoremenu | xnoreme | xprop | xr | xrestore | xunmenu | xunme | xwininfo | y | yank ) \\b """ vimErrSetting: name: "invalid.deprecated.legacy-setting.viml" match: """(?x) \\b ( autoprint | beautify | bioskey | biosk | conskey | consk | flash | graphic | hardtabs | ht | mesg | noautoprint | nobeautify | nobioskey | nobiosk | noconskey | noconsk | noflash | nographic | nohardtabs | nomesg | nonovice | noopen | nooptimize | noop | noredraw | noslowopen | noslow | nosourceany | novice | now1200 | now300 | now9600 | open | optimize | op | redraw | slowopen | slow | sourceany | w1200 | w300 | w9600 ) \\b """ vimFTCmd: name: "support.function.vimFTCmd.viml" match: """(?x) \\b ( filet | filetype ) \\b """ vimFTOption: name: "support.function.vimFTOption.viml" match: """(?x) \\b ( detect | indent | off | on | plugin ) \\b """ vimFgBgAttrib: name: "support.constant.attribute.viml" match: """(?x) \\b ( background | bg | fg | foreground | none ) \\b """ vimFuncKey: name: "support.function.vimFuncKey.viml" match: """(?x) \\b ( def | fu | function ) \\b """ vimFuncName: name: "support.function.viml" match: """(?x) \\b ( abs | acos | add | and | appendbufline | append | argc | argidx | arglistid | argv | asin | assert_beeps | assert_equalfile | assert_equal | assert_exception | assert_fails | assert_false | assert_inrange | assert_match | assert_nobeep | assert_notequal | assert_notmatch | assert_report | assert_true | atan2 | atan | balloon_gettext | balloon_show | balloon_split | browsedir | browse | bufadd | bufexists | buflisted | bufloaded | bufload | bufname | bufnr | bufwinid | bufwinnr | byte2line | byteidxcomp | byteidx | call | ceil | ch_canread | ch_close_in | ch_close | ch_evalexpr | ch_evalraw | ch_getbufnr | ch_getjob | ch_info | ch_logfile | ch_log | ch_open | ch_readblob | ch_readraw | ch_read | ch_sendexpr | ch_sendraw | ch_setoptions | ch_status | changenr | char2nr | charclass | charcol | charidx | chdir | cindent | clearmatches | col | complete_add | complete_check | complete_info | complete | confirm | copy | cosh | cos | count | cscope_connection | cursor | debugbreak | deepcopy | deletebufline | delete | did_filetype | diff_filler | diff_hlID | echoraw | empty | environ | escape | eval | eventhandler | executable | execute | exepath | exists | expandcmd | expand | exp | extendnew | extend | feedkeys | filereadable | filewritable | filter | finddir | findfile | flattennew | flatten | float2nr | floor | fmod | fnameescape | fnamemodify | foldclosedend | foldclosed | foldlevel | foldtextresult | foldtext | foreground | fullcommand | funcref | function | garbagecollect | getbufinfo | getbufline | getbufvar | getchangelist | getcharmod | getcharpos | getcharsearch | getchar | getcmdline | getcmdpos | getcmdtype | getcmdwintype | getcompletion | getcurpos | getcursorcharpos | getcwd | getenv | getfontname | getfperm | getfsize | getftime | getftype | getimstatus | getjumplist | getline | getloclist | getmarklist | getmatches | getmousepos | getpid | getpos | getqflist | getreginfo | getregtype | getreg | gettabinfo | gettabvar | gettabwinvar | gettagstack | gettext | getwininfo | getwinposx | getwinposy | getwinpos | getwinvar | get | glob2regpat | globpath | glob | has_key | haslocaldir | hasmapto | has | histadd | histdel | histget | histnr | hlID | hlexists | hostname | iconv | indent | index | inputdialog | inputlist | inputrestore | inputsave | inputsecret | input | insert | interrupt | invert | isdirectory | isinf | islocked | isnan | items | job_getchannel | job_info | job_setoptions | job_start | job_status | job_stop | join | js_decode | js_encode | json_decode | json_encode | keys | len | libcallnr | libcall | line2byte | line | lispindent | list2str | listener_add | listener_flush | listener_remove | localtime | log10 | log | luaeval | maparg | mapcheck | mapnew | mapset | map | matchaddpos | matchadd | matcharg | matchdelete | matchend | matchfuzzypos | matchfuzzy | matchlist | matchstrpos | matchstr | match | max | menu_info | min | mkdir | mode | mzeval | nextnonblank | nr2char | or | pathshorten | perleval | popup_atcursor | popup_beval | popup_clear | popup_close | popup_create | popup_dialog | popup_filter_menu | popup_filter_yesno | popup_findinfo | popup_findpreview | popup_getoptions | popup_getpos | popup_hide | popup_list | popup_locate | popup_menu | popup_move | popup_notification | popup_setoptions | popup_settext | popup_show | pow | prevnonblank | printf | prompt_getprompt | prompt_setcallback | prompt_setinterrupt | prompt_setprompt | prop_add | prop_clear | prop_find | prop_list | prop_remove | prop_type_add | prop_type_change | prop_type_delete | prop_type_get | prop_type_list | pum_getpos | pumvisible | py3eval | pyeval | pyxeval | rand | range | readblob | readdirex | readdir | readfile | reduce | reg_executing | reg_recording | reltimefloat | reltimestr | reltime | remote_expr | remote_foreground | remote_peek | remote_read | remote_send | remote_startserver | remove | rename | repeat | resolve | reverse | round | rubyeval | screenattr | screenchars | screenchar | screencol | screenpos | screenrow | screenstring | searchcount | searchdecl | searchpairpos | searchpair | searchpos | search | server2client | serverlist | setbufline | setbufvar | setcellwidths | setcharpos | setcharsearch | setcmdpos | setcursorcharpos | setenv | setfperm | setline | setloclist | setmatches | setpos | setqflist | setreg | settabvar | settabwinvar | settagstack | setwinvar | sha256 | shellescape | shiftwidth | sign_define | sign_getdefined | sign_getplaced | sign_jump | sign_placelist | sign_place | sign_undefine | sign_unplacelist | sign_unplace | simplify | sinh | sin | slice | sort | sound_clear | sound_playevent | sound_playfile | sound_stop | soundfold | spellbadword | spellsuggest | split | sqrt | srand | state | str2float | str2list | str2nr | strcharlen | strcharpart | strchars | strdisplaywidth | strftime | strgetchar | stridx | string | strlen | strpart | strptime | strridx | strtrans | strwidth | submatch | substitute | swapinfo | swapname | synIDattr | synIDtrans | synID | synconcealed | synstack | systemlist | system | tabpagebuflist | tabpagenr | tabpagewinnr | tagfiles | taglist | tanh | tan | tempname | term_dumpdiff | term_dumpload | term_dumpwrite | term_getaltscreen | term_getansicolors | term_getattr | term_getcursor | term_getjob | term_getline | term_getscrolled | term_getsize | term_getstatus | term_gettitle | term_gettty | term_list | term_scrape | term_sendkeys | term_setansicolors | term_setapi | term_setkill | term_setrestore | term_setsize | term_start | term_wait | terminalprops | test_alloc_fail | test_autochdir | test_feedinput | test_garbagecollect_now | test_garbagecollect_soon | test_getvalue | test_ignore_error | test_null_blob | test_null_channel | test_null_dict | test_null_function | test_null_job | test_null_list | test_null_partial | test_null_string | test_option_not_set | test_override | test_refcount | test_scrollbar | test_setmouse | test_settime | test_srand_seed | test_unknown | test_void | timer_info | timer_pause | timer_start | timer_stopall | timer_stop | tolower | toupper | trim | trunc | tr | typename | type | undofile | undotree | uniq | values | virtcol | visualmode | wildmenumode | win_execute | win_findbuf | win_getid | win_gettype | win_gotoid | win_id2tabwin | win_id2win | win_screenpos | win_splitmove | winbufnr | wincol | windowsversion | winheight | winlayout | winline | winnr | winrestcmd | winrestview | winsaveview | winwidth | wordcount | writefile | xor ) \\b """ vimGroup: name: "support.type.group.viml" match: """(?xi) \\b ( Boolean | Character | Comment | Conditional | Constant | Debug | Define | Delimiter | Error | Exception | Float | Function | Identifier | Ignore | Include | Keyword | Label | Macro | Number | Operator | PreCondit | PreProc | Repeat | SpecialChar | SpecialComment | Special | Statement | StorageClass | String | Structure | Tag | Todo | Typedef | Type | Underlined ) \\b """ vimGroupSpecial: name: "support.function.vimGroupSpecial.viml" match: """(?x) \\b ( ALLBUT | ALL | CONTAINED | TOP ) \\b """ vimHLGroup: name: "support.type.highlight-group.viml" match: """(?xi) \\b ( ColorColumn | CursorColumn | CursorIM | CursorLineNr | CursorLine | Cursor | DiffAdd | DiffChange | DiffDelete | DiffText | Directory | EndOfBuffer | ErrorMsg | FoldColumn | Folded | IncSearch | LineNrAbove | LineNrBelow | LineNr | MatchParen | Menu | ModeMsg | MoreMsg | NonText | Normal | PmenuSbar | PmenuSel | PmenuThumb | Pmenu | Question | QuickFixLine | Scrollbar | Search | SignColumn | SpecialKey | SpellBad | SpellCap | SpellLocal | SpellRare | StatusLineNC | StatusLineTerm | StatusLine | TabLineFill | TabLineSel | TabLine | Terminal | Title | Tooltip | VertSplit | VisualNOS | Visual | WarningMsg | WildMenu ) \\b """ vimHiAttrib: name: "support.function.vimHiAttrib.viml" match: """(?x) \\b ( bold | inverse | italic | nocombine | none | reverse | standout | strikethrough | undercurl | underline ) \\b """ vimHiClear: name: "support.function.vimHiClear.viml" match: """(?x) \\b ( clear ) \\b """ vimHiCtermColor: name: "support.constant.colour.color.$1.viml" match: """(?x) \\b ( black | blue | brown | cyan | darkblue | darkcyan | darkgray | darkgreen | darkgrey | darkmagenta | darkred | darkyellow | gray | green | grey40 | grey50 | grey90 | grey | lightblue | lightcyan | lightgray | lightgreen | lightgrey | lightmagenta | lightred | lightyellow | magenta | red | seagreen | white | yellow ) \\b """ vimMapModKey: name: "support.function.vimMapModKey.viml" match: """(?x) \\b ( buffer | expr | leader | localleader | nowait | plug | script | sid | silent | unique ) \\b """ vimOption: name: "support.variable.option.viml" match: """(?x) \\b ( acd | ai | akm | aleph | allowrevins | altkeymap | al | ambiwidth | ambw | antialias | anti | arabicshape | arabic | arab | ari | arshape | ar | asd | autochdir | autoindent | autoread | autoshelldir | autowriteall | autowrite | awa | aw | background | backspace | backupcopy | backupdir | backupext | backupskip | backup | balloondelay | balloonevalterm | ballooneval | balloonexpr | bdir | bdlay | belloff | bevalterm | beval | bexpr | bex | bg | bh | binary | bin | bkc | bk | bl | bomb | bo | breakat | breakindentopt | breakindent | briopt | bri | brk | browsedir | bsdir | bsk | bs | bt | bufhidden | buflisted | buftype | casemap | cb | ccv | cc | cdpath | cd | cedit | cfu | cf | charconvert | ch | cindent | cinkeys | cink | cinoptions | cino | cinwords | cinw | cin | ci | clipboard | cmdheight | cmdwinheight | cmp | cms | cm | cocu | cole | colorcolumn | columns | commentstring | comments | compatible | completefunc | completeopt | completepopup | completeslash | complete | com | confirm | copyindent | cot | co | cpoptions | cpo | cpp | cpt | cp | crb | cryptmethod | cscopepathcomp | cscopeprg | cscopequickfix | cscoperelative | cscopetagorder | cscopetag | cscopeverbose | csl | cspc | csprg | csqf | csre | csto | cst | csverb | cuc | culopt | cul | cursorbind | cursorcolumn | cursorlineopt | cursorline | cursor | cwh | debug | deco | define | def | delcombine | dex | dg | dictionary | dict | diffexpr | diffopt | diff | digraph | dip | directory | dir | display | dy | eadirection | ead | ea | eb | edcompatible | ed | efm | ef | ei | ek | emoji | emo | encoding | enc | endofline | eol | ep | equalalways | equalprg | errorbells | errorfile | errorformat | esckeys | et | eventignore | expandtab | exrc | ex | fcl | fcs | fdc | fde | fdi | fdls | fdl | fdm | fdn | fdo | fdt | fencs | fenc | fen | fex | ffs | ff | fic | fileencodings | fileencoding | fileformats | fileformat | fileignorecase | filetype | fillchars | fixendofline | fixeol | fkmap | fk | flp | fml | fmr | foldclose | foldcolumn | foldenable | foldexpr | foldignore | foldlevelstart | foldlevel | foldmarker | foldmethod | foldminlines | foldnestmax | foldopen | foldtext | formatexpr | formatlistpat | formatoptions | formatprg | fo | fp | fsync | fs | ft | gcr | gdefault | gd | gfm | gfn | gfs | gfw | ghr | go | gp | grepformat | grepprg | gtl | gtt | guicursor | guifontset | guifontwide | guifont | guiheadroom | guioptions | guipty | guitablabel | guitabtooltip | helpfile | helpheight | helplang | hf | hh | hidden | hid | highlight | history | hi | hkmapp | hkmap | hkp | hk | hlg | hlsearch | hls | hl | iconstring | icon | ic | ignorecase | imactivatefunc | imactivatekey | imaf | imak | imcmdline | imc | imdisable | imd | iminsert | imi | imsearch | imsf | imstatusfunc | imstyle | imst | ims | im | includeexpr | include | incsearch | inc | indentexpr | indentkeys | inde | indk | inex | infercase | inf | insertmode | invacd | invai | invakm | invallowrevins | invaltkeymap | invantialias | invanti | invarabicshape | invarabic | invarab | invari | invarshape | invar | invasd | invautochdir | invautoindent | invautoread | invautoshelldir | invautowriteall | invautowrite | invawa | invaw | invbackup | invballoonevalterm | invballooneval | invbevalterm | invbeval | invbinary | invbin | invbk | invbl | invbomb | invbreakindent | invbri | invbuflisted | invcf | invcindent | invcin | invci | invcompatible | invconfirm | invcopyindent | invcp | invcrb | invcscoperelative | invcscopetag | invcscopeverbose | invcsre | invcst | invcsverb | invcuc | invcul | invcursorbind | invcursorcolumn | invcursorline | invdeco | invdelcombine | invdg | invdiff | invdigraph | invea | inveb | invedcompatible | inved | invek | invemoji | invemo | invendofline | inveol | invequalalways | inverrorbells | invesckeys | invet | invexpandtab | invexrc | invex | invfen | invfic | invfileignorecase | invfixendofline | invfixeol | invfkmap | invfk | invfoldenable | invfsync | invfs | invgdefault | invgd | invguipty | invhidden | invhid | invhkmapp | invhkmap | invhkp | invhk | invhlsearch | invhls | invicon | invic | invignorecase | invimcmdline | invimc | invimdisable | invimd | invim | invincsearch | invinfercase | invinf | invinsertmode | invis | invjoinspaces | invjs | invlangnoremap | invlangremap | invlazyredraw | invlbr | invlinebreak | invlisp | invlist | invlnr | invloadplugins | invlpl | invlrm | invlz | invmacatsui | invmagic | invma | invmh | invmle | invml | invmodelineexpr | invmodeline | invmodifiable | invmodified | invmod | invmore | invmousefocus | invmousef | invmousehide | invnumber | invnu | invodev | invopendevice | invpaste | invpi | invpreserveindent | invpreviewwindow | invprompt | invpvw | invreadonly | invrelativenumber | invremap | invrestorescreen | invrevins | invrightleft | invri | invrl | invrnu | invro | invrs | invruler | invru | invsb | invscb | invscf | invscrollbind | invscrollfocus | invscs | invsc | invsecure | invsft | invshellslash | invshelltemp | invshiftround | invshortname | invshowcmd | invshowfulltag | invshowmatch | invshowmode | invsi | invsmartcase | invsmartindent | invsmarttab | invsmd | invsm | invsn | invsol | invspell | invsplitbelow | invsplitright | invspr | invsr | invssl | invstartofline | invsta | invstmp | invswapfile | invswf | invtagbsearch | invtagrelative | invtagstack | invta | invtbidi | invtbi | invtbs | invtermbidi | invterse | invtextauto | invtextmode | invtf | invtgst | invtildeop | invtimeout | invtitle | invtop | invto | invtr | invttimeout | invttybuiltin | invttyfast | invtx | invudf | invundofile | invvb | invvisualbell | invwarn | invwa | invwb | invweirdinvert | invwfh | invwfw | invwic | invwildignorecase | invwildmenu | invwinfixheight | invwinfixwidth | invwiv | invwmnu | invwrapscan | invwrap | invwriteany | invwritebackup | invwrite | invws | isfname | isf | isident | isi | iskeyword | isk | isprint | isp | is | joinspaces | js | keymap | keymodel | keywordprg | key | kmp | km | kp | langmap | langmenu | langnoremap | langremap | laststatus | lazyredraw | lbr | lcs | level | linebreak | linespace | lines | lispwords | lisp | listchars | list | lmap | lm | lnr | loadplugins | lpl | lrm | lsp | ls | luadll | lw | lz | macatsui | magic | makeef | makeencoding | makeprg | matchpairs | matchtime | mat | maxcombine | maxfuncdepth | maxmapdepth | maxmempattern | maxmemtot | maxmem | ma | mco | mef | menc | menuitems | mfd | mh | mis | mkspellmem | mle | mls | ml | mmd | mmp | mmt | mm | modelineexpr | modelines | modeline | modifiable | modified | mod | more | mousefocus | mousef | mousehide | mousemodel | mousem | mouseshape | mouses | mousetime | mouset | mouse | mps | mp | msm | mzquantum | mzq | mzschemedll | mzschemegcdll | nf | noacd | noai | noakm | noallowrevins | noaltkeymap | noantialias | noanti | noarabicshape | noarabic | noarab | noari | noarshape | noar | noasd | noautochdir | noautoindent | noautoread | noautoshelldir | noautowriteall | noautowrite | noawa | noaw | nobackup | noballoonevalterm | noballooneval | nobevalterm | nobeval | nobinary | nobin | nobk | nobl | nobomb | nobreakindent | nobri | nobuflisted | nocf | nocindent | nocin | noci | nocompatible | noconfirm | nocopyindent | nocp | nocrb | nocscoperelative | nocscopetag | nocscopeverbose | nocsre | nocst | nocsverb | nocuc | nocul | nocursorbind | nocursorcolumn | nocursorline | nodeco | nodelcombine | nodg | nodiff | nodigraph | noea | noeb | noedcompatible | noed | noek | noemoji | noemo | noendofline | noeol | noequalalways | noerrorbells | noesckeys | noet | noexpandtab | noexrc | noex | nofen | nofic | nofileignorecase | nofixendofline | nofixeol | nofkmap | nofk | nofoldenable | nofsync | nofs | nogdefault | nogd | noguipty | nohidden | nohid | nohkmapp | nohkmap | nohkp | nohk | nohlsearch | nohls | noicon | noic | noignorecase | noimcmdline | noimc | noimdisable | noimd | noim | noincsearch | noinfercase | noinf | noinsertmode | nois | nojoinspaces | nojs | nolangnoremap | nolangremap | nolazyredraw | nolbr | nolinebreak | nolisp | nolist | nolnr | noloadplugins | nolpl | nolrm | nolz | nomacatsui | nomagic | noma | nomh | nomle | noml | nomodelineexpr | nomodeline | nomodifiable | nomodified | nomod | nomore | nomousefocus | nomousef | nomousehide | nonumber | nonu | noodev | noopendevice | nopaste | nopi | nopreserveindent | nopreviewwindow | noprompt | nopvw | noreadonly | norelativenumber | noremap | norestorescreen | norevins | norightleft | nori | norl | nornu | noro | nors | noruler | noru | nosb | noscb | noscf | noscrollbind | noscrollfocus | noscs | nosc | nosecure | nosft | noshellslash | noshelltemp | noshiftround | noshortname | noshowcmd | noshowfulltag | noshowmatch | noshowmode | nosi | nosmartcase | nosmartindent | nosmarttab | nosmd | nosm | nosn | nosol | nospell | nosplitbelow | nosplitright | nospr | nosr | nossl | nostartofline | nosta | nostmp | noswapfile | noswf | notagbsearch | notagrelative | notagstack | nota | notbidi | notbi | notbs | notermbidi | noterse | notextauto | notextmode | notf | notgst | notildeop | notimeout | notitle | notop | noto | notr | nottimeout | nottybuiltin | nottyfast | notx | noudf | noundofile | novb | novisualbell | nowarn | nowa | nowb | noweirdinvert | nowfh | nowfw | nowic | nowildignorecase | nowildmenu | nowinfixheight | nowinfixwidth | nowiv | nowmnu | nowrapscan | nowrap | nowriteany | nowritebackup | nowrite | nows | nrformats | numberwidth | number | nuw | nu | odev | oft | ofu | omnifunc | opendevice | operatorfunc | opfunc | osfiletype | packpath | paragraphs | para | pastetoggle | paste | patchexpr | patchmode | path | pa | pdev | penc | perldll | pexpr | pex | pfn | pheader | ph | pi | pmbcs | pmbfn | pm | popt | pp | preserveindent | previewheight | previewpopup | previewwindow | printdevice | printencoding | printexpr | printfont | printheader | printmbcharset | printmbfont | printoptions | prompt | pt | pumheight | pumwidth | pvh | pvp | pvw | pw | pythondll | pythonhome | pythonthreedll | pythonthreehome | pyxversion | pyx | qe | qftf | quickfixtextfunc | quoteescape | rdt | readonly | redrawtime | regexpengine | relativenumber | remap | renderoptions | report | restorescreen | revins | re | rightleftcmd | rightleft | ri | rlc | rl | rnu | rop | ro | rs | rtp | rubydll | ruf | rulerformat | ruler | runtimepath | ru | sbo | sbr | sb | scb | scf | scl | scrollbind | scrollfocus | scrolljump | scrolloff | scrollopt | scroll | scr | scs | sc | sections | sect | secure | selection | selectmode | sel | sessionoptions | sft | shcf | shellcmdflag | shellpipe | shellquote | shellredir | shellslash | shelltemp | shelltype | shellxescape | shellxquote | shell | shiftround | shiftwidth | shm | shortmess | shortname | showbreak | showcmd | showfulltag | showmatch | showmode | showtabline | shq | sh | sidescrolloff | sidescroll | signcolumn | siso | si | sj | slm | smartcase | smartindent | smarttab | smc | smd | sm | sn | softtabstop | sol | so | spc | spellcapcheck | spellfile | spelllang | spelloptions | spellsuggest | spell | spf | splitbelow | splitright | spl | spo | spr | sps | sp | srr | sr | ssl | ssop | ss | stal | startofline | statusline | sta | stl | stmp | sts | st | sua | suffixesadd | suffixes | su | swapfile | swapsync | swb | swf | switchbuf | sws | sw | sxe | sxq | synmaxcol | syntax | syn | t_8b | t_8f | t_8u | t_AB | t_AF | t_AL | t_AU | t_BD | t_BE | t_CS | t_CV | t_Ce | t_Co | t_Cs | t_DL | t_EC | t_EI | t_F1 | t_F2 | t_F3 | t_F4 | t_F5 | t_F6 | t_F7 | t_F8 | t_F9 | t_GP | t_IE | t_IS | t_K1 | t_K3 | t_K4 | t_K5 | t_K6 | t_K7 | t_K8 | t_K9 | t_KA | t_KB | t_KC | t_KD | t_KE | t_KF | t_KG | t_KH | t_KI | t_KJ | t_KK | t_KL | t_PE | t_PS | t_RB | t_RC | t_RF | t_RI | t_RS | t_RT | t_RV | t_Ri | t_SC | t_SH | t_SI | t_SR | t_ST | t_Sb | t_Sf | t_Si | t_TE | t_TI | t_Te | t_Ts | t_VS | t_WP | t_WS | t_ZH | t_ZR | t_al | t_bc | t_cd | t_ce | t_cl | t_cm | t_cs | t_da | t_db | t_dl | t_fd | t_fe | t_fs | t_k1 | t_k2 | t_k3 | t_k4 | t_k5 | t_k6 | t_k7 | t_k8 | t_k9 | t_kB | t_kD | t_kI | t_kN | t_kP | t_kb | t_kd | t_ke | t_kh | t_kl | t_kr | t_ks | t_ku | t_le | t_mb | t_md | t_me | t_mr | t_ms | t_nd | t_op | t_se | t_so | t_sr | t_te | t_ti | t_ts | t_u7 | t_ue | t_us | t_ut | t_vb | t_ve | t_vi | t_vs | t_xn | t_xs | tabline | tabpagemax | tabstop | tagbsearch | tagcase | tagfunc | taglength | tagrelative | tagstack | tags | tag | tal | ta | tbidi | tbis | tbi | tbs | tb | tcldll | tc | tenc | termbidi | termencoding | termguicolors | termwinkey | termwinscroll | termwinsize | termwintype | term | terse | textauto | textmode | textwidth | tfu | tf | tgc | tgst | thesaurus | tildeop | timeoutlen | timeout | titlelen | titleold | titlestring | title | tl | tm | toolbariconsize | toolbar | top | to | tpm | tr | tsl | tsr | ts | ttimeoutlen | ttimeout | ttm | ttybuiltin | ttyfast | ttymouse | ttym | ttyscroll | ttytype | tty | twk | twsl | tws | twt | tw | tx | uc | udf | udir | ul | undodir | undofile | undolevels | undoreload | updatecount | updatetime | ur | ut | varsofttabstop | vartabstop | vbs | vb | vdir | verbosefile | verbose | ve | vfile | viewdir | viewoptions | vif | viminfofile | viminfo | virtualedit | visualbell | vi | vop | vsts | vts | wak | warn | wa | wb | wcm | wcr | wc | wd | weirdinvert | wfh | wfw | whichwrap | wh | wic | wig | wildcharm | wildchar | wildignorecase | wildignore | wildmenu | wildmode | wildoptions | wim | winaltkeys | wincolor | window | winfixheight | winfixwidth | winheight | winminheight | winminwidth | winptydll | winwidth | wiv | wiw | wi | wmh | wmnu | wmw | wm | wop | wrapmargin | wrapscan | wrap | writeany | writebackup | writedelay | write | ws | ww ) \\b """ vimPattern: name: "support.function.vimPattern.viml" match: """(?x) \\b ( end | skip | start ) \\b """ vimStdPlugin: name: "support.class.stdplugin.viml" match: """(?x) \\b ( Arguments | Asm | Break | Cfilter | Clear | Continue | DiffOrig | Evaluate | Finish | Gdb | Lfilter | Man | N | Next | Over | P | Print | Program | Run | Source | Step | Stop | S | TOhtml | TermdebugCommand | Termdebug | Winbar | XMLent | XMLns ) \\b """ vimSynCase: name: "support.function.vimSynCase.viml" match: """(?x) \\b ( ignore | match ) \\b """ vimSynType: name: "support.function.vimSynType.viml" match: """(?x) \\b ( case | clear | cluster | enable | include | iskeyword | keyword | list | manual | match | off | on | region | reset | sync ) \\b """ vimSyncC: name: "support.function.vimSyncC.viml" match: """(?x) \\b ( ccomment | clear | fromstart ) \\b """ vimSyncLinecont: name: "support.function.vimSyncLinecont.viml" match: """(?x) \\b ( linecont ) \\b """ vimSyncMatch: name: "support.function.vimSyncMatch.viml" match: """(?x) \\b ( match ) \\b """ vimSyncNone: name: "support.function.vimSyncNone.viml" match: """(?x) \\b ( NONE ) \\b """ vimSyncRegion: name: "support.function.vimSyncRegion.viml" match: """(?x) \\b ( region ) \\b """ vimUserAttrbCmplt: name: "support.function.vimUserAttrbCmplt.viml" match: """(?x) \\b ( augroup | behave | buffer | color | command | compiler | cscope | customlist | custom | dir | environment | event | expression | file_in_path | filetype | file | function | help | highlight | history | locale | mapping | menu | option | packadd | shellcmd | sign | syntax | syntime | tag_listfiles | tag | user | var ) \\b """ vimUserAttrbKey: name: "support.function.vimUserAttrbKey.viml" match: """(?x) \\b ( bang? | bar | com | complete | cou | count | n | nargs | ra | range | re | register ) \\b """ vimUserCommand: name: "support.function.vimUserCommand.viml" match: """(?x) \\b ( com | command ) \\b """
130471
name: "<NAME>imL" scopeName: "source.viml" injectionSelector: "source.gfm source.embedded.viml" fileTypes: [ "vim" "vimrc" "gvimrc" "nvimrc" "_vimrc" "exrc" "nexrc" "vmb" ] firstLineMatch: """(?x) # Vimball (?:^|\\n)UseVimball\\b | # Hashbang ^\\#!.*(?:\\s|\\/|(?<=!)\\b) (?:vim|nvim) (?:$|\\s) | # Modeline (?: # Vim/Vi modeline, accounting for all possible variations (?:(?:^|[ \\t])(?:vi|Vi(?=m))(?:m[<=>]?[0-9]+|m)?|[ \\t]ex)(?=:(?=[ \\t]*set?[ \\t][^\\r\\n:]+:)|:(?![ \\t]*set?[ \\t])) (?:(?:[ \\t]*:[ \\t]*|[ \\t])\\w*(?:[ \\t]*=(?:[^\\\\\\s]|\\\\.)*)?)*[ \\t:] (?:filetype|ft|syntax)[ \\t]*= (?i:vim) (?=$|\\s|:) | # Emacs modeline, assuming a major mode for VimScript even exists -\\*-(?i:[ \\t]*(?=[^:;\\s]+[ \\t]*-\\*-)|(?:.*?[ \\t;]|(?<=-\\*-))[ \\t]*mode[ \\t]*:[ \\t]*) (?i:Vim|VimL|VimScript) (?=[ \\t;]|(?<![-*])-\\*-).*?-\\*- ) """ foldingStartMarker: "^(?:if|while|for|fu|function|augroup|aug)" foldingStopMarker: "(?:endif|endwhile|endfor|endf|endfunction|augroup\\.END|aug\\.END)$" limitLineLength: no patterns: [{ # VimBall archive name: "meta.file-archive.vimball" begin: '\\A(?=" Vimball Archiver)' end: "(?=A)B" patterns: [{ # Help file name: "meta.file-record.help-file.vimball" begin: "^(.*?\\S.*?\\.txt)(\\t)(\\[{3}1)(?=$)" end: "(?!\\G)(?=^.*?\\S.*?\\t\\[{3}1$)" beginCaptures: 0: name: "markup.heading.1.vimball" 1: name: "entity.name.file.path.vimball" 2: name: "punctuation.whitespace.tab.separator.vimball" 3: name: "punctuation.definition.header.vimball" contentName: "text.embedded.vim-help" patterns: [{ # Line count begin: "\\G" end: "^(\\d+$)?" endCaptures: 0: name: "comment.ignored.line-count.viml" 1: name: "sublimelinter.gutter-mark" }, include: "text.vim-help"] },{ # Vim script file name: "meta.file-record.vimball.viml" begin: "^(.*?\\S.*?[ \\t]*?)(\\t)(\\[{3}1)(?=$)" end: "(?!\\G)(?=^.*?\\S.*?\\t\\[{3}1$)" beginCaptures: 0: name: "markup.heading.1.vimball" 1: name: "entity.name.file.path.vimball" 2: name: "punctuation.whitespace.tab.separator.vimball" 3: name: "punctuation.definition.header.vimball" patterns: [{ # Line count begin: "\\G" end: "^(\\d+$)?" endCaptures: 0: name: "comment.ignored.line-count.viml" 1: name: "sublimelinter.gutter-mark" }, include: "#main"] }, include: "#main"] }, include: "#main"] repository: main: patterns: [ {include: "#vimTodo"} {include: "#comments"} {include: "#modelines"} {include: "#pathname"} {include: "#escape"} {include: "#strings"} {include: "#hashbang"} {include: "#numbers"} {include: "#syntax"} {include: "#highlightLink"} {include: "#funcDef"} {include: "#auCmd"} {include: "#auGroup"} {include: "#parameter"} {include: "#assignment"} {include: "#expr"} {include: "#keyword"} {include: "#register"} {include: "#filetype"} {include: "#variable"} {include: "#supportType"} {include: "#supportVariable"} {include: "#extraVimOptions"} {include: "#extraVimFunc"} {include: "#keywordLists"} ] strings: patterns: [{ name: "string.quoted.double.empty.viml" match: '(")(")' captures: 1: name: "punctuation.definition.string.begin.viml" 2: name: "punctuation.definition.string.end.viml" },{ name: "string.quoted.single.empty.viml" match: "(')(')" captures: 1: name: "punctuation.definition.string.begin.viml" 2: name: "punctuation.definition.string.end.viml" },{ name: "string.quoted.double.viml" match: '(")((?:[^\\\\"]|\\\\.)*)(")' captures: 1: name: "punctuation.definition.string.begin.viml" 2: patterns: [include: "#escape"] 3: name: "punctuation.definition.string.end.viml" },{ name: "string.quoted.single.viml" match: "(')((?:[^']|'')*)(')" captures: 1: name: "punctuation.definition.string.begin.viml" 2: patterns: [{ name: "constant.character.escape.quotes.viml" match: "''" }] 3: name: "punctuation.definition.string.end.viml" },{ name: "string.regexp.interpolated.viml" match: "(/)(?:\\\\\\\\|\\\\/|[^\\n/])*(/)" captures: 1: name: "punctuation.section.regexp.begin.viml" 2: name: "punctuation.section.regexp.end.viml" }] # Something prefixed with a backslash escape: patterns: [ {include: "#escapedCodePoint"} {include: "#escapedKey"} {match: "(\\\\)b", name: "constant.character.escape.backspace.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)e", name: "constant.character.escape.escape.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)f", name: "constant.character.escape.form-feed.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)n", name: "constant.character.escape.newline.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)r", name: "constant.character.escape.return.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)t", name: "constant.character.escape.tab.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)\\1",name: "constant.character.escape.backslash.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: '(\\\\)"', name: "constant.character.escape.quote.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\).", name: "constant.character.escape.other.viml", captures: 1: name: "punctuation.definition.escape.viml"} ] # Characters specified by codepoint escapedCodePoint: patterns: [{ # Hexadecimal, short: \x20 name: "constant.character.escape.codepoint.hex.short.viml" match: "(\\\\)[xX][0-9A-Fa-f]{1,2}" captures: 1: name: "punctuation.definition.escape.backslash.viml" },{ # Codepoint, long: \u0020 \u00000020 name: "constant.character.escape.codepoint.hex.long.viml" match: "(\\\\)(?:u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8})" captures: 1: name: "punctuation.definition.escape.backslash.viml" },{ # Codepoint, octal: \040 name: "constant.character.escape.codepoint.octal.viml" match: "(\\\\)([0-7]{1,3})" captures: 1: name: "punctuation.definition.escape.backslash.viml" }] escapedKey: name: "constant.character.escape.keymapping.viml" match: '(\\\\<\\*?)(?:[^">\\\\]|\\\\.)+(>)' captures: 1: name: "punctuation.definition.escape.key.begin.viml" 2: name: "punctuation.definition.escape.key.end.viml" # This only exists to stop stuff like ~/.vim/ being highlighted like a regex pathname: name: "constant.pathname.viml" begin: "~/" end: "(?=\\s)" comments: patterns: [{ # Fully-commented line with a leading field-name name: "comment.line.quotes.viml" begin: '^\\s*(")(?=(\\s*[A-Z]\\w+)+:)' end: "((:))(.*)$" contentName: "support.constant.field.viml" beginCaptures: 1: name: "punctuation.definition.comment.viml" endCaptures: 1: name: "support.constant.field.viml" 2: name: "punctuation.separator.key-value.colon.viml" 3: patterns: [include: "#commentInnards"] },{ # Fully-commented line name: "comment.line.quotes.viml" begin: '^\\s*(")' end: '$' beginCaptures: 1: name: "punctuation.definition.comment.viml" patterns: [include: "#commentInnards"] },{ # Trailing comment, no closing quote name: "comment.inline.quotes.viml" patterns: [include: "#commentInnards"] begin: '(?<!^)\\s*(")(?=[^\\n"]*$)' end: "$" beginCaptures: 1: name: "punctuation.definition.comment.viml" }] commentInnards: patterns: [ {include: "#modelines"} {include: "#todo"} ] # Vim modelines modelines: patterns: [{ # Using "vim:set" name: "string.other.modeline.viml" patterns: [include: "#main"] begin: "(?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|[\\t\\x20]ex):\\s*(?=set?\\s)" end: ":|$" },{ name: "string.other.modeline.viml" patterns: [include: "#main"] begin: "(?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|[\\t\\x20]ex):" end: "$" }] # Embedded interpreter directive hashbang: name: "comment.line.shebang.viml" begin: "\\A#!" end: "$" beginCaptures: 0: name: "punctuation.definition.comment.shebang.viml" numbers: patterns: [{ name: "constant.numeric.hex.short.viml" match: "0[xX][0-9A-Fa-f]+" },{ name: "constant.numeric.hex.long.viml" match: "0[zZ][0-9A-Fa-f]+" },{ name: "constant.numeric.float.exponential.viml" match: "(?<!\\w)-?\\d+\\.\\d+[eE][-+]?\\d+" },{ name: "constant.numeric.float.viml" match: "(?<!\\w)-?\\d+\\.\\d+" },{ name: "constant.numeric.integer.viml" match: "(?<!\\w)-?\\d+" }] funcDef: patterns: [{ name: "storage.function.viml" match: "\\b(fu(nc?|nction)?|end(f|fu|func?|function)?)\\b" },{ name: "entity.name.function.viml" match: "(?:([sSgGbBwWtTlL]?(:))?[\\w#]+)(?=\\()" captures: 1: name: "storage.modifier.scope.viml" 2: name: "punctuation.definition.scope.key-value.viml" },{ name: "storage.modifier.$1.function.viml" match: "(?<=\\)|\\s)(abort|dict|closure|range)(?=\\s|$)" }] auCmd: name: "meta.autocmd.viml" match: "\\b(autocmd|au)(!)?\\b\\s+(?!\\*)(\\S+)\\s+(\\S+)(?:\\s+(\\+\\+(nested|once)))?" captures: 1: name: "storage.type.autocmd.viml" 2: name: "storage.modifier.force.viml" 3: name: "meta.events-list.viml", patterns: [include: "#main"] 4: name: "string.unquoted.autocmd-suffix-list.viml" 5: name: "storage.modifier.$6.viml" auGroup: patterns: [ name: "meta.augroup.viml" begin: "\\b(augroup|aug)(!)?\\b\\s*([\\w#]+)" end: "\\b(\\1)\\s+(END)\\b" patterns: [include: "#main"] beginCaptures: 1: name: "storage.type.function.viml" 2: name: "storage.modifier.force.viml" 3: name: "entity.name.function.viml" endCaptures: 1: name: "storage.type.augroup.viml" 2: name: "keyword.control.end" ] parameter: name: "meta.parameter.viml" match: "(-)(\\w+)(=)" captures: 1: name: "punctuation.definition.parameter.viml" 2: name: "entity.name.parameter.viml" 3: name: "punctuation.assignment.parameter.viml" assignment: patterns: [{ name: "keyword.operator.assignment.compound.viml" match: "[-+.]=" },{ name: "keyword.operator.assignment.viml" match: "=" }] expr: patterns: [ name: "keyword.operator.logical.viml" match: "[&|=]{2}[?#]?|[!><]=[#?]?|[=!]~(?!\\/)[#?]?|[><][#?*]|\\b(?:isnot|is)\\b|\\\\|[-+%*]" {match: "\\s[><]\\s",name: "keyword.operator.logical.viml"} {match: "(?<=\\S)!", name: "storage.modifier.force.viml"} {match: "!(?=\\S)", name: "keyword.operator.logical.not.viml"} {match: "{", name: "punctuation.expression.bracket.curly.begin.viml"} {match: "}", name: "punctuation.expression.bracket.curly.end.viml"} {match: "\\[", name: "punctuation.expression.bracket.square.begin.viml"} {match: "\\]", name: "punctuation.expression.bracket.square.end.viml"} {match: "\\(", name: "punctuation.expression.bracket.round.begin.viml"} {match: "\\)", name: "punctuation.expression.bracket.round.end.viml"} {match: "\\|", name: "punctuation.separator.statement.viml"} {match: ",", name: "punctuation.separator.comma.viml"} {match: ":", name: "punctuation.separator.colon.viml"} {match: "\\.{3}", name: "keyword.operator.rest.viml"} {match: "\\.", name: "punctuation.delimiter.property.dot.viml"} {match: "&(?=\\w+)", name: "punctuation.definition.option.viml"} ] keyword: patterns: [{ name: "keyword.control.$1.viml" match: "\\b(if|while|for|return|try|catch|finally|finish|end(if|for|while|try)?|else(if)?|do|in|:)\\b" },{ name: "keyword.operator.$1.viml" match: "\\b(unlet)\\b" },{ name: "storage.type.let.viml" match: "\\blet\\b" },{ name: "support.constant.vimball.use.viml" match: "(?<=^|\\n)UseVimball(?=\\s*$)" }] register: name: "variable.other.register.viml" match: "(@)([-\"A-Za-z\\d:.%#=*+~_/])" captures: 1: name: "punctuation.definition.register.viml" variable: patterns: [{ name: "variable.language.self.viml" match: "\\b(self)\\b" },{ name: "support.variable.environment.viml" match: "(\\$)\\w+" captures: 1: name: "punctuation.definition.variable.viml" },{ name: "variable.other.viml" match: "(&?)(?:([sSgGbBwWlLaAvV](:))|[@$]|&(?!&))\\w*" captures: 1: name: "punctuation.definition.reference.viml" 2: name: "storage.modifier.scope.viml" 3: name: "punctuation.definition.scope.key-value.viml" }] supportType: name: "entity.tag.name.viml" match: "(<).*?(>)" captures: 1: name: "punctuation.definition.bracket.angle.begin.viml" 2: name: "punctuation.definition.bracket.angle.end.viml" supportVariable: name: "support.variable.viml" match: "\\b(?:am(?:enu)?|(?:hl|inc)?search|[Bb]uf(?:[Nn]ew[Ff]ile|[Rr]ead)?|[Ff]ile[Tt]ype)\\b" # Highlighting link, used heavily in syntax-definition files highlightLink: match: "(?x)^\\s* (:)? \\s* (?# 1: punctuation.separator.key-value.colon.viml) (hi|highlight) (?# 2: support.function.highlight.viml) (!)? (?# 3: storage.modifier.force.viml) (?:\\s+(def|default))? (?# 4: support.function.highlight-default.viml) (?:\\s+(link)) (?# 5: support.function.highlight-link.viml) (?:\\s+([-\\w]+)) (?# 6: variable.parameter.group-name.viml) (?:\\s+(?:(NONE)|([-\\w]+)))?" captures: 1: name: "punctuation.separator.key-value.colon.viml" 2: name: "support.function.highlight.viml" 3: name: "storage.modifier.force.viml" 4: name: "support.function.highlight-default.viml" 5: name: "support.function.highlight-link.viml" 6: name: "variable.parameter.group-name.viml" 7: name: "support.constant.highlighting.viml" 8: name: "variable.parameter.group-name.viml" # Filetype assignment filetype: match: "\\b(?:(setf|setfiletype)(?:\\s+(FALLBACK))?\\s+|(ft|filetype)\\s*(=))([.\\w]+)" captures: 1: name: "support.function.command.viml" 2: name: "support.variable.option.viml" 3: name: "storage.modifier.fallback.viml" 4: name: "keyword.operator.assignment.viml" 5: name: "variable.parameter.function.filetype.viml" # Syntax highlighting definitions syntax: name: "meta.syntax-item.viml" begin: "^\\s*(:)?(?:(VimFold\\w)\\s+)?\\s*(syntax|syn?)(?=\\s|$)" end: "$" beginCaptures: 1: name: "punctuation.separator.key-value.colon.viml" 2: name: "support.function.fold-command.viml" 3: name: "storage.type.syntax-item.viml" patterns: [{ # Case-matching match: "\\G\\s+(case)(?:\\s+(match|ignore))?(?=\\s|$)" captures: 1: name: "support.function.syntax-case.viml" 2: name: "support.constant.$2-case.viml" },{ # Spell-checking match: "\\G\\s+(spell)(?:\\s+(toplevel|notoplevel|default))?(?=\\s|$)" captures: 1: name: "support.function.syntax-spellcheck.viml" 2: name: "support.constant.$2-checking.viml" },{ # Keyword lists begin: "\\G\\s+(keyword)(?:\\s+([-\\w]+))?" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-keywords.viml" 2: name: "variable.parameter.group-name.viml" contentName: "keyword.other.syntax-definition.viml" patterns: [ {include: "#syntaxOptions"} {include: "#assignment"} {include: "#expr"} ] },{ # Pattern-based match begin: "\\G\\s+(match)(?:\\s+([-\\w]+))?\\s*" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-match.viml" 2: name: "variable.parameter.group-name.viml" patterns: [include: "#syntaxRegex"] },{ # Multiline pattern-based match begin: "\\G\\s+(region)(?:\\s+([-\\w]+))?" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-region.viml" 2: name: "variable.parameter.group-name.viml" patterns: [ {include: "#syntaxOptions"} {include: "#main"} ] },{ # Group cluster begin: "\\G\\s+(cluster)(?:\\s+([-\\w]+))?(?=\\s|$)" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-cluster.viml" 2: name: "variable.parameter.group-name.viml" patterns: [ {include: "#syntaxOptions"} {include: "#main"} ] },{ # Concealment match: "\\G\\s+(conceal)(?:\\s+(on|off)(?=\\s|$))?" captures: 1: name: "support.function.syntax-conceal.viml" 2: name: "support.constant.boolean.$2.viml" },{ # Inclusion match: "\\G\\s+(include)(?:\\s+((@)?[-\\w]+))?(?:\\s+(\\S+))?" captures: 1: name: "support.function.syntax-include.viml" 2: name: "variable.parameter.group-name.viml" 3: name: "punctuation.definition.group-reference.viml" 4: name: "string.unquoted.filename.viml", patterns: [include: "#supportType"] },{ # Sync/Redrawing mode begin: "\\G\\s+(sync)(?=\\s|$)" end: "$" beginCaptures: 1: name: "support.function.syntax-sync.viml" patterns: [{ match: "\\G\\s+(fromstart)(?=\\s|$)" captures: 1: name: "support.constant.sync-$1.viml" },{ match: "\\G\\s+(ccomment|clear)(?:\\s+(?![-\\w]+\\s*=)([-\\w]+))?" captures: 1: name: "support.constant.sync-$1.viml" 2: name: "variable.parameter.group-name.viml" },{ match: "\\G\\s+(minlines|lines)\\s*(=)(\\d*)" captures: 1: name: "support.constant.sync-mode.viml" 2: name: "punctuation.assignment.parameter.viml" 3: name: "constant.numeric.integer.viml" },{ match: "(?x)\\G\\s+(match|region)(?:\\s+(?![-\\w]+\\s*=)([-\\w]+))?" captures: 1: name: "support.constant.sync-mode.viml" 2: name: "variable.parameter.group-name.viml" 3: name: "support.constant.sync-mode-location.viml" },{ begin: "(?<=\\s)(groupt?here|linecont)(?:\\s+(?![-\\w]+\\s*=)([-\\w]+))?(?=\\s|$)" end: "(?=$)" beginCaptures: 1: name: "support.constant.sync-match.viml" 2: name: "variable.parameter.group-name.viml" patterns: [include: "#syntaxRegex"] }, include: "#syntaxOptions"] }, include: "#main"] # Syntax item arguments, as described in :syn-arguments syntaxOptions: patterns: [{ # Options that take a regex name: "meta.syntax-item.pattern-argument.viml" begin: "(?<=\\s)(start|skip|end)(?:\\s*(=))" end: "(?=$|\\s)" beginCaptures: 1: name: "support.constant.$1-pattern.viml" 2: name: "punctuation.assignment.parameter.viml" patterns: [include: "#regex"] },{ # Everything else name: "meta.syntax-item.argument.viml" match: """(?x)(?<=\\s) ((?:matchgroup|contains|containedin|nextgroup|add|remove|minlines|linebreaks|maxlines)(?=\\s*=) |(?:cchar|conceal|concealends|contained|display|excludenl|extend|fold|keepend|oneline|skipempty|skipnl|skipwhite|transparent)) (?:(?=$|\\s)|\\s*(=)(\\S*)?)""" captures: 1: name: "support.constant.syntax-$1.viml" 2: name: "punctuation.assignment.parameter.viml" 3: name: "string.unquoted.syntax-option.viml", patterns: [ {include: "#numbers"} {match: ",", name: "punctuation.separator.comma.viml"} {match: "@", name: "punctuation.definition.group-reference.viml"} ] }] # Body of any syntax-item option which uses an unlabelled regex syntaxRegex: patterns: [ {include: "#syntaxOptions"} # Ensure only one regex is matched name: "string.regexp.viml" begin: "(?<=\\s)(\\S)" end: "(?:(\\1)(\\S*)(.*))?$" patterns: [include: "#regexInnards"] beginCaptures: 1: name: "punctuation.definition.string.begin.viml" endCaptures: 1: name: "punctuation.definition.string.end.viml" 2: patterns: [include: "#regexOffset"] 3: patterns: [include: "#syntaxOptions", {include: "#main"}] ] # Regular expression regex: name: "string.regexp.viml" begin: "(?<=\\s|=)(\\S)" end: "$|(\\1)(\\S*)" patterns: [include: "#regexInnards"] beginCaptures: 1: name: "punctuation.definition.string.begin.viml" endCaptures: 1: name: "punctuation.definition.string.end.viml" 2: patterns: [include: "#regexOffset"] # Pattern offset regexOffset: name: "meta.pattern-offset.viml" match: "(ms|me|hs|he|rs|re|lc)(=)(?:(\\d+)|([se])(?:([-+])(\\d+))?)(,)?" captures: 1: name: "constant.language.pattern-offset.viml" 2: name: "punctuation.assignment.parameter.viml" 3: name: "constant.numeric.integer.viml" 4: name: "constant.language.pattern-position.viml" 5: name: "keyword.operator.arithmetic.viml" 6: name: "constant.numeric.integer.viml" 7: name: "punctuation.separator.comma.viml" regexInnards: patterns: [{ # Character class begin: "\\[" end: "\\]|$" beginCaptures: 0: name: "punctuation.definition.character-class.begin.viml" endCaptures: 0: name: "punctuation.definition.character-class.end.viml" patterns: [include: "#regexInnards"] },{ # Escaped character name: "constant.character.escape.viml" match: "(\\\\)." captures: 1: name: "punctuation.definition.backslash.escape.viml" }] # Extra functions not picked up by keyword parser extraVimFunc: name: "support.function.viml" match: """(?x)\\b ((?:echo(?:hl?)?)|exe(?:c(?:ute)?)?|[lxvn]?noremap|smapc(?:lear)?|mapmode|xmap|(?:[xs]un|snore)map |Plugin|autocmd|[cinvo]?(?:un|nore)?(?:map|menu)|(?:range)?go(?:to)?|(?:count)?(?:pop?|tag?|tn(?:ext)?|tp(?:revious)?|tr(?:ewind)?) |(?:range)?(?:s(?:ubstitute)?|ret(?:ab)?|g(?:lobal)?)|unm(?:ap)?|map_l|mapc(?:lear)?|N?buffer|N?bnext|N?bNext|N?bprevious|N?bmod |ab(?:breviate)?|norea(?:bbrev)?|[ic](?:un|nore)?ab|split_f|rangefold|[ic](?:un|nore)?ab|[ic]abbrev|edit_f|next_f|[vcoxli]u |(?:range)?(?:w(?:rite)?|up(?:date)?)|sar|cno|[vl]n|[io]?no|[xn]n|snor|lm(?:ap)?|lunmap|lear|[vnx]m|om|[ci]m|ap|nun|sunm) \\b""" # Extra options not picked up by keyword parser extraVimOptions: name: "support.variable.option.viml" match: """(?x)\\b (no)? (altwerase|bf|escapetime|extended|filec|iclower|keytime|leftright|li|lock|noprint|octal|recdir|searchincr |shellmeta|ttywerase|windowname|wl|wraplen) \\b""" # The following lists are auto-extracted from Vim's syntax file. # Run `bin/update` to repopulate them. keywordLists: patterns: [ {include: "#vimTodo"} {include: "#vimAugroupKey"} {include: "#vimAutoEvent"} {include: "#vimBehaveModel"} {include: "#vimCommand"} {include: "#vimFTCmd"} {include: "#vimFTOption"} {include: "#vimFgBgAttrib"} {include: "#vimFuncKey"} {include: "#vimFuncName"} {include: "#vimGroup"} {include: "#vimGroupSpecial"} {include: "#vimHLGroup"} {include: "#vimHiAttrib"} {include: "#vimHiClear"} {include: "#vimHiCtermColor"} {include: "#vimMapModKey"} {include: "#vimOption"} {include: "#vimPattern"} {include: "#vimStdPlugin"} {include: "#vimSynCase"} {include: "#vimSynType"} {include: "#vimSyncC"} {include: "#vimSyncLinecont"} {include: "#vimSyncMatch"} {include: "#vimSyncNone"} {include: "#vimSyncRegion"} {include: "#vimUserAttrbCmplt"} {include: "#vimUserAttrbKey"} {include: "#vimUserCommand"} {include: "#vimErrSetting"} ] vimTodo: name: "support.constant.${1:/downcase}.viml" match: """(?x) \\b ( COMBAK | FIXME | TODO | XXX ) \\b """ vimAugroupKey: name: "support.function.vimAugroupKey.viml" match: """(?x) \\b ( aug | augroup ) \\b """ vimAutoEvent: name: "support.function.auto-event.viml" match: """(?xi) \\b ( BufAdd | BufCreate | BufDelete | BufEnter | BufFilePost | BufFilePre | BufHidden | BufLeave | BufNewFile | BufNew | BufReadCmd | BufReadPost | BufReadPre | BufRead | BufUnload | BufWinEnter | BufWinLeave | BufWipeout | BufWriteCmd | BufWritePost | BufWritePre | BufWrite | CmdUndefined | CmdlineChanged | CmdlineEnter | CmdlineLeave | CmdwinEnter | CmdwinLeave | ColorSchemePre | ColorScheme | CompleteChanged | CompleteDonePre | CompleteDone | CursorHoldI | CursorHold | CursorMovedI | CursorMoved | DiffUpdated | DirChanged | EncodingChanged | ExitPre | FileAppendCmd | FileAppendPost | FileAppendPre | FileChangedRO | FileChangedShellPost | FileChangedShell | FileEncoding | FileReadCmd | FileReadPost | FileReadPre | FileType | FileWriteCmd | FileWritePost | FileWritePre | FilterReadPost | FilterReadPre | FilterWritePost | FilterWritePre | FocusGained | FocusLost | FuncUndefined | GUIEnter | GUIFailed | InsertChange | InsertCharPre | InsertEnter | InsertLeavePre | InsertLeave | MenuPopup | OptionSet | QuickFixCmdPost | QuickFixCmdPre | QuitPre | RemoteReply | SafeStateAgain | SafeState | SessionLoadPost | ShellCmdPost | ShellFilterPost | SigUSR1 | SourceCmd | SourcePost | SourcePre | SpellFileMissing | StdinReadPost | StdinReadPre | SwapExists | Syntax | TabClosed | TabEnter | TabLeave | TabNew | TermChanged | TermResponse | TerminalOpen | TerminalWinOpen | TextChangedI | TextChangedP | TextChanged | TextYankPost | User | VimEnter | VimLeavePre | VimLeave | VimResized | VimResume | VimSuspend | WinEnter | WinLeave | WinNew ) \\b """ vimBehaveModel: name: "support.function.vimBehaveModel.viml" match: """(?x) \\b ( mswin | xterm ) \\b """ vimCommand: name: "support.function.command.viml" match: """(?x) \\b ( abc | abclear | abo | aboveleft | ab | addd | all? | ar | args | arga | argadd | argd | argdelete | argdo | arge | argedit | argg | argglobal | argl | arglocal | argu | argument | as | ascii | au | a | bN | bNext | b | buffer | ba | ball | badd? | balt | bd | bdelete | bel | belowright | bf | bfirst | bl | blast | bm | bmodified | bn | bnext | bo | botright | bp | bprevious | br | brewind | break? | breaka | breakadd | breakd | breakdel | breakl | breaklist | bro | browse | bufdo | buffers | bun | bunload | bw | bwipeout | cN | cNext | cNf | cNfile | c | change | cabc | cabclear | cabo | cabove | cad | caddbuffer | cadde | caddexpr | caddf | caddfile | caf | cafter | call? | cat | catch | ca | cb | cbuffer | cbe | cbefore | cbel | cbelow | cbo | cbottom | ccl | cclose | cc | cdo | cd | ce | center | cex | cexpr | cf | cfile | cfdo | cfir | cfirst | cg | cgetfile | cgetb | cgetbuffer | cgete | cgetexpr | changes | chd | chdir | che | checkpath | checkt | checktime | chi | chistory | cl | clist | cla | clast | class | cle | clearjumps | clo | close | cmapc | cmapclear | cn | cnext | cnew | cnewer | cnf | cnfile | cnor | co | copy | col | colder | colo | colorscheme | comc | comclear | comp | compiler | com | con | continue | conf | confirm | const? | copen? | cp | cprevious | cpf | cpfile | cq | cquit | cr | crewind | cscope | cstag | cs | cuna | cunabbrev | cun | cw | cwindow | d | delete | debugg | debuggreedy | debug | defc | defcompile | def | delc | delcommand | delel | delep | deletel | deletep | deletl | deletp | delf | delfunction | dell | delm | delmarks | delp | dep | di | display | dif | diffupdate | diffg | diffget | diffo | diffoff | diffp | diffpatch | diffput? | diffs | diffsplit | difft | diffthis | dig | digraphs | dir | disa | disassemble | dj | djump | dli | dlist | dl | doaut | doau | do | dp | dr | drop | ds | dsearch | dsp | dsplit | e | edit | earlier | ea | echoc | echoconsole | echoe | echoerr | echom | echomsg | echon | ec | el | else | elseif? | em | emenu | en | endif | enddef | endf | endfunction | endfor? | endt | endtry | endw | endwhile | enew? | eval | exit? | export | exp | exu | exusage | ex | f | file | files | filetype | filet | filt | filter | find? | fina | finally | fini | finish | fir | first | fix | fixdel | fo | fold | foldc | foldclose | foldd | folddoopen | folddoc | folddoclosed | foldo | foldopen | for | fu | function | go | goto | gr | grep | grepa | grepadd | gui | gvim | g | h | help | ha | hardcopy | helpc | helpclose | helpf | helpfind | helpg | helpgrep | helpt | helptags | hide? | his | history | hi | iabc | iabclear | ia | if | ij | ijump | il | ilist | imapc | imapclear | import | imp | inor | interface | intro | in | is | isearch | isp | isplit | iuna | iunabbrev | i | j | join | ju | jumps | kee | keepmarks | keepalt | keepa | keepj | keepjumps | keepp | keeppatterns | k | lN | lNext | lNf | lNfile | l | list | la | last | lab | labove | lad | laddexpr | laddb | laddbuffer | laddf | laddfile | laf | lafter | lan | language | later | lat | lb | lbuffer | lbe | lbefore | lbel | lbelow | lbo | lbottom | lcd? | lch | lchdir | lcl | lclose | lcscope | lcs | ldo? | le | left | lefta | leftabove | leg | legacy | lex | lexpr | lf | lfile | lfdo | lfir | lfirst | lg | lgetfile | lgetb | lgetbuffer | lgete | lgetexpr | lgr | lgrep | lgrepa | lgrepadd | lh | lhelpgrep | lhi | lhistory | lla | llast | lli | llist | ll | lmake? | lmapc | lmapclear | lma | lne | lnext | lnew | lnewer | lnf | lnfile | lo | loadview | loadkeymap | loadk | loc | lockmarks | lockv | lockvar | lol | lolder | lop | lopen | lp | lprevious | lpf | lpfile | lr | lrewind | ls | lt | ltag | luado | luafile | lua | lv | lvimgrep | lvimgrepa | lvimgrepadd | lw | lwindow | m | move | ma | mark | make? | marks | mat | match | menut | menutranslate | mes | messages | mk | mkexrc | mks | mksession | mksp | mkspell | mkv | mkvimrc | mkview? | mode? | mz | mzscheme | mzf | mzfile | n | next | nb | nbkey | nbc | nbclose | nbs | nbstart | new | nmapc | nmapclear | noautocmd | noa | noh | nohlsearch | nore | nor | nos | noswapfile | nu | number | o | open | ol | oldfiles | omapc | omapclear | on | only | opt | options | ownsyntax | p | print | pa | packadd | packl | packloadall | pc | pclose | pe | perl | ped | pedit | perldo? | pop? | popup? | pp | ppop | pre | preserve | prev | previous | prof | profile | profd | profdel | promptf | promptfind | promptr | promptrepl | pro | ps | psearch | ptN | ptNext | ptag? | ptf | ptfirst | ptj | ptjump | ptl | ptlast | ptn | ptnext | ptp | ptprevious | ptr | ptrewind | pts | ptselect | put? | pwd? | py3do | py3f | py3file | py3 | py | python | pydo | pyf | pyfile | python3 | pythonx | pyxdo | pyxfile | pyx | q | quit | qa | qall | quita | quitall | r | read | rec | recover | redo? | redir? | redr | redraw | redraws | redrawstatus | redrawt | redrawtabline | reg | registers | res | resize | ret | retab | retu | return | rew | rewind | ri | right | rightb | rightbelow | ru | runtime | ruby? | rubydo? | rubyf | rubyfile | rundo | rv | rviminfo | sIc | sIe | sIg | sIl | sIn | sIp | sIr | sI | sN | sNext | sa | sargument | sall? | san | sandbox | sav | saveas | sbN | sbNext | sb | sbuffer | sba | sball | sbf | sbfirst | sbl | sblast | sbm | sbmodified | sbn | sbnext | sbp | sbprevious | sbr | sbrewind | scI | sce | scg | sci | scl | scp | scr | scriptnames | scripte | scriptencoding | scriptv | scriptversion | scscope | scs | sc | set? | setf | setfiletype | setg | setglobal | setl | setlocal | sf | sfind | sfir | sfirst | sgI | sgc | sge | sgi | sgl | sgn | sgp | sgr | sg | sh | shell | sic | sie | sign | sig | sil | silent | sim | simalt | sin | sip | sir | si | sl | sleep | sla | slast | sm | smagic | sm | smap | smenu | sme | smile | sn | snext | sno | snomagic | snoremenu | snoreme | so | source | sort? | sp | split | spe | spellgood | spelld | spelldump | spelli | spellinfo | spellr | spellrare | spellr | spellrepall | spellr | spellrrare | spellu | spellundo | spellw | spellwrong | spr | sprevious | srI | src | sre | srewind | srg | sri | srl | srn | srp | sr | st | stop | stag? | star | startinsert | startg | startgreplace | startr | startreplace | stj | stjump | stopi | stopinsert | sts | stselect | substitutepattern | substituterepeat | sun | sunhide | sunmenu | sunme | sus | suspend | sv | sview | sw | swapname | syncbind | sync | syntime | syn | sy | tN | tNext | tag? | tabN | tabNext | tabc | tabclose | tabdo? | tabe | tabedit | tabf | tabfind | tabfir | tabfirst | tabl | tablast | tabm | tabmove | tabn | tabnext | tabnew | tabo | tabonly | tabp | tabprevious | tabr | tabrewind | tabs | tab | tags | tcl? | tcd | tch | tchdir | tcldo? | tclf | tclfile | te | tearoff | ter | terminal | tf | tfirst | th | throw | tj | tjump | tl | tlast | tlmenu | tlm | tlnoremenu | tln | tlunmenu | tlu | tm | tmenu | tmap? | tmapc | tmapclear | tn | tnext | tno | tnoremap | to | topleft | tp | tprevious | tr | trewind | try | ts | tselect | tu | tunmenu | tunmap? | type | t | u | undo | una | unabbreviate | undoj | undojoin | undol | undolist | unh | unhide | unlo | unlockvar | unl | uns | unsilent | up | update | var | ve | version | verb | verbose | vert | vertical | vi | visual | view? | vim9 | vim9cmd | vim9s | vim9script | vim | vimgrep | vimgrepa | vimgrepadd | viu | viusage | vmapc | vmapclear | vnew? | vs | vsplit | v | wN | wNext | w | write | wa | wall | wh | while | win | winsize | winc | wincmd | windo | winp | winpos | wn | wnext | wp | wprevious | wqa | wqall | wq | wundo | wv | wviminfo | x | xit | xa | xall | xmapc | xmapclear | xmenu | xme | xnoremenu | xnoreme | xprop | xr | xrestore | xunmenu | xunme | xwininfo | y | yank ) \\b """ vimErrSetting: name: "invalid.deprecated.legacy-setting.viml" match: """(?x) \\b ( autoprint | beautify | bioskey | biosk | conskey | consk | flash | graphic | hardtabs | ht | mesg | noautoprint | nobeautify | nobioskey | nobiosk | noconskey | noconsk | noflash | nographic | nohardtabs | nomesg | nonovice | noopen | nooptimize | noop | noredraw | noslowopen | noslow | nosourceany | novice | now1200 | now300 | now9600 | open | optimize | op | redraw | slowopen | slow | sourceany | w1200 | w300 | w9600 ) \\b """ vimFTCmd: name: "support.function.vimFTCmd.viml" match: """(?x) \\b ( filet | filetype ) \\b """ vimFTOption: name: "support.function.vimFTOption.viml" match: """(?x) \\b ( detect | indent | off | on | plugin ) \\b """ vimFgBgAttrib: name: "support.constant.attribute.viml" match: """(?x) \\b ( background | bg | fg | foreground | none ) \\b """ vimFuncKey: name: "support.function.vimFuncKey.viml" match: """(?x) \\b ( def | fu | function ) \\b """ vimFuncName: name: "support.function.viml" match: """(?x) \\b ( abs | acos | add | and | appendbufline | append | argc | argidx | arglistid | argv | asin | assert_beeps | assert_equalfile | assert_equal | assert_exception | assert_fails | assert_false | assert_inrange | assert_match | assert_nobeep | assert_notequal | assert_notmatch | assert_report | assert_true | atan2 | atan | balloon_gettext | balloon_show | balloon_split | browsedir | browse | bufadd | bufexists | buflisted | bufloaded | bufload | bufname | bufnr | bufwinid | bufwinnr | byte2line | byteidxcomp | byteidx | call | ceil | ch_canread | ch_close_in | ch_close | ch_evalexpr | ch_evalraw | ch_getbufnr | ch_getjob | ch_info | ch_logfile | ch_log | ch_open | ch_readblob | ch_readraw | ch_read | ch_sendexpr | ch_sendraw | ch_setoptions | ch_status | changenr | char2nr | charclass | charcol | charidx | chdir | cindent | clearmatches | col | complete_add | complete_check | complete_info | complete | confirm | copy | cosh | cos | count | cscope_connection | cursor | debugbreak | deepcopy | deletebufline | delete | did_filetype | diff_filler | diff_hlID | echoraw | empty | environ | escape | eval | eventhandler | executable | execute | exepath | exists | expandcmd | expand | exp | extendnew | extend | feedkeys | filereadable | filewritable | filter | finddir | findfile | flattennew | flatten | float2nr | floor | fmod | fnameescape | fnamemodify | foldclosedend | foldclosed | foldlevel | foldtextresult | foldtext | foreground | fullcommand | funcref | function | garbagecollect | getbufinfo | getbufline | getbufvar | getchangelist | getcharmod | getcharpos | getcharsearch | getchar | getcmdline | getcmdpos | getcmdtype | getcmdwintype | getcompletion | getcurpos | getcursorcharpos | getcwd | getenv | getfontname | getfperm | getfsize | getftime | getftype | getimstatus | getjumplist | getline | getloclist | getmarklist | getmatches | getmousepos | getpid | getpos | getqflist | getreginfo | getregtype | getreg | gettabinfo | gettabvar | gettabwinvar | gettagstack | gettext | getwininfo | getwinposx | getwinposy | getwinpos | getwinvar | get | glob2regpat | globpath | glob | has_key | haslocaldir | hasmapto | has | histadd | histdel | histget | histnr | hlID | hlexists | hostname | iconv | indent | index | inputdialog | inputlist | inputrestore | inputsave | inputsecret | input | insert | interrupt | invert | isdirectory | isinf | islocked | isnan | items | job_getchannel | job_info | job_setoptions | job_start | job_status | job_stop | join | js_decode | js_encode | json_decode | json_encode | keys | len | libcallnr | libcall | line2byte | line | lispindent | list2str | listener_add | listener_flush | listener_remove | localtime | log10 | log | luaeval | maparg | mapcheck | mapnew | mapset | map | matchaddpos | matchadd | matcharg | matchdelete | matchend | matchfuzzypos | matchfuzzy | matchlist | matchstrpos | matchstr | match | max | menu_info | min | mkdir | mode | mzeval | nextnonblank | nr2char | or | pathshorten | perleval | popup_atcursor | popup_beval | popup_clear | popup_close | popup_create | popup_dialog | popup_filter_menu | popup_filter_yesno | popup_findinfo | popup_findpreview | popup_getoptions | popup_getpos | popup_hide | popup_list | popup_locate | popup_menu | popup_move | popup_notification | popup_setoptions | popup_settext | popup_show | pow | prevnonblank | printf | prompt_getprompt | prompt_setcallback | prompt_setinterrupt | prompt_setprompt | prop_add | prop_clear | prop_find | prop_list | prop_remove | prop_type_add | prop_type_change | prop_type_delete | prop_type_get | prop_type_list | pum_getpos | pumvisible | py3eval | pyeval | pyxeval | rand | range | readblob | readdirex | readdir | readfile | reduce | reg_executing | reg_recording | reltimefloat | reltimestr | reltime | remote_expr | remote_foreground | remote_peek | remote_read | remote_send | remote_startserver | remove | rename | repeat | resolve | reverse | round | rubyeval | screenattr | screenchars | screenchar | screencol | screenpos | screenrow | screenstring | searchcount | searchdecl | searchpairpos | searchpair | searchpos | search | server2client | serverlist | setbufline | setbufvar | setcellwidths | setcharpos | setcharsearch | setcmdpos | setcursorcharpos | setenv | setfperm | setline | setloclist | setmatches | setpos | setqflist | setreg | settabvar | settabwinvar | settagstack | setwinvar | sha256 | shellescape | shiftwidth | sign_define | sign_getdefined | sign_getplaced | sign_jump | sign_placelist | sign_place | sign_undefine | sign_unplacelist | sign_unplace | simplify | sinh | sin | slice | sort | sound_clear | sound_playevent | sound_playfile | sound_stop | soundfold | spellbadword | spellsuggest | split | sqrt | srand | state | str2float | str2list | str2nr | strcharlen | strcharpart | strchars | strdisplaywidth | strftime | strgetchar | stridx | string | strlen | strpart | strptime | strridx | strtrans | strwidth | submatch | substitute | swapinfo | swapname | synIDattr | synIDtrans | synID | synconcealed | synstack | systemlist | system | tabpagebuflist | tabpagenr | tabpagewinnr | tagfiles | taglist | tanh | tan | tempname | term_dumpdiff | term_dumpload | term_dumpwrite | term_getaltscreen | term_getansicolors | term_getattr | term_getcursor | term_getjob | term_getline | term_getscrolled | term_getsize | term_getstatus | term_gettitle | term_gettty | term_list | term_scrape | term_sendkeys | term_setansicolors | term_setapi | term_setkill | term_setrestore | term_setsize | term_start | term_wait | terminalprops | test_alloc_fail | test_autochdir | test_feedinput | test_garbagecollect_now | test_garbagecollect_soon | test_getvalue | test_ignore_error | test_null_blob | test_null_channel | test_null_dict | test_null_function | test_null_job | test_null_list | test_null_partial | test_null_string | test_option_not_set | test_override | test_refcount | test_scrollbar | test_setmouse | test_settime | test_srand_seed | test_unknown | test_void | timer_info | timer_pause | timer_start | timer_stopall | timer_stop | tolower | toupper | trim | trunc | tr | typename | type | undofile | undotree | uniq | values | virtcol | visualmode | wildmenumode | win_execute | win_findbuf | win_getid | win_gettype | win_gotoid | win_id2tabwin | win_id2win | win_screenpos | win_splitmove | winbufnr | wincol | windowsversion | winheight | winlayout | winline | winnr | winrestcmd | winrestview | winsaveview | winwidth | wordcount | writefile | xor ) \\b """ vimGroup: name: "support.type.group.viml" match: """(?xi) \\b ( Boolean | Character | Comment | Conditional | Constant | Debug | Define | Delimiter | Error | Exception | Float | Function | Identifier | Ignore | Include | Keyword | Label | Macro | Number | Operator | PreCondit | PreProc | Repeat | SpecialChar | SpecialComment | Special | Statement | StorageClass | String | Structure | Tag | Todo | Typedef | Type | Underlined ) \\b """ vimGroupSpecial: name: "support.function.vimGroupSpecial.viml" match: """(?x) \\b ( ALLBUT | ALL | CONTAINED | TOP ) \\b """ vimHLGroup: name: "support.type.highlight-group.viml" match: """(?xi) \\b ( ColorColumn | CursorColumn | CursorIM | CursorLineNr | CursorLine | Cursor | DiffAdd | DiffChange | DiffDelete | DiffText | Directory | EndOfBuffer | ErrorMsg | FoldColumn | Folded | IncSearch | LineNrAbove | LineNrBelow | LineNr | MatchParen | Menu | ModeMsg | MoreMsg | NonText | Normal | PmenuSbar | PmenuSel | PmenuThumb | Pmenu | Question | QuickFixLine | Scrollbar | Search | SignColumn | SpecialKey | SpellBad | SpellCap | SpellLocal | SpellRare | StatusLineNC | StatusLineTerm | StatusLine | TabLineFill | TabLineSel | TabLine | Terminal | Title | Tooltip | VertSplit | VisualNOS | Visual | WarningMsg | WildMenu ) \\b """ vimHiAttrib: name: "support.function.vimHiAttrib.viml" match: """(?x) \\b ( bold | inverse | italic | nocombine | none | reverse | standout | strikethrough | undercurl | underline ) \\b """ vimHiClear: name: "support.function.vimHiClear.viml" match: """(?x) \\b ( clear ) \\b """ vimHiCtermColor: name: "support.constant.colour.color.$1.viml" match: """(?x) \\b ( black | blue | brown | cyan | darkblue | darkcyan | darkgray | darkgreen | darkgrey | darkmagenta | darkred | darkyellow | gray | green | grey40 | grey50 | grey90 | grey | lightblue | lightcyan | lightgray | lightgreen | lightgrey | lightmagenta | lightred | lightyellow | magenta | red | seagreen | white | yellow ) \\b """ vimMapModKey: name: "support.function.vimMapModKey.viml" match: """(?x) \\b ( buffer | expr | leader | localleader | nowait | plug | script | sid | silent | unique ) \\b """ vimOption: name: "support.variable.option.viml" match: """(?x) \\b ( acd | ai | akm | aleph | allowrevins | altkeymap | al | ambiwidth | ambw | antialias | anti | arabicshape | arabic | arab | ari | arshape | ar | asd | autochdir | autoindent | autoread | autoshelldir | autowriteall | autowrite | awa | aw | background | backspace | backupcopy | backupdir | backupext | backupskip | backup | balloondelay | balloonevalterm | ballooneval | balloonexpr | bdir | bdlay | belloff | bevalterm | beval | bexpr | bex | bg | bh | binary | bin | bkc | bk | bl | bomb | bo | breakat | breakindentopt | breakindent | briopt | bri | brk | browsedir | bsdir | bsk | bs | bt | bufhidden | buflisted | buftype | casemap | cb | ccv | cc | cdpath | cd | cedit | cfu | cf | charconvert | ch | cindent | cinkeys | cink | cinoptions | cino | cinwords | cinw | cin | ci | clipboard | cmdheight | cmdwinheight | cmp | cms | cm | cocu | cole | colorcolumn | columns | commentstring | comments | compatible | completefunc | completeopt | completepopup | completeslash | complete | com | confirm | copyindent | cot | co | cpoptions | cpo | cpp | cpt | cp | crb | cryptmethod | cscopepathcomp | cscopeprg | cscopequickfix | cscoperelative | cscopetagorder | cscopetag | cscopeverbose | csl | cspc | csprg | csqf | csre | csto | cst | csverb | cuc | culopt | cul | cursorbind | cursorcolumn | cursorlineopt | cursorline | cursor | cwh | debug | deco | define | def | delcombine | dex | dg | dictionary | dict | diffexpr | diffopt | diff | digraph | dip | directory | dir | display | dy | eadirection | ead | ea | eb | edcompatible | ed | efm | ef | ei | ek | emoji | emo | encoding | enc | endofline | eol | ep | equalalways | equalprg | errorbells | errorfile | errorformat | esckeys | et | eventignore | expandtab | exrc | ex | fcl | fcs | fdc | fde | fdi | fdls | fdl | fdm | fdn | fdo | fdt | fencs | fenc | fen | fex | ffs | ff | fic | fileencodings | fileencoding | fileformats | fileformat | fileignorecase | filetype | fillchars | fixendofline | fixeol | fkmap | fk | flp | fml | fmr | foldclose | foldcolumn | foldenable | foldexpr | foldignore | foldlevelstart | foldlevel | foldmarker | foldmethod | foldminlines | foldnestmax | foldopen | foldtext | formatexpr | formatlistpat | formatoptions | formatprg | fo | fp | fsync | fs | ft | gcr | gdefault | gd | gfm | gfn | gfs | gfw | ghr | go | gp | grepformat | grepprg | gtl | gtt | guicursor | guifontset | guifontwide | guifont | guiheadroom | guioptions | guipty | guitablabel | guitabtooltip | helpfile | helpheight | helplang | hf | hh | hidden | hid | highlight | history | hi | hkmapp | hkmap | hkp | hk | hlg | hlsearch | hls | hl | iconstring | icon | ic | ignorecase | imactivatefunc | imactivatekey | imaf | imak | imcmdline | imc | imdisable | imd | iminsert | imi | imsearch | imsf | imstatusfunc | imstyle | imst | ims | im | includeexpr | include | incsearch | inc | indentexpr | indentkeys | inde | indk | inex | infercase | inf | insertmode | invacd | invai | invakm | invallowrevins | invaltkeymap | invantialias | invanti | invarabicshape | invarabic | invarab | invari | invarshape | invar | invasd | invautochdir | invautoindent | invautoread | invautoshelldir | invautowriteall | invautowrite | invawa | invaw | invbackup | invballoonevalterm | invballooneval | invbevalterm | invbeval | invbinary | invbin | invbk | invbl | invbomb | invbreakindent | invbri | invbuflisted | invcf | invcindent | invcin | invci | invcompatible | invconfirm | invcopyindent | invcp | invcrb | invcscoperelative | invcscopetag | invcscopeverbose | invcsre | invcst | invcsverb | invcuc | invcul | invcursorbind | invcursorcolumn | invcursorline | invdeco | invdelcombine | invdg | invdiff | invdigraph | invea | inveb | invedcompatible | inved | invek | invemoji | invemo | invendofline | inveol | invequalalways | inverrorbells | invesckeys | invet | invexpandtab | invexrc | invex | invfen | invfic | invfileignorecase | invfixendofline | invfixeol | invfkmap | invfk | invfoldenable | invfsync | invfs | invgdefault | invgd | invguipty | invhidden | invhid | invhkmapp | invhkmap | invhkp | invhk | invhlsearch | invhls | invicon | invic | invignorecase | invimcmdline | invimc | invimdisable | invimd | invim | invincsearch | invinfercase | invinf | invinsertmode | invis | invjoinspaces | invjs | invlangnoremap | invlangremap | invlazyredraw | invlbr | invlinebreak | invlisp | invlist | invlnr | invloadplugins | invlpl | invlrm | invlz | invmacatsui | invmagic | invma | invmh | invmle | invml | invmodelineexpr | invmodeline | invmodifiable | invmodified | invmod | invmore | invmousefocus | invmousef | invmousehide | invnumber | invnu | invodev | invopendevice | invpaste | invpi | invpreserveindent | invpreviewwindow | invprompt | invpvw | invreadonly | invrelativenumber | invremap | invrestorescreen | invrevins | invrightleft | invri | invrl | invrnu | invro | invrs | invruler | invru | invsb | invscb | invscf | invscrollbind | invscrollfocus | invscs | invsc | invsecure | invsft | invshellslash | invshelltemp | invshiftround | invshortname | invshowcmd | invshowfulltag | invshowmatch | invshowmode | invsi | invsmartcase | invsmartindent | invsmarttab | invsmd | invsm | invsn | invsol | invspell | invsplitbelow | invsplitright | invspr | invsr | invssl | invstartofline | invsta | invstmp | invswapfile | invswf | invtagbsearch | invtagrelative | invtagstack | invta | invtbidi | invtbi | invtbs | invtermbidi | invterse | invtextauto | invtextmode | invtf | invtgst | invtildeop | invtimeout | invtitle | invtop | invto | invtr | invttimeout | invttybuiltin | invttyfast | invtx | invudf | invundofile | invvb | invvisualbell | invwarn | invwa | invwb | invweirdinvert | invwfh | invwfw | invwic | invwildignorecase | invwildmenu | invwinfixheight | invwinfixwidth | invwiv | invwmnu | invwrapscan | invwrap | invwriteany | invwritebackup | invwrite | invws | isfname | isf | isident | isi | iskeyword | isk | isprint | isp | is | joinspaces | js | keymap | keymodel | keywordprg | key | kmp | km | kp | langmap | langmenu | langnoremap | langremap | laststatus | lazyredraw | lbr | lcs | level | linebreak | linespace | lines | lispwords | lisp | listchars | list | lmap | lm | lnr | loadplugins | lpl | lrm | lsp | ls | luadll | lw | lz | macatsui | magic | makeef | makeencoding | makeprg | matchpairs | matchtime | mat | maxcombine | maxfuncdepth | maxmapdepth | maxmempattern | maxmemtot | maxmem | ma | mco | mef | menc | menuitems | mfd | mh | mis | mkspellmem | mle | mls | ml | mmd | mmp | mmt | mm | modelineexpr | modelines | modeline | modifiable | modified | mod | more | mousefocus | mousef | mousehide | mousemodel | mousem | mouseshape | mouses | mousetime | mouset | mouse | mps | mp | msm | mzquantum | mzq | mzschemedll | mzschemegcdll | nf | noacd | noai | noakm | noallowrevins | noaltkeymap | noantialias | noanti | noarabicshape | noarabic | noarab | noari | noarshape | noar | noasd | noautochdir | noautoindent | noautoread | noautoshelldir | noautowriteall | noautowrite | noawa | noaw | nobackup | noballoonevalterm | noballooneval | nobevalterm | nobeval | nobinary | nobin | nobk | nobl | nobomb | nobreakindent | nobri | nobuflisted | nocf | nocindent | nocin | noci | nocompatible | noconfirm | nocopyindent | nocp | nocrb | nocscoperelative | nocscopetag | nocscopeverbose | nocsre | nocst | nocsverb | nocuc | nocul | nocursorbind | nocursorcolumn | nocursorline | nodeco | nodelcombine | nodg | nodiff | nodigraph | noea | noeb | noedcompatible | noed | noek | noemoji | noemo | noendofline | noeol | noequalalways | noerrorbells | noesckeys | noet | noexpandtab | noexrc | noex | nofen | nofic | nofileignorecase | nofixendofline | nofixeol | nofkmap | nofk | nofoldenable | nofsync | nofs | nogdefault | nogd | noguipty | nohidden | nohid | nohkmapp | nohkmap | nohkp | nohk | nohlsearch | nohls | noicon | noic | noignorecase | noimcmdline | noimc | noimdisable | noimd | noim | noincsearch | noinfercase | noinf | noinsertmode | nois | nojoinspaces | nojs | nolangnoremap | nolangremap | nolazyredraw | nolbr | nolinebreak | nolisp | nolist | nolnr | noloadplugins | nolpl | nolrm | nolz | nomacatsui | nomagic | noma | nomh | nomle | noml | nomodelineexpr | nomodeline | nomodifiable | nomodified | nomod | nomore | nomousefocus | nomousef | nomousehide | nonumber | nonu | noodev | noopendevice | nopaste | nopi | nopreserveindent | nopreviewwindow | noprompt | nopvw | noreadonly | norelativenumber | noremap | norestorescreen | norevins | norightleft | nori | norl | nornu | noro | nors | noruler | noru | nosb | noscb | noscf | noscrollbind | noscrollfocus | noscs | nosc | nosecure | nosft | noshellslash | noshelltemp | noshiftround | noshortname | noshowcmd | noshowfulltag | noshowmatch | noshowmode | nosi | nosmartcase | nosmartindent | nosmarttab | nosmd | nosm | nosn | nosol | nospell | nosplitbelow | nosplitright | nospr | nosr | nossl | nostartofline | nosta | nostmp | noswapfile | noswf | notagbsearch | notagrelative | notagstack | nota | notbidi | notbi | notbs | notermbidi | noterse | notextauto | notextmode | notf | notgst | notildeop | notimeout | notitle | notop | noto | notr | nottimeout | nottybuiltin | nottyfast | notx | noudf | noundofile | novb | novisualbell | nowarn | nowa | nowb | noweirdinvert | nowfh | nowfw | nowic | nowildignorecase | nowildmenu | nowinfixheight | nowinfixwidth | nowiv | nowmnu | nowrapscan | nowrap | nowriteany | nowritebackup | nowrite | nows | nrformats | numberwidth | number | nuw | nu | odev | oft | ofu | omnifunc | opendevice | operatorfunc | opfunc | osfiletype | packpath | paragraphs | para | pastetoggle | paste | patchexpr | patchmode | path | pa | pdev | penc | perldll | pexpr | pex | pfn | pheader | ph | pi | pmbcs | pmbfn | pm | popt | pp | preserveindent | previewheight | previewpopup | previewwindow | printdevice | printencoding | printexpr | printfont | printheader | printmbcharset | printmbfont | printoptions | prompt | pt | pumheight | pumwidth | pvh | pvp | pvw | pw | pythondll | pythonhome | pythonthreedll | pythonthreehome | pyxversion | pyx | qe | qftf | quickfixtextfunc | quoteescape | rdt | readonly | redrawtime | regexpengine | relativenumber | remap | renderoptions | report | restorescreen | revins | re | rightleftcmd | rightleft | ri | rlc | rl | rnu | rop | ro | rs | rtp | rubydll | ruf | rulerformat | ruler | runtimepath | ru | sbo | sbr | sb | scb | scf | scl | scrollbind | scrollfocus | scrolljump | scrolloff | scrollopt | scroll | scr | scs | sc | sections | sect | secure | selection | selectmode | sel | sessionoptions | sft | shcf | shellcmdflag | shellpipe | shellquote | shellredir | shellslash | shelltemp | shelltype | shellxescape | shellxquote | shell | shiftround | shiftwidth | shm | shortmess | shortname | showbreak | showcmd | showfulltag | showmatch | showmode | showtabline | shq | sh | sidescrolloff | sidescroll | signcolumn | siso | si | sj | slm | smartcase | smartindent | smarttab | smc | smd | sm | sn | softtabstop | sol | so | spc | spellcapcheck | spellfile | spelllang | spelloptions | spellsuggest | spell | spf | splitbelow | splitright | spl | spo | spr | sps | sp | srr | sr | ssl | ssop | ss | stal | startofline | statusline | sta | stl | stmp | sts | st | sua | suffixesadd | suffixes | su | swapfile | swapsync | swb | swf | switchbuf | sws | sw | sxe | sxq | synmaxcol | syntax | syn | t_8b | t_8f | t_8u | t_AB | t_AF | t_AL | t_AU | t_BD | t_BE | t_CS | t_CV | t_Ce | t_Co | t_Cs | t_DL | t_EC | t_EI | t_F1 | t_F2 | t_F3 | t_F4 | t_F5 | t_F6 | t_F7 | t_F8 | t_F9 | t_GP | t_IE | t_IS | t_K1 | t_K3 | t_K4 | t_K5 | t_K6 | t_K7 | t_K8 | t_K9 | t_KA | t_KB | t_KC | t_KD | t_KE | t_KF | t_KG | t_KH | t_KI | t_KJ | t_KK | t_KL | t_PE | t_PS | t_RB | t_RC | t_RF | t_RI | t_RS | t_RT | t_RV | t_Ri | t_SC | t_SH | t_SI | t_SR | t_ST | t_Sb | t_Sf | t_Si | t_TE | t_TI | t_Te | t_Ts | t_VS | t_WP | t_WS | t_ZH | t_ZR | t_al | t_bc | t_cd | t_ce | t_cl | t_cm | t_cs | t_da | t_db | t_dl | t_fd | t_fe | t_fs | t_k1 | t_k2 | t_k3 | t_k4 | t_k5 | t_k6 | t_k7 | t_k8 | t_k9 | t_kB | t_kD | t_kI | t_kN | t_kP | t_kb | t_kd | t_ke | t_kh | t_kl | t_kr | t_ks | t_ku | t_le | t_mb | t_md | t_me | t_mr | t_ms | t_nd | t_op | t_se | t_so | t_sr | t_te | t_ti | t_ts | t_u7 | t_ue | t_us | t_ut | t_vb | t_ve | t_vi | t_vs | t_xn | t_xs | tabline | tabpagemax | tabstop | tagbsearch | tagcase | tagfunc | taglength | tagrelative | tagstack | tags | tag | tal | ta | tbidi | tbis | tbi | tbs | tb | tcldll | tc | tenc | termbidi | termencoding | termguicolors | termwinkey | termwinscroll | termwinsize | termwintype | term | terse | textauto | textmode | textwidth | tfu | tf | tgc | tgst | thesaurus | tildeop | timeoutlen | timeout | titlelen | titleold | titlestring | title | tl | tm | toolbariconsize | toolbar | top | to | tpm | tr | tsl | tsr | ts | ttimeoutlen | ttimeout | ttm | ttybuiltin | ttyfast | ttymouse | ttym | ttyscroll | ttytype | tty | twk | twsl | tws | twt | tw | tx | uc | udf | udir | ul | undodir | undofile | undolevels | undoreload | updatecount | updatetime | ur | ut | varsofttabstop | vartabstop | vbs | vb | vdir | verbosefile | verbose | ve | vfile | viewdir | viewoptions | vif | viminfofile | viminfo | virtualedit | visualbell | vi | vop | vsts | vts | wak | warn | wa | wb | wcm | wcr | wc | wd | weirdinvert | wfh | wfw | whichwrap | wh | wic | wig | wildcharm | wildchar | wildignorecase | wildignore | wildmenu | wildmode | wildoptions | wim | winaltkeys | wincolor | window | winfixheight | winfixwidth | winheight | winminheight | winminwidth | winptydll | winwidth | wiv | wiw | wi | wmh | wmnu | wmw | wm | wop | wrapmargin | wrapscan | wrap | writeany | writebackup | writedelay | write | ws | ww ) \\b """ vimPattern: name: "support.function.vimPattern.viml" match: """(?x) \\b ( end | skip | start ) \\b """ vimStdPlugin: name: "support.class.stdplugin.viml" match: """(?x) \\b ( Arguments | Asm | Break | Cfilter | Clear | Continue | DiffOrig | Evaluate | Finish | Gdb | Lfilter | Man | N | Next | Over | P | Print | Program | Run | Source | Step | Stop | S | TOhtml | TermdebugCommand | Termdebug | Winbar | XMLent | XMLns ) \\b """ vimSynCase: name: "support.function.vimSynCase.viml" match: """(?x) \\b ( ignore | match ) \\b """ vimSynType: name: "support.function.vimSynType.viml" match: """(?x) \\b ( case | clear | cluster | enable | include | iskeyword | keyword | list | manual | match | off | on | region | reset | sync ) \\b """ vimSyncC: name: "support.function.vimSyncC.viml" match: """(?x) \\b ( ccomment | clear | fromstart ) \\b """ vimSyncLinecont: name: "support.function.vimSyncLinecont.viml" match: """(?x) \\b ( linecont ) \\b """ vimSyncMatch: name: "support.function.vimSyncMatch.viml" match: """(?x) \\b ( match ) \\b """ vimSyncNone: name: "support.function.vimSyncNone.viml" match: """(?x) \\b ( NONE ) \\b """ vimSyncRegion: name: "support.function.vimSyncRegion.viml" match: """(?x) \\b ( region ) \\b """ vimUserAttrbCmplt: name: "support.function.vimUserAttrbCmplt.viml" match: """(?x) \\b ( augroup | behave | buffer | color | command | compiler | cscope | customlist | custom | dir | environment | event | expression | file_in_path | filetype | file | function | help | highlight | history | locale | mapping | menu | option | packadd | shellcmd | sign | syntax | syntime | tag_listfiles | tag | user | var ) \\b """ vimUserAttrbKey: name: "support.function.vimUserAttrbKey.viml" match: """(?x) \\b ( bang? | bar | com | complete | cou | count | n | nargs | ra | range | re | register ) \\b """ vimUserCommand: name: "support.function.vimUserCommand.viml" match: """(?x) \\b ( com | command ) \\b """
true
name: "PI:NAME:<NAME>END_PIimL" scopeName: "source.viml" injectionSelector: "source.gfm source.embedded.viml" fileTypes: [ "vim" "vimrc" "gvimrc" "nvimrc" "_vimrc" "exrc" "nexrc" "vmb" ] firstLineMatch: """(?x) # Vimball (?:^|\\n)UseVimball\\b | # Hashbang ^\\#!.*(?:\\s|\\/|(?<=!)\\b) (?:vim|nvim) (?:$|\\s) | # Modeline (?: # Vim/Vi modeline, accounting for all possible variations (?:(?:^|[ \\t])(?:vi|Vi(?=m))(?:m[<=>]?[0-9]+|m)?|[ \\t]ex)(?=:(?=[ \\t]*set?[ \\t][^\\r\\n:]+:)|:(?![ \\t]*set?[ \\t])) (?:(?:[ \\t]*:[ \\t]*|[ \\t])\\w*(?:[ \\t]*=(?:[^\\\\\\s]|\\\\.)*)?)*[ \\t:] (?:filetype|ft|syntax)[ \\t]*= (?i:vim) (?=$|\\s|:) | # Emacs modeline, assuming a major mode for VimScript even exists -\\*-(?i:[ \\t]*(?=[^:;\\s]+[ \\t]*-\\*-)|(?:.*?[ \\t;]|(?<=-\\*-))[ \\t]*mode[ \\t]*:[ \\t]*) (?i:Vim|VimL|VimScript) (?=[ \\t;]|(?<![-*])-\\*-).*?-\\*- ) """ foldingStartMarker: "^(?:if|while|for|fu|function|augroup|aug)" foldingStopMarker: "(?:endif|endwhile|endfor|endf|endfunction|augroup\\.END|aug\\.END)$" limitLineLength: no patterns: [{ # VimBall archive name: "meta.file-archive.vimball" begin: '\\A(?=" Vimball Archiver)' end: "(?=A)B" patterns: [{ # Help file name: "meta.file-record.help-file.vimball" begin: "^(.*?\\S.*?\\.txt)(\\t)(\\[{3}1)(?=$)" end: "(?!\\G)(?=^.*?\\S.*?\\t\\[{3}1$)" beginCaptures: 0: name: "markup.heading.1.vimball" 1: name: "entity.name.file.path.vimball" 2: name: "punctuation.whitespace.tab.separator.vimball" 3: name: "punctuation.definition.header.vimball" contentName: "text.embedded.vim-help" patterns: [{ # Line count begin: "\\G" end: "^(\\d+$)?" endCaptures: 0: name: "comment.ignored.line-count.viml" 1: name: "sublimelinter.gutter-mark" }, include: "text.vim-help"] },{ # Vim script file name: "meta.file-record.vimball.viml" begin: "^(.*?\\S.*?[ \\t]*?)(\\t)(\\[{3}1)(?=$)" end: "(?!\\G)(?=^.*?\\S.*?\\t\\[{3}1$)" beginCaptures: 0: name: "markup.heading.1.vimball" 1: name: "entity.name.file.path.vimball" 2: name: "punctuation.whitespace.tab.separator.vimball" 3: name: "punctuation.definition.header.vimball" patterns: [{ # Line count begin: "\\G" end: "^(\\d+$)?" endCaptures: 0: name: "comment.ignored.line-count.viml" 1: name: "sublimelinter.gutter-mark" }, include: "#main"] }, include: "#main"] }, include: "#main"] repository: main: patterns: [ {include: "#vimTodo"} {include: "#comments"} {include: "#modelines"} {include: "#pathname"} {include: "#escape"} {include: "#strings"} {include: "#hashbang"} {include: "#numbers"} {include: "#syntax"} {include: "#highlightLink"} {include: "#funcDef"} {include: "#auCmd"} {include: "#auGroup"} {include: "#parameter"} {include: "#assignment"} {include: "#expr"} {include: "#keyword"} {include: "#register"} {include: "#filetype"} {include: "#variable"} {include: "#supportType"} {include: "#supportVariable"} {include: "#extraVimOptions"} {include: "#extraVimFunc"} {include: "#keywordLists"} ] strings: patterns: [{ name: "string.quoted.double.empty.viml" match: '(")(")' captures: 1: name: "punctuation.definition.string.begin.viml" 2: name: "punctuation.definition.string.end.viml" },{ name: "string.quoted.single.empty.viml" match: "(')(')" captures: 1: name: "punctuation.definition.string.begin.viml" 2: name: "punctuation.definition.string.end.viml" },{ name: "string.quoted.double.viml" match: '(")((?:[^\\\\"]|\\\\.)*)(")' captures: 1: name: "punctuation.definition.string.begin.viml" 2: patterns: [include: "#escape"] 3: name: "punctuation.definition.string.end.viml" },{ name: "string.quoted.single.viml" match: "(')((?:[^']|'')*)(')" captures: 1: name: "punctuation.definition.string.begin.viml" 2: patterns: [{ name: "constant.character.escape.quotes.viml" match: "''" }] 3: name: "punctuation.definition.string.end.viml" },{ name: "string.regexp.interpolated.viml" match: "(/)(?:\\\\\\\\|\\\\/|[^\\n/])*(/)" captures: 1: name: "punctuation.section.regexp.begin.viml" 2: name: "punctuation.section.regexp.end.viml" }] # Something prefixed with a backslash escape: patterns: [ {include: "#escapedCodePoint"} {include: "#escapedKey"} {match: "(\\\\)b", name: "constant.character.escape.backspace.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)e", name: "constant.character.escape.escape.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)f", name: "constant.character.escape.form-feed.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)n", name: "constant.character.escape.newline.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)r", name: "constant.character.escape.return.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)t", name: "constant.character.escape.tab.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\)\\1",name: "constant.character.escape.backslash.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: '(\\\\)"', name: "constant.character.escape.quote.viml", captures: 1: name: "punctuation.definition.escape.viml"} {match: "(\\\\).", name: "constant.character.escape.other.viml", captures: 1: name: "punctuation.definition.escape.viml"} ] # Characters specified by codepoint escapedCodePoint: patterns: [{ # Hexadecimal, short: \x20 name: "constant.character.escape.codepoint.hex.short.viml" match: "(\\\\)[xX][0-9A-Fa-f]{1,2}" captures: 1: name: "punctuation.definition.escape.backslash.viml" },{ # Codepoint, long: \u0020 \u00000020 name: "constant.character.escape.codepoint.hex.long.viml" match: "(\\\\)(?:u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8})" captures: 1: name: "punctuation.definition.escape.backslash.viml" },{ # Codepoint, octal: \040 name: "constant.character.escape.codepoint.octal.viml" match: "(\\\\)([0-7]{1,3})" captures: 1: name: "punctuation.definition.escape.backslash.viml" }] escapedKey: name: "constant.character.escape.keymapping.viml" match: '(\\\\<\\*?)(?:[^">\\\\]|\\\\.)+(>)' captures: 1: name: "punctuation.definition.escape.key.begin.viml" 2: name: "punctuation.definition.escape.key.end.viml" # This only exists to stop stuff like ~/.vim/ being highlighted like a regex pathname: name: "constant.pathname.viml" begin: "~/" end: "(?=\\s)" comments: patterns: [{ # Fully-commented line with a leading field-name name: "comment.line.quotes.viml" begin: '^\\s*(")(?=(\\s*[A-Z]\\w+)+:)' end: "((:))(.*)$" contentName: "support.constant.field.viml" beginCaptures: 1: name: "punctuation.definition.comment.viml" endCaptures: 1: name: "support.constant.field.viml" 2: name: "punctuation.separator.key-value.colon.viml" 3: patterns: [include: "#commentInnards"] },{ # Fully-commented line name: "comment.line.quotes.viml" begin: '^\\s*(")' end: '$' beginCaptures: 1: name: "punctuation.definition.comment.viml" patterns: [include: "#commentInnards"] },{ # Trailing comment, no closing quote name: "comment.inline.quotes.viml" patterns: [include: "#commentInnards"] begin: '(?<!^)\\s*(")(?=[^\\n"]*$)' end: "$" beginCaptures: 1: name: "punctuation.definition.comment.viml" }] commentInnards: patterns: [ {include: "#modelines"} {include: "#todo"} ] # Vim modelines modelines: patterns: [{ # Using "vim:set" name: "string.other.modeline.viml" patterns: [include: "#main"] begin: "(?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|[\\t\\x20]ex):\\s*(?=set?\\s)" end: ":|$" },{ name: "string.other.modeline.viml" patterns: [include: "#main"] begin: "(?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|[\\t\\x20]ex):" end: "$" }] # Embedded interpreter directive hashbang: name: "comment.line.shebang.viml" begin: "\\A#!" end: "$" beginCaptures: 0: name: "punctuation.definition.comment.shebang.viml" numbers: patterns: [{ name: "constant.numeric.hex.short.viml" match: "0[xX][0-9A-Fa-f]+" },{ name: "constant.numeric.hex.long.viml" match: "0[zZ][0-9A-Fa-f]+" },{ name: "constant.numeric.float.exponential.viml" match: "(?<!\\w)-?\\d+\\.\\d+[eE][-+]?\\d+" },{ name: "constant.numeric.float.viml" match: "(?<!\\w)-?\\d+\\.\\d+" },{ name: "constant.numeric.integer.viml" match: "(?<!\\w)-?\\d+" }] funcDef: patterns: [{ name: "storage.function.viml" match: "\\b(fu(nc?|nction)?|end(f|fu|func?|function)?)\\b" },{ name: "entity.name.function.viml" match: "(?:([sSgGbBwWtTlL]?(:))?[\\w#]+)(?=\\()" captures: 1: name: "storage.modifier.scope.viml" 2: name: "punctuation.definition.scope.key-value.viml" },{ name: "storage.modifier.$1.function.viml" match: "(?<=\\)|\\s)(abort|dict|closure|range)(?=\\s|$)" }] auCmd: name: "meta.autocmd.viml" match: "\\b(autocmd|au)(!)?\\b\\s+(?!\\*)(\\S+)\\s+(\\S+)(?:\\s+(\\+\\+(nested|once)))?" captures: 1: name: "storage.type.autocmd.viml" 2: name: "storage.modifier.force.viml" 3: name: "meta.events-list.viml", patterns: [include: "#main"] 4: name: "string.unquoted.autocmd-suffix-list.viml" 5: name: "storage.modifier.$6.viml" auGroup: patterns: [ name: "meta.augroup.viml" begin: "\\b(augroup|aug)(!)?\\b\\s*([\\w#]+)" end: "\\b(\\1)\\s+(END)\\b" patterns: [include: "#main"] beginCaptures: 1: name: "storage.type.function.viml" 2: name: "storage.modifier.force.viml" 3: name: "entity.name.function.viml" endCaptures: 1: name: "storage.type.augroup.viml" 2: name: "keyword.control.end" ] parameter: name: "meta.parameter.viml" match: "(-)(\\w+)(=)" captures: 1: name: "punctuation.definition.parameter.viml" 2: name: "entity.name.parameter.viml" 3: name: "punctuation.assignment.parameter.viml" assignment: patterns: [{ name: "keyword.operator.assignment.compound.viml" match: "[-+.]=" },{ name: "keyword.operator.assignment.viml" match: "=" }] expr: patterns: [ name: "keyword.operator.logical.viml" match: "[&|=]{2}[?#]?|[!><]=[#?]?|[=!]~(?!\\/)[#?]?|[><][#?*]|\\b(?:isnot|is)\\b|\\\\|[-+%*]" {match: "\\s[><]\\s",name: "keyword.operator.logical.viml"} {match: "(?<=\\S)!", name: "storage.modifier.force.viml"} {match: "!(?=\\S)", name: "keyword.operator.logical.not.viml"} {match: "{", name: "punctuation.expression.bracket.curly.begin.viml"} {match: "}", name: "punctuation.expression.bracket.curly.end.viml"} {match: "\\[", name: "punctuation.expression.bracket.square.begin.viml"} {match: "\\]", name: "punctuation.expression.bracket.square.end.viml"} {match: "\\(", name: "punctuation.expression.bracket.round.begin.viml"} {match: "\\)", name: "punctuation.expression.bracket.round.end.viml"} {match: "\\|", name: "punctuation.separator.statement.viml"} {match: ",", name: "punctuation.separator.comma.viml"} {match: ":", name: "punctuation.separator.colon.viml"} {match: "\\.{3}", name: "keyword.operator.rest.viml"} {match: "\\.", name: "punctuation.delimiter.property.dot.viml"} {match: "&(?=\\w+)", name: "punctuation.definition.option.viml"} ] keyword: patterns: [{ name: "keyword.control.$1.viml" match: "\\b(if|while|for|return|try|catch|finally|finish|end(if|for|while|try)?|else(if)?|do|in|:)\\b" },{ name: "keyword.operator.$1.viml" match: "\\b(unlet)\\b" },{ name: "storage.type.let.viml" match: "\\blet\\b" },{ name: "support.constant.vimball.use.viml" match: "(?<=^|\\n)UseVimball(?=\\s*$)" }] register: name: "variable.other.register.viml" match: "(@)([-\"A-Za-z\\d:.%#=*+~_/])" captures: 1: name: "punctuation.definition.register.viml" variable: patterns: [{ name: "variable.language.self.viml" match: "\\b(self)\\b" },{ name: "support.variable.environment.viml" match: "(\\$)\\w+" captures: 1: name: "punctuation.definition.variable.viml" },{ name: "variable.other.viml" match: "(&?)(?:([sSgGbBwWlLaAvV](:))|[@$]|&(?!&))\\w*" captures: 1: name: "punctuation.definition.reference.viml" 2: name: "storage.modifier.scope.viml" 3: name: "punctuation.definition.scope.key-value.viml" }] supportType: name: "entity.tag.name.viml" match: "(<).*?(>)" captures: 1: name: "punctuation.definition.bracket.angle.begin.viml" 2: name: "punctuation.definition.bracket.angle.end.viml" supportVariable: name: "support.variable.viml" match: "\\b(?:am(?:enu)?|(?:hl|inc)?search|[Bb]uf(?:[Nn]ew[Ff]ile|[Rr]ead)?|[Ff]ile[Tt]ype)\\b" # Highlighting link, used heavily in syntax-definition files highlightLink: match: "(?x)^\\s* (:)? \\s* (?# 1: punctuation.separator.key-value.colon.viml) (hi|highlight) (?# 2: support.function.highlight.viml) (!)? (?# 3: storage.modifier.force.viml) (?:\\s+(def|default))? (?# 4: support.function.highlight-default.viml) (?:\\s+(link)) (?# 5: support.function.highlight-link.viml) (?:\\s+([-\\w]+)) (?# 6: variable.parameter.group-name.viml) (?:\\s+(?:(NONE)|([-\\w]+)))?" captures: 1: name: "punctuation.separator.key-value.colon.viml" 2: name: "support.function.highlight.viml" 3: name: "storage.modifier.force.viml" 4: name: "support.function.highlight-default.viml" 5: name: "support.function.highlight-link.viml" 6: name: "variable.parameter.group-name.viml" 7: name: "support.constant.highlighting.viml" 8: name: "variable.parameter.group-name.viml" # Filetype assignment filetype: match: "\\b(?:(setf|setfiletype)(?:\\s+(FALLBACK))?\\s+|(ft|filetype)\\s*(=))([.\\w]+)" captures: 1: name: "support.function.command.viml" 2: name: "support.variable.option.viml" 3: name: "storage.modifier.fallback.viml" 4: name: "keyword.operator.assignment.viml" 5: name: "variable.parameter.function.filetype.viml" # Syntax highlighting definitions syntax: name: "meta.syntax-item.viml" begin: "^\\s*(:)?(?:(VimFold\\w)\\s+)?\\s*(syntax|syn?)(?=\\s|$)" end: "$" beginCaptures: 1: name: "punctuation.separator.key-value.colon.viml" 2: name: "support.function.fold-command.viml" 3: name: "storage.type.syntax-item.viml" patterns: [{ # Case-matching match: "\\G\\s+(case)(?:\\s+(match|ignore))?(?=\\s|$)" captures: 1: name: "support.function.syntax-case.viml" 2: name: "support.constant.$2-case.viml" },{ # Spell-checking match: "\\G\\s+(spell)(?:\\s+(toplevel|notoplevel|default))?(?=\\s|$)" captures: 1: name: "support.function.syntax-spellcheck.viml" 2: name: "support.constant.$2-checking.viml" },{ # Keyword lists begin: "\\G\\s+(keyword)(?:\\s+([-\\w]+))?" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-keywords.viml" 2: name: "variable.parameter.group-name.viml" contentName: "keyword.other.syntax-definition.viml" patterns: [ {include: "#syntaxOptions"} {include: "#assignment"} {include: "#expr"} ] },{ # Pattern-based match begin: "\\G\\s+(match)(?:\\s+([-\\w]+))?\\s*" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-match.viml" 2: name: "variable.parameter.group-name.viml" patterns: [include: "#syntaxRegex"] },{ # Multiline pattern-based match begin: "\\G\\s+(region)(?:\\s+([-\\w]+))?" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-region.viml" 2: name: "variable.parameter.group-name.viml" patterns: [ {include: "#syntaxOptions"} {include: "#main"} ] },{ # Group cluster begin: "\\G\\s+(cluster)(?:\\s+([-\\w]+))?(?=\\s|$)" end: "(?=$)" beginCaptures: 1: name: "support.function.syntax-cluster.viml" 2: name: "variable.parameter.group-name.viml" patterns: [ {include: "#syntaxOptions"} {include: "#main"} ] },{ # Concealment match: "\\G\\s+(conceal)(?:\\s+(on|off)(?=\\s|$))?" captures: 1: name: "support.function.syntax-conceal.viml" 2: name: "support.constant.boolean.$2.viml" },{ # Inclusion match: "\\G\\s+(include)(?:\\s+((@)?[-\\w]+))?(?:\\s+(\\S+))?" captures: 1: name: "support.function.syntax-include.viml" 2: name: "variable.parameter.group-name.viml" 3: name: "punctuation.definition.group-reference.viml" 4: name: "string.unquoted.filename.viml", patterns: [include: "#supportType"] },{ # Sync/Redrawing mode begin: "\\G\\s+(sync)(?=\\s|$)" end: "$" beginCaptures: 1: name: "support.function.syntax-sync.viml" patterns: [{ match: "\\G\\s+(fromstart)(?=\\s|$)" captures: 1: name: "support.constant.sync-$1.viml" },{ match: "\\G\\s+(ccomment|clear)(?:\\s+(?![-\\w]+\\s*=)([-\\w]+))?" captures: 1: name: "support.constant.sync-$1.viml" 2: name: "variable.parameter.group-name.viml" },{ match: "\\G\\s+(minlines|lines)\\s*(=)(\\d*)" captures: 1: name: "support.constant.sync-mode.viml" 2: name: "punctuation.assignment.parameter.viml" 3: name: "constant.numeric.integer.viml" },{ match: "(?x)\\G\\s+(match|region)(?:\\s+(?![-\\w]+\\s*=)([-\\w]+))?" captures: 1: name: "support.constant.sync-mode.viml" 2: name: "variable.parameter.group-name.viml" 3: name: "support.constant.sync-mode-location.viml" },{ begin: "(?<=\\s)(groupt?here|linecont)(?:\\s+(?![-\\w]+\\s*=)([-\\w]+))?(?=\\s|$)" end: "(?=$)" beginCaptures: 1: name: "support.constant.sync-match.viml" 2: name: "variable.parameter.group-name.viml" patterns: [include: "#syntaxRegex"] }, include: "#syntaxOptions"] }, include: "#main"] # Syntax item arguments, as described in :syn-arguments syntaxOptions: patterns: [{ # Options that take a regex name: "meta.syntax-item.pattern-argument.viml" begin: "(?<=\\s)(start|skip|end)(?:\\s*(=))" end: "(?=$|\\s)" beginCaptures: 1: name: "support.constant.$1-pattern.viml" 2: name: "punctuation.assignment.parameter.viml" patterns: [include: "#regex"] },{ # Everything else name: "meta.syntax-item.argument.viml" match: """(?x)(?<=\\s) ((?:matchgroup|contains|containedin|nextgroup|add|remove|minlines|linebreaks|maxlines)(?=\\s*=) |(?:cchar|conceal|concealends|contained|display|excludenl|extend|fold|keepend|oneline|skipempty|skipnl|skipwhite|transparent)) (?:(?=$|\\s)|\\s*(=)(\\S*)?)""" captures: 1: name: "support.constant.syntax-$1.viml" 2: name: "punctuation.assignment.parameter.viml" 3: name: "string.unquoted.syntax-option.viml", patterns: [ {include: "#numbers"} {match: ",", name: "punctuation.separator.comma.viml"} {match: "@", name: "punctuation.definition.group-reference.viml"} ] }] # Body of any syntax-item option which uses an unlabelled regex syntaxRegex: patterns: [ {include: "#syntaxOptions"} # Ensure only one regex is matched name: "string.regexp.viml" begin: "(?<=\\s)(\\S)" end: "(?:(\\1)(\\S*)(.*))?$" patterns: [include: "#regexInnards"] beginCaptures: 1: name: "punctuation.definition.string.begin.viml" endCaptures: 1: name: "punctuation.definition.string.end.viml" 2: patterns: [include: "#regexOffset"] 3: patterns: [include: "#syntaxOptions", {include: "#main"}] ] # Regular expression regex: name: "string.regexp.viml" begin: "(?<=\\s|=)(\\S)" end: "$|(\\1)(\\S*)" patterns: [include: "#regexInnards"] beginCaptures: 1: name: "punctuation.definition.string.begin.viml" endCaptures: 1: name: "punctuation.definition.string.end.viml" 2: patterns: [include: "#regexOffset"] # Pattern offset regexOffset: name: "meta.pattern-offset.viml" match: "(ms|me|hs|he|rs|re|lc)(=)(?:(\\d+)|([se])(?:([-+])(\\d+))?)(,)?" captures: 1: name: "constant.language.pattern-offset.viml" 2: name: "punctuation.assignment.parameter.viml" 3: name: "constant.numeric.integer.viml" 4: name: "constant.language.pattern-position.viml" 5: name: "keyword.operator.arithmetic.viml" 6: name: "constant.numeric.integer.viml" 7: name: "punctuation.separator.comma.viml" regexInnards: patterns: [{ # Character class begin: "\\[" end: "\\]|$" beginCaptures: 0: name: "punctuation.definition.character-class.begin.viml" endCaptures: 0: name: "punctuation.definition.character-class.end.viml" patterns: [include: "#regexInnards"] },{ # Escaped character name: "constant.character.escape.viml" match: "(\\\\)." captures: 1: name: "punctuation.definition.backslash.escape.viml" }] # Extra functions not picked up by keyword parser extraVimFunc: name: "support.function.viml" match: """(?x)\\b ((?:echo(?:hl?)?)|exe(?:c(?:ute)?)?|[lxvn]?noremap|smapc(?:lear)?|mapmode|xmap|(?:[xs]un|snore)map |Plugin|autocmd|[cinvo]?(?:un|nore)?(?:map|menu)|(?:range)?go(?:to)?|(?:count)?(?:pop?|tag?|tn(?:ext)?|tp(?:revious)?|tr(?:ewind)?) |(?:range)?(?:s(?:ubstitute)?|ret(?:ab)?|g(?:lobal)?)|unm(?:ap)?|map_l|mapc(?:lear)?|N?buffer|N?bnext|N?bNext|N?bprevious|N?bmod |ab(?:breviate)?|norea(?:bbrev)?|[ic](?:un|nore)?ab|split_f|rangefold|[ic](?:un|nore)?ab|[ic]abbrev|edit_f|next_f|[vcoxli]u |(?:range)?(?:w(?:rite)?|up(?:date)?)|sar|cno|[vl]n|[io]?no|[xn]n|snor|lm(?:ap)?|lunmap|lear|[vnx]m|om|[ci]m|ap|nun|sunm) \\b""" # Extra options not picked up by keyword parser extraVimOptions: name: "support.variable.option.viml" match: """(?x)\\b (no)? (altwerase|bf|escapetime|extended|filec|iclower|keytime|leftright|li|lock|noprint|octal|recdir|searchincr |shellmeta|ttywerase|windowname|wl|wraplen) \\b""" # The following lists are auto-extracted from Vim's syntax file. # Run `bin/update` to repopulate them. keywordLists: patterns: [ {include: "#vimTodo"} {include: "#vimAugroupKey"} {include: "#vimAutoEvent"} {include: "#vimBehaveModel"} {include: "#vimCommand"} {include: "#vimFTCmd"} {include: "#vimFTOption"} {include: "#vimFgBgAttrib"} {include: "#vimFuncKey"} {include: "#vimFuncName"} {include: "#vimGroup"} {include: "#vimGroupSpecial"} {include: "#vimHLGroup"} {include: "#vimHiAttrib"} {include: "#vimHiClear"} {include: "#vimHiCtermColor"} {include: "#vimMapModKey"} {include: "#vimOption"} {include: "#vimPattern"} {include: "#vimStdPlugin"} {include: "#vimSynCase"} {include: "#vimSynType"} {include: "#vimSyncC"} {include: "#vimSyncLinecont"} {include: "#vimSyncMatch"} {include: "#vimSyncNone"} {include: "#vimSyncRegion"} {include: "#vimUserAttrbCmplt"} {include: "#vimUserAttrbKey"} {include: "#vimUserCommand"} {include: "#vimErrSetting"} ] vimTodo: name: "support.constant.${1:/downcase}.viml" match: """(?x) \\b ( COMBAK | FIXME | TODO | XXX ) \\b """ vimAugroupKey: name: "support.function.vimAugroupKey.viml" match: """(?x) \\b ( aug | augroup ) \\b """ vimAutoEvent: name: "support.function.auto-event.viml" match: """(?xi) \\b ( BufAdd | BufCreate | BufDelete | BufEnter | BufFilePost | BufFilePre | BufHidden | BufLeave | BufNewFile | BufNew | BufReadCmd | BufReadPost | BufReadPre | BufRead | BufUnload | BufWinEnter | BufWinLeave | BufWipeout | BufWriteCmd | BufWritePost | BufWritePre | BufWrite | CmdUndefined | CmdlineChanged | CmdlineEnter | CmdlineLeave | CmdwinEnter | CmdwinLeave | ColorSchemePre | ColorScheme | CompleteChanged | CompleteDonePre | CompleteDone | CursorHoldI | CursorHold | CursorMovedI | CursorMoved | DiffUpdated | DirChanged | EncodingChanged | ExitPre | FileAppendCmd | FileAppendPost | FileAppendPre | FileChangedRO | FileChangedShellPost | FileChangedShell | FileEncoding | FileReadCmd | FileReadPost | FileReadPre | FileType | FileWriteCmd | FileWritePost | FileWritePre | FilterReadPost | FilterReadPre | FilterWritePost | FilterWritePre | FocusGained | FocusLost | FuncUndefined | GUIEnter | GUIFailed | InsertChange | InsertCharPre | InsertEnter | InsertLeavePre | InsertLeave | MenuPopup | OptionSet | QuickFixCmdPost | QuickFixCmdPre | QuitPre | RemoteReply | SafeStateAgain | SafeState | SessionLoadPost | ShellCmdPost | ShellFilterPost | SigUSR1 | SourceCmd | SourcePost | SourcePre | SpellFileMissing | StdinReadPost | StdinReadPre | SwapExists | Syntax | TabClosed | TabEnter | TabLeave | TabNew | TermChanged | TermResponse | TerminalOpen | TerminalWinOpen | TextChangedI | TextChangedP | TextChanged | TextYankPost | User | VimEnter | VimLeavePre | VimLeave | VimResized | VimResume | VimSuspend | WinEnter | WinLeave | WinNew ) \\b """ vimBehaveModel: name: "support.function.vimBehaveModel.viml" match: """(?x) \\b ( mswin | xterm ) \\b """ vimCommand: name: "support.function.command.viml" match: """(?x) \\b ( abc | abclear | abo | aboveleft | ab | addd | all? | ar | args | arga | argadd | argd | argdelete | argdo | arge | argedit | argg | argglobal | argl | arglocal | argu | argument | as | ascii | au | a | bN | bNext | b | buffer | ba | ball | badd? | balt | bd | bdelete | bel | belowright | bf | bfirst | bl | blast | bm | bmodified | bn | bnext | bo | botright | bp | bprevious | br | brewind | break? | breaka | breakadd | breakd | breakdel | breakl | breaklist | bro | browse | bufdo | buffers | bun | bunload | bw | bwipeout | cN | cNext | cNf | cNfile | c | change | cabc | cabclear | cabo | cabove | cad | caddbuffer | cadde | caddexpr | caddf | caddfile | caf | cafter | call? | cat | catch | ca | cb | cbuffer | cbe | cbefore | cbel | cbelow | cbo | cbottom | ccl | cclose | cc | cdo | cd | ce | center | cex | cexpr | cf | cfile | cfdo | cfir | cfirst | cg | cgetfile | cgetb | cgetbuffer | cgete | cgetexpr | changes | chd | chdir | che | checkpath | checkt | checktime | chi | chistory | cl | clist | cla | clast | class | cle | clearjumps | clo | close | cmapc | cmapclear | cn | cnext | cnew | cnewer | cnf | cnfile | cnor | co | copy | col | colder | colo | colorscheme | comc | comclear | comp | compiler | com | con | continue | conf | confirm | const? | copen? | cp | cprevious | cpf | cpfile | cq | cquit | cr | crewind | cscope | cstag | cs | cuna | cunabbrev | cun | cw | cwindow | d | delete | debugg | debuggreedy | debug | defc | defcompile | def | delc | delcommand | delel | delep | deletel | deletep | deletl | deletp | delf | delfunction | dell | delm | delmarks | delp | dep | di | display | dif | diffupdate | diffg | diffget | diffo | diffoff | diffp | diffpatch | diffput? | diffs | diffsplit | difft | diffthis | dig | digraphs | dir | disa | disassemble | dj | djump | dli | dlist | dl | doaut | doau | do | dp | dr | drop | ds | dsearch | dsp | dsplit | e | edit | earlier | ea | echoc | echoconsole | echoe | echoerr | echom | echomsg | echon | ec | el | else | elseif? | em | emenu | en | endif | enddef | endf | endfunction | endfor? | endt | endtry | endw | endwhile | enew? | eval | exit? | export | exp | exu | exusage | ex | f | file | files | filetype | filet | filt | filter | find? | fina | finally | fini | finish | fir | first | fix | fixdel | fo | fold | foldc | foldclose | foldd | folddoopen | folddoc | folddoclosed | foldo | foldopen | for | fu | function | go | goto | gr | grep | grepa | grepadd | gui | gvim | g | h | help | ha | hardcopy | helpc | helpclose | helpf | helpfind | helpg | helpgrep | helpt | helptags | hide? | his | history | hi | iabc | iabclear | ia | if | ij | ijump | il | ilist | imapc | imapclear | import | imp | inor | interface | intro | in | is | isearch | isp | isplit | iuna | iunabbrev | i | j | join | ju | jumps | kee | keepmarks | keepalt | keepa | keepj | keepjumps | keepp | keeppatterns | k | lN | lNext | lNf | lNfile | l | list | la | last | lab | labove | lad | laddexpr | laddb | laddbuffer | laddf | laddfile | laf | lafter | lan | language | later | lat | lb | lbuffer | lbe | lbefore | lbel | lbelow | lbo | lbottom | lcd? | lch | lchdir | lcl | lclose | lcscope | lcs | ldo? | le | left | lefta | leftabove | leg | legacy | lex | lexpr | lf | lfile | lfdo | lfir | lfirst | lg | lgetfile | lgetb | lgetbuffer | lgete | lgetexpr | lgr | lgrep | lgrepa | lgrepadd | lh | lhelpgrep | lhi | lhistory | lla | llast | lli | llist | ll | lmake? | lmapc | lmapclear | lma | lne | lnext | lnew | lnewer | lnf | lnfile | lo | loadview | loadkeymap | loadk | loc | lockmarks | lockv | lockvar | lol | lolder | lop | lopen | lp | lprevious | lpf | lpfile | lr | lrewind | ls | lt | ltag | luado | luafile | lua | lv | lvimgrep | lvimgrepa | lvimgrepadd | lw | lwindow | m | move | ma | mark | make? | marks | mat | match | menut | menutranslate | mes | messages | mk | mkexrc | mks | mksession | mksp | mkspell | mkv | mkvimrc | mkview? | mode? | mz | mzscheme | mzf | mzfile | n | next | nb | nbkey | nbc | nbclose | nbs | nbstart | new | nmapc | nmapclear | noautocmd | noa | noh | nohlsearch | nore | nor | nos | noswapfile | nu | number | o | open | ol | oldfiles | omapc | omapclear | on | only | opt | options | ownsyntax | p | print | pa | packadd | packl | packloadall | pc | pclose | pe | perl | ped | pedit | perldo? | pop? | popup? | pp | ppop | pre | preserve | prev | previous | prof | profile | profd | profdel | promptf | promptfind | promptr | promptrepl | pro | ps | psearch | ptN | ptNext | ptag? | ptf | ptfirst | ptj | ptjump | ptl | ptlast | ptn | ptnext | ptp | ptprevious | ptr | ptrewind | pts | ptselect | put? | pwd? | py3do | py3f | py3file | py3 | py | python | pydo | pyf | pyfile | python3 | pythonx | pyxdo | pyxfile | pyx | q | quit | qa | qall | quita | quitall | r | read | rec | recover | redo? | redir? | redr | redraw | redraws | redrawstatus | redrawt | redrawtabline | reg | registers | res | resize | ret | retab | retu | return | rew | rewind | ri | right | rightb | rightbelow | ru | runtime | ruby? | rubydo? | rubyf | rubyfile | rundo | rv | rviminfo | sIc | sIe | sIg | sIl | sIn | sIp | sIr | sI | sN | sNext | sa | sargument | sall? | san | sandbox | sav | saveas | sbN | sbNext | sb | sbuffer | sba | sball | sbf | sbfirst | sbl | sblast | sbm | sbmodified | sbn | sbnext | sbp | sbprevious | sbr | sbrewind | scI | sce | scg | sci | scl | scp | scr | scriptnames | scripte | scriptencoding | scriptv | scriptversion | scscope | scs | sc | set? | setf | setfiletype | setg | setglobal | setl | setlocal | sf | sfind | sfir | sfirst | sgI | sgc | sge | sgi | sgl | sgn | sgp | sgr | sg | sh | shell | sic | sie | sign | sig | sil | silent | sim | simalt | sin | sip | sir | si | sl | sleep | sla | slast | sm | smagic | sm | smap | smenu | sme | smile | sn | snext | sno | snomagic | snoremenu | snoreme | so | source | sort? | sp | split | spe | spellgood | spelld | spelldump | spelli | spellinfo | spellr | spellrare | spellr | spellrepall | spellr | spellrrare | spellu | spellundo | spellw | spellwrong | spr | sprevious | srI | src | sre | srewind | srg | sri | srl | srn | srp | sr | st | stop | stag? | star | startinsert | startg | startgreplace | startr | startreplace | stj | stjump | stopi | stopinsert | sts | stselect | substitutepattern | substituterepeat | sun | sunhide | sunmenu | sunme | sus | suspend | sv | sview | sw | swapname | syncbind | sync | syntime | syn | sy | tN | tNext | tag? | tabN | tabNext | tabc | tabclose | tabdo? | tabe | tabedit | tabf | tabfind | tabfir | tabfirst | tabl | tablast | tabm | tabmove | tabn | tabnext | tabnew | tabo | tabonly | tabp | tabprevious | tabr | tabrewind | tabs | tab | tags | tcl? | tcd | tch | tchdir | tcldo? | tclf | tclfile | te | tearoff | ter | terminal | tf | tfirst | th | throw | tj | tjump | tl | tlast | tlmenu | tlm | tlnoremenu | tln | tlunmenu | tlu | tm | tmenu | tmap? | tmapc | tmapclear | tn | tnext | tno | tnoremap | to | topleft | tp | tprevious | tr | trewind | try | ts | tselect | tu | tunmenu | tunmap? | type | t | u | undo | una | unabbreviate | undoj | undojoin | undol | undolist | unh | unhide | unlo | unlockvar | unl | uns | unsilent | up | update | var | ve | version | verb | verbose | vert | vertical | vi | visual | view? | vim9 | vim9cmd | vim9s | vim9script | vim | vimgrep | vimgrepa | vimgrepadd | viu | viusage | vmapc | vmapclear | vnew? | vs | vsplit | v | wN | wNext | w | write | wa | wall | wh | while | win | winsize | winc | wincmd | windo | winp | winpos | wn | wnext | wp | wprevious | wqa | wqall | wq | wundo | wv | wviminfo | x | xit | xa | xall | xmapc | xmapclear | xmenu | xme | xnoremenu | xnoreme | xprop | xr | xrestore | xunmenu | xunme | xwininfo | y | yank ) \\b """ vimErrSetting: name: "invalid.deprecated.legacy-setting.viml" match: """(?x) \\b ( autoprint | beautify | bioskey | biosk | conskey | consk | flash | graphic | hardtabs | ht | mesg | noautoprint | nobeautify | nobioskey | nobiosk | noconskey | noconsk | noflash | nographic | nohardtabs | nomesg | nonovice | noopen | nooptimize | noop | noredraw | noslowopen | noslow | nosourceany | novice | now1200 | now300 | now9600 | open | optimize | op | redraw | slowopen | slow | sourceany | w1200 | w300 | w9600 ) \\b """ vimFTCmd: name: "support.function.vimFTCmd.viml" match: """(?x) \\b ( filet | filetype ) \\b """ vimFTOption: name: "support.function.vimFTOption.viml" match: """(?x) \\b ( detect | indent | off | on | plugin ) \\b """ vimFgBgAttrib: name: "support.constant.attribute.viml" match: """(?x) \\b ( background | bg | fg | foreground | none ) \\b """ vimFuncKey: name: "support.function.vimFuncKey.viml" match: """(?x) \\b ( def | fu | function ) \\b """ vimFuncName: name: "support.function.viml" match: """(?x) \\b ( abs | acos | add | and | appendbufline | append | argc | argidx | arglistid | argv | asin | assert_beeps | assert_equalfile | assert_equal | assert_exception | assert_fails | assert_false | assert_inrange | assert_match | assert_nobeep | assert_notequal | assert_notmatch | assert_report | assert_true | atan2 | atan | balloon_gettext | balloon_show | balloon_split | browsedir | browse | bufadd | bufexists | buflisted | bufloaded | bufload | bufname | bufnr | bufwinid | bufwinnr | byte2line | byteidxcomp | byteidx | call | ceil | ch_canread | ch_close_in | ch_close | ch_evalexpr | ch_evalraw | ch_getbufnr | ch_getjob | ch_info | ch_logfile | ch_log | ch_open | ch_readblob | ch_readraw | ch_read | ch_sendexpr | ch_sendraw | ch_setoptions | ch_status | changenr | char2nr | charclass | charcol | charidx | chdir | cindent | clearmatches | col | complete_add | complete_check | complete_info | complete | confirm | copy | cosh | cos | count | cscope_connection | cursor | debugbreak | deepcopy | deletebufline | delete | did_filetype | diff_filler | diff_hlID | echoraw | empty | environ | escape | eval | eventhandler | executable | execute | exepath | exists | expandcmd | expand | exp | extendnew | extend | feedkeys | filereadable | filewritable | filter | finddir | findfile | flattennew | flatten | float2nr | floor | fmod | fnameescape | fnamemodify | foldclosedend | foldclosed | foldlevel | foldtextresult | foldtext | foreground | fullcommand | funcref | function | garbagecollect | getbufinfo | getbufline | getbufvar | getchangelist | getcharmod | getcharpos | getcharsearch | getchar | getcmdline | getcmdpos | getcmdtype | getcmdwintype | getcompletion | getcurpos | getcursorcharpos | getcwd | getenv | getfontname | getfperm | getfsize | getftime | getftype | getimstatus | getjumplist | getline | getloclist | getmarklist | getmatches | getmousepos | getpid | getpos | getqflist | getreginfo | getregtype | getreg | gettabinfo | gettabvar | gettabwinvar | gettagstack | gettext | getwininfo | getwinposx | getwinposy | getwinpos | getwinvar | get | glob2regpat | globpath | glob | has_key | haslocaldir | hasmapto | has | histadd | histdel | histget | histnr | hlID | hlexists | hostname | iconv | indent | index | inputdialog | inputlist | inputrestore | inputsave | inputsecret | input | insert | interrupt | invert | isdirectory | isinf | islocked | isnan | items | job_getchannel | job_info | job_setoptions | job_start | job_status | job_stop | join | js_decode | js_encode | json_decode | json_encode | keys | len | libcallnr | libcall | line2byte | line | lispindent | list2str | listener_add | listener_flush | listener_remove | localtime | log10 | log | luaeval | maparg | mapcheck | mapnew | mapset | map | matchaddpos | matchadd | matcharg | matchdelete | matchend | matchfuzzypos | matchfuzzy | matchlist | matchstrpos | matchstr | match | max | menu_info | min | mkdir | mode | mzeval | nextnonblank | nr2char | or | pathshorten | perleval | popup_atcursor | popup_beval | popup_clear | popup_close | popup_create | popup_dialog | popup_filter_menu | popup_filter_yesno | popup_findinfo | popup_findpreview | popup_getoptions | popup_getpos | popup_hide | popup_list | popup_locate | popup_menu | popup_move | popup_notification | popup_setoptions | popup_settext | popup_show | pow | prevnonblank | printf | prompt_getprompt | prompt_setcallback | prompt_setinterrupt | prompt_setprompt | prop_add | prop_clear | prop_find | prop_list | prop_remove | prop_type_add | prop_type_change | prop_type_delete | prop_type_get | prop_type_list | pum_getpos | pumvisible | py3eval | pyeval | pyxeval | rand | range | readblob | readdirex | readdir | readfile | reduce | reg_executing | reg_recording | reltimefloat | reltimestr | reltime | remote_expr | remote_foreground | remote_peek | remote_read | remote_send | remote_startserver | remove | rename | repeat | resolve | reverse | round | rubyeval | screenattr | screenchars | screenchar | screencol | screenpos | screenrow | screenstring | searchcount | searchdecl | searchpairpos | searchpair | searchpos | search | server2client | serverlist | setbufline | setbufvar | setcellwidths | setcharpos | setcharsearch | setcmdpos | setcursorcharpos | setenv | setfperm | setline | setloclist | setmatches | setpos | setqflist | setreg | settabvar | settabwinvar | settagstack | setwinvar | sha256 | shellescape | shiftwidth | sign_define | sign_getdefined | sign_getplaced | sign_jump | sign_placelist | sign_place | sign_undefine | sign_unplacelist | sign_unplace | simplify | sinh | sin | slice | sort | sound_clear | sound_playevent | sound_playfile | sound_stop | soundfold | spellbadword | spellsuggest | split | sqrt | srand | state | str2float | str2list | str2nr | strcharlen | strcharpart | strchars | strdisplaywidth | strftime | strgetchar | stridx | string | strlen | strpart | strptime | strridx | strtrans | strwidth | submatch | substitute | swapinfo | swapname | synIDattr | synIDtrans | synID | synconcealed | synstack | systemlist | system | tabpagebuflist | tabpagenr | tabpagewinnr | tagfiles | taglist | tanh | tan | tempname | term_dumpdiff | term_dumpload | term_dumpwrite | term_getaltscreen | term_getansicolors | term_getattr | term_getcursor | term_getjob | term_getline | term_getscrolled | term_getsize | term_getstatus | term_gettitle | term_gettty | term_list | term_scrape | term_sendkeys | term_setansicolors | term_setapi | term_setkill | term_setrestore | term_setsize | term_start | term_wait | terminalprops | test_alloc_fail | test_autochdir | test_feedinput | test_garbagecollect_now | test_garbagecollect_soon | test_getvalue | test_ignore_error | test_null_blob | test_null_channel | test_null_dict | test_null_function | test_null_job | test_null_list | test_null_partial | test_null_string | test_option_not_set | test_override | test_refcount | test_scrollbar | test_setmouse | test_settime | test_srand_seed | test_unknown | test_void | timer_info | timer_pause | timer_start | timer_stopall | timer_stop | tolower | toupper | trim | trunc | tr | typename | type | undofile | undotree | uniq | values | virtcol | visualmode | wildmenumode | win_execute | win_findbuf | win_getid | win_gettype | win_gotoid | win_id2tabwin | win_id2win | win_screenpos | win_splitmove | winbufnr | wincol | windowsversion | winheight | winlayout | winline | winnr | winrestcmd | winrestview | winsaveview | winwidth | wordcount | writefile | xor ) \\b """ vimGroup: name: "support.type.group.viml" match: """(?xi) \\b ( Boolean | Character | Comment | Conditional | Constant | Debug | Define | Delimiter | Error | Exception | Float | Function | Identifier | Ignore | Include | Keyword | Label | Macro | Number | Operator | PreCondit | PreProc | Repeat | SpecialChar | SpecialComment | Special | Statement | StorageClass | String | Structure | Tag | Todo | Typedef | Type | Underlined ) \\b """ vimGroupSpecial: name: "support.function.vimGroupSpecial.viml" match: """(?x) \\b ( ALLBUT | ALL | CONTAINED | TOP ) \\b """ vimHLGroup: name: "support.type.highlight-group.viml" match: """(?xi) \\b ( ColorColumn | CursorColumn | CursorIM | CursorLineNr | CursorLine | Cursor | DiffAdd | DiffChange | DiffDelete | DiffText | Directory | EndOfBuffer | ErrorMsg | FoldColumn | Folded | IncSearch | LineNrAbove | LineNrBelow | LineNr | MatchParen | Menu | ModeMsg | MoreMsg | NonText | Normal | PmenuSbar | PmenuSel | PmenuThumb | Pmenu | Question | QuickFixLine | Scrollbar | Search | SignColumn | SpecialKey | SpellBad | SpellCap | SpellLocal | SpellRare | StatusLineNC | StatusLineTerm | StatusLine | TabLineFill | TabLineSel | TabLine | Terminal | Title | Tooltip | VertSplit | VisualNOS | Visual | WarningMsg | WildMenu ) \\b """ vimHiAttrib: name: "support.function.vimHiAttrib.viml" match: """(?x) \\b ( bold | inverse | italic | nocombine | none | reverse | standout | strikethrough | undercurl | underline ) \\b """ vimHiClear: name: "support.function.vimHiClear.viml" match: """(?x) \\b ( clear ) \\b """ vimHiCtermColor: name: "support.constant.colour.color.$1.viml" match: """(?x) \\b ( black | blue | brown | cyan | darkblue | darkcyan | darkgray | darkgreen | darkgrey | darkmagenta | darkred | darkyellow | gray | green | grey40 | grey50 | grey90 | grey | lightblue | lightcyan | lightgray | lightgreen | lightgrey | lightmagenta | lightred | lightyellow | magenta | red | seagreen | white | yellow ) \\b """ vimMapModKey: name: "support.function.vimMapModKey.viml" match: """(?x) \\b ( buffer | expr | leader | localleader | nowait | plug | script | sid | silent | unique ) \\b """ vimOption: name: "support.variable.option.viml" match: """(?x) \\b ( acd | ai | akm | aleph | allowrevins | altkeymap | al | ambiwidth | ambw | antialias | anti | arabicshape | arabic | arab | ari | arshape | ar | asd | autochdir | autoindent | autoread | autoshelldir | autowriteall | autowrite | awa | aw | background | backspace | backupcopy | backupdir | backupext | backupskip | backup | balloondelay | balloonevalterm | ballooneval | balloonexpr | bdir | bdlay | belloff | bevalterm | beval | bexpr | bex | bg | bh | binary | bin | bkc | bk | bl | bomb | bo | breakat | breakindentopt | breakindent | briopt | bri | brk | browsedir | bsdir | bsk | bs | bt | bufhidden | buflisted | buftype | casemap | cb | ccv | cc | cdpath | cd | cedit | cfu | cf | charconvert | ch | cindent | cinkeys | cink | cinoptions | cino | cinwords | cinw | cin | ci | clipboard | cmdheight | cmdwinheight | cmp | cms | cm | cocu | cole | colorcolumn | columns | commentstring | comments | compatible | completefunc | completeopt | completepopup | completeslash | complete | com | confirm | copyindent | cot | co | cpoptions | cpo | cpp | cpt | cp | crb | cryptmethod | cscopepathcomp | cscopeprg | cscopequickfix | cscoperelative | cscopetagorder | cscopetag | cscopeverbose | csl | cspc | csprg | csqf | csre | csto | cst | csverb | cuc | culopt | cul | cursorbind | cursorcolumn | cursorlineopt | cursorline | cursor | cwh | debug | deco | define | def | delcombine | dex | dg | dictionary | dict | diffexpr | diffopt | diff | digraph | dip | directory | dir | display | dy | eadirection | ead | ea | eb | edcompatible | ed | efm | ef | ei | ek | emoji | emo | encoding | enc | endofline | eol | ep | equalalways | equalprg | errorbells | errorfile | errorformat | esckeys | et | eventignore | expandtab | exrc | ex | fcl | fcs | fdc | fde | fdi | fdls | fdl | fdm | fdn | fdo | fdt | fencs | fenc | fen | fex | ffs | ff | fic | fileencodings | fileencoding | fileformats | fileformat | fileignorecase | filetype | fillchars | fixendofline | fixeol | fkmap | fk | flp | fml | fmr | foldclose | foldcolumn | foldenable | foldexpr | foldignore | foldlevelstart | foldlevel | foldmarker | foldmethod | foldminlines | foldnestmax | foldopen | foldtext | formatexpr | formatlistpat | formatoptions | formatprg | fo | fp | fsync | fs | ft | gcr | gdefault | gd | gfm | gfn | gfs | gfw | ghr | go | gp | grepformat | grepprg | gtl | gtt | guicursor | guifontset | guifontwide | guifont | guiheadroom | guioptions | guipty | guitablabel | guitabtooltip | helpfile | helpheight | helplang | hf | hh | hidden | hid | highlight | history | hi | hkmapp | hkmap | hkp | hk | hlg | hlsearch | hls | hl | iconstring | icon | ic | ignorecase | imactivatefunc | imactivatekey | imaf | imak | imcmdline | imc | imdisable | imd | iminsert | imi | imsearch | imsf | imstatusfunc | imstyle | imst | ims | im | includeexpr | include | incsearch | inc | indentexpr | indentkeys | inde | indk | inex | infercase | inf | insertmode | invacd | invai | invakm | invallowrevins | invaltkeymap | invantialias | invanti | invarabicshape | invarabic | invarab | invari | invarshape | invar | invasd | invautochdir | invautoindent | invautoread | invautoshelldir | invautowriteall | invautowrite | invawa | invaw | invbackup | invballoonevalterm | invballooneval | invbevalterm | invbeval | invbinary | invbin | invbk | invbl | invbomb | invbreakindent | invbri | invbuflisted | invcf | invcindent | invcin | invci | invcompatible | invconfirm | invcopyindent | invcp | invcrb | invcscoperelative | invcscopetag | invcscopeverbose | invcsre | invcst | invcsverb | invcuc | invcul | invcursorbind | invcursorcolumn | invcursorline | invdeco | invdelcombine | invdg | invdiff | invdigraph | invea | inveb | invedcompatible | inved | invek | invemoji | invemo | invendofline | inveol | invequalalways | inverrorbells | invesckeys | invet | invexpandtab | invexrc | invex | invfen | invfic | invfileignorecase | invfixendofline | invfixeol | invfkmap | invfk | invfoldenable | invfsync | invfs | invgdefault | invgd | invguipty | invhidden | invhid | invhkmapp | invhkmap | invhkp | invhk | invhlsearch | invhls | invicon | invic | invignorecase | invimcmdline | invimc | invimdisable | invimd | invim | invincsearch | invinfercase | invinf | invinsertmode | invis | invjoinspaces | invjs | invlangnoremap | invlangremap | invlazyredraw | invlbr | invlinebreak | invlisp | invlist | invlnr | invloadplugins | invlpl | invlrm | invlz | invmacatsui | invmagic | invma | invmh | invmle | invml | invmodelineexpr | invmodeline | invmodifiable | invmodified | invmod | invmore | invmousefocus | invmousef | invmousehide | invnumber | invnu | invodev | invopendevice | invpaste | invpi | invpreserveindent | invpreviewwindow | invprompt | invpvw | invreadonly | invrelativenumber | invremap | invrestorescreen | invrevins | invrightleft | invri | invrl | invrnu | invro | invrs | invruler | invru | invsb | invscb | invscf | invscrollbind | invscrollfocus | invscs | invsc | invsecure | invsft | invshellslash | invshelltemp | invshiftround | invshortname | invshowcmd | invshowfulltag | invshowmatch | invshowmode | invsi | invsmartcase | invsmartindent | invsmarttab | invsmd | invsm | invsn | invsol | invspell | invsplitbelow | invsplitright | invspr | invsr | invssl | invstartofline | invsta | invstmp | invswapfile | invswf | invtagbsearch | invtagrelative | invtagstack | invta | invtbidi | invtbi | invtbs | invtermbidi | invterse | invtextauto | invtextmode | invtf | invtgst | invtildeop | invtimeout | invtitle | invtop | invto | invtr | invttimeout | invttybuiltin | invttyfast | invtx | invudf | invundofile | invvb | invvisualbell | invwarn | invwa | invwb | invweirdinvert | invwfh | invwfw | invwic | invwildignorecase | invwildmenu | invwinfixheight | invwinfixwidth | invwiv | invwmnu | invwrapscan | invwrap | invwriteany | invwritebackup | invwrite | invws | isfname | isf | isident | isi | iskeyword | isk | isprint | isp | is | joinspaces | js | keymap | keymodel | keywordprg | key | kmp | km | kp | langmap | langmenu | langnoremap | langremap | laststatus | lazyredraw | lbr | lcs | level | linebreak | linespace | lines | lispwords | lisp | listchars | list | lmap | lm | lnr | loadplugins | lpl | lrm | lsp | ls | luadll | lw | lz | macatsui | magic | makeef | makeencoding | makeprg | matchpairs | matchtime | mat | maxcombine | maxfuncdepth | maxmapdepth | maxmempattern | maxmemtot | maxmem | ma | mco | mef | menc | menuitems | mfd | mh | mis | mkspellmem | mle | mls | ml | mmd | mmp | mmt | mm | modelineexpr | modelines | modeline | modifiable | modified | mod | more | mousefocus | mousef | mousehide | mousemodel | mousem | mouseshape | mouses | mousetime | mouset | mouse | mps | mp | msm | mzquantum | mzq | mzschemedll | mzschemegcdll | nf | noacd | noai | noakm | noallowrevins | noaltkeymap | noantialias | noanti | noarabicshape | noarabic | noarab | noari | noarshape | noar | noasd | noautochdir | noautoindent | noautoread | noautoshelldir | noautowriteall | noautowrite | noawa | noaw | nobackup | noballoonevalterm | noballooneval | nobevalterm | nobeval | nobinary | nobin | nobk | nobl | nobomb | nobreakindent | nobri | nobuflisted | nocf | nocindent | nocin | noci | nocompatible | noconfirm | nocopyindent | nocp | nocrb | nocscoperelative | nocscopetag | nocscopeverbose | nocsre | nocst | nocsverb | nocuc | nocul | nocursorbind | nocursorcolumn | nocursorline | nodeco | nodelcombine | nodg | nodiff | nodigraph | noea | noeb | noedcompatible | noed | noek | noemoji | noemo | noendofline | noeol | noequalalways | noerrorbells | noesckeys | noet | noexpandtab | noexrc | noex | nofen | nofic | nofileignorecase | nofixendofline | nofixeol | nofkmap | nofk | nofoldenable | nofsync | nofs | nogdefault | nogd | noguipty | nohidden | nohid | nohkmapp | nohkmap | nohkp | nohk | nohlsearch | nohls | noicon | noic | noignorecase | noimcmdline | noimc | noimdisable | noimd | noim | noincsearch | noinfercase | noinf | noinsertmode | nois | nojoinspaces | nojs | nolangnoremap | nolangremap | nolazyredraw | nolbr | nolinebreak | nolisp | nolist | nolnr | noloadplugins | nolpl | nolrm | nolz | nomacatsui | nomagic | noma | nomh | nomle | noml | nomodelineexpr | nomodeline | nomodifiable | nomodified | nomod | nomore | nomousefocus | nomousef | nomousehide | nonumber | nonu | noodev | noopendevice | nopaste | nopi | nopreserveindent | nopreviewwindow | noprompt | nopvw | noreadonly | norelativenumber | noremap | norestorescreen | norevins | norightleft | nori | norl | nornu | noro | nors | noruler | noru | nosb | noscb | noscf | noscrollbind | noscrollfocus | noscs | nosc | nosecure | nosft | noshellslash | noshelltemp | noshiftround | noshortname | noshowcmd | noshowfulltag | noshowmatch | noshowmode | nosi | nosmartcase | nosmartindent | nosmarttab | nosmd | nosm | nosn | nosol | nospell | nosplitbelow | nosplitright | nospr | nosr | nossl | nostartofline | nosta | nostmp | noswapfile | noswf | notagbsearch | notagrelative | notagstack | nota | notbidi | notbi | notbs | notermbidi | noterse | notextauto | notextmode | notf | notgst | notildeop | notimeout | notitle | notop | noto | notr | nottimeout | nottybuiltin | nottyfast | notx | noudf | noundofile | novb | novisualbell | nowarn | nowa | nowb | noweirdinvert | nowfh | nowfw | nowic | nowildignorecase | nowildmenu | nowinfixheight | nowinfixwidth | nowiv | nowmnu | nowrapscan | nowrap | nowriteany | nowritebackup | nowrite | nows | nrformats | numberwidth | number | nuw | nu | odev | oft | ofu | omnifunc | opendevice | operatorfunc | opfunc | osfiletype | packpath | paragraphs | para | pastetoggle | paste | patchexpr | patchmode | path | pa | pdev | penc | perldll | pexpr | pex | pfn | pheader | ph | pi | pmbcs | pmbfn | pm | popt | pp | preserveindent | previewheight | previewpopup | previewwindow | printdevice | printencoding | printexpr | printfont | printheader | printmbcharset | printmbfont | printoptions | prompt | pt | pumheight | pumwidth | pvh | pvp | pvw | pw | pythondll | pythonhome | pythonthreedll | pythonthreehome | pyxversion | pyx | qe | qftf | quickfixtextfunc | quoteescape | rdt | readonly | redrawtime | regexpengine | relativenumber | remap | renderoptions | report | restorescreen | revins | re | rightleftcmd | rightleft | ri | rlc | rl | rnu | rop | ro | rs | rtp | rubydll | ruf | rulerformat | ruler | runtimepath | ru | sbo | sbr | sb | scb | scf | scl | scrollbind | scrollfocus | scrolljump | scrolloff | scrollopt | scroll | scr | scs | sc | sections | sect | secure | selection | selectmode | sel | sessionoptions | sft | shcf | shellcmdflag | shellpipe | shellquote | shellredir | shellslash | shelltemp | shelltype | shellxescape | shellxquote | shell | shiftround | shiftwidth | shm | shortmess | shortname | showbreak | showcmd | showfulltag | showmatch | showmode | showtabline | shq | sh | sidescrolloff | sidescroll | signcolumn | siso | si | sj | slm | smartcase | smartindent | smarttab | smc | smd | sm | sn | softtabstop | sol | so | spc | spellcapcheck | spellfile | spelllang | spelloptions | spellsuggest | spell | spf | splitbelow | splitright | spl | spo | spr | sps | sp | srr | sr | ssl | ssop | ss | stal | startofline | statusline | sta | stl | stmp | sts | st | sua | suffixesadd | suffixes | su | swapfile | swapsync | swb | swf | switchbuf | sws | sw | sxe | sxq | synmaxcol | syntax | syn | t_8b | t_8f | t_8u | t_AB | t_AF | t_AL | t_AU | t_BD | t_BE | t_CS | t_CV | t_Ce | t_Co | t_Cs | t_DL | t_EC | t_EI | t_F1 | t_F2 | t_F3 | t_F4 | t_F5 | t_F6 | t_F7 | t_F8 | t_F9 | t_GP | t_IE | t_IS | t_K1 | t_K3 | t_K4 | t_K5 | t_K6 | t_K7 | t_K8 | t_K9 | t_KA | t_KB | t_KC | t_KD | t_KE | t_KF | t_KG | t_KH | t_KI | t_KJ | t_KK | t_KL | t_PE | t_PS | t_RB | t_RC | t_RF | t_RI | t_RS | t_RT | t_RV | t_Ri | t_SC | t_SH | t_SI | t_SR | t_ST | t_Sb | t_Sf | t_Si | t_TE | t_TI | t_Te | t_Ts | t_VS | t_WP | t_WS | t_ZH | t_ZR | t_al | t_bc | t_cd | t_ce | t_cl | t_cm | t_cs | t_da | t_db | t_dl | t_fd | t_fe | t_fs | t_k1 | t_k2 | t_k3 | t_k4 | t_k5 | t_k6 | t_k7 | t_k8 | t_k9 | t_kB | t_kD | t_kI | t_kN | t_kP | t_kb | t_kd | t_ke | t_kh | t_kl | t_kr | t_ks | t_ku | t_le | t_mb | t_md | t_me | t_mr | t_ms | t_nd | t_op | t_se | t_so | t_sr | t_te | t_ti | t_ts | t_u7 | t_ue | t_us | t_ut | t_vb | t_ve | t_vi | t_vs | t_xn | t_xs | tabline | tabpagemax | tabstop | tagbsearch | tagcase | tagfunc | taglength | tagrelative | tagstack | tags | tag | tal | ta | tbidi | tbis | tbi | tbs | tb | tcldll | tc | tenc | termbidi | termencoding | termguicolors | termwinkey | termwinscroll | termwinsize | termwintype | term | terse | textauto | textmode | textwidth | tfu | tf | tgc | tgst | thesaurus | tildeop | timeoutlen | timeout | titlelen | titleold | titlestring | title | tl | tm | toolbariconsize | toolbar | top | to | tpm | tr | tsl | tsr | ts | ttimeoutlen | ttimeout | ttm | ttybuiltin | ttyfast | ttymouse | ttym | ttyscroll | ttytype | tty | twk | twsl | tws | twt | tw | tx | uc | udf | udir | ul | undodir | undofile | undolevels | undoreload | updatecount | updatetime | ur | ut | varsofttabstop | vartabstop | vbs | vb | vdir | verbosefile | verbose | ve | vfile | viewdir | viewoptions | vif | viminfofile | viminfo | virtualedit | visualbell | vi | vop | vsts | vts | wak | warn | wa | wb | wcm | wcr | wc | wd | weirdinvert | wfh | wfw | whichwrap | wh | wic | wig | wildcharm | wildchar | wildignorecase | wildignore | wildmenu | wildmode | wildoptions | wim | winaltkeys | wincolor | window | winfixheight | winfixwidth | winheight | winminheight | winminwidth | winptydll | winwidth | wiv | wiw | wi | wmh | wmnu | wmw | wm | wop | wrapmargin | wrapscan | wrap | writeany | writebackup | writedelay | write | ws | ww ) \\b """ vimPattern: name: "support.function.vimPattern.viml" match: """(?x) \\b ( end | skip | start ) \\b """ vimStdPlugin: name: "support.class.stdplugin.viml" match: """(?x) \\b ( Arguments | Asm | Break | Cfilter | Clear | Continue | DiffOrig | Evaluate | Finish | Gdb | Lfilter | Man | N | Next | Over | P | Print | Program | Run | Source | Step | Stop | S | TOhtml | TermdebugCommand | Termdebug | Winbar | XMLent | XMLns ) \\b """ vimSynCase: name: "support.function.vimSynCase.viml" match: """(?x) \\b ( ignore | match ) \\b """ vimSynType: name: "support.function.vimSynType.viml" match: """(?x) \\b ( case | clear | cluster | enable | include | iskeyword | keyword | list | manual | match | off | on | region | reset | sync ) \\b """ vimSyncC: name: "support.function.vimSyncC.viml" match: """(?x) \\b ( ccomment | clear | fromstart ) \\b """ vimSyncLinecont: name: "support.function.vimSyncLinecont.viml" match: """(?x) \\b ( linecont ) \\b """ vimSyncMatch: name: "support.function.vimSyncMatch.viml" match: """(?x) \\b ( match ) \\b """ vimSyncNone: name: "support.function.vimSyncNone.viml" match: """(?x) \\b ( NONE ) \\b """ vimSyncRegion: name: "support.function.vimSyncRegion.viml" match: """(?x) \\b ( region ) \\b """ vimUserAttrbCmplt: name: "support.function.vimUserAttrbCmplt.viml" match: """(?x) \\b ( augroup | behave | buffer | color | command | compiler | cscope | customlist | custom | dir | environment | event | expression | file_in_path | filetype | file | function | help | highlight | history | locale | mapping | menu | option | packadd | shellcmd | sign | syntax | syntime | tag_listfiles | tag | user | var ) \\b """ vimUserAttrbKey: name: "support.function.vimUserAttrbKey.viml" match: """(?x) \\b ( bang? | bar | com | complete | cou | count | n | nargs | ra | range | re | register ) \\b """ vimUserCommand: name: "support.function.vimUserCommand.viml" match: """(?x) \\b ( com | command ) \\b """
[ { "context": "eoverview Tests for no-cond-assign rule.\n# @author Stephen Murray <spmurrayzzz>\n###\n\n'use strict'\n\n#---------------", "end": 76, "score": 0.9998177289962769, "start": 62, "tag": "NAME", "value": "Stephen Murray" }, { "context": "or no-cond-assign rule.\n# @author Stephen Murray <spmurrayzzz>\n###\n\n'use strict'\n\n#----------------------------", "end": 89, "score": 0.9994454383850098, "start": 78, "tag": "USERNAME", "value": "spmurrayzzz" } ]
src/tests/rules/no-cond-assign.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-cond-assign rule. # @author Stephen Murray <spmurrayzzz> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-cond-assign' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-cond-assign', rule, valid: [ ''' x = 0 if x == 0 b = 1 ''' ''' x = 0 if x is 0 b = 1 ''' , code: ''' x = 0 if x == 0 b = 1 ''' options: ['always'] , ''' x = 5 while x < 5 x = x + 1 ''' ''' if (someNode = someNode.parentNode) isnt null ; ''' , code: ''' if (someNode = someNode.parentNode) isnt null ; ''' options: ['except-parens'] , 'if (a = b) then ;' 'yes if (a = b)' 'a = b if yes' 'while (a = b) then ;' 'if someNode or (someNode = parentNode) then ;' 'while someNode || (someNode = parentNode) then ;' , code: ''' if ((node) -> node = parentNode)(someNode) ; ''' options: ['except-parens'] , code: ''' if ((node) -> node = parentNode)(someNode) ; ''' options: ['always'] , code: ''' if do (node = someNode) -> node = parentNode ; ''' options: ['always'] , code: ''' if (node) -> return node = parentNode ; ''' options: ['except-parens'] , code: ''' if (node) -> return node = parentNode ; ''' options: ['always'] , code: 'x = 0', options: ['always'] , 'b = if (x is 0) then 1 else 0' ] invalid: [ code: ''' if x = 0 b = 1 ''' errors: [messageId: 'missing', type: 'IfStatement', line: 1, column: 4] , code: ''' while x = 0 b = 1 ''' errors: [messageId: 'missing', type: 'WhileStatement'] , code: 'if someNode or (someNode = parentNode) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "an 'if' statement" type: 'IfStatement' ] , code: 'while someNode || (someNode = parentNode) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "a 'while' statement" type: 'WhileStatement' ] , code: 'if x = 0 then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "an 'if' statement" type: 'IfStatement' ] , code: 'yes while x = 0' options: ['always'] errors: [ messageId: 'unexpected' data: type: "a 'while' statement" type: 'WhileStatement' ] , code: 'if (x = 0) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "an 'if' statement" type: 'IfStatement' ] , code: 'while (x = 0) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "a 'while' statement" type: 'WhileStatement' ] ]
199845
###* # @fileoverview Tests for no-cond-assign rule. # @author <NAME> <spmurrayzzz> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-cond-assign' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-cond-assign', rule, valid: [ ''' x = 0 if x == 0 b = 1 ''' ''' x = 0 if x is 0 b = 1 ''' , code: ''' x = 0 if x == 0 b = 1 ''' options: ['always'] , ''' x = 5 while x < 5 x = x + 1 ''' ''' if (someNode = someNode.parentNode) isnt null ; ''' , code: ''' if (someNode = someNode.parentNode) isnt null ; ''' options: ['except-parens'] , 'if (a = b) then ;' 'yes if (a = b)' 'a = b if yes' 'while (a = b) then ;' 'if someNode or (someNode = parentNode) then ;' 'while someNode || (someNode = parentNode) then ;' , code: ''' if ((node) -> node = parentNode)(someNode) ; ''' options: ['except-parens'] , code: ''' if ((node) -> node = parentNode)(someNode) ; ''' options: ['always'] , code: ''' if do (node = someNode) -> node = parentNode ; ''' options: ['always'] , code: ''' if (node) -> return node = parentNode ; ''' options: ['except-parens'] , code: ''' if (node) -> return node = parentNode ; ''' options: ['always'] , code: 'x = 0', options: ['always'] , 'b = if (x is 0) then 1 else 0' ] invalid: [ code: ''' if x = 0 b = 1 ''' errors: [messageId: 'missing', type: 'IfStatement', line: 1, column: 4] , code: ''' while x = 0 b = 1 ''' errors: [messageId: 'missing', type: 'WhileStatement'] , code: 'if someNode or (someNode = parentNode) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "an 'if' statement" type: 'IfStatement' ] , code: 'while someNode || (someNode = parentNode) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "a 'while' statement" type: 'WhileStatement' ] , code: 'if x = 0 then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "an 'if' statement" type: 'IfStatement' ] , code: 'yes while x = 0' options: ['always'] errors: [ messageId: 'unexpected' data: type: "a 'while' statement" type: 'WhileStatement' ] , code: 'if (x = 0) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "an 'if' statement" type: 'IfStatement' ] , code: 'while (x = 0) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "a 'while' statement" type: 'WhileStatement' ] ]
true
###* # @fileoverview Tests for no-cond-assign rule. # @author PI:NAME:<NAME>END_PI <spmurrayzzz> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-cond-assign' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-cond-assign', rule, valid: [ ''' x = 0 if x == 0 b = 1 ''' ''' x = 0 if x is 0 b = 1 ''' , code: ''' x = 0 if x == 0 b = 1 ''' options: ['always'] , ''' x = 5 while x < 5 x = x + 1 ''' ''' if (someNode = someNode.parentNode) isnt null ; ''' , code: ''' if (someNode = someNode.parentNode) isnt null ; ''' options: ['except-parens'] , 'if (a = b) then ;' 'yes if (a = b)' 'a = b if yes' 'while (a = b) then ;' 'if someNode or (someNode = parentNode) then ;' 'while someNode || (someNode = parentNode) then ;' , code: ''' if ((node) -> node = parentNode)(someNode) ; ''' options: ['except-parens'] , code: ''' if ((node) -> node = parentNode)(someNode) ; ''' options: ['always'] , code: ''' if do (node = someNode) -> node = parentNode ; ''' options: ['always'] , code: ''' if (node) -> return node = parentNode ; ''' options: ['except-parens'] , code: ''' if (node) -> return node = parentNode ; ''' options: ['always'] , code: 'x = 0', options: ['always'] , 'b = if (x is 0) then 1 else 0' ] invalid: [ code: ''' if x = 0 b = 1 ''' errors: [messageId: 'missing', type: 'IfStatement', line: 1, column: 4] , code: ''' while x = 0 b = 1 ''' errors: [messageId: 'missing', type: 'WhileStatement'] , code: 'if someNode or (someNode = parentNode) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "an 'if' statement" type: 'IfStatement' ] , code: 'while someNode || (someNode = parentNode) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "a 'while' statement" type: 'WhileStatement' ] , code: 'if x = 0 then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "an 'if' statement" type: 'IfStatement' ] , code: 'yes while x = 0' options: ['always'] errors: [ messageId: 'unexpected' data: type: "a 'while' statement" type: 'WhileStatement' ] , code: 'if (x = 0) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "an 'if' statement" type: 'IfStatement' ] , code: 'while (x = 0) then ;' options: ['always'] errors: [ messageId: 'unexpected' data: type: "a 'while' statement" type: 'WhileStatement' ] ]
[ { "context": "###\n# @author Argi Karunia <https://github.com/hkyo89>\n# @link https://gi", "end": 27, "score": 0.9998809099197388, "start": 15, "tag": "NAME", "value": "Argi Karunia" }, { "context": "###\n# @author Argi Karunia <https://github.com/hkyo89>\n# @link https://github.com/tokopedia/nodame\n#", "end": 54, "score": 0.9994176626205444, "start": 48, "tag": "USERNAME", "value": "hkyo89" }, { "context": "/github.com/hkyo89>\n# @link https://github.com/tokopedia/nodame\n# @license http://opensource.org/licenses/", "end": 95, "score": 0.9345776438713074, "start": 86, "tag": "USERNAME", "value": "tokopedia" } ]
src/json.coffee
tokopedia/nodame
2
### # @author Argi Karunia <https://github.com/hkyo89> # @link https://github.com/tokopedia/nodame # @license http://opensource.org/licenses/MIT # # @version 1.0.0 ### class JSON read: (obj, params) -> throw ReferenceError 'obj is undefined' unless obj? throw ReferenceError 'params is undefined' unless params? if typeof params is 'string' params = params.split('.') if params.length is 0 return obj if params.length > 1 obj = obj[params[0]] params.shift() @read obj, params else obj = obj[params[0]] obj module.exports = new JSON()
109001
### # @author <NAME> <https://github.com/hkyo89> # @link https://github.com/tokopedia/nodame # @license http://opensource.org/licenses/MIT # # @version 1.0.0 ### class JSON read: (obj, params) -> throw ReferenceError 'obj is undefined' unless obj? throw ReferenceError 'params is undefined' unless params? if typeof params is 'string' params = params.split('.') if params.length is 0 return obj if params.length > 1 obj = obj[params[0]] params.shift() @read obj, params else obj = obj[params[0]] obj module.exports = new JSON()
true
### # @author PI:NAME:<NAME>END_PI <https://github.com/hkyo89> # @link https://github.com/tokopedia/nodame # @license http://opensource.org/licenses/MIT # # @version 1.0.0 ### class JSON read: (obj, params) -> throw ReferenceError 'obj is undefined' unless obj? throw ReferenceError 'params is undefined' unless params? if typeof params is 'string' params = params.split('.') if params.length is 0 return obj if params.length > 1 obj = obj[params[0]] params.shift() @read obj, params else obj = obj[params[0]] obj module.exports = new JSON()
[ { "context": ">\n\n token = {}\n\n userOfApplication =\n name: 'Nombre usuario',\n email: 'nombreusuario@gertuproject.info',\n ", "end": 467, "score": 0.7198461890220642, "start": 453, "tag": "NAME", "value": "Nombre usuario" }, { "context": "ication =\n name: 'Nombre usuario',\n email: 'nombreusuario@gertuproject.info',\n password: '123456',\n radius: 10000\n\n us", "end": 513, "score": 0.9999329447746277, "start": 482, "tag": "EMAIL", "value": "nombreusuario@gertuproject.info" }, { "context": "'nombreusuario@gertuproject.info',\n password: '123456',\n radius: 10000\n\n userWithSameEmail =\n na", "end": 537, "score": 0.9993273615837097, "start": 531, "tag": "PASSWORD", "value": "123456" }, { "context": " radius: 10000\n\n userWithSameEmail =\n name: 'Nombre usuario 2',\n email: 'nombreusuario@gertuproject.info',", "end": 606, "score": 0.771369218826294, "start": 592, "tag": "NAME", "value": "Nombre usuario" }, { "context": "Email =\n name: 'Nombre usuario 2',\n email: 'nombreusuario@gertuproject.info',\n password: '123456',\n radius: 10000\n\n us", "end": 654, "score": 0.9999311566352844, "start": 623, "tag": "EMAIL", "value": "nombreusuario@gertuproject.info" }, { "context": "'nombreusuario@gertuproject.info',\n password: '123456',\n radius: 10000\n\n userWithDifferentEmail =\n ", "end": 678, "score": 0.9992969632148743, "start": 672, "tag": "PASSWORD", "value": "123456" }, { "context": "ius: 10000\n\n userWithDifferentEmail =\n name: 'Nombre usuario 2',\n email: 'nombreusuario2@gertuproject.info'", "end": 752, "score": 0.727445125579834, "start": 738, "tag": "NAME", "value": "Nombre usuario" }, { "context": "Email =\n name: 'Nombre usuario 2',\n email: 'nombreusuario2@gertuproject.info',\n password: '123456',\n radius: 10000\n\n sh", "end": 801, "score": 0.9999299645423889, "start": 769, "tag": "EMAIL", "value": "nombreusuario2@gertuproject.info" }, { "context": "nombreusuario2@gertuproject.info',\n password: '123456',\n radius: 10000\n\n shop1 = new Shop(\n name", "end": 825, "score": 0.9993171095848083, "start": 819, "tag": "PASSWORD", "value": "123456" }, { "context": " shop1 = new Shop(\n name: 'Shop 1'\n email: 'emailshop1@mail.com'\n password: '123456',\n loc:\n latitude:", "end": 917, "score": 0.9999246001243591, "start": 898, "tag": "EMAIL", "value": "emailshop1@mail.com" }, { "context": "'\n email: 'emailshop1@mail.com'\n password: '123456',\n loc:\n latitude: 0,\n longitude: 0\n", "end": 940, "score": 0.9993181824684143, "start": 934, "tag": "PASSWORD", "value": "123456" }, { "context": " shop2 = new Shop(\n name: 'Shop 2'\n email: 'emailshop2@mail.com'\n password: '123456',\n loc:\n latitude:", "end": 1065, "score": 0.9999275803565979, "start": 1046, "tag": "EMAIL", "value": "emailshop2@mail.com" }, { "context": "'\n email: 'emailshop2@mail.com'\n password: '123456',\n loc:\n latitude: 10,\n longitude: 1", "end": 1088, "score": 0.9993081092834473, "start": 1082, "tag": "PASSWORD", "value": "123456" }, { "context": "iPreffix + '/users/session').\n send({email: 'nonexistantmail@mail.com', password: 'nonexistantpassword'}).\n end (e", "end": 2818, "score": 0.9998034834861755, "start": 2794, "tag": "EMAIL", "value": "nonexistantmail@mail.com" }, { "context": "nd({email: 'nonexistantmail@mail.com', password: 'nonexistantpassword'}).\n end (err, res) ->\n res.should.ha", "end": 2851, "score": 0.9994332194328308, "start": 2832, "tag": "PASSWORD", "value": "nonexistantpassword" }, { "context": " send({email: userOfApplication.email, password: 'nonexistantpassword'}).\n end (err, res) ->\n\n res.should.h", "end": 3142, "score": 0.999451756477356, "start": 3123, "tag": "PASSWORD", "value": "nonexistantpassword" }, { "context": " send({email: userOfApplication.email, password: userOfApplication.password}).\n end (err, res) ->\n\n res.should.ha", "end": 3414, "score": 0.9984655380249023, "start": 3388, "tag": "PASSWORD", "value": "userOfApplication.password" }, { "context": "t(apiPreffix + '/users').\n send({firstName: 'new name', email: 'newemail@mail.com', token: token}).\n ", "end": 4231, "score": 0.7556232810020447, "start": 4223, "tag": "NAME", "value": "new name" }, { "context": "rs').\n send({firstName: 'new name', email: 'newemail@mail.com', token: token}).\n end (err, res) ->\n ", "end": 4260, "score": 0.9998920559883118, "start": 4243, "tag": "EMAIL", "value": "newemail@mail.com" }, { "context": "/' + deal1._id + '/comment').\n send({token: 'wrongtoken', comment: 'new comment', rating: 5}).\n end ", "end": 6689, "score": 0.7013269662857056, "start": 6679, "tag": "KEY", "value": "wrongtoken" }, { "context": " (done) ->\n\n newUser = new User(\n email: 'thisemail@mail.com',\n password: '123456',\n firstName: 'thi", "end": 10395, "score": 0.9999202489852905, "start": 10377, "tag": "EMAIL", "value": "thisemail@mail.com" }, { "context": " email: 'thisemail@mail.com',\n password: '123456',\n firstName: 'this user'\n )\n\n newUs", "end": 10421, "score": 0.9991815090179443, "start": 10415, "tag": "PASSWORD", "value": "123456" }, { "context": "com',\n password: '123456',\n firstName: 'this user'\n )\n\n newUser.save ( (err) ->\n\n newT", "end": 10451, "score": 0.6097356677055359, "start": 10442, "tag": "NAME", "value": "this user" }, { "context": "\n token : Math.random() * 16\n user : newUser\n last_access : new Date()\n )\n\n n", "end": 10576, "score": 0.5357356071472168, "start": 10569, "tag": "USERNAME", "value": "newUser" }, { "context": " (done) ->\n\n newUser = new User(\n email: 'thisemail2@mail.com',\n password: '123456',\n firstName: 'thi", "end": 10964, "score": 0.9999160170555115, "start": 10945, "tag": "EMAIL", "value": "thisemail2@mail.com" }, { "context": " email: 'thisemail2@mail.com',\n password: '123456',\n firstName: 'this user'\n )\n\n newUs", "end": 10990, "score": 0.999138593673706, "start": 10984, "tag": "PASSWORD", "value": "123456" }, { "context": " (done) ->\n\n newUser = new User(\n email: 'thisemail3@mail.com',\n password: '123456',\n firstName: 'thi", "end": 11555, "score": 0.9999163150787354, "start": 11536, "tag": "EMAIL", "value": "thisemail3@mail.com" }, { "context": " email: 'thisemail3@mail.com',\n password: '123456',\n firstName: 'this user'\n )\n\n newUs", "end": 11581, "score": 0.9991356730461121, "start": 11575, "tag": "PASSWORD", "value": "123456" }, { "context": ",\n password: '123456',\n firstName: 'this user'\n )\n\n newUser.save ( (err) ->\n\n newT", "end": 11611, "score": 0.49793145060539246, "start": 11607, "tag": "USERNAME", "value": "user" } ]
test/mobileapi/api.coffee
gertu/gertu
1
should = require "should" app = require "../../server" mongoose = require "mongoose" request = require "supertest" User = mongoose.model "User" Shop = mongoose.model "Shop" Deal = mongoose.model "Deal" Token = mongoose.model "Token" Reservation = mongoose.model "Reservation" server = request.agent(app) apiPreffix = '/mobile/v1' describe "Mobile API testing", -> token = {} userOfApplication = name: 'Nombre usuario', email: 'nombreusuario@gertuproject.info', password: '123456', radius: 10000 userWithSameEmail = name: 'Nombre usuario 2', email: 'nombreusuario@gertuproject.info', password: '123456', radius: 10000 userWithDifferentEmail = name: 'Nombre usuario 2', email: 'nombreusuario2@gertuproject.info', password: '123456', radius: 10000 shop1 = new Shop( name: 'Shop 1' email: 'emailshop1@mail.com' password: '123456', loc: latitude: 0, longitude: 0 ) shop2 = new Shop( name: 'Shop 2' email: 'emailshop2@mail.com' password: '123456', loc: latitude: 10, longitude: 10 ) deal1 = new Deal( name: 'Deal 1', price: 2, gertuprice: 1, discount: 0.5, shop: shop1, quantity: 10) deal2 = new Deal( name: 'Deal 2', price: 4, gertuprice: 1, discount: 0.75, shop: shop1, quantity: 0) deal3 = new Deal( name: 'Deal 3', price: 4, gertuprice: 1, discount: 0.75, shop: shop2, quantity: 5) before (done) -> User.remove().exec() Deal.remove().exec() Shop.remove().exec() Token.remove().exec() Reservation.remove().exec() shop1.save( (err) -> shop2.save( (err) -> deal1.save( (err) -> deal2.save( (err) -> deal3.save( (err) -> done() ) ) ) ) ) it "should signup a new user", (done) -> server. post(apiPreffix + '/users'). send(userOfApplication). end (err, res) -> res.should.have.status 200 token = JSON.parse(res.text).token token.should.not.be.undefined done() it "should not signup a user with a existant email", (done) -> server. post(apiPreffix + '/users'). send(userWithSameEmail). end (err, res) -> res.should.have.status 409 res.text.should.include 11000 done() it "should signup a new user with different email", (done) -> server. post(apiPreffix + '/users'). send(userWithDifferentEmail). end (err, res) -> res.should.have.status 200 done() it "should NOT signin a non existant user", (done) -> server. post(apiPreffix + '/users/session'). send({email: 'nonexistantmail@mail.com', password: 'nonexistantpassword'}). end (err, res) -> res.should.have.status 403 done() it "should NOT signin the newly created user with a wrong password", (done) -> server. post(apiPreffix + '/users/session'). send({email: userOfApplication.email, password: 'nonexistantpassword'}). end (err, res) -> res.should.have.status 403 done() it "should signin the newly created user", (done) -> server. post(apiPreffix + '/users/session'). send({email: userOfApplication.email, password: userOfApplication.password}). end (err, res) -> res.should.have.status 200 userOfApplication._id = JSON.parse(res.text)._id token = JSON.parse(res.text).token done() it "should be a token for the logged in user", (done) -> Token.find({_id: token}).exec( (err, tokens) -> tokens.should.not.be.undefined tokens.should.have.length 1 done() ) it "should return the current user", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 200 res.text.should.include userOfApplication.email done() it "should change info in the current user", (done) -> userOfApplication.name = 'new name' server. put(apiPreffix + '/users'). send({firstName: 'new name', email: 'newemail@mail.com', token: token}). end (err, res) -> res.should.have.status 200 res.text.should.include 'new name' done() it "should throw authorization error on logging out, as no token has been passed", (done) -> server. del(apiPreffix + '/users/session'). send(). end (err, res) -> res.should.have.status 403 done() it "should throw authorization error on returning the current user, as no token is passed", (done) -> server. get(apiPreffix + '/users'). send(). end (err, res) -> res.should.have.status 403 done() it "should NOT return the current user, as there is no user logged in", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 200 res.text.should.not.include userOfApplication.email done() it "should return 3 deals when 3 are present", (done) -> server. get(apiPreffix + '/deals'). send(). end (err, res) -> res.should.have.status 200 allDeals = JSON.parse(res.text) allDeals.should.not.have.length 4 allDeals.should.have.length 3 done() it "should return first deal when requested", (done) -> deal1.save( (err) -> server. get(apiPreffix + '/deals/' + deal1._id). send(). end (err, res) -> res.should.have.status 200 res.text.should.include deal1.name res.text.should.include deal1._id done() ) it "should return 2 near deals when user is at position", (done) -> server. post(apiPreffix + '/deals'). send({longitude: 0, latitude: 0, token: token}). end (err, res) -> res.should.have.status 200 allDeals = JSON.parse(res.text) allDeals.should.not.have.length 3 allDeals.should.have.length 2 done() it "should throw authorization error on commenting a deal, as no token is passed", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({comment: 'new comment', rating: 5}). end (err, res) -> res.should.have.status 403 done() it "should throw authorization error on commenting a deal, as invalid token is passed", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({token: 'wrongtoken', comment: 'new comment', rating: 5}). end (err, res) -> res.should.have.status 403 done() it "should NOT add a comment in a deal if comments and rating are ommitted", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({token: token}). end (err, res) -> res.should.have.status 400 done() it "should add a comment in a deal", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({token: token, comment: 'new comment', rating: 5}). end (err, res) -> returnedDeal = JSON.parse(res.text) res.should.have.status 200 returnedDeal.comments.should.have.length 1 done() it "should make a reservation for a deal", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/reservation'). send({token: token}). end (err, res) -> returnedReservation = JSON.parse(res.text) res.should.have.status 200 returnedReservation.should.have.property "_id" done() it "should mark one less item in quantity allowed for a deal", (done) -> Deal.findOne({_id: deal1._id}).exec( (err, deal) -> deal.should.not.be.undefined deal.should.have.property 'quantity', 9 done() ) it "should throw authorization error on reserving a deal, as invalid token is passed", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/reservation'). send({token: 'wrongtoken'}). end (err, res) -> res.should.have.status 403 done() it "should not make a reservation if deal quantity is consumed", (done) -> server. post(apiPreffix + '/deals/' + deal2._id + '/reservation'). send({token: token}). end (err, res) -> res.should.have.status 410 done() it "should throw error when dreserved deal does not exist", (done) -> server. post(apiPreffix + '/deals/notexistantdeal/reservation'). send({token: token}). end (err, res) -> res.should.have.status 404 done() it "should return the reservations for a user", (done) -> server. post(apiPreffix + '/users/reservations'). send({token: token}). end (err, res) -> allReservations = JSON.parse(res.text) allReservations.should.have.length 1 res.should.have.status 200 done() it "should throw authorization error on returning, as invalid token is passed", (done) -> server. post(apiPreffix + '/users/reservations'). send({token: 'wrongtoken'}). end (err, res) -> res.should.have.status 403 done() it "should throw authorization error on returning, as no token is passed", (done) -> server. post(apiPreffix + '/users/reservations'). send(). end (err, res) -> res.should.have.status 403 done() it "should still be able to retrieve the current user", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 200 done() it "should log out current user", (done) -> server. del(apiPreffix + '/users/session'). send({token: token}). end (err, res) -> res.should.have.status 200 done() it "should NOT be able to retrieve the current user, as user is logged out", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 403 done() it "should be able to give access to a new token", (done) -> newUser = new User( email: 'thisemail@mail.com', password: '123456', firstName: 'this user' ) newUser.save ( (err) -> newToken = new Token( token : Math.random() * 16 user : newUser last_access : new Date() ) newToken.save( (err) -> server. get(apiPreffix + '/users'). send({token: newToken._id}). end (err, res) -> res.should.have.status 200 done() ) ) it "should be able to give access to a valid lasting token", (done) -> newUser = new User( email: 'thisemail2@mail.com', password: '123456', firstName: 'this user' ) newUser.save ( (err) -> newToken = new Token( token : Math.random() * 16 user : newUser last_access : new Date(new Date() - (5 * 60000)) ) newToken.save( (err) -> server. get(apiPreffix + '/users'). send({token: newToken._id}). end (err, res) -> res.should.have.status 200 done() ) ) it "should NOT be able to give access to a expired token", (done) -> newUser = new User( email: 'thisemail3@mail.com', password: '123456', firstName: 'this user' ) newUser.save ( (err) -> newToken = new Token( token : Math.random() * 16 user : newUser last_access : new Date(new Date() - (21 * 60000)) ) newToken.save( (err) -> server. get(apiPreffix + '/users'). send({token: newToken._id}). end (err, res) -> res.should.have.status 403 done() ) ) after (done) -> #Token.remove().exec() User.remove().exec() Deal.remove().exec() Shop.remove().exec() Reservation.remove().exec() done()
209551
should = require "should" app = require "../../server" mongoose = require "mongoose" request = require "supertest" User = mongoose.model "User" Shop = mongoose.model "Shop" Deal = mongoose.model "Deal" Token = mongoose.model "Token" Reservation = mongoose.model "Reservation" server = request.agent(app) apiPreffix = '/mobile/v1' describe "Mobile API testing", -> token = {} userOfApplication = name: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>', radius: 10000 userWithSameEmail = name: '<NAME> 2', email: '<EMAIL>', password: '<PASSWORD>', radius: 10000 userWithDifferentEmail = name: '<NAME> 2', email: '<EMAIL>', password: '<PASSWORD>', radius: 10000 shop1 = new Shop( name: 'Shop 1' email: '<EMAIL>' password: '<PASSWORD>', loc: latitude: 0, longitude: 0 ) shop2 = new Shop( name: 'Shop 2' email: '<EMAIL>' password: '<PASSWORD>', loc: latitude: 10, longitude: 10 ) deal1 = new Deal( name: 'Deal 1', price: 2, gertuprice: 1, discount: 0.5, shop: shop1, quantity: 10) deal2 = new Deal( name: 'Deal 2', price: 4, gertuprice: 1, discount: 0.75, shop: shop1, quantity: 0) deal3 = new Deal( name: 'Deal 3', price: 4, gertuprice: 1, discount: 0.75, shop: shop2, quantity: 5) before (done) -> User.remove().exec() Deal.remove().exec() Shop.remove().exec() Token.remove().exec() Reservation.remove().exec() shop1.save( (err) -> shop2.save( (err) -> deal1.save( (err) -> deal2.save( (err) -> deal3.save( (err) -> done() ) ) ) ) ) it "should signup a new user", (done) -> server. post(apiPreffix + '/users'). send(userOfApplication). end (err, res) -> res.should.have.status 200 token = JSON.parse(res.text).token token.should.not.be.undefined done() it "should not signup a user with a existant email", (done) -> server. post(apiPreffix + '/users'). send(userWithSameEmail). end (err, res) -> res.should.have.status 409 res.text.should.include 11000 done() it "should signup a new user with different email", (done) -> server. post(apiPreffix + '/users'). send(userWithDifferentEmail). end (err, res) -> res.should.have.status 200 done() it "should NOT signin a non existant user", (done) -> server. post(apiPreffix + '/users/session'). send({email: '<EMAIL>', password: '<PASSWORD>'}). end (err, res) -> res.should.have.status 403 done() it "should NOT signin the newly created user with a wrong password", (done) -> server. post(apiPreffix + '/users/session'). send({email: userOfApplication.email, password: '<PASSWORD>'}). end (err, res) -> res.should.have.status 403 done() it "should signin the newly created user", (done) -> server. post(apiPreffix + '/users/session'). send({email: userOfApplication.email, password: <PASSWORD>}). end (err, res) -> res.should.have.status 200 userOfApplication._id = JSON.parse(res.text)._id token = JSON.parse(res.text).token done() it "should be a token for the logged in user", (done) -> Token.find({_id: token}).exec( (err, tokens) -> tokens.should.not.be.undefined tokens.should.have.length 1 done() ) it "should return the current user", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 200 res.text.should.include userOfApplication.email done() it "should change info in the current user", (done) -> userOfApplication.name = 'new name' server. put(apiPreffix + '/users'). send({firstName: '<NAME>', email: '<EMAIL>', token: token}). end (err, res) -> res.should.have.status 200 res.text.should.include 'new name' done() it "should throw authorization error on logging out, as no token has been passed", (done) -> server. del(apiPreffix + '/users/session'). send(). end (err, res) -> res.should.have.status 403 done() it "should throw authorization error on returning the current user, as no token is passed", (done) -> server. get(apiPreffix + '/users'). send(). end (err, res) -> res.should.have.status 403 done() it "should NOT return the current user, as there is no user logged in", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 200 res.text.should.not.include userOfApplication.email done() it "should return 3 deals when 3 are present", (done) -> server. get(apiPreffix + '/deals'). send(). end (err, res) -> res.should.have.status 200 allDeals = JSON.parse(res.text) allDeals.should.not.have.length 4 allDeals.should.have.length 3 done() it "should return first deal when requested", (done) -> deal1.save( (err) -> server. get(apiPreffix + '/deals/' + deal1._id). send(). end (err, res) -> res.should.have.status 200 res.text.should.include deal1.name res.text.should.include deal1._id done() ) it "should return 2 near deals when user is at position", (done) -> server. post(apiPreffix + '/deals'). send({longitude: 0, latitude: 0, token: token}). end (err, res) -> res.should.have.status 200 allDeals = JSON.parse(res.text) allDeals.should.not.have.length 3 allDeals.should.have.length 2 done() it "should throw authorization error on commenting a deal, as no token is passed", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({comment: 'new comment', rating: 5}). end (err, res) -> res.should.have.status 403 done() it "should throw authorization error on commenting a deal, as invalid token is passed", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({token: '<KEY>', comment: 'new comment', rating: 5}). end (err, res) -> res.should.have.status 403 done() it "should NOT add a comment in a deal if comments and rating are ommitted", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({token: token}). end (err, res) -> res.should.have.status 400 done() it "should add a comment in a deal", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({token: token, comment: 'new comment', rating: 5}). end (err, res) -> returnedDeal = JSON.parse(res.text) res.should.have.status 200 returnedDeal.comments.should.have.length 1 done() it "should make a reservation for a deal", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/reservation'). send({token: token}). end (err, res) -> returnedReservation = JSON.parse(res.text) res.should.have.status 200 returnedReservation.should.have.property "_id" done() it "should mark one less item in quantity allowed for a deal", (done) -> Deal.findOne({_id: deal1._id}).exec( (err, deal) -> deal.should.not.be.undefined deal.should.have.property 'quantity', 9 done() ) it "should throw authorization error on reserving a deal, as invalid token is passed", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/reservation'). send({token: 'wrongtoken'}). end (err, res) -> res.should.have.status 403 done() it "should not make a reservation if deal quantity is consumed", (done) -> server. post(apiPreffix + '/deals/' + deal2._id + '/reservation'). send({token: token}). end (err, res) -> res.should.have.status 410 done() it "should throw error when dreserved deal does not exist", (done) -> server. post(apiPreffix + '/deals/notexistantdeal/reservation'). send({token: token}). end (err, res) -> res.should.have.status 404 done() it "should return the reservations for a user", (done) -> server. post(apiPreffix + '/users/reservations'). send({token: token}). end (err, res) -> allReservations = JSON.parse(res.text) allReservations.should.have.length 1 res.should.have.status 200 done() it "should throw authorization error on returning, as invalid token is passed", (done) -> server. post(apiPreffix + '/users/reservations'). send({token: 'wrongtoken'}). end (err, res) -> res.should.have.status 403 done() it "should throw authorization error on returning, as no token is passed", (done) -> server. post(apiPreffix + '/users/reservations'). send(). end (err, res) -> res.should.have.status 403 done() it "should still be able to retrieve the current user", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 200 done() it "should log out current user", (done) -> server. del(apiPreffix + '/users/session'). send({token: token}). end (err, res) -> res.should.have.status 200 done() it "should NOT be able to retrieve the current user, as user is logged out", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 403 done() it "should be able to give access to a new token", (done) -> newUser = new User( email: '<EMAIL>', password: '<PASSWORD>', firstName: '<NAME>' ) newUser.save ( (err) -> newToken = new Token( token : Math.random() * 16 user : newUser last_access : new Date() ) newToken.save( (err) -> server. get(apiPreffix + '/users'). send({token: newToken._id}). end (err, res) -> res.should.have.status 200 done() ) ) it "should be able to give access to a valid lasting token", (done) -> newUser = new User( email: '<EMAIL>', password: '<PASSWORD>', firstName: 'this user' ) newUser.save ( (err) -> newToken = new Token( token : Math.random() * 16 user : newUser last_access : new Date(new Date() - (5 * 60000)) ) newToken.save( (err) -> server. get(apiPreffix + '/users'). send({token: newToken._id}). end (err, res) -> res.should.have.status 200 done() ) ) it "should NOT be able to give access to a expired token", (done) -> newUser = new User( email: '<EMAIL>', password: '<PASSWORD>', firstName: 'this user' ) newUser.save ( (err) -> newToken = new Token( token : Math.random() * 16 user : newUser last_access : new Date(new Date() - (21 * 60000)) ) newToken.save( (err) -> server. get(apiPreffix + '/users'). send({token: newToken._id}). end (err, res) -> res.should.have.status 403 done() ) ) after (done) -> #Token.remove().exec() User.remove().exec() Deal.remove().exec() Shop.remove().exec() Reservation.remove().exec() done()
true
should = require "should" app = require "../../server" mongoose = require "mongoose" request = require "supertest" User = mongoose.model "User" Shop = mongoose.model "Shop" Deal = mongoose.model "Deal" Token = mongoose.model "Token" Reservation = mongoose.model "Reservation" server = request.agent(app) apiPreffix = '/mobile/v1' describe "Mobile API testing", -> token = {} userOfApplication = name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', radius: 10000 userWithSameEmail = name: 'PI:NAME:<NAME>END_PI 2', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', radius: 10000 userWithDifferentEmail = name: 'PI:NAME:<NAME>END_PI 2', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', radius: 10000 shop1 = new Shop( name: 'Shop 1' email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI', loc: latitude: 0, longitude: 0 ) shop2 = new Shop( name: 'Shop 2' email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI', loc: latitude: 10, longitude: 10 ) deal1 = new Deal( name: 'Deal 1', price: 2, gertuprice: 1, discount: 0.5, shop: shop1, quantity: 10) deal2 = new Deal( name: 'Deal 2', price: 4, gertuprice: 1, discount: 0.75, shop: shop1, quantity: 0) deal3 = new Deal( name: 'Deal 3', price: 4, gertuprice: 1, discount: 0.75, shop: shop2, quantity: 5) before (done) -> User.remove().exec() Deal.remove().exec() Shop.remove().exec() Token.remove().exec() Reservation.remove().exec() shop1.save( (err) -> shop2.save( (err) -> deal1.save( (err) -> deal2.save( (err) -> deal3.save( (err) -> done() ) ) ) ) ) it "should signup a new user", (done) -> server. post(apiPreffix + '/users'). send(userOfApplication). end (err, res) -> res.should.have.status 200 token = JSON.parse(res.text).token token.should.not.be.undefined done() it "should not signup a user with a existant email", (done) -> server. post(apiPreffix + '/users'). send(userWithSameEmail). end (err, res) -> res.should.have.status 409 res.text.should.include 11000 done() it "should signup a new user with different email", (done) -> server. post(apiPreffix + '/users'). send(userWithDifferentEmail). end (err, res) -> res.should.have.status 200 done() it "should NOT signin a non existant user", (done) -> server. post(apiPreffix + '/users/session'). send({email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}). end (err, res) -> res.should.have.status 403 done() it "should NOT signin the newly created user with a wrong password", (done) -> server. post(apiPreffix + '/users/session'). send({email: userOfApplication.email, password: 'PI:PASSWORD:<PASSWORD>END_PI'}). end (err, res) -> res.should.have.status 403 done() it "should signin the newly created user", (done) -> server. post(apiPreffix + '/users/session'). send({email: userOfApplication.email, password: PI:PASSWORD:<PASSWORD>END_PI}). end (err, res) -> res.should.have.status 200 userOfApplication._id = JSON.parse(res.text)._id token = JSON.parse(res.text).token done() it "should be a token for the logged in user", (done) -> Token.find({_id: token}).exec( (err, tokens) -> tokens.should.not.be.undefined tokens.should.have.length 1 done() ) it "should return the current user", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 200 res.text.should.include userOfApplication.email done() it "should change info in the current user", (done) -> userOfApplication.name = 'new name' server. put(apiPreffix + '/users'). send({firstName: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI', token: token}). end (err, res) -> res.should.have.status 200 res.text.should.include 'new name' done() it "should throw authorization error on logging out, as no token has been passed", (done) -> server. del(apiPreffix + '/users/session'). send(). end (err, res) -> res.should.have.status 403 done() it "should throw authorization error on returning the current user, as no token is passed", (done) -> server. get(apiPreffix + '/users'). send(). end (err, res) -> res.should.have.status 403 done() it "should NOT return the current user, as there is no user logged in", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 200 res.text.should.not.include userOfApplication.email done() it "should return 3 deals when 3 are present", (done) -> server. get(apiPreffix + '/deals'). send(). end (err, res) -> res.should.have.status 200 allDeals = JSON.parse(res.text) allDeals.should.not.have.length 4 allDeals.should.have.length 3 done() it "should return first deal when requested", (done) -> deal1.save( (err) -> server. get(apiPreffix + '/deals/' + deal1._id). send(). end (err, res) -> res.should.have.status 200 res.text.should.include deal1.name res.text.should.include deal1._id done() ) it "should return 2 near deals when user is at position", (done) -> server. post(apiPreffix + '/deals'). send({longitude: 0, latitude: 0, token: token}). end (err, res) -> res.should.have.status 200 allDeals = JSON.parse(res.text) allDeals.should.not.have.length 3 allDeals.should.have.length 2 done() it "should throw authorization error on commenting a deal, as no token is passed", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({comment: 'new comment', rating: 5}). end (err, res) -> res.should.have.status 403 done() it "should throw authorization error on commenting a deal, as invalid token is passed", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({token: 'PI:KEY:<KEY>END_PI', comment: 'new comment', rating: 5}). end (err, res) -> res.should.have.status 403 done() it "should NOT add a comment in a deal if comments and rating are ommitted", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({token: token}). end (err, res) -> res.should.have.status 400 done() it "should add a comment in a deal", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/comment'). send({token: token, comment: 'new comment', rating: 5}). end (err, res) -> returnedDeal = JSON.parse(res.text) res.should.have.status 200 returnedDeal.comments.should.have.length 1 done() it "should make a reservation for a deal", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/reservation'). send({token: token}). end (err, res) -> returnedReservation = JSON.parse(res.text) res.should.have.status 200 returnedReservation.should.have.property "_id" done() it "should mark one less item in quantity allowed for a deal", (done) -> Deal.findOne({_id: deal1._id}).exec( (err, deal) -> deal.should.not.be.undefined deal.should.have.property 'quantity', 9 done() ) it "should throw authorization error on reserving a deal, as invalid token is passed", (done) -> server. post(apiPreffix + '/deals/' + deal1._id + '/reservation'). send({token: 'wrongtoken'}). end (err, res) -> res.should.have.status 403 done() it "should not make a reservation if deal quantity is consumed", (done) -> server. post(apiPreffix + '/deals/' + deal2._id + '/reservation'). send({token: token}). end (err, res) -> res.should.have.status 410 done() it "should throw error when dreserved deal does not exist", (done) -> server. post(apiPreffix + '/deals/notexistantdeal/reservation'). send({token: token}). end (err, res) -> res.should.have.status 404 done() it "should return the reservations for a user", (done) -> server. post(apiPreffix + '/users/reservations'). send({token: token}). end (err, res) -> allReservations = JSON.parse(res.text) allReservations.should.have.length 1 res.should.have.status 200 done() it "should throw authorization error on returning, as invalid token is passed", (done) -> server. post(apiPreffix + '/users/reservations'). send({token: 'wrongtoken'}). end (err, res) -> res.should.have.status 403 done() it "should throw authorization error on returning, as no token is passed", (done) -> server. post(apiPreffix + '/users/reservations'). send(). end (err, res) -> res.should.have.status 403 done() it "should still be able to retrieve the current user", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 200 done() it "should log out current user", (done) -> server. del(apiPreffix + '/users/session'). send({token: token}). end (err, res) -> res.should.have.status 200 done() it "should NOT be able to retrieve the current user, as user is logged out", (done) -> server. get(apiPreffix + '/users'). send({token: token}). end (err, res) -> res.should.have.status 403 done() it "should be able to give access to a new token", (done) -> newUser = new User( email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', firstName: 'PI:NAME:<NAME>END_PI' ) newUser.save ( (err) -> newToken = new Token( token : Math.random() * 16 user : newUser last_access : new Date() ) newToken.save( (err) -> server. get(apiPreffix + '/users'). send({token: newToken._id}). end (err, res) -> res.should.have.status 200 done() ) ) it "should be able to give access to a valid lasting token", (done) -> newUser = new User( email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', firstName: 'this user' ) newUser.save ( (err) -> newToken = new Token( token : Math.random() * 16 user : newUser last_access : new Date(new Date() - (5 * 60000)) ) newToken.save( (err) -> server. get(apiPreffix + '/users'). send({token: newToken._id}). end (err, res) -> res.should.have.status 200 done() ) ) it "should NOT be able to give access to a expired token", (done) -> newUser = new User( email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', firstName: 'this user' ) newUser.save ( (err) -> newToken = new Token( token : Math.random() * 16 user : newUser last_access : new Date(new Date() - (21 * 60000)) ) newToken.save( (err) -> server. get(apiPreffix + '/users'). send({token: newToken._id}). end (err, res) -> res.should.have.status 403 done() ) ) after (done) -> #Token.remove().exec() User.remove().exec() Deal.remove().exec() Shop.remove().exec() Reservation.remove().exec() done()
[ { "context": "nito - Finite State Machines \n# Copyright (c) 2014 Jon Nordby <jononor@gmail.com>\n# Finito may be freely distri", "end": 65, "score": 0.999817967414856, "start": 55, "tag": "NAME", "value": "Jon Nordby" }, { "context": " State Machines \n# Copyright (c) 2014 Jon Nordby <jononor@gmail.com>\n# Finito may be freely distributed under the MIT", "end": 84, "score": 0.9999328851699829, "start": 67, "tag": "EMAIL", "value": "jononor@gmail.com" } ]
test/Fsm.coffee
jonnor/finito
5
# Finito - Finite State Machines # Copyright (c) 2014 Jon Nordby <jononor@gmail.com> # Finito may be freely distributed under the MIT license ## if typeof process isnt 'undefined' and process.execPath and process.execPath.indexOf('node') isnt -1 finito = require '../' chai = require 'chai' path = require 'path' else finito = require '../build/finito' chai = window.chai finito.Definition.validate = true # TODO: make possible to run in browser, fetching data using HTTP add_equivalance_test = (basepath) -> fsmfile = path.join path.resolve __dirname, '..', basepath+'.fsm' jsonfile = path.join path.resolve __dirname, '..', basepath+'.json' describe 'FSM DSL: ' + basepath, -> json = null fsm = null before (finish) -> finito.Definition.fromFile fsmfile, (err, res) -> return finish err if err fsm = res finito.Definition.fromFile jsonfile, (err, res) -> return finish err if err json = res return finish null describe 'parsing the .fsm and .json definitions', (finish) -> it 'initial state should be equal', -> chai.expect(fsm.data.initial.state).to.equal json.data.initial.state it 'number of states should be equal', -> chai.expect(fsm.data.states.length).to.equal json.data.states.length it 'number of transitions should be equal', -> chai.expect(fsm.data.transitions.length).to.equal json.data.transitions.length # Data-driven tests cases = [ 'examples/first/machine' 'examples/trafficlights/machine' ] for data in cases add_equivalance_test data
117289
# Finito - Finite State Machines # Copyright (c) 2014 <NAME> <<EMAIL>> # Finito may be freely distributed under the MIT license ## if typeof process isnt 'undefined' and process.execPath and process.execPath.indexOf('node') isnt -1 finito = require '../' chai = require 'chai' path = require 'path' else finito = require '../build/finito' chai = window.chai finito.Definition.validate = true # TODO: make possible to run in browser, fetching data using HTTP add_equivalance_test = (basepath) -> fsmfile = path.join path.resolve __dirname, '..', basepath+'.fsm' jsonfile = path.join path.resolve __dirname, '..', basepath+'.json' describe 'FSM DSL: ' + basepath, -> json = null fsm = null before (finish) -> finito.Definition.fromFile fsmfile, (err, res) -> return finish err if err fsm = res finito.Definition.fromFile jsonfile, (err, res) -> return finish err if err json = res return finish null describe 'parsing the .fsm and .json definitions', (finish) -> it 'initial state should be equal', -> chai.expect(fsm.data.initial.state).to.equal json.data.initial.state it 'number of states should be equal', -> chai.expect(fsm.data.states.length).to.equal json.data.states.length it 'number of transitions should be equal', -> chai.expect(fsm.data.transitions.length).to.equal json.data.transitions.length # Data-driven tests cases = [ 'examples/first/machine' 'examples/trafficlights/machine' ] for data in cases add_equivalance_test data
true
# Finito - Finite State Machines # Copyright (c) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Finito may be freely distributed under the MIT license ## if typeof process isnt 'undefined' and process.execPath and process.execPath.indexOf('node') isnt -1 finito = require '../' chai = require 'chai' path = require 'path' else finito = require '../build/finito' chai = window.chai finito.Definition.validate = true # TODO: make possible to run in browser, fetching data using HTTP add_equivalance_test = (basepath) -> fsmfile = path.join path.resolve __dirname, '..', basepath+'.fsm' jsonfile = path.join path.resolve __dirname, '..', basepath+'.json' describe 'FSM DSL: ' + basepath, -> json = null fsm = null before (finish) -> finito.Definition.fromFile fsmfile, (err, res) -> return finish err if err fsm = res finito.Definition.fromFile jsonfile, (err, res) -> return finish err if err json = res return finish null describe 'parsing the .fsm and .json definitions', (finish) -> it 'initial state should be equal', -> chai.expect(fsm.data.initial.state).to.equal json.data.initial.state it 'number of states should be equal', -> chai.expect(fsm.data.states.length).to.equal json.data.states.length it 'number of transitions should be equal', -> chai.expect(fsm.data.transitions.length).to.equal json.data.transitions.length # Data-driven tests cases = [ 'examples/first/machine' 'examples/trafficlights/machine' ] for data in cases add_equivalance_test data
[ { "context": "ss_key,\n new_credential:this.attr('password'),\n partner_code: 'tmus'\n ", "end": 7775, "score": 0.6003761291503906, "start": 7767, "tag": "PASSWORD", "value": "password" } ]
models/user/user.coffee
signonsridhar/sridhar_hbs
0
define(['bases/model', '_', 'models/auth/auth', 'models/bundle/bundle', 'env!dev:models/user/fixture/email_uniqueness', 'env!dev:models/user/fixture/get_user', 'env!dev:models/user/fixture/delete_user', 'env!dev:models/user/fixture/remove_bundle_for_user', 'env!dev:models/user/fixture/add_bundle_for_user', 'env!dev:models/user/fixture/set_name' 'env!dev:models/user/fixture/change_user_email' 'env!dev:models/user/fixture/confirm_reset_credential' ], (BaseModel, _, Auth, Bundle)-> password_format_check = (password)-> special_chars = "! @ # $ % ^ & * ( ) - _ = + , < . > [ { ] } | ~".split(' ') has_number = false has_alpha = false has_invalid_char = false len = password.length if len < 8 or len > 16 return false for i in [0..len] #this.check(password, VALID.ERROR.FORMAT).regex(/^(?=.*[_$@.])(?=.*[^_$@.])[\w$@.]{8,15}$/) raw_val = password[i] int_val = parseInt(raw_val) #console.log('int_val', int_val) if !_.isNaN(int_val) and int_val >= 0 and int_val <= 9 has_number = true if /^[a-zA-Z()]$/.test(raw_val) has_alpha = true #console.log('invalid_char', /^[a-z0-9]+$/i.test(raw_val), special_chars.indexOf(raw_val)) if !(/^[a-z0-9]+$/i.test(raw_val)) and special_chars.indexOf(raw_val) < 0 has_invalid_char = true if !(has_alpha and has_number) or has_invalid_char return false else return true User = BaseModel.extend({ id:'userid' TYPE:'USER', get_authenticated_user:(auth = null)-> auth = Auth.get_auth() if not auth? access_key = auth.get_access_key() user_id = auth.get_user_id() $.get("/bss/user?action=getuser&accesskeyid=#{access_key}&userid=#{user_id}").then((response)-> data = response.data code = response.code return new User(data) ) },{ init:()-> this.setup_validations() this.debounced_validate_email_unique = _.debounce(()=> this.is_email_unique().then((status)=> this.validity('email', status) ) , 300) is_email_unique:()-> user_id = auth.get_user_id() if auth? $.get('/bss/authentication?action=checkcredentialavailability', {identification: this.attr('email'), user_id: user_id}) .then((response)=> if response.data == "true" then VALID.YES else VALID.ERROR.UNIQUE ).fail((response)=> this.validity('email', VALID.ERROR.INVALID) ) validations:{ first_name:()-> first_name = this.attr('first_name') this.check(first_name, VALID.ERROR.REQUIRED).notEmpty() this.check(first_name, VALID.ERROR.SIZE).len(2, 40) this.check(first_name, VALID.ERROR.FORMAT).regex('^[-a-zA-Z0-9.,&()!?-@\' ]*$') this.validity('first_name', VALID.YES) last_name:()-> last_name = this.attr('last_name') this.check(last_name, VALID.ERROR.REQUIRED).notEmpty() this.check(last_name, VALID.ERROR.SIZE).len(2, 40) this.check(last_name, VALID.ERROR.FORMAT).regex('^[-a-zA-Z0-9.,&()!?-@\' ]*$') this.validity('last_name', VALID.YES) phone:()-> phone = this.attr('phone') this.check(phone, VALID.ERROR.REQUIRED).notEmpty() ### this.check(phone, VALID.ERROR.FORMAT).isNumeric().len(10) ### this.validity('phone', VALID.YES) email:()-> email = this.attr('email') this.check(email, VALID.ERROR.REQUIRED).notEmpty() this.check(email, VALID.ERROR.SIZE).len(3, 70) this.check(email, VALID.ERROR.FORMAT).regex("^\\s*[_+A-Za-z0-9-]+(\\.[_+A-Za-z0-9-]+)*@[A-Za-z0-9.-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})\\s*$") this.debounced_validate_email_unique() valid_email_format:()-> email = this.attr('valid_email_format') this.check(email, VALID.ERROR.REQUIRED).notEmpty() this.check(email, VALID.ERROR.SIZE).len(3, 70) this.check(email, VALID.ERROR.FORMAT).regex("^\\s*[_+A-Za-z0-9-]+(\\.[_+A-Za-z0-9-]+)*@[A-Za-z0-9.-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})\\s*$") this.validity('valid_email_format', VALID.YES) confirm_email:()-> confirm_email = this.attr('confirm_email') this.check(confirm_email, VALID.ERROR.REQUIRED).notEmpty() this.check(confirm_email, VALID.ERROR.SIZE).len(3, 70) this.check(email, VALID.ERROR.FORMAT).regex("^\\s*[_+A-Za-z0-9-]+(\\.[_+A-Za-z0-9-]+)*@[A-Za-z0-9.-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})\\s*$") if this.attr('email') == this.attr('confirm_email') this.validity('confirm_email', VALID.YES) else this.validity('confirm_email', VALID.ERROR.EQUAL) password:()-> password = this.attr('password') this.check(password, VALID.ERROR.REQUIRED).notEmpty() if not password_format_check(password) this.validity('password', VALID.ERROR.FORMAT) return this.validity('password', VALID.YES) confirm_password:()-> password = this.attr('confirm_password') this.check(password, VALID.ERROR.REQUIRED).notEmpty() if not password_format_check(password) console.log(' IS IT HERE????', password) this.validity('confirm_password', VALID.ERROR.FORMAT) return result = if this.attr('password') == this.attr('confirm_password') then VALID.YES else VALID.ERROR.EQUAL this.validity('confirm_password', result) } get_bundles:()-> $.get('/bss/user?action=getuser', {userid: this.attr('userid') }).then (response)-> bundles = response.data.bundles BaseModel.models.call(Bundle, bundles) get_name:()-> this.full_name() full_name:can.compute(()-> return this.attr("first_name") + ' ' + this.attr('last_name') ) delete_item:()-> $.get('/bss/user?action=deleteuser', {userid: this.attr('userid') }) remove_bundle_for_user:(bundleid)-> $.get('/bss/user?action=removebundleforuser', {userid: this.attr('userid'), bundleid: bundleid } ) add_bundle_for_user:(bundle_ids)-> addUserWithBundleReq ={} addUserWithBundleReq.user_id = this.attr('userid') addUserWithBundleReq.bundle_ids = bundle_ids $.post('/bss/user?action=addbundleforuser', JSON.stringify(addUserWithBundleReq) ) set_name:()-> $.get('/bss/user?action=setname', {userid: this.attr('userid'), firstname: this.attr('first_name'), lastname: this.attr('last_name') } ) set_email:()-> $.get('/bss/authentication?action=changeuseremail', {userid: this.attr('userid'), email: this.attr('email')} ) set_password: (access_key)-> req = { temporary_token : access_key, new_credential:this.attr('password'), partner_code: 'tmus' } $.post('/bss/authentication?action=confirmresetcredential', JSON.stringify(req)) ### userid: identification: old_credential: new_credential: ### update_password:(form_data)-> #/bss/authentication?action=setcredential&accesskeyid=&userid=&identification=&old_credential=&new_credential= req = { identification: this.attr('user.email'), old_credential: form_data.old_credential, new_credential: form_data.new_credential, partner_code: 'tmus' } $.post('/bss/authentication?action=setcredential', JSON.stringify(req)) get_all_extensions_chained:()-> _.chain(this.bundles).pluck('extensions').compact().pluck(0).flatten().compact() get_first_extension_number:()-> this.get_all_extensions_chained().first().pick('extension_number').value().extension_number save_security: (access_key)-> req = { temporary_token : access_key, new_credential:this.attr('password'), partner_code: 'tmus', security_questions: this.value('security_questions') } $.post('/bss/authentication?action=savesecuritysetup', JSON.stringify(req)) }) )
104649
define(['bases/model', '_', 'models/auth/auth', 'models/bundle/bundle', 'env!dev:models/user/fixture/email_uniqueness', 'env!dev:models/user/fixture/get_user', 'env!dev:models/user/fixture/delete_user', 'env!dev:models/user/fixture/remove_bundle_for_user', 'env!dev:models/user/fixture/add_bundle_for_user', 'env!dev:models/user/fixture/set_name' 'env!dev:models/user/fixture/change_user_email' 'env!dev:models/user/fixture/confirm_reset_credential' ], (BaseModel, _, Auth, Bundle)-> password_format_check = (password)-> special_chars = "! @ # $ % ^ & * ( ) - _ = + , < . > [ { ] } | ~".split(' ') has_number = false has_alpha = false has_invalid_char = false len = password.length if len < 8 or len > 16 return false for i in [0..len] #this.check(password, VALID.ERROR.FORMAT).regex(/^(?=.*[_$@.])(?=.*[^_$@.])[\w$@.]{8,15}$/) raw_val = password[i] int_val = parseInt(raw_val) #console.log('int_val', int_val) if !_.isNaN(int_val) and int_val >= 0 and int_val <= 9 has_number = true if /^[a-zA-Z()]$/.test(raw_val) has_alpha = true #console.log('invalid_char', /^[a-z0-9]+$/i.test(raw_val), special_chars.indexOf(raw_val)) if !(/^[a-z0-9]+$/i.test(raw_val)) and special_chars.indexOf(raw_val) < 0 has_invalid_char = true if !(has_alpha and has_number) or has_invalid_char return false else return true User = BaseModel.extend({ id:'userid' TYPE:'USER', get_authenticated_user:(auth = null)-> auth = Auth.get_auth() if not auth? access_key = auth.get_access_key() user_id = auth.get_user_id() $.get("/bss/user?action=getuser&accesskeyid=#{access_key}&userid=#{user_id}").then((response)-> data = response.data code = response.code return new User(data) ) },{ init:()-> this.setup_validations() this.debounced_validate_email_unique = _.debounce(()=> this.is_email_unique().then((status)=> this.validity('email', status) ) , 300) is_email_unique:()-> user_id = auth.get_user_id() if auth? $.get('/bss/authentication?action=checkcredentialavailability', {identification: this.attr('email'), user_id: user_id}) .then((response)=> if response.data == "true" then VALID.YES else VALID.ERROR.UNIQUE ).fail((response)=> this.validity('email', VALID.ERROR.INVALID) ) validations:{ first_name:()-> first_name = this.attr('first_name') this.check(first_name, VALID.ERROR.REQUIRED).notEmpty() this.check(first_name, VALID.ERROR.SIZE).len(2, 40) this.check(first_name, VALID.ERROR.FORMAT).regex('^[-a-zA-Z0-9.,&()!?-@\' ]*$') this.validity('first_name', VALID.YES) last_name:()-> last_name = this.attr('last_name') this.check(last_name, VALID.ERROR.REQUIRED).notEmpty() this.check(last_name, VALID.ERROR.SIZE).len(2, 40) this.check(last_name, VALID.ERROR.FORMAT).regex('^[-a-zA-Z0-9.,&()!?-@\' ]*$') this.validity('last_name', VALID.YES) phone:()-> phone = this.attr('phone') this.check(phone, VALID.ERROR.REQUIRED).notEmpty() ### this.check(phone, VALID.ERROR.FORMAT).isNumeric().len(10) ### this.validity('phone', VALID.YES) email:()-> email = this.attr('email') this.check(email, VALID.ERROR.REQUIRED).notEmpty() this.check(email, VALID.ERROR.SIZE).len(3, 70) this.check(email, VALID.ERROR.FORMAT).regex("^\\s*[_+A-Za-z0-9-]+(\\.[_+A-Za-z0-9-]+)*@[A-Za-z0-9.-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})\\s*$") this.debounced_validate_email_unique() valid_email_format:()-> email = this.attr('valid_email_format') this.check(email, VALID.ERROR.REQUIRED).notEmpty() this.check(email, VALID.ERROR.SIZE).len(3, 70) this.check(email, VALID.ERROR.FORMAT).regex("^\\s*[_+A-Za-z0-9-]+(\\.[_+A-Za-z0-9-]+)*@[A-Za-z0-9.-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})\\s*$") this.validity('valid_email_format', VALID.YES) confirm_email:()-> confirm_email = this.attr('confirm_email') this.check(confirm_email, VALID.ERROR.REQUIRED).notEmpty() this.check(confirm_email, VALID.ERROR.SIZE).len(3, 70) this.check(email, VALID.ERROR.FORMAT).regex("^\\s*[_+A-Za-z0-9-]+(\\.[_+A-Za-z0-9-]+)*@[A-Za-z0-9.-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})\\s*$") if this.attr('email') == this.attr('confirm_email') this.validity('confirm_email', VALID.YES) else this.validity('confirm_email', VALID.ERROR.EQUAL) password:()-> password = this.attr('password') this.check(password, VALID.ERROR.REQUIRED).notEmpty() if not password_format_check(password) this.validity('password', VALID.ERROR.FORMAT) return this.validity('password', VALID.YES) confirm_password:()-> password = this.attr('confirm_password') this.check(password, VALID.ERROR.REQUIRED).notEmpty() if not password_format_check(password) console.log(' IS IT HERE????', password) this.validity('confirm_password', VALID.ERROR.FORMAT) return result = if this.attr('password') == this.attr('confirm_password') then VALID.YES else VALID.ERROR.EQUAL this.validity('confirm_password', result) } get_bundles:()-> $.get('/bss/user?action=getuser', {userid: this.attr('userid') }).then (response)-> bundles = response.data.bundles BaseModel.models.call(Bundle, bundles) get_name:()-> this.full_name() full_name:can.compute(()-> return this.attr("first_name") + ' ' + this.attr('last_name') ) delete_item:()-> $.get('/bss/user?action=deleteuser', {userid: this.attr('userid') }) remove_bundle_for_user:(bundleid)-> $.get('/bss/user?action=removebundleforuser', {userid: this.attr('userid'), bundleid: bundleid } ) add_bundle_for_user:(bundle_ids)-> addUserWithBundleReq ={} addUserWithBundleReq.user_id = this.attr('userid') addUserWithBundleReq.bundle_ids = bundle_ids $.post('/bss/user?action=addbundleforuser', JSON.stringify(addUserWithBundleReq) ) set_name:()-> $.get('/bss/user?action=setname', {userid: this.attr('userid'), firstname: this.attr('first_name'), lastname: this.attr('last_name') } ) set_email:()-> $.get('/bss/authentication?action=changeuseremail', {userid: this.attr('userid'), email: this.attr('email')} ) set_password: (access_key)-> req = { temporary_token : access_key, new_credential:this.attr('<PASSWORD>'), partner_code: 'tmus' } $.post('/bss/authentication?action=confirmresetcredential', JSON.stringify(req)) ### userid: identification: old_credential: new_credential: ### update_password:(form_data)-> #/bss/authentication?action=setcredential&accesskeyid=&userid=&identification=&old_credential=&new_credential= req = { identification: this.attr('user.email'), old_credential: form_data.old_credential, new_credential: form_data.new_credential, partner_code: 'tmus' } $.post('/bss/authentication?action=setcredential', JSON.stringify(req)) get_all_extensions_chained:()-> _.chain(this.bundles).pluck('extensions').compact().pluck(0).flatten().compact() get_first_extension_number:()-> this.get_all_extensions_chained().first().pick('extension_number').value().extension_number save_security: (access_key)-> req = { temporary_token : access_key, new_credential:this.attr('password'), partner_code: 'tmus', security_questions: this.value('security_questions') } $.post('/bss/authentication?action=savesecuritysetup', JSON.stringify(req)) }) )
true
define(['bases/model', '_', 'models/auth/auth', 'models/bundle/bundle', 'env!dev:models/user/fixture/email_uniqueness', 'env!dev:models/user/fixture/get_user', 'env!dev:models/user/fixture/delete_user', 'env!dev:models/user/fixture/remove_bundle_for_user', 'env!dev:models/user/fixture/add_bundle_for_user', 'env!dev:models/user/fixture/set_name' 'env!dev:models/user/fixture/change_user_email' 'env!dev:models/user/fixture/confirm_reset_credential' ], (BaseModel, _, Auth, Bundle)-> password_format_check = (password)-> special_chars = "! @ # $ % ^ & * ( ) - _ = + , < . > [ { ] } | ~".split(' ') has_number = false has_alpha = false has_invalid_char = false len = password.length if len < 8 or len > 16 return false for i in [0..len] #this.check(password, VALID.ERROR.FORMAT).regex(/^(?=.*[_$@.])(?=.*[^_$@.])[\w$@.]{8,15}$/) raw_val = password[i] int_val = parseInt(raw_val) #console.log('int_val', int_val) if !_.isNaN(int_val) and int_val >= 0 and int_val <= 9 has_number = true if /^[a-zA-Z()]$/.test(raw_val) has_alpha = true #console.log('invalid_char', /^[a-z0-9]+$/i.test(raw_val), special_chars.indexOf(raw_val)) if !(/^[a-z0-9]+$/i.test(raw_val)) and special_chars.indexOf(raw_val) < 0 has_invalid_char = true if !(has_alpha and has_number) or has_invalid_char return false else return true User = BaseModel.extend({ id:'userid' TYPE:'USER', get_authenticated_user:(auth = null)-> auth = Auth.get_auth() if not auth? access_key = auth.get_access_key() user_id = auth.get_user_id() $.get("/bss/user?action=getuser&accesskeyid=#{access_key}&userid=#{user_id}").then((response)-> data = response.data code = response.code return new User(data) ) },{ init:()-> this.setup_validations() this.debounced_validate_email_unique = _.debounce(()=> this.is_email_unique().then((status)=> this.validity('email', status) ) , 300) is_email_unique:()-> user_id = auth.get_user_id() if auth? $.get('/bss/authentication?action=checkcredentialavailability', {identification: this.attr('email'), user_id: user_id}) .then((response)=> if response.data == "true" then VALID.YES else VALID.ERROR.UNIQUE ).fail((response)=> this.validity('email', VALID.ERROR.INVALID) ) validations:{ first_name:()-> first_name = this.attr('first_name') this.check(first_name, VALID.ERROR.REQUIRED).notEmpty() this.check(first_name, VALID.ERROR.SIZE).len(2, 40) this.check(first_name, VALID.ERROR.FORMAT).regex('^[-a-zA-Z0-9.,&()!?-@\' ]*$') this.validity('first_name', VALID.YES) last_name:()-> last_name = this.attr('last_name') this.check(last_name, VALID.ERROR.REQUIRED).notEmpty() this.check(last_name, VALID.ERROR.SIZE).len(2, 40) this.check(last_name, VALID.ERROR.FORMAT).regex('^[-a-zA-Z0-9.,&()!?-@\' ]*$') this.validity('last_name', VALID.YES) phone:()-> phone = this.attr('phone') this.check(phone, VALID.ERROR.REQUIRED).notEmpty() ### this.check(phone, VALID.ERROR.FORMAT).isNumeric().len(10) ### this.validity('phone', VALID.YES) email:()-> email = this.attr('email') this.check(email, VALID.ERROR.REQUIRED).notEmpty() this.check(email, VALID.ERROR.SIZE).len(3, 70) this.check(email, VALID.ERROR.FORMAT).regex("^\\s*[_+A-Za-z0-9-]+(\\.[_+A-Za-z0-9-]+)*@[A-Za-z0-9.-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})\\s*$") this.debounced_validate_email_unique() valid_email_format:()-> email = this.attr('valid_email_format') this.check(email, VALID.ERROR.REQUIRED).notEmpty() this.check(email, VALID.ERROR.SIZE).len(3, 70) this.check(email, VALID.ERROR.FORMAT).regex("^\\s*[_+A-Za-z0-9-]+(\\.[_+A-Za-z0-9-]+)*@[A-Za-z0-9.-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})\\s*$") this.validity('valid_email_format', VALID.YES) confirm_email:()-> confirm_email = this.attr('confirm_email') this.check(confirm_email, VALID.ERROR.REQUIRED).notEmpty() this.check(confirm_email, VALID.ERROR.SIZE).len(3, 70) this.check(email, VALID.ERROR.FORMAT).regex("^\\s*[_+A-Za-z0-9-]+(\\.[_+A-Za-z0-9-]+)*@[A-Za-z0-9.-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})\\s*$") if this.attr('email') == this.attr('confirm_email') this.validity('confirm_email', VALID.YES) else this.validity('confirm_email', VALID.ERROR.EQUAL) password:()-> password = this.attr('password') this.check(password, VALID.ERROR.REQUIRED).notEmpty() if not password_format_check(password) this.validity('password', VALID.ERROR.FORMAT) return this.validity('password', VALID.YES) confirm_password:()-> password = this.attr('confirm_password') this.check(password, VALID.ERROR.REQUIRED).notEmpty() if not password_format_check(password) console.log(' IS IT HERE????', password) this.validity('confirm_password', VALID.ERROR.FORMAT) return result = if this.attr('password') == this.attr('confirm_password') then VALID.YES else VALID.ERROR.EQUAL this.validity('confirm_password', result) } get_bundles:()-> $.get('/bss/user?action=getuser', {userid: this.attr('userid') }).then (response)-> bundles = response.data.bundles BaseModel.models.call(Bundle, bundles) get_name:()-> this.full_name() full_name:can.compute(()-> return this.attr("first_name") + ' ' + this.attr('last_name') ) delete_item:()-> $.get('/bss/user?action=deleteuser', {userid: this.attr('userid') }) remove_bundle_for_user:(bundleid)-> $.get('/bss/user?action=removebundleforuser', {userid: this.attr('userid'), bundleid: bundleid } ) add_bundle_for_user:(bundle_ids)-> addUserWithBundleReq ={} addUserWithBundleReq.user_id = this.attr('userid') addUserWithBundleReq.bundle_ids = bundle_ids $.post('/bss/user?action=addbundleforuser', JSON.stringify(addUserWithBundleReq) ) set_name:()-> $.get('/bss/user?action=setname', {userid: this.attr('userid'), firstname: this.attr('first_name'), lastname: this.attr('last_name') } ) set_email:()-> $.get('/bss/authentication?action=changeuseremail', {userid: this.attr('userid'), email: this.attr('email')} ) set_password: (access_key)-> req = { temporary_token : access_key, new_credential:this.attr('PI:PASSWORD:<PASSWORD>END_PI'), partner_code: 'tmus' } $.post('/bss/authentication?action=confirmresetcredential', JSON.stringify(req)) ### userid: identification: old_credential: new_credential: ### update_password:(form_data)-> #/bss/authentication?action=setcredential&accesskeyid=&userid=&identification=&old_credential=&new_credential= req = { identification: this.attr('user.email'), old_credential: form_data.old_credential, new_credential: form_data.new_credential, partner_code: 'tmus' } $.post('/bss/authentication?action=setcredential', JSON.stringify(req)) get_all_extensions_chained:()-> _.chain(this.bundles).pluck('extensions').compact().pluck(0).flatten().compact() get_first_extension_number:()-> this.get_all_extensions_chained().first().pick('extension_number').value().extension_number save_security: (access_key)-> req = { temporary_token : access_key, new_credential:this.attr('password'), partner_code: 'tmus', security_questions: this.value('security_questions') } $.post('/bss/authentication?action=savesecuritysetup', JSON.stringify(req)) }) )
[ { "context": "d.be.false\n\t\t\tvalidator.testInternal({key: [\"a\", \"s\", \"d\"]}, {rule: \"maxLength\", maxLength:2}, \"key\")", "end": 904, "score": 0.505500853061676, "start": 903, "tag": "KEY", "value": "s" }, { "context": "uld.not.be.false\n\t\t\tvalidator.testInternal({key: -223572357235}, \"nonNegative\", \"key\").should.not.be.false\n\n\t\t\tv", "end": 2467, "score": 0.9914147853851318, "start": 2455, "tag": "KEY", "value": "223572357235" }, { "context": ").should.be.false\n\t\t\tvalidator.testInternal({key: 9235472346}, \"nonNegative\", \"key\").should.be.false\n\n\tdescrib", "end": 2853, "score": 0.9992014765739441, "start": 2843, "tag": "KEY", "value": "9235472346" }, { "context": " @ruleset\n\n\t\t\tvalidator.validate({book: {author: \"Steven King\"}}, {book: 'book'}).length.should.equal 0\n\t\t\tvali", "end": 3685, "score": 0.9998477101325989, "start": 3674, "tag": "NAME", "value": "Steven King" }, { "context": "ld.equal 0\n\t\t\tvalidator.validate({book: {author: \"Steven King, Steven King, Steven King, Steven King\"}}, {book:", "end": 3778, "score": 0.999832808971405, "start": 3767, "tag": "NAME", "value": "Steven King" }, { "context": "\t\tvalidator.validate({book: {author: \"Steven King, Steven King, Steven King, Steven King\"}}, {book: 'book'}).len", "end": 3791, "score": 0.881678581237793, "start": 3780, "tag": "NAME", "value": "Steven King" }, { "context": "alidate({book: {author: \"Steven King, Steven King, Steven King, Steven King\"}}, {book: 'book'}).length.should.eq", "end": 3804, "score": 0.8093557953834534, "start": 3793, "tag": "NAME", "value": "Steven King" }, { "context": ": {author: \"Steven King, Steven King, Steven King, Steven King\"}}, {book: 'book'}).length.should.equal 1\n\t\t\tvali", "end": 3817, "score": 0.7723002433776855, "start": 3806, "tag": "NAME", "value": "Steven King" }, { "context": " agent, @ruleset\n\n\t\t\tvalidator.validate({author: \"Steven King\"}, 'book').length.should.equal 0\n\t\t\tvalidator.val", "end": 4366, "score": 0.999833881855011, "start": 4355, "tag": "NAME", "value": "Steven King" }, { "context": "\tvalidator.validate({pages: [12, 123.6], author: 'Steven'}, 'book').length.should.be.equal 1\n\t\t\tvalidator.", "end": 5059, "score": 0.9998434782028198, "start": 5053, "tag": "NAME", "value": "Steven" }, { "context": "al 1\n\t\t\tvalidator.validate({pages: [12], author: 'Steven'}, 'book').length.should.be.equal 0\n\n\t\tit \"should", "end": 5147, "score": 0.9998593926429749, "start": 5141, "tag": "NAME", "value": "Steven" } ]
test/test_validator.coffee
livechat/express-validate
1
_ = require 'underscore' sinon = require 'sinon' should = require 'should' validator = require '../src/validator' describe "Validator", ()-> describe "rules", -> it "required rule", () -> validator.testInternal({key: 5}, "required", "key").should.be.false validator.testInternal({key: {}}, "required", "key").should.be.false validator.testInternal({key: []}, "required", "key").should.be.false validator.testInternal({key: null}, "required", "key").should.not.be.false validator.testInternal({}, "required", "key").should.not.be.false it "max length rule", () -> validator.testInternal({key: "ads"}, "maxLength", "key").should.not.be.false validator.testInternal({key: "ads"}, {rule: "maxLength", maxLength:20}, "key").should.be.false validator.testInternal({key: ["ads"]}, {rule: "maxLength", maxLength:2}, "key").should.be.false validator.testInternal({key: ["a", "s", "d"]}, {rule: "maxLength", maxLength:2}, "key").should.not.be.false validator.testInternal({key: {}}, {rule: "maxLength", maxLength:2}, "key").should.not.be.false it "integer rule", () -> validator.testInternal({key: "ads"}, "integer", "key").should.not.be.false validator.testInternal({key: []}, "integer", "key").should.not.be.false validator.testInternal({key: {}}, "integer", "key").should.not.be.false validator.testInternal({key: 5.2}, "integer", "key").should.not.be.false validator.testInternal({key: -5.2}, "integer", "key").should.not.be.false validator.testInternal({key: NaN}, "integer", "key").should.not.be.false validator.testInternal({key: -Infinity}, "integer", "key").should.not.be.false validator.testInternal({key: Infinity}, "integer", "key").should.not.be.false validator.testInternal({key: 0}, "integer", "key").should.be.false validator.testInternal({key: 1}, "integer", "key").should.be.false validator.testInternal({key: -1}, "integer", "key").should.be.false validator.testInternal({key: "-1"}, "integer", "key").should.be.false validator.testInternal({key: "1"}, "integer", "key").should.be.false validator.testInternal({key: "0"}, "integer", "key").should.be.false it "non-negative rule", () -> validator.testInternal({key: "-1"}, "nonNegative", "key").should.not.be.false validator.testInternal({key: -1}, "nonNegative", "key").should.not.be.false validator.testInternal({key: -2}, "nonNegative", "key").should.not.be.false validator.testInternal({key: -223572357235}, "nonNegative", "key").should.not.be.false validator.testInternal({key: "0"}, "nonNegative", "key").should.be.false validator.testInternal({key: 0}, "nonNegative", "key").should.be.false validator.testInternal({key: 1}, "nonNegative", "key").should.be.false validator.testInternal({key: 2}, "nonNegative", "key").should.be.false validator.testInternal({key: 9235472346}, "nonNegative", "key").should.be.false describe "validate", -> it "should validate simple object", () -> validator.validate({key: "value"}, {key: "required"}).length.should.equal 0 validator.validate({key: "value"}, {key: ["required"]}).length.should.equal 0 validator.validate({key: "value"}, {key: ["required", "maxLength"]}).length.should.equal 1 validator.validate({key: "value"}, {key: ["required", {rule: "maxLength", maxLength: 30}]}).length.should.equal 0 it "should validate recurrent object", () -> validator.addRule "book", recurrent: true message: "invalid book's properties" ruleset: author: ['required', {rule: "maxLength", maxLength: 30}] pages: ['integer'] test: (agent) -> return @validate agent, @ruleset validator.validate({book: {author: "Steven King"}}, {book: 'book'}).length.should.equal 0 validator.validate({book: {author: "Steven King, Steven King, Steven King, Steven King"}}, {book: 'book'}).length.should.equal 1 validator.validate({book: {pages: 30}}, {book: 'book'}).length.should.equal 1 validator.validate({book: {pages: -123.3}}, {book: 'book'}).length.should.equal 1 it "should validate root properties", () -> validator.addRule "book", recurrent: true message: "invalid book's properties" ruleset: author: ['required', {rule: "maxLength", maxLength: 30}] pages: ['integer'] test: (agent) -> return @validate agent, @ruleset validator.validate({author: "Steven King"}, 'book').length.should.equal 0 validator.validate({pages: -123.2}, 'book').length.should.equal 2 it "should validate lists", () -> validator.validate({integers: [1,2,3.2,4.3,5]}, {integers: {rule: 'list', ruleset: 'integer'}}).length.should.equal 1 validator.validate({integers: [1,2,5]}, {integers: {rule: 'list', ruleset: 'integer'}}).length.should.equal 0 it "should validate compound object", () -> validator.addRule "book", recurrent: true message: "invalid book's properties" ruleset: author: ['required', {rule: "maxLength", maxLength: 30}] pages: {rule: 'list', ruleset: 'integer'} validator.validate({pages: [12, 123.6], author: 'Steven'}, 'book').length.should.be.equal 1 validator.validate({pages: [12], author: 'Steven'}, 'book').length.should.be.equal 0 it "should crash when rule is not found", () -> f = -> validator.validate({asdf:5}, 'missingRule') f.should.throw() f = -> validator.validate({asdf:5}, 'required') f.should.not.throw() f = -> validator.validate({asdf:5}, {asdf: [{rule:'list', ruleset: 'integer'}]}) f.should.not.throw()
83797
_ = require 'underscore' sinon = require 'sinon' should = require 'should' validator = require '../src/validator' describe "Validator", ()-> describe "rules", -> it "required rule", () -> validator.testInternal({key: 5}, "required", "key").should.be.false validator.testInternal({key: {}}, "required", "key").should.be.false validator.testInternal({key: []}, "required", "key").should.be.false validator.testInternal({key: null}, "required", "key").should.not.be.false validator.testInternal({}, "required", "key").should.not.be.false it "max length rule", () -> validator.testInternal({key: "ads"}, "maxLength", "key").should.not.be.false validator.testInternal({key: "ads"}, {rule: "maxLength", maxLength:20}, "key").should.be.false validator.testInternal({key: ["ads"]}, {rule: "maxLength", maxLength:2}, "key").should.be.false validator.testInternal({key: ["a", "<KEY>", "d"]}, {rule: "maxLength", maxLength:2}, "key").should.not.be.false validator.testInternal({key: {}}, {rule: "maxLength", maxLength:2}, "key").should.not.be.false it "integer rule", () -> validator.testInternal({key: "ads"}, "integer", "key").should.not.be.false validator.testInternal({key: []}, "integer", "key").should.not.be.false validator.testInternal({key: {}}, "integer", "key").should.not.be.false validator.testInternal({key: 5.2}, "integer", "key").should.not.be.false validator.testInternal({key: -5.2}, "integer", "key").should.not.be.false validator.testInternal({key: NaN}, "integer", "key").should.not.be.false validator.testInternal({key: -Infinity}, "integer", "key").should.not.be.false validator.testInternal({key: Infinity}, "integer", "key").should.not.be.false validator.testInternal({key: 0}, "integer", "key").should.be.false validator.testInternal({key: 1}, "integer", "key").should.be.false validator.testInternal({key: -1}, "integer", "key").should.be.false validator.testInternal({key: "-1"}, "integer", "key").should.be.false validator.testInternal({key: "1"}, "integer", "key").should.be.false validator.testInternal({key: "0"}, "integer", "key").should.be.false it "non-negative rule", () -> validator.testInternal({key: "-1"}, "nonNegative", "key").should.not.be.false validator.testInternal({key: -1}, "nonNegative", "key").should.not.be.false validator.testInternal({key: -2}, "nonNegative", "key").should.not.be.false validator.testInternal({key: -<KEY>}, "nonNegative", "key").should.not.be.false validator.testInternal({key: "0"}, "nonNegative", "key").should.be.false validator.testInternal({key: 0}, "nonNegative", "key").should.be.false validator.testInternal({key: 1}, "nonNegative", "key").should.be.false validator.testInternal({key: 2}, "nonNegative", "key").should.be.false validator.testInternal({key: <KEY>}, "nonNegative", "key").should.be.false describe "validate", -> it "should validate simple object", () -> validator.validate({key: "value"}, {key: "required"}).length.should.equal 0 validator.validate({key: "value"}, {key: ["required"]}).length.should.equal 0 validator.validate({key: "value"}, {key: ["required", "maxLength"]}).length.should.equal 1 validator.validate({key: "value"}, {key: ["required", {rule: "maxLength", maxLength: 30}]}).length.should.equal 0 it "should validate recurrent object", () -> validator.addRule "book", recurrent: true message: "invalid book's properties" ruleset: author: ['required', {rule: "maxLength", maxLength: 30}] pages: ['integer'] test: (agent) -> return @validate agent, @ruleset validator.validate({book: {author: "<NAME>"}}, {book: 'book'}).length.should.equal 0 validator.validate({book: {author: "<NAME>, <NAME>, <NAME>, <NAME>"}}, {book: 'book'}).length.should.equal 1 validator.validate({book: {pages: 30}}, {book: 'book'}).length.should.equal 1 validator.validate({book: {pages: -123.3}}, {book: 'book'}).length.should.equal 1 it "should validate root properties", () -> validator.addRule "book", recurrent: true message: "invalid book's properties" ruleset: author: ['required', {rule: "maxLength", maxLength: 30}] pages: ['integer'] test: (agent) -> return @validate agent, @ruleset validator.validate({author: "<NAME>"}, 'book').length.should.equal 0 validator.validate({pages: -123.2}, 'book').length.should.equal 2 it "should validate lists", () -> validator.validate({integers: [1,2,3.2,4.3,5]}, {integers: {rule: 'list', ruleset: 'integer'}}).length.should.equal 1 validator.validate({integers: [1,2,5]}, {integers: {rule: 'list', ruleset: 'integer'}}).length.should.equal 0 it "should validate compound object", () -> validator.addRule "book", recurrent: true message: "invalid book's properties" ruleset: author: ['required', {rule: "maxLength", maxLength: 30}] pages: {rule: 'list', ruleset: 'integer'} validator.validate({pages: [12, 123.6], author: '<NAME>'}, 'book').length.should.be.equal 1 validator.validate({pages: [12], author: '<NAME>'}, 'book').length.should.be.equal 0 it "should crash when rule is not found", () -> f = -> validator.validate({asdf:5}, 'missingRule') f.should.throw() f = -> validator.validate({asdf:5}, 'required') f.should.not.throw() f = -> validator.validate({asdf:5}, {asdf: [{rule:'list', ruleset: 'integer'}]}) f.should.not.throw()
true
_ = require 'underscore' sinon = require 'sinon' should = require 'should' validator = require '../src/validator' describe "Validator", ()-> describe "rules", -> it "required rule", () -> validator.testInternal({key: 5}, "required", "key").should.be.false validator.testInternal({key: {}}, "required", "key").should.be.false validator.testInternal({key: []}, "required", "key").should.be.false validator.testInternal({key: null}, "required", "key").should.not.be.false validator.testInternal({}, "required", "key").should.not.be.false it "max length rule", () -> validator.testInternal({key: "ads"}, "maxLength", "key").should.not.be.false validator.testInternal({key: "ads"}, {rule: "maxLength", maxLength:20}, "key").should.be.false validator.testInternal({key: ["ads"]}, {rule: "maxLength", maxLength:2}, "key").should.be.false validator.testInternal({key: ["a", "PI:KEY:<KEY>END_PI", "d"]}, {rule: "maxLength", maxLength:2}, "key").should.not.be.false validator.testInternal({key: {}}, {rule: "maxLength", maxLength:2}, "key").should.not.be.false it "integer rule", () -> validator.testInternal({key: "ads"}, "integer", "key").should.not.be.false validator.testInternal({key: []}, "integer", "key").should.not.be.false validator.testInternal({key: {}}, "integer", "key").should.not.be.false validator.testInternal({key: 5.2}, "integer", "key").should.not.be.false validator.testInternal({key: -5.2}, "integer", "key").should.not.be.false validator.testInternal({key: NaN}, "integer", "key").should.not.be.false validator.testInternal({key: -Infinity}, "integer", "key").should.not.be.false validator.testInternal({key: Infinity}, "integer", "key").should.not.be.false validator.testInternal({key: 0}, "integer", "key").should.be.false validator.testInternal({key: 1}, "integer", "key").should.be.false validator.testInternal({key: -1}, "integer", "key").should.be.false validator.testInternal({key: "-1"}, "integer", "key").should.be.false validator.testInternal({key: "1"}, "integer", "key").should.be.false validator.testInternal({key: "0"}, "integer", "key").should.be.false it "non-negative rule", () -> validator.testInternal({key: "-1"}, "nonNegative", "key").should.not.be.false validator.testInternal({key: -1}, "nonNegative", "key").should.not.be.false validator.testInternal({key: -2}, "nonNegative", "key").should.not.be.false validator.testInternal({key: -PI:KEY:<KEY>END_PI}, "nonNegative", "key").should.not.be.false validator.testInternal({key: "0"}, "nonNegative", "key").should.be.false validator.testInternal({key: 0}, "nonNegative", "key").should.be.false validator.testInternal({key: 1}, "nonNegative", "key").should.be.false validator.testInternal({key: 2}, "nonNegative", "key").should.be.false validator.testInternal({key: PI:KEY:<KEY>END_PI}, "nonNegative", "key").should.be.false describe "validate", -> it "should validate simple object", () -> validator.validate({key: "value"}, {key: "required"}).length.should.equal 0 validator.validate({key: "value"}, {key: ["required"]}).length.should.equal 0 validator.validate({key: "value"}, {key: ["required", "maxLength"]}).length.should.equal 1 validator.validate({key: "value"}, {key: ["required", {rule: "maxLength", maxLength: 30}]}).length.should.equal 0 it "should validate recurrent object", () -> validator.addRule "book", recurrent: true message: "invalid book's properties" ruleset: author: ['required', {rule: "maxLength", maxLength: 30}] pages: ['integer'] test: (agent) -> return @validate agent, @ruleset validator.validate({book: {author: "PI:NAME:<NAME>END_PI"}}, {book: 'book'}).length.should.equal 0 validator.validate({book: {author: "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"}}, {book: 'book'}).length.should.equal 1 validator.validate({book: {pages: 30}}, {book: 'book'}).length.should.equal 1 validator.validate({book: {pages: -123.3}}, {book: 'book'}).length.should.equal 1 it "should validate root properties", () -> validator.addRule "book", recurrent: true message: "invalid book's properties" ruleset: author: ['required', {rule: "maxLength", maxLength: 30}] pages: ['integer'] test: (agent) -> return @validate agent, @ruleset validator.validate({author: "PI:NAME:<NAME>END_PI"}, 'book').length.should.equal 0 validator.validate({pages: -123.2}, 'book').length.should.equal 2 it "should validate lists", () -> validator.validate({integers: [1,2,3.2,4.3,5]}, {integers: {rule: 'list', ruleset: 'integer'}}).length.should.equal 1 validator.validate({integers: [1,2,5]}, {integers: {rule: 'list', ruleset: 'integer'}}).length.should.equal 0 it "should validate compound object", () -> validator.addRule "book", recurrent: true message: "invalid book's properties" ruleset: author: ['required', {rule: "maxLength", maxLength: 30}] pages: {rule: 'list', ruleset: 'integer'} validator.validate({pages: [12, 123.6], author: 'PI:NAME:<NAME>END_PI'}, 'book').length.should.be.equal 1 validator.validate({pages: [12], author: 'PI:NAME:<NAME>END_PI'}, 'book').length.should.be.equal 0 it "should crash when rule is not found", () -> f = -> validator.validate({asdf:5}, 'missingRule') f.should.throw() f = -> validator.validate({asdf:5}, 'required') f.should.not.throw() f = -> validator.validate({asdf:5}, {asdf: [{rule:'list', ruleset: 'integer'}]}) f.should.not.throw()
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.9998857378959656, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespin", "end": 52, "score": 0.9999312162399292, "start": 40, "tag": "EMAIL", "value": "niwi@niwi.be" }, { "context": " Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David B", "end": 94, "score": 0.9998789429664612, "start": 75, "tag": "NAME", "value": "Jesús Espino Garcia" }, { "context": "iwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bame", "end": 114, "score": 0.9999338984489441, "start": 96, "tag": "EMAIL", "value": "jespinog@gmail.com" }, { "context": "o Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free s", "end": 158, "score": 0.9998765587806702, "start": 137, "tag": "NAME", "value": "David Barragán Merino" }, { "context": ".com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free software: you can redis", "end": 180, "score": 0.99993497133255, "start": 160, "tag": "EMAIL", "value": "bameda@dbarragan.com" } ]
public/taiga-front/app/coffee/app.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: app.coffee ### @taiga = taiga = {} # Generic function for generate hash from a arbitrary length # collection of parameters. taiga.generateHash = (components=[]) -> components = _.map(components, (x) -> JSON.stringify(x)) return hex_sha1(components.join(":")) taiga.generateUniqueSessionIdentifier = -> date = (new Date()).getTime() randomNumber = Math.floor(Math.random() * 0x9000000) return taiga.generateHash([date, randomNumber]) taiga.sessionId = taiga.generateUniqueSessionIdentifier() configure = ($routeProvider, $locationProvider, $httpProvider, $provide, $tgEventsProvider, tgLoaderProvider) -> $routeProvider.when("/", {templateUrl: "/partials/projects.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/", {templateUrl: "/partials/project.html"}) $routeProvider.when("/project/:pslug/backlog", {templateUrl: "/partials/backlog.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/taskboard/:sslug", {templateUrl: "/partials/taskboard.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/search", {templateUrl: "/partials/search.html", reloadOnSearch: false}) $routeProvider.when("/project/:pslug/kanban", {templateUrl: "/partials/kanban.html", resolve: {loader: tgLoaderProvider.add()}}) # User stories $routeProvider.when("/project/:pslug/us/:usref", {templateUrl: "/partials/us-detail.html", resolve: {loader: tgLoaderProvider.add()}}) # Tasks $routeProvider.when("/project/:pslug/task/:taskref", {templateUrl: "/partials/task-detail.html", resolve: {loader: tgLoaderProvider.add()}}) # Wiki $routeProvider.when("/project/:pslug/wiki", {redirectTo: (params) -> "/project/#{params.pslug}/wiki/home"}, ) $routeProvider.when("/project/:pslug/wiki/:slug", {templateUrl: "/partials/wiki.html", resolve: {loader: tgLoaderProvider.add()}}) # Team $routeProvider.when("/project/:pslug/team", {templateUrl: "/partials/views/team/team.html", resolve: {loader: tgLoaderProvider.add()}}) # Issues $routeProvider.when("/project/:pslug/issues", {templateUrl: "/partials/issues.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/issue/:issueref", {templateUrl: "/partials/issues-detail.html", resolve: {loader: tgLoaderProvider.add()}}) # Admin $routeProvider.when("/project/:pslug/admin/project-profile/details", {templateUrl: "/partials/admin-project-profile.html"}) $routeProvider.when("/project/:pslug/admin/project-profile/default-values", {templateUrl: "/partials/admin-project-default-values.html"}) $routeProvider.when("/project/:pslug/admin/project-profile/modules", {templateUrl: "/partials/admin-project-modules.html"}) $routeProvider.when("/project/:pslug/admin/project-values/us-status", {templateUrl: "/partials/admin-project-values-us-status.html"}) $routeProvider.when("/project/:pslug/admin/project-values/us-points", {templateUrl: "/partials/admin-project-values-us-points.html"}) $routeProvider.when("/project/:pslug/admin/project-values/task-status", {templateUrl: "/partials/admin-project-values-task-status.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-status", {templateUrl: "/partials/admin-project-values-issue-status.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-types", {templateUrl: "/partials/admin-project-values-issue-types.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-priorities", {templateUrl: "/partials/admin-project-values-issue-priorities.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-severities", {templateUrl: "/partials/admin-project-values-issue-severities.html"}) $routeProvider.when("/project/:pslug/admin/memberships", {templateUrl: "/partials/admin-memberships.html"}) $routeProvider.when("/project/:pslug/admin/roles", {templateUrl: "/partials/admin-roles.html"}) $routeProvider.when("/project/:pslug/admin/third-parties/github", {templateUrl: "/partials/admin-third-parties-github.html"}) $routeProvider.when("/project/:pslug/admin/third-parties/gitlab", {templateUrl: "/partials/admin-third-parties-gitlab.html"}) $routeProvider.when("/project/:pslug/admin/third-parties/bitbucket", {templateUrl: "/partials/admin-third-parties-bitbucket.html"}) # User settings $routeProvider.when("/project/:pslug/user-settings/user-profile", {templateUrl: "/partials/user-profile.html"}) $routeProvider.when("/project/:pslug/user-settings/user-change-password", {templateUrl: "/partials/user-change-password.html"}) $routeProvider.when("/project/:pslug/user-settings/user-avatar", {templateUrl: "/partials/user-avatar.html"}) $routeProvider.when("/project/:pslug/user-settings/mail-notifications", {templateUrl: "/partials/mail-notifications.html"}) $routeProvider.when("/change-email/:email_token", {templateUrl: "/partials/change-email.html"}) $routeProvider.when("/cancel-account/:cancel_token", {templateUrl: "/partials/cancel-account.html"}) # Auth $routeProvider.when("/login", {templateUrl: "/partials/login.html"}) $routeProvider.when("/register", {templateUrl: "/partials/register.html"}) $routeProvider.when("/forgot-password", {templateUrl: "/partials/forgot-password.html"}) $routeProvider.when("/change-password", {templateUrl: "/partials/change-password-from-recovery.html"}) $routeProvider.when("/change-password/:token", {templateUrl: "/partials/change-password-from-recovery.html"}) $routeProvider.when("/invitation/:token", {templateUrl: "/partials/invitation.html"}) # Errors/Exceptions $routeProvider.when("/error", {templateUrl: "/partials/error.html"}) $routeProvider.when("/not-found", {templateUrl: "/partials/not-found.html"}) $routeProvider.when("/permission-denied", {templateUrl: "/partials/permission-denied.html"}) $routeProvider.otherwise({redirectTo: '/not-found'}) $locationProvider.html5Mode({enabled: true, requireBase: false}) defaultHeaders = { "Content-Type": "application/json" "Accept-Language": "en" "X-Session-Id": taiga.sessionId } $httpProvider.defaults.headers.delete = defaultHeaders $httpProvider.defaults.headers.patch = defaultHeaders $httpProvider.defaults.headers.post = defaultHeaders $httpProvider.defaults.headers.put = defaultHeaders $httpProvider.defaults.headers.get = { "X-Session-Id": taiga.sessionId } $tgEventsProvider.setSessionId(taiga.sessionId) # Add next param when user try to access to a secction need auth permissions. authHttpIntercept = ($q, $location, $navUrls, $lightboxService) -> httpResponseError = (response) -> if response.status == 0 $lightboxService.closeAll() $location.path($navUrls.resolve("error")) $location.replace() else if response.status == 401 nextPath = $location.path() $location.url($navUrls.resolve("login")).search("next=#{nextPath}") return $q.reject(response) return { responseError: httpResponseError } $provide.factory("authHttpIntercept", ["$q", "$location", "$tgNavUrls", "lightboxService", authHttpIntercept]) $httpProvider.interceptors.push('authHttpIntercept'); # If there is an error in the version throw a notify error versionCheckHttpIntercept = ($q, $confirm) -> versionErrorMsg = "Someone inside Taiga has changed this before and our Oompa Loompas cannot apply your changes. Please reload and apply your changes again (they will be lost)." #TODO: i18n httpResponseError = (response) -> if response.status == 400 && response.data.version $confirm.notify("error", versionErrorMsg, null, 10000) return $q.reject(response) return $q.reject(response) return { responseError: httpResponseError } $provide.factory("versionCheckHttpIntercept", ["$q", "$tgConfirm", versionCheckHttpIntercept]) $httpProvider.interceptors.push('versionCheckHttpIntercept'); window.checksley.updateValidators({ linewidth: (val, width) -> lines = taiga.nl2br(val).split("<br />") valid = _.every lines, (line) -> line.length < width return valid }) window.checksley.updateMessages("default", { linewidth: "The subject must have a maximum size of %s" }) init = ($log, $i18n, $config, $rootscope, $auth, $events, $analytics) -> $i18n.initialize($config.get("defaultLanguage")) $log.debug("Initialize application") if $auth.isAuthenticated() $events.setupConnection() $analytics.initialize() modules = [ # Main Global Modules "taigaBase", "taigaCommon", "taigaResources", "taigaLocales", "taigaAuth", "taigaEvents", # Specific Modules "taigaRelatedTasks", "taigaBacklog", "taigaTaskboard", "taigaKanban" "taigaIssues", "taigaUserStories", "taigaTasks", "taigaTeam", "taigaWiki", "taigaSearch", "taigaAdmin", "taigaNavMenu", "taigaProject", "taigaUserSettings", "taigaFeedback", "taigaPlugins", "taigaIntegrations", # Vendor modules "ngRoute", "ngAnimate", ] # Main module definition module = angular.module("taiga", modules) module.config([ "$routeProvider", "$locationProvider", "$httpProvider", "$provide", "$tgEventsProvider", "tgLoaderProvider", configure ]) module.run([ "$log", "$tgI18n", "$tgConfig", "$rootScope", "$tgAuth", "$tgEvents", "$tgAnalytics", init ])
35482
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: app.coffee ### @taiga = taiga = {} # Generic function for generate hash from a arbitrary length # collection of parameters. taiga.generateHash = (components=[]) -> components = _.map(components, (x) -> JSON.stringify(x)) return hex_sha1(components.join(":")) taiga.generateUniqueSessionIdentifier = -> date = (new Date()).getTime() randomNumber = Math.floor(Math.random() * 0x9000000) return taiga.generateHash([date, randomNumber]) taiga.sessionId = taiga.generateUniqueSessionIdentifier() configure = ($routeProvider, $locationProvider, $httpProvider, $provide, $tgEventsProvider, tgLoaderProvider) -> $routeProvider.when("/", {templateUrl: "/partials/projects.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/", {templateUrl: "/partials/project.html"}) $routeProvider.when("/project/:pslug/backlog", {templateUrl: "/partials/backlog.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/taskboard/:sslug", {templateUrl: "/partials/taskboard.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/search", {templateUrl: "/partials/search.html", reloadOnSearch: false}) $routeProvider.when("/project/:pslug/kanban", {templateUrl: "/partials/kanban.html", resolve: {loader: tgLoaderProvider.add()}}) # User stories $routeProvider.when("/project/:pslug/us/:usref", {templateUrl: "/partials/us-detail.html", resolve: {loader: tgLoaderProvider.add()}}) # Tasks $routeProvider.when("/project/:pslug/task/:taskref", {templateUrl: "/partials/task-detail.html", resolve: {loader: tgLoaderProvider.add()}}) # Wiki $routeProvider.when("/project/:pslug/wiki", {redirectTo: (params) -> "/project/#{params.pslug}/wiki/home"}, ) $routeProvider.when("/project/:pslug/wiki/:slug", {templateUrl: "/partials/wiki.html", resolve: {loader: tgLoaderProvider.add()}}) # Team $routeProvider.when("/project/:pslug/team", {templateUrl: "/partials/views/team/team.html", resolve: {loader: tgLoaderProvider.add()}}) # Issues $routeProvider.when("/project/:pslug/issues", {templateUrl: "/partials/issues.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/issue/:issueref", {templateUrl: "/partials/issues-detail.html", resolve: {loader: tgLoaderProvider.add()}}) # Admin $routeProvider.when("/project/:pslug/admin/project-profile/details", {templateUrl: "/partials/admin-project-profile.html"}) $routeProvider.when("/project/:pslug/admin/project-profile/default-values", {templateUrl: "/partials/admin-project-default-values.html"}) $routeProvider.when("/project/:pslug/admin/project-profile/modules", {templateUrl: "/partials/admin-project-modules.html"}) $routeProvider.when("/project/:pslug/admin/project-values/us-status", {templateUrl: "/partials/admin-project-values-us-status.html"}) $routeProvider.when("/project/:pslug/admin/project-values/us-points", {templateUrl: "/partials/admin-project-values-us-points.html"}) $routeProvider.when("/project/:pslug/admin/project-values/task-status", {templateUrl: "/partials/admin-project-values-task-status.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-status", {templateUrl: "/partials/admin-project-values-issue-status.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-types", {templateUrl: "/partials/admin-project-values-issue-types.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-priorities", {templateUrl: "/partials/admin-project-values-issue-priorities.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-severities", {templateUrl: "/partials/admin-project-values-issue-severities.html"}) $routeProvider.when("/project/:pslug/admin/memberships", {templateUrl: "/partials/admin-memberships.html"}) $routeProvider.when("/project/:pslug/admin/roles", {templateUrl: "/partials/admin-roles.html"}) $routeProvider.when("/project/:pslug/admin/third-parties/github", {templateUrl: "/partials/admin-third-parties-github.html"}) $routeProvider.when("/project/:pslug/admin/third-parties/gitlab", {templateUrl: "/partials/admin-third-parties-gitlab.html"}) $routeProvider.when("/project/:pslug/admin/third-parties/bitbucket", {templateUrl: "/partials/admin-third-parties-bitbucket.html"}) # User settings $routeProvider.when("/project/:pslug/user-settings/user-profile", {templateUrl: "/partials/user-profile.html"}) $routeProvider.when("/project/:pslug/user-settings/user-change-password", {templateUrl: "/partials/user-change-password.html"}) $routeProvider.when("/project/:pslug/user-settings/user-avatar", {templateUrl: "/partials/user-avatar.html"}) $routeProvider.when("/project/:pslug/user-settings/mail-notifications", {templateUrl: "/partials/mail-notifications.html"}) $routeProvider.when("/change-email/:email_token", {templateUrl: "/partials/change-email.html"}) $routeProvider.when("/cancel-account/:cancel_token", {templateUrl: "/partials/cancel-account.html"}) # Auth $routeProvider.when("/login", {templateUrl: "/partials/login.html"}) $routeProvider.when("/register", {templateUrl: "/partials/register.html"}) $routeProvider.when("/forgot-password", {templateUrl: "/partials/forgot-password.html"}) $routeProvider.when("/change-password", {templateUrl: "/partials/change-password-from-recovery.html"}) $routeProvider.when("/change-password/:token", {templateUrl: "/partials/change-password-from-recovery.html"}) $routeProvider.when("/invitation/:token", {templateUrl: "/partials/invitation.html"}) # Errors/Exceptions $routeProvider.when("/error", {templateUrl: "/partials/error.html"}) $routeProvider.when("/not-found", {templateUrl: "/partials/not-found.html"}) $routeProvider.when("/permission-denied", {templateUrl: "/partials/permission-denied.html"}) $routeProvider.otherwise({redirectTo: '/not-found'}) $locationProvider.html5Mode({enabled: true, requireBase: false}) defaultHeaders = { "Content-Type": "application/json" "Accept-Language": "en" "X-Session-Id": taiga.sessionId } $httpProvider.defaults.headers.delete = defaultHeaders $httpProvider.defaults.headers.patch = defaultHeaders $httpProvider.defaults.headers.post = defaultHeaders $httpProvider.defaults.headers.put = defaultHeaders $httpProvider.defaults.headers.get = { "X-Session-Id": taiga.sessionId } $tgEventsProvider.setSessionId(taiga.sessionId) # Add next param when user try to access to a secction need auth permissions. authHttpIntercept = ($q, $location, $navUrls, $lightboxService) -> httpResponseError = (response) -> if response.status == 0 $lightboxService.closeAll() $location.path($navUrls.resolve("error")) $location.replace() else if response.status == 401 nextPath = $location.path() $location.url($navUrls.resolve("login")).search("next=#{nextPath}") return $q.reject(response) return { responseError: httpResponseError } $provide.factory("authHttpIntercept", ["$q", "$location", "$tgNavUrls", "lightboxService", authHttpIntercept]) $httpProvider.interceptors.push('authHttpIntercept'); # If there is an error in the version throw a notify error versionCheckHttpIntercept = ($q, $confirm) -> versionErrorMsg = "Someone inside Taiga has changed this before and our Oompa Loompas cannot apply your changes. Please reload and apply your changes again (they will be lost)." #TODO: i18n httpResponseError = (response) -> if response.status == 400 && response.data.version $confirm.notify("error", versionErrorMsg, null, 10000) return $q.reject(response) return $q.reject(response) return { responseError: httpResponseError } $provide.factory("versionCheckHttpIntercept", ["$q", "$tgConfirm", versionCheckHttpIntercept]) $httpProvider.interceptors.push('versionCheckHttpIntercept'); window.checksley.updateValidators({ linewidth: (val, width) -> lines = taiga.nl2br(val).split("<br />") valid = _.every lines, (line) -> line.length < width return valid }) window.checksley.updateMessages("default", { linewidth: "The subject must have a maximum size of %s" }) init = ($log, $i18n, $config, $rootscope, $auth, $events, $analytics) -> $i18n.initialize($config.get("defaultLanguage")) $log.debug("Initialize application") if $auth.isAuthenticated() $events.setupConnection() $analytics.initialize() modules = [ # Main Global Modules "taigaBase", "taigaCommon", "taigaResources", "taigaLocales", "taigaAuth", "taigaEvents", # Specific Modules "taigaRelatedTasks", "taigaBacklog", "taigaTaskboard", "taigaKanban" "taigaIssues", "taigaUserStories", "taigaTasks", "taigaTeam", "taigaWiki", "taigaSearch", "taigaAdmin", "taigaNavMenu", "taigaProject", "taigaUserSettings", "taigaFeedback", "taigaPlugins", "taigaIntegrations", # Vendor modules "ngRoute", "ngAnimate", ] # Main module definition module = angular.module("taiga", modules) module.config([ "$routeProvider", "$locationProvider", "$httpProvider", "$provide", "$tgEventsProvider", "tgLoaderProvider", configure ]) module.run([ "$log", "$tgI18n", "$tgConfig", "$rootScope", "$tgAuth", "$tgEvents", "$tgAnalytics", init ])
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: app.coffee ### @taiga = taiga = {} # Generic function for generate hash from a arbitrary length # collection of parameters. taiga.generateHash = (components=[]) -> components = _.map(components, (x) -> JSON.stringify(x)) return hex_sha1(components.join(":")) taiga.generateUniqueSessionIdentifier = -> date = (new Date()).getTime() randomNumber = Math.floor(Math.random() * 0x9000000) return taiga.generateHash([date, randomNumber]) taiga.sessionId = taiga.generateUniqueSessionIdentifier() configure = ($routeProvider, $locationProvider, $httpProvider, $provide, $tgEventsProvider, tgLoaderProvider) -> $routeProvider.when("/", {templateUrl: "/partials/projects.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/", {templateUrl: "/partials/project.html"}) $routeProvider.when("/project/:pslug/backlog", {templateUrl: "/partials/backlog.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/taskboard/:sslug", {templateUrl: "/partials/taskboard.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/search", {templateUrl: "/partials/search.html", reloadOnSearch: false}) $routeProvider.when("/project/:pslug/kanban", {templateUrl: "/partials/kanban.html", resolve: {loader: tgLoaderProvider.add()}}) # User stories $routeProvider.when("/project/:pslug/us/:usref", {templateUrl: "/partials/us-detail.html", resolve: {loader: tgLoaderProvider.add()}}) # Tasks $routeProvider.when("/project/:pslug/task/:taskref", {templateUrl: "/partials/task-detail.html", resolve: {loader: tgLoaderProvider.add()}}) # Wiki $routeProvider.when("/project/:pslug/wiki", {redirectTo: (params) -> "/project/#{params.pslug}/wiki/home"}, ) $routeProvider.when("/project/:pslug/wiki/:slug", {templateUrl: "/partials/wiki.html", resolve: {loader: tgLoaderProvider.add()}}) # Team $routeProvider.when("/project/:pslug/team", {templateUrl: "/partials/views/team/team.html", resolve: {loader: tgLoaderProvider.add()}}) # Issues $routeProvider.when("/project/:pslug/issues", {templateUrl: "/partials/issues.html", resolve: {loader: tgLoaderProvider.add()}}) $routeProvider.when("/project/:pslug/issue/:issueref", {templateUrl: "/partials/issues-detail.html", resolve: {loader: tgLoaderProvider.add()}}) # Admin $routeProvider.when("/project/:pslug/admin/project-profile/details", {templateUrl: "/partials/admin-project-profile.html"}) $routeProvider.when("/project/:pslug/admin/project-profile/default-values", {templateUrl: "/partials/admin-project-default-values.html"}) $routeProvider.when("/project/:pslug/admin/project-profile/modules", {templateUrl: "/partials/admin-project-modules.html"}) $routeProvider.when("/project/:pslug/admin/project-values/us-status", {templateUrl: "/partials/admin-project-values-us-status.html"}) $routeProvider.when("/project/:pslug/admin/project-values/us-points", {templateUrl: "/partials/admin-project-values-us-points.html"}) $routeProvider.when("/project/:pslug/admin/project-values/task-status", {templateUrl: "/partials/admin-project-values-task-status.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-status", {templateUrl: "/partials/admin-project-values-issue-status.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-types", {templateUrl: "/partials/admin-project-values-issue-types.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-priorities", {templateUrl: "/partials/admin-project-values-issue-priorities.html"}) $routeProvider.when("/project/:pslug/admin/project-values/issue-severities", {templateUrl: "/partials/admin-project-values-issue-severities.html"}) $routeProvider.when("/project/:pslug/admin/memberships", {templateUrl: "/partials/admin-memberships.html"}) $routeProvider.when("/project/:pslug/admin/roles", {templateUrl: "/partials/admin-roles.html"}) $routeProvider.when("/project/:pslug/admin/third-parties/github", {templateUrl: "/partials/admin-third-parties-github.html"}) $routeProvider.when("/project/:pslug/admin/third-parties/gitlab", {templateUrl: "/partials/admin-third-parties-gitlab.html"}) $routeProvider.when("/project/:pslug/admin/third-parties/bitbucket", {templateUrl: "/partials/admin-third-parties-bitbucket.html"}) # User settings $routeProvider.when("/project/:pslug/user-settings/user-profile", {templateUrl: "/partials/user-profile.html"}) $routeProvider.when("/project/:pslug/user-settings/user-change-password", {templateUrl: "/partials/user-change-password.html"}) $routeProvider.when("/project/:pslug/user-settings/user-avatar", {templateUrl: "/partials/user-avatar.html"}) $routeProvider.when("/project/:pslug/user-settings/mail-notifications", {templateUrl: "/partials/mail-notifications.html"}) $routeProvider.when("/change-email/:email_token", {templateUrl: "/partials/change-email.html"}) $routeProvider.when("/cancel-account/:cancel_token", {templateUrl: "/partials/cancel-account.html"}) # Auth $routeProvider.when("/login", {templateUrl: "/partials/login.html"}) $routeProvider.when("/register", {templateUrl: "/partials/register.html"}) $routeProvider.when("/forgot-password", {templateUrl: "/partials/forgot-password.html"}) $routeProvider.when("/change-password", {templateUrl: "/partials/change-password-from-recovery.html"}) $routeProvider.when("/change-password/:token", {templateUrl: "/partials/change-password-from-recovery.html"}) $routeProvider.when("/invitation/:token", {templateUrl: "/partials/invitation.html"}) # Errors/Exceptions $routeProvider.when("/error", {templateUrl: "/partials/error.html"}) $routeProvider.when("/not-found", {templateUrl: "/partials/not-found.html"}) $routeProvider.when("/permission-denied", {templateUrl: "/partials/permission-denied.html"}) $routeProvider.otherwise({redirectTo: '/not-found'}) $locationProvider.html5Mode({enabled: true, requireBase: false}) defaultHeaders = { "Content-Type": "application/json" "Accept-Language": "en" "X-Session-Id": taiga.sessionId } $httpProvider.defaults.headers.delete = defaultHeaders $httpProvider.defaults.headers.patch = defaultHeaders $httpProvider.defaults.headers.post = defaultHeaders $httpProvider.defaults.headers.put = defaultHeaders $httpProvider.defaults.headers.get = { "X-Session-Id": taiga.sessionId } $tgEventsProvider.setSessionId(taiga.sessionId) # Add next param when user try to access to a secction need auth permissions. authHttpIntercept = ($q, $location, $navUrls, $lightboxService) -> httpResponseError = (response) -> if response.status == 0 $lightboxService.closeAll() $location.path($navUrls.resolve("error")) $location.replace() else if response.status == 401 nextPath = $location.path() $location.url($navUrls.resolve("login")).search("next=#{nextPath}") return $q.reject(response) return { responseError: httpResponseError } $provide.factory("authHttpIntercept", ["$q", "$location", "$tgNavUrls", "lightboxService", authHttpIntercept]) $httpProvider.interceptors.push('authHttpIntercept'); # If there is an error in the version throw a notify error versionCheckHttpIntercept = ($q, $confirm) -> versionErrorMsg = "Someone inside Taiga has changed this before and our Oompa Loompas cannot apply your changes. Please reload and apply your changes again (they will be lost)." #TODO: i18n httpResponseError = (response) -> if response.status == 400 && response.data.version $confirm.notify("error", versionErrorMsg, null, 10000) return $q.reject(response) return $q.reject(response) return { responseError: httpResponseError } $provide.factory("versionCheckHttpIntercept", ["$q", "$tgConfirm", versionCheckHttpIntercept]) $httpProvider.interceptors.push('versionCheckHttpIntercept'); window.checksley.updateValidators({ linewidth: (val, width) -> lines = taiga.nl2br(val).split("<br />") valid = _.every lines, (line) -> line.length < width return valid }) window.checksley.updateMessages("default", { linewidth: "The subject must have a maximum size of %s" }) init = ($log, $i18n, $config, $rootscope, $auth, $events, $analytics) -> $i18n.initialize($config.get("defaultLanguage")) $log.debug("Initialize application") if $auth.isAuthenticated() $events.setupConnection() $analytics.initialize() modules = [ # Main Global Modules "taigaBase", "taigaCommon", "taigaResources", "taigaLocales", "taigaAuth", "taigaEvents", # Specific Modules "taigaRelatedTasks", "taigaBacklog", "taigaTaskboard", "taigaKanban" "taigaIssues", "taigaUserStories", "taigaTasks", "taigaTeam", "taigaWiki", "taigaSearch", "taigaAdmin", "taigaNavMenu", "taigaProject", "taigaUserSettings", "taigaFeedback", "taigaPlugins", "taigaIntegrations", # Vendor modules "ngRoute", "ngAnimate", ] # Main module definition module = angular.module("taiga", modules) module.config([ "$routeProvider", "$locationProvider", "$httpProvider", "$provide", "$tgEventsProvider", "tgLoaderProvider", configure ]) module.run([ "$log", "$tgI18n", "$tgConfig", "$rootScope", "$tgAuth", "$tgEvents", "$tgAnalytics", init ])
[ { "context": "#!\n# * async\n# * https://github.com/caolan/async\n# *\n# * Copyright 2010-2014 Caolan McMahon\n", "end": 42, "score": 0.9996331334114075, "start": 36, "tag": "USERNAME", "value": "caolan" }, { "context": "ithub.com/caolan/async\n# *\n# * Copyright 2010-2014 Caolan McMahon\n# * Released under the MIT license\n# \n\n#jshint on", "end": 91, "score": 0.9998760223388672, "start": 77, "tag": "NAME", "value": "Caolan McMahon" } ]
deps/npm/node_modules/request/node_modules/form-data/node_modules/async/lib/async.coffee
lxe/io.coffee
0
#! # * async # * https://github.com/caolan/async # * # * Copyright 2010-2014 Caolan McMahon # * Released under the MIT license # #jshint onevar: false, indent:4 #global setImmediate: false, setTimeout: false, console: false (-> # global on the server, window in the browser only_once = (fn) -> called = false -> throw new Error("Callback was already called.") if called called = true fn.apply root, arguments return async = {} root = undefined previous_async = undefined root = this previous_async = root.async if root? async.noConflict = -> root.async = previous_async async #// cross-browser compatiblity functions //// _toString = Object::toString _isArray = Array.isArray or (obj) -> _toString.call(obj) is "[object Array]" _each = (arr, iterator) -> return arr.forEach(iterator) if arr.forEach i = 0 while i < arr.length iterator arr[i], i, arr i += 1 return _map = (arr, iterator) -> return arr.map(iterator) if arr.map results = [] _each arr, (x, i, a) -> results.push iterator(x, i, a) return results _reduce = (arr, iterator, memo) -> return arr.reduce(iterator, memo) if arr.reduce _each arr, (x, i, a) -> memo = iterator(memo, x, i, a) return memo _keys = (obj) -> return Object.keys(obj) if Object.keys keys = [] for k of obj keys.push k if obj.hasOwnProperty(k) keys #// exported async module functions //// #// nextTick implementation with browser-compatible fallback //// if typeof process is "undefined" or not (process.nextTick) if typeof setImmediate is "function" async.nextTick = (fn) -> # not a direct alias for IE10 compatibility setImmediate fn return async.setImmediate = async.nextTick else async.nextTick = (fn) -> setTimeout fn, 0 return async.setImmediate = async.nextTick else async.nextTick = process.nextTick if typeof setImmediate isnt "undefined" async.setImmediate = (fn) -> # not a direct alias for IE10 compatibility setImmediate fn return else async.setImmediate = async.nextTick async.each = (arr, iterator, callback) -> done = (err) -> if err callback err callback = -> else completed += 1 callback() if completed >= arr.length return callback = callback or -> return callback() unless arr.length completed = 0 _each arr, (x) -> iterator x, only_once(done) return return async.forEach = async.each async.eachSeries = (arr, iterator, callback) -> callback = callback or -> return callback() unless arr.length completed = 0 iterate = -> iterator arr[completed], (err) -> if err callback err callback = -> else completed += 1 if completed >= arr.length callback() else iterate() return return iterate() return async.forEachSeries = async.eachSeries async.eachLimit = (arr, limit, iterator, callback) -> fn = _eachLimit(limit) fn.apply null, [ arr iterator callback ] return async.forEachLimit = async.eachLimit _eachLimit = (limit) -> (arr, iterator, callback) -> callback = callback or -> return callback() if not arr.length or limit <= 0 completed = 0 started = 0 running = 0 (replenish = -> return callback() if completed >= arr.length while running < limit and started < arr.length started += 1 running += 1 iterator arr[started - 1], (err) -> if err callback err callback = -> else completed += 1 running -= 1 if completed >= arr.length callback() else replenish() return return )() return doParallel = (fn) -> -> args = Array::slice.call(arguments) fn.apply null, [async.each].concat(args) doParallelLimit = (limit, fn) -> -> args = Array::slice.call(arguments) fn.apply null, [_eachLimit(limit)].concat(args) doSeries = (fn) -> -> args = Array::slice.call(arguments) fn.apply null, [async.eachSeries].concat(args) _asyncMap = (eachfn, arr, iterator, callback) -> arr = _map(arr, (x, i) -> index: i value: x ) unless callback eachfn arr, (x, callback) -> iterator x.value, (err) -> callback err return return else results = [] eachfn arr, ((x, callback) -> iterator x.value, (err, v) -> results[x.index] = v callback err return return ), (err) -> callback err, results return return async.map = doParallel(_asyncMap) async.mapSeries = doSeries(_asyncMap) async.mapLimit = (arr, limit, iterator, callback) -> _mapLimit(limit) arr, iterator, callback _mapLimit = (limit) -> doParallelLimit limit, _asyncMap # reduce only has a series version, as doing reduce in parallel won't # work in many situations. async.reduce = (arr, memo, iterator, callback) -> async.eachSeries arr, ((x, callback) -> iterator memo, x, (err, v) -> memo = v callback err return return ), (err) -> callback err, memo return return # inject alias async.inject = async.reduce # foldl alias async.foldl = async.reduce async.reduceRight = (arr, memo, iterator, callback) -> reversed = _map(arr, (x) -> x ).reverse() async.reduce reversed, memo, iterator, callback return # foldr alias async.foldr = async.reduceRight _filter = (eachfn, arr, iterator, callback) -> results = [] arr = _map(arr, (x, i) -> index: i value: x ) eachfn arr, ((x, callback) -> iterator x.value, (v) -> results.push x if v callback() return return ), (err) -> callback _map(results.sort((a, b) -> a.index - b.index ), (x) -> x.value ) return return async.filter = doParallel(_filter) async.filterSeries = doSeries(_filter) # select alias async.select = async.filter async.selectSeries = async.filterSeries _reject = (eachfn, arr, iterator, callback) -> results = [] arr = _map(arr, (x, i) -> index: i value: x ) eachfn arr, ((x, callback) -> iterator x.value, (v) -> results.push x unless v callback() return return ), (err) -> callback _map(results.sort((a, b) -> a.index - b.index ), (x) -> x.value ) return return async.reject = doParallel(_reject) async.rejectSeries = doSeries(_reject) _detect = (eachfn, arr, iterator, main_callback) -> eachfn arr, ((x, callback) -> iterator x, (result) -> if result main_callback x main_callback = -> else callback() return return ), (err) -> main_callback() return return async.detect = doParallel(_detect) async.detectSeries = doSeries(_detect) async.some = (arr, iterator, main_callback) -> async.each arr, ((x, callback) -> iterator x, (v) -> if v main_callback true main_callback = -> callback() return return ), (err) -> main_callback false return return # any alias async.any = async.some async.every = (arr, iterator, main_callback) -> async.each arr, ((x, callback) -> iterator x, (v) -> unless v main_callback false main_callback = -> callback() return return ), (err) -> main_callback true return return # all alias async.all = async.every async.sortBy = (arr, iterator, callback) -> async.map arr, ((x, callback) -> iterator x, (err, criteria) -> if err callback err else callback null, value: x criteria: criteria return return ), (err, results) -> if err callback err else fn = (left, right) -> a = left.criteria b = right.criteria (if a < b then -1 else (if a > b then 1 else 0)) callback null, _map(results.sort(fn), (x) -> x.value ) return return async.auto = (tasks, callback) -> callback = callback or -> keys = _keys(tasks) remainingTasks = keys.length return callback() unless remainingTasks results = {} listeners = [] addListener = (fn) -> listeners.unshift fn return removeListener = (fn) -> i = 0 while i < listeners.length if listeners[i] is fn listeners.splice i, 1 return i += 1 return taskComplete = -> remainingTasks-- _each listeners.slice(0), (fn) -> fn() return return addListener -> unless remainingTasks theCallback = callback # prevent final callback from calling itself if it errors callback = -> theCallback null, results return _each keys, (k) -> task = (if _isArray(tasks[k]) then tasks[k] else [tasks[k]]) taskCallback = (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 if err safeResults = {} _each _keys(results), (rkey) -> safeResults[rkey] = results[rkey] return safeResults[k] = args callback err, safeResults # stop subsequent errors hitting callback multiple times callback = -> else results[k] = args async.setImmediate taskComplete return requires = task.slice(0, Math.abs(task.length - 1)) or [] ready = -> _reduce(requires, (a, x) -> a and results.hasOwnProperty(x) , true) and not results.hasOwnProperty(k) if ready() task[task.length - 1] taskCallback, results else listener = -> if ready() removeListener listener task[task.length - 1] taskCallback, results return addListener listener return return async.retry = (times, task, callback) -> DEFAULT_TIMES = 5 attempts = [] # Use defaults if times not passed if typeof times is "function" callback = task task = times times = DEFAULT_TIMES # Make sure times is a number times = parseInt(times, 10) or DEFAULT_TIMES wrappedTask = (wrappedCallback, wrappedResults) -> retryAttempt = (task, finalAttempt) -> (seriesCallback) -> task ((err, result) -> seriesCallback not err or finalAttempt, err: err result: result return ), wrappedResults return attempts.push retryAttempt(task, not (times -= 1)) while times async.series attempts, (done, data) -> data = data[data.length - 1] (wrappedCallback or callback) data.err, data.result return return # If a callback is passed, run this as a controll flow (if callback then wrappedTask() else wrappedTask) async.waterfall = (tasks, callback) -> callback = callback or -> unless _isArray(tasks) err = new Error("First argument to waterfall must be an array of functions") return callback(err) return callback() unless tasks.length wrapIterator = (iterator) -> (err) -> if err callback.apply null, arguments callback = -> else args = Array::slice.call(arguments, 1) next = iterator.next() if next args.push wrapIterator(next) else args.push callback async.setImmediate -> iterator.apply null, args return return wrapIterator(async.iterator(tasks))() return _parallel = (eachfn, tasks, callback) -> callback = callback or -> if _isArray(tasks) eachfn.map tasks, ((fn, callback) -> if fn fn (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 callback.call null, err, args return return ), callback else results = {} eachfn.each _keys(tasks), ((k, callback) -> tasks[k] (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 results[k] = args callback err return return ), (err) -> callback err, results return return async.parallel = (tasks, callback) -> _parallel map: async.map each: async.each , tasks, callback return async.parallelLimit = (tasks, limit, callback) -> _parallel map: _mapLimit(limit) each: _eachLimit(limit) , tasks, callback return async.series = (tasks, callback) -> callback = callback or -> if _isArray(tasks) async.mapSeries tasks, ((fn, callback) -> if fn fn (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 callback.call null, err, args return return ), callback else results = {} async.eachSeries _keys(tasks), ((k, callback) -> tasks[k] (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 results[k] = args callback err return return ), (err) -> callback err, results return return async.iterator = (tasks) -> makeCallback = (index) -> fn = -> tasks[index].apply null, arguments if tasks.length fn.next() fn.next = -> (if (index < tasks.length - 1) then makeCallback(index + 1) else null) fn makeCallback 0 async.apply = (fn) -> args = Array::slice.call(arguments, 1) -> fn.apply null, args.concat(Array::slice.call(arguments)) _concat = (eachfn, arr, fn, callback) -> r = [] eachfn arr, ((x, cb) -> fn x, (err, y) -> r = r.concat(y or []) cb err return return ), (err) -> callback err, r return return async.concat = doParallel(_concat) async.concatSeries = doSeries(_concat) async.whilst = (test, iterator, callback) -> if test() iterator (err) -> return callback(err) if err async.whilst test, iterator, callback return else callback() return async.doWhilst = (iterator, test, callback) -> iterator (err) -> return callback(err) if err args = Array::slice.call(arguments, 1) if test.apply(null, args) async.doWhilst iterator, test, callback else callback() return return async.until = (test, iterator, callback) -> unless test() iterator (err) -> return callback(err) if err async.until test, iterator, callback return else callback() return async.doUntil = (iterator, test, callback) -> iterator (err) -> return callback(err) if err args = Array::slice.call(arguments, 1) unless test.apply(null, args) async.doUntil iterator, test, callback else callback() return return async.queue = (worker, concurrency) -> _insert = (q, data, pos, callback) -> q.started = true unless q.started data = [data] unless _isArray(data) if data.length is 0 # call drain immediately if there are no tasks return async.setImmediate(-> q.drain() if q.drain return ) _each data, (task) -> item = data: task callback: (if typeof callback is "function" then callback else null) if pos q.tasks.unshift item else q.tasks.push item q.saturated() if q.saturated and q.tasks.length is q.concurrency async.setImmediate q.process return return concurrency = 1 if concurrency is `undefined` workers = 0 q = tasks: [] concurrency: concurrency saturated: null empty: null drain: null started: false paused: false push: (data, callback) -> _insert q, data, false, callback return kill: -> q.drain = null q.tasks = [] return unshift: (data, callback) -> _insert q, data, true, callback return process: -> if not q.paused and workers < q.concurrency and q.tasks.length task = q.tasks.shift() q.empty() if q.empty and q.tasks.length is 0 workers += 1 next = -> workers -= 1 task.callback.apply task, arguments if task.callback q.drain() if q.drain and q.tasks.length + workers is 0 q.process() return cb = only_once(next) worker task.data, cb return length: -> q.tasks.length running: -> workers idle: -> q.tasks.length + workers is 0 pause: -> return if q.paused is true q.paused = true q.process() return resume: -> return if q.paused is false q.paused = false q.process() return q async.priorityQueue = (worker, concurrency) -> _compareTasks = (a, b) -> a.priority - b.priority _binarySearch = (sequence, item, compare) -> beg = -1 end = sequence.length - 1 while beg < end mid = beg + ((end - beg + 1) >>> 1) if compare(item, sequence[mid]) >= 0 beg = mid else end = mid - 1 beg _insert = (q, data, priority, callback) -> q.started = true unless q.started data = [data] unless _isArray(data) if data.length is 0 # call drain immediately if there are no tasks return async.setImmediate(-> q.drain() if q.drain return ) _each data, (task) -> item = data: task priority: priority callback: (if typeof callback is "function" then callback else null) q.tasks.splice _binarySearch(q.tasks, item, _compareTasks) + 1, 0, item q.saturated() if q.saturated and q.tasks.length is q.concurrency async.setImmediate q.process return return # Start with a normal queue q = async.queue(worker, concurrency) # Override push to accept second parameter representing priority q.push = (data, priority, callback) -> _insert q, data, priority, callback return # Remove unshift function delete q.unshift q async.cargo = (worker, payload) -> working = false tasks = [] cargo = tasks: tasks payload: payload saturated: null empty: null drain: null drained: true push: (data, callback) -> data = [data] unless _isArray(data) _each data, (task) -> tasks.push data: task callback: (if typeof callback is "function" then callback else null) cargo.drained = false cargo.saturated() if cargo.saturated and tasks.length is payload return async.setImmediate cargo.process return process: process = -> return if working if tasks.length is 0 cargo.drain() if cargo.drain and not cargo.drained cargo.drained = true return ts = (if typeof payload is "number" then tasks.splice(0, payload) else tasks.splice(0, tasks.length)) ds = _map(ts, (task) -> task.data ) cargo.empty() if cargo.empty working = true worker ds, -> working = false args = arguments _each ts, (data) -> data.callback.apply null, args if data.callback return process() return return length: -> tasks.length running: -> working cargo _console_fn = (name) -> (fn) -> args = Array::slice.call(arguments, 1) fn.apply null, args.concat([(err) -> args = Array::slice.call(arguments, 1) if typeof console isnt "undefined" if err console.error err if console.error else if console[name] _each args, (x) -> console[name] x return return ]) return async.log = _console_fn("log") async.dir = _console_fn("dir") #async.info = _console_fn('info'); # async.warn = _console_fn('warn'); # async.error = _console_fn('error'); async.memoize = (fn, hasher) -> memo = {} queues = {} hasher = hasher or (x) -> x memoized = -> args = Array::slice.call(arguments) callback = args.pop() key = hasher.apply(null, args) if key of memo async.nextTick -> callback.apply null, memo[key] return else if key of queues queues[key].push callback else queues[key] = [callback] fn.apply null, args.concat([-> memo[key] = arguments q = queues[key] delete queues[key] i = 0 l = q.length while i < l q[i].apply null, arguments i++ return ]) return memoized.memo = memo memoized.unmemoized = fn memoized async.unmemoize = (fn) -> -> (fn.unmemoized or fn).apply null, arguments async.times = (count, iterator, callback) -> counter = [] i = 0 while i < count counter.push i i++ async.map counter, iterator, callback async.timesSeries = (count, iterator, callback) -> counter = [] i = 0 while i < count counter.push i i++ async.mapSeries counter, iterator, callback async.seq = -> # functions... fns = arguments -> that = this args = Array::slice.call(arguments) callback = args.pop() async.reduce fns, args, ((newargs, fn, cb) -> fn.apply that, newargs.concat([-> err = arguments[0] nextargs = Array::slice.call(arguments, 1) cb err, nextargs return ]) return ), (err, results) -> callback.apply that, [err].concat(results) return return async.compose = -> # functions... async.seq.apply null, Array::reverse.call(arguments) _applyEach = (eachfn, fns) -> #args... go = -> that = this args = Array::slice.call(arguments) callback = args.pop() eachfn fns, ((fn, cb) -> fn.apply that, args.concat([cb]) return ), callback if arguments.length > 2 args = Array::slice.call(arguments, 2) go.apply this, args else go async.applyEach = doParallel(_applyEach) async.applyEachSeries = doSeries(_applyEach) async.forever = (fn, callback) -> next = (err) -> if err return callback(err) if callback throw err fn next return next() return # Node.js if typeof module isnt "undefined" and module.exports module.exports = async # AMD / RequireJS else if typeof define isnt "undefined" and define.amd define [], -> async # included directly via <script> tag else root.async = async return )()
211743
#! # * async # * https://github.com/caolan/async # * # * Copyright 2010-2014 <NAME> # * Released under the MIT license # #jshint onevar: false, indent:4 #global setImmediate: false, setTimeout: false, console: false (-> # global on the server, window in the browser only_once = (fn) -> called = false -> throw new Error("Callback was already called.") if called called = true fn.apply root, arguments return async = {} root = undefined previous_async = undefined root = this previous_async = root.async if root? async.noConflict = -> root.async = previous_async async #// cross-browser compatiblity functions //// _toString = Object::toString _isArray = Array.isArray or (obj) -> _toString.call(obj) is "[object Array]" _each = (arr, iterator) -> return arr.forEach(iterator) if arr.forEach i = 0 while i < arr.length iterator arr[i], i, arr i += 1 return _map = (arr, iterator) -> return arr.map(iterator) if arr.map results = [] _each arr, (x, i, a) -> results.push iterator(x, i, a) return results _reduce = (arr, iterator, memo) -> return arr.reduce(iterator, memo) if arr.reduce _each arr, (x, i, a) -> memo = iterator(memo, x, i, a) return memo _keys = (obj) -> return Object.keys(obj) if Object.keys keys = [] for k of obj keys.push k if obj.hasOwnProperty(k) keys #// exported async module functions //// #// nextTick implementation with browser-compatible fallback //// if typeof process is "undefined" or not (process.nextTick) if typeof setImmediate is "function" async.nextTick = (fn) -> # not a direct alias for IE10 compatibility setImmediate fn return async.setImmediate = async.nextTick else async.nextTick = (fn) -> setTimeout fn, 0 return async.setImmediate = async.nextTick else async.nextTick = process.nextTick if typeof setImmediate isnt "undefined" async.setImmediate = (fn) -> # not a direct alias for IE10 compatibility setImmediate fn return else async.setImmediate = async.nextTick async.each = (arr, iterator, callback) -> done = (err) -> if err callback err callback = -> else completed += 1 callback() if completed >= arr.length return callback = callback or -> return callback() unless arr.length completed = 0 _each arr, (x) -> iterator x, only_once(done) return return async.forEach = async.each async.eachSeries = (arr, iterator, callback) -> callback = callback or -> return callback() unless arr.length completed = 0 iterate = -> iterator arr[completed], (err) -> if err callback err callback = -> else completed += 1 if completed >= arr.length callback() else iterate() return return iterate() return async.forEachSeries = async.eachSeries async.eachLimit = (arr, limit, iterator, callback) -> fn = _eachLimit(limit) fn.apply null, [ arr iterator callback ] return async.forEachLimit = async.eachLimit _eachLimit = (limit) -> (arr, iterator, callback) -> callback = callback or -> return callback() if not arr.length or limit <= 0 completed = 0 started = 0 running = 0 (replenish = -> return callback() if completed >= arr.length while running < limit and started < arr.length started += 1 running += 1 iterator arr[started - 1], (err) -> if err callback err callback = -> else completed += 1 running -= 1 if completed >= arr.length callback() else replenish() return return )() return doParallel = (fn) -> -> args = Array::slice.call(arguments) fn.apply null, [async.each].concat(args) doParallelLimit = (limit, fn) -> -> args = Array::slice.call(arguments) fn.apply null, [_eachLimit(limit)].concat(args) doSeries = (fn) -> -> args = Array::slice.call(arguments) fn.apply null, [async.eachSeries].concat(args) _asyncMap = (eachfn, arr, iterator, callback) -> arr = _map(arr, (x, i) -> index: i value: x ) unless callback eachfn arr, (x, callback) -> iterator x.value, (err) -> callback err return return else results = [] eachfn arr, ((x, callback) -> iterator x.value, (err, v) -> results[x.index] = v callback err return return ), (err) -> callback err, results return return async.map = doParallel(_asyncMap) async.mapSeries = doSeries(_asyncMap) async.mapLimit = (arr, limit, iterator, callback) -> _mapLimit(limit) arr, iterator, callback _mapLimit = (limit) -> doParallelLimit limit, _asyncMap # reduce only has a series version, as doing reduce in parallel won't # work in many situations. async.reduce = (arr, memo, iterator, callback) -> async.eachSeries arr, ((x, callback) -> iterator memo, x, (err, v) -> memo = v callback err return return ), (err) -> callback err, memo return return # inject alias async.inject = async.reduce # foldl alias async.foldl = async.reduce async.reduceRight = (arr, memo, iterator, callback) -> reversed = _map(arr, (x) -> x ).reverse() async.reduce reversed, memo, iterator, callback return # foldr alias async.foldr = async.reduceRight _filter = (eachfn, arr, iterator, callback) -> results = [] arr = _map(arr, (x, i) -> index: i value: x ) eachfn arr, ((x, callback) -> iterator x.value, (v) -> results.push x if v callback() return return ), (err) -> callback _map(results.sort((a, b) -> a.index - b.index ), (x) -> x.value ) return return async.filter = doParallel(_filter) async.filterSeries = doSeries(_filter) # select alias async.select = async.filter async.selectSeries = async.filterSeries _reject = (eachfn, arr, iterator, callback) -> results = [] arr = _map(arr, (x, i) -> index: i value: x ) eachfn arr, ((x, callback) -> iterator x.value, (v) -> results.push x unless v callback() return return ), (err) -> callback _map(results.sort((a, b) -> a.index - b.index ), (x) -> x.value ) return return async.reject = doParallel(_reject) async.rejectSeries = doSeries(_reject) _detect = (eachfn, arr, iterator, main_callback) -> eachfn arr, ((x, callback) -> iterator x, (result) -> if result main_callback x main_callback = -> else callback() return return ), (err) -> main_callback() return return async.detect = doParallel(_detect) async.detectSeries = doSeries(_detect) async.some = (arr, iterator, main_callback) -> async.each arr, ((x, callback) -> iterator x, (v) -> if v main_callback true main_callback = -> callback() return return ), (err) -> main_callback false return return # any alias async.any = async.some async.every = (arr, iterator, main_callback) -> async.each arr, ((x, callback) -> iterator x, (v) -> unless v main_callback false main_callback = -> callback() return return ), (err) -> main_callback true return return # all alias async.all = async.every async.sortBy = (arr, iterator, callback) -> async.map arr, ((x, callback) -> iterator x, (err, criteria) -> if err callback err else callback null, value: x criteria: criteria return return ), (err, results) -> if err callback err else fn = (left, right) -> a = left.criteria b = right.criteria (if a < b then -1 else (if a > b then 1 else 0)) callback null, _map(results.sort(fn), (x) -> x.value ) return return async.auto = (tasks, callback) -> callback = callback or -> keys = _keys(tasks) remainingTasks = keys.length return callback() unless remainingTasks results = {} listeners = [] addListener = (fn) -> listeners.unshift fn return removeListener = (fn) -> i = 0 while i < listeners.length if listeners[i] is fn listeners.splice i, 1 return i += 1 return taskComplete = -> remainingTasks-- _each listeners.slice(0), (fn) -> fn() return return addListener -> unless remainingTasks theCallback = callback # prevent final callback from calling itself if it errors callback = -> theCallback null, results return _each keys, (k) -> task = (if _isArray(tasks[k]) then tasks[k] else [tasks[k]]) taskCallback = (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 if err safeResults = {} _each _keys(results), (rkey) -> safeResults[rkey] = results[rkey] return safeResults[k] = args callback err, safeResults # stop subsequent errors hitting callback multiple times callback = -> else results[k] = args async.setImmediate taskComplete return requires = task.slice(0, Math.abs(task.length - 1)) or [] ready = -> _reduce(requires, (a, x) -> a and results.hasOwnProperty(x) , true) and not results.hasOwnProperty(k) if ready() task[task.length - 1] taskCallback, results else listener = -> if ready() removeListener listener task[task.length - 1] taskCallback, results return addListener listener return return async.retry = (times, task, callback) -> DEFAULT_TIMES = 5 attempts = [] # Use defaults if times not passed if typeof times is "function" callback = task task = times times = DEFAULT_TIMES # Make sure times is a number times = parseInt(times, 10) or DEFAULT_TIMES wrappedTask = (wrappedCallback, wrappedResults) -> retryAttempt = (task, finalAttempt) -> (seriesCallback) -> task ((err, result) -> seriesCallback not err or finalAttempt, err: err result: result return ), wrappedResults return attempts.push retryAttempt(task, not (times -= 1)) while times async.series attempts, (done, data) -> data = data[data.length - 1] (wrappedCallback or callback) data.err, data.result return return # If a callback is passed, run this as a controll flow (if callback then wrappedTask() else wrappedTask) async.waterfall = (tasks, callback) -> callback = callback or -> unless _isArray(tasks) err = new Error("First argument to waterfall must be an array of functions") return callback(err) return callback() unless tasks.length wrapIterator = (iterator) -> (err) -> if err callback.apply null, arguments callback = -> else args = Array::slice.call(arguments, 1) next = iterator.next() if next args.push wrapIterator(next) else args.push callback async.setImmediate -> iterator.apply null, args return return wrapIterator(async.iterator(tasks))() return _parallel = (eachfn, tasks, callback) -> callback = callback or -> if _isArray(tasks) eachfn.map tasks, ((fn, callback) -> if fn fn (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 callback.call null, err, args return return ), callback else results = {} eachfn.each _keys(tasks), ((k, callback) -> tasks[k] (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 results[k] = args callback err return return ), (err) -> callback err, results return return async.parallel = (tasks, callback) -> _parallel map: async.map each: async.each , tasks, callback return async.parallelLimit = (tasks, limit, callback) -> _parallel map: _mapLimit(limit) each: _eachLimit(limit) , tasks, callback return async.series = (tasks, callback) -> callback = callback or -> if _isArray(tasks) async.mapSeries tasks, ((fn, callback) -> if fn fn (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 callback.call null, err, args return return ), callback else results = {} async.eachSeries _keys(tasks), ((k, callback) -> tasks[k] (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 results[k] = args callback err return return ), (err) -> callback err, results return return async.iterator = (tasks) -> makeCallback = (index) -> fn = -> tasks[index].apply null, arguments if tasks.length fn.next() fn.next = -> (if (index < tasks.length - 1) then makeCallback(index + 1) else null) fn makeCallback 0 async.apply = (fn) -> args = Array::slice.call(arguments, 1) -> fn.apply null, args.concat(Array::slice.call(arguments)) _concat = (eachfn, arr, fn, callback) -> r = [] eachfn arr, ((x, cb) -> fn x, (err, y) -> r = r.concat(y or []) cb err return return ), (err) -> callback err, r return return async.concat = doParallel(_concat) async.concatSeries = doSeries(_concat) async.whilst = (test, iterator, callback) -> if test() iterator (err) -> return callback(err) if err async.whilst test, iterator, callback return else callback() return async.doWhilst = (iterator, test, callback) -> iterator (err) -> return callback(err) if err args = Array::slice.call(arguments, 1) if test.apply(null, args) async.doWhilst iterator, test, callback else callback() return return async.until = (test, iterator, callback) -> unless test() iterator (err) -> return callback(err) if err async.until test, iterator, callback return else callback() return async.doUntil = (iterator, test, callback) -> iterator (err) -> return callback(err) if err args = Array::slice.call(arguments, 1) unless test.apply(null, args) async.doUntil iterator, test, callback else callback() return return async.queue = (worker, concurrency) -> _insert = (q, data, pos, callback) -> q.started = true unless q.started data = [data] unless _isArray(data) if data.length is 0 # call drain immediately if there are no tasks return async.setImmediate(-> q.drain() if q.drain return ) _each data, (task) -> item = data: task callback: (if typeof callback is "function" then callback else null) if pos q.tasks.unshift item else q.tasks.push item q.saturated() if q.saturated and q.tasks.length is q.concurrency async.setImmediate q.process return return concurrency = 1 if concurrency is `undefined` workers = 0 q = tasks: [] concurrency: concurrency saturated: null empty: null drain: null started: false paused: false push: (data, callback) -> _insert q, data, false, callback return kill: -> q.drain = null q.tasks = [] return unshift: (data, callback) -> _insert q, data, true, callback return process: -> if not q.paused and workers < q.concurrency and q.tasks.length task = q.tasks.shift() q.empty() if q.empty and q.tasks.length is 0 workers += 1 next = -> workers -= 1 task.callback.apply task, arguments if task.callback q.drain() if q.drain and q.tasks.length + workers is 0 q.process() return cb = only_once(next) worker task.data, cb return length: -> q.tasks.length running: -> workers idle: -> q.tasks.length + workers is 0 pause: -> return if q.paused is true q.paused = true q.process() return resume: -> return if q.paused is false q.paused = false q.process() return q async.priorityQueue = (worker, concurrency) -> _compareTasks = (a, b) -> a.priority - b.priority _binarySearch = (sequence, item, compare) -> beg = -1 end = sequence.length - 1 while beg < end mid = beg + ((end - beg + 1) >>> 1) if compare(item, sequence[mid]) >= 0 beg = mid else end = mid - 1 beg _insert = (q, data, priority, callback) -> q.started = true unless q.started data = [data] unless _isArray(data) if data.length is 0 # call drain immediately if there are no tasks return async.setImmediate(-> q.drain() if q.drain return ) _each data, (task) -> item = data: task priority: priority callback: (if typeof callback is "function" then callback else null) q.tasks.splice _binarySearch(q.tasks, item, _compareTasks) + 1, 0, item q.saturated() if q.saturated and q.tasks.length is q.concurrency async.setImmediate q.process return return # Start with a normal queue q = async.queue(worker, concurrency) # Override push to accept second parameter representing priority q.push = (data, priority, callback) -> _insert q, data, priority, callback return # Remove unshift function delete q.unshift q async.cargo = (worker, payload) -> working = false tasks = [] cargo = tasks: tasks payload: payload saturated: null empty: null drain: null drained: true push: (data, callback) -> data = [data] unless _isArray(data) _each data, (task) -> tasks.push data: task callback: (if typeof callback is "function" then callback else null) cargo.drained = false cargo.saturated() if cargo.saturated and tasks.length is payload return async.setImmediate cargo.process return process: process = -> return if working if tasks.length is 0 cargo.drain() if cargo.drain and not cargo.drained cargo.drained = true return ts = (if typeof payload is "number" then tasks.splice(0, payload) else tasks.splice(0, tasks.length)) ds = _map(ts, (task) -> task.data ) cargo.empty() if cargo.empty working = true worker ds, -> working = false args = arguments _each ts, (data) -> data.callback.apply null, args if data.callback return process() return return length: -> tasks.length running: -> working cargo _console_fn = (name) -> (fn) -> args = Array::slice.call(arguments, 1) fn.apply null, args.concat([(err) -> args = Array::slice.call(arguments, 1) if typeof console isnt "undefined" if err console.error err if console.error else if console[name] _each args, (x) -> console[name] x return return ]) return async.log = _console_fn("log") async.dir = _console_fn("dir") #async.info = _console_fn('info'); # async.warn = _console_fn('warn'); # async.error = _console_fn('error'); async.memoize = (fn, hasher) -> memo = {} queues = {} hasher = hasher or (x) -> x memoized = -> args = Array::slice.call(arguments) callback = args.pop() key = hasher.apply(null, args) if key of memo async.nextTick -> callback.apply null, memo[key] return else if key of queues queues[key].push callback else queues[key] = [callback] fn.apply null, args.concat([-> memo[key] = arguments q = queues[key] delete queues[key] i = 0 l = q.length while i < l q[i].apply null, arguments i++ return ]) return memoized.memo = memo memoized.unmemoized = fn memoized async.unmemoize = (fn) -> -> (fn.unmemoized or fn).apply null, arguments async.times = (count, iterator, callback) -> counter = [] i = 0 while i < count counter.push i i++ async.map counter, iterator, callback async.timesSeries = (count, iterator, callback) -> counter = [] i = 0 while i < count counter.push i i++ async.mapSeries counter, iterator, callback async.seq = -> # functions... fns = arguments -> that = this args = Array::slice.call(arguments) callback = args.pop() async.reduce fns, args, ((newargs, fn, cb) -> fn.apply that, newargs.concat([-> err = arguments[0] nextargs = Array::slice.call(arguments, 1) cb err, nextargs return ]) return ), (err, results) -> callback.apply that, [err].concat(results) return return async.compose = -> # functions... async.seq.apply null, Array::reverse.call(arguments) _applyEach = (eachfn, fns) -> #args... go = -> that = this args = Array::slice.call(arguments) callback = args.pop() eachfn fns, ((fn, cb) -> fn.apply that, args.concat([cb]) return ), callback if arguments.length > 2 args = Array::slice.call(arguments, 2) go.apply this, args else go async.applyEach = doParallel(_applyEach) async.applyEachSeries = doSeries(_applyEach) async.forever = (fn, callback) -> next = (err) -> if err return callback(err) if callback throw err fn next return next() return # Node.js if typeof module isnt "undefined" and module.exports module.exports = async # AMD / RequireJS else if typeof define isnt "undefined" and define.amd define [], -> async # included directly via <script> tag else root.async = async return )()
true
#! # * async # * https://github.com/caolan/async # * # * Copyright 2010-2014 PI:NAME:<NAME>END_PI # * Released under the MIT license # #jshint onevar: false, indent:4 #global setImmediate: false, setTimeout: false, console: false (-> # global on the server, window in the browser only_once = (fn) -> called = false -> throw new Error("Callback was already called.") if called called = true fn.apply root, arguments return async = {} root = undefined previous_async = undefined root = this previous_async = root.async if root? async.noConflict = -> root.async = previous_async async #// cross-browser compatiblity functions //// _toString = Object::toString _isArray = Array.isArray or (obj) -> _toString.call(obj) is "[object Array]" _each = (arr, iterator) -> return arr.forEach(iterator) if arr.forEach i = 0 while i < arr.length iterator arr[i], i, arr i += 1 return _map = (arr, iterator) -> return arr.map(iterator) if arr.map results = [] _each arr, (x, i, a) -> results.push iterator(x, i, a) return results _reduce = (arr, iterator, memo) -> return arr.reduce(iterator, memo) if arr.reduce _each arr, (x, i, a) -> memo = iterator(memo, x, i, a) return memo _keys = (obj) -> return Object.keys(obj) if Object.keys keys = [] for k of obj keys.push k if obj.hasOwnProperty(k) keys #// exported async module functions //// #// nextTick implementation with browser-compatible fallback //// if typeof process is "undefined" or not (process.nextTick) if typeof setImmediate is "function" async.nextTick = (fn) -> # not a direct alias for IE10 compatibility setImmediate fn return async.setImmediate = async.nextTick else async.nextTick = (fn) -> setTimeout fn, 0 return async.setImmediate = async.nextTick else async.nextTick = process.nextTick if typeof setImmediate isnt "undefined" async.setImmediate = (fn) -> # not a direct alias for IE10 compatibility setImmediate fn return else async.setImmediate = async.nextTick async.each = (arr, iterator, callback) -> done = (err) -> if err callback err callback = -> else completed += 1 callback() if completed >= arr.length return callback = callback or -> return callback() unless arr.length completed = 0 _each arr, (x) -> iterator x, only_once(done) return return async.forEach = async.each async.eachSeries = (arr, iterator, callback) -> callback = callback or -> return callback() unless arr.length completed = 0 iterate = -> iterator arr[completed], (err) -> if err callback err callback = -> else completed += 1 if completed >= arr.length callback() else iterate() return return iterate() return async.forEachSeries = async.eachSeries async.eachLimit = (arr, limit, iterator, callback) -> fn = _eachLimit(limit) fn.apply null, [ arr iterator callback ] return async.forEachLimit = async.eachLimit _eachLimit = (limit) -> (arr, iterator, callback) -> callback = callback or -> return callback() if not arr.length or limit <= 0 completed = 0 started = 0 running = 0 (replenish = -> return callback() if completed >= arr.length while running < limit and started < arr.length started += 1 running += 1 iterator arr[started - 1], (err) -> if err callback err callback = -> else completed += 1 running -= 1 if completed >= arr.length callback() else replenish() return return )() return doParallel = (fn) -> -> args = Array::slice.call(arguments) fn.apply null, [async.each].concat(args) doParallelLimit = (limit, fn) -> -> args = Array::slice.call(arguments) fn.apply null, [_eachLimit(limit)].concat(args) doSeries = (fn) -> -> args = Array::slice.call(arguments) fn.apply null, [async.eachSeries].concat(args) _asyncMap = (eachfn, arr, iterator, callback) -> arr = _map(arr, (x, i) -> index: i value: x ) unless callback eachfn arr, (x, callback) -> iterator x.value, (err) -> callback err return return else results = [] eachfn arr, ((x, callback) -> iterator x.value, (err, v) -> results[x.index] = v callback err return return ), (err) -> callback err, results return return async.map = doParallel(_asyncMap) async.mapSeries = doSeries(_asyncMap) async.mapLimit = (arr, limit, iterator, callback) -> _mapLimit(limit) arr, iterator, callback _mapLimit = (limit) -> doParallelLimit limit, _asyncMap # reduce only has a series version, as doing reduce in parallel won't # work in many situations. async.reduce = (arr, memo, iterator, callback) -> async.eachSeries arr, ((x, callback) -> iterator memo, x, (err, v) -> memo = v callback err return return ), (err) -> callback err, memo return return # inject alias async.inject = async.reduce # foldl alias async.foldl = async.reduce async.reduceRight = (arr, memo, iterator, callback) -> reversed = _map(arr, (x) -> x ).reverse() async.reduce reversed, memo, iterator, callback return # foldr alias async.foldr = async.reduceRight _filter = (eachfn, arr, iterator, callback) -> results = [] arr = _map(arr, (x, i) -> index: i value: x ) eachfn arr, ((x, callback) -> iterator x.value, (v) -> results.push x if v callback() return return ), (err) -> callback _map(results.sort((a, b) -> a.index - b.index ), (x) -> x.value ) return return async.filter = doParallel(_filter) async.filterSeries = doSeries(_filter) # select alias async.select = async.filter async.selectSeries = async.filterSeries _reject = (eachfn, arr, iterator, callback) -> results = [] arr = _map(arr, (x, i) -> index: i value: x ) eachfn arr, ((x, callback) -> iterator x.value, (v) -> results.push x unless v callback() return return ), (err) -> callback _map(results.sort((a, b) -> a.index - b.index ), (x) -> x.value ) return return async.reject = doParallel(_reject) async.rejectSeries = doSeries(_reject) _detect = (eachfn, arr, iterator, main_callback) -> eachfn arr, ((x, callback) -> iterator x, (result) -> if result main_callback x main_callback = -> else callback() return return ), (err) -> main_callback() return return async.detect = doParallel(_detect) async.detectSeries = doSeries(_detect) async.some = (arr, iterator, main_callback) -> async.each arr, ((x, callback) -> iterator x, (v) -> if v main_callback true main_callback = -> callback() return return ), (err) -> main_callback false return return # any alias async.any = async.some async.every = (arr, iterator, main_callback) -> async.each arr, ((x, callback) -> iterator x, (v) -> unless v main_callback false main_callback = -> callback() return return ), (err) -> main_callback true return return # all alias async.all = async.every async.sortBy = (arr, iterator, callback) -> async.map arr, ((x, callback) -> iterator x, (err, criteria) -> if err callback err else callback null, value: x criteria: criteria return return ), (err, results) -> if err callback err else fn = (left, right) -> a = left.criteria b = right.criteria (if a < b then -1 else (if a > b then 1 else 0)) callback null, _map(results.sort(fn), (x) -> x.value ) return return async.auto = (tasks, callback) -> callback = callback or -> keys = _keys(tasks) remainingTasks = keys.length return callback() unless remainingTasks results = {} listeners = [] addListener = (fn) -> listeners.unshift fn return removeListener = (fn) -> i = 0 while i < listeners.length if listeners[i] is fn listeners.splice i, 1 return i += 1 return taskComplete = -> remainingTasks-- _each listeners.slice(0), (fn) -> fn() return return addListener -> unless remainingTasks theCallback = callback # prevent final callback from calling itself if it errors callback = -> theCallback null, results return _each keys, (k) -> task = (if _isArray(tasks[k]) then tasks[k] else [tasks[k]]) taskCallback = (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 if err safeResults = {} _each _keys(results), (rkey) -> safeResults[rkey] = results[rkey] return safeResults[k] = args callback err, safeResults # stop subsequent errors hitting callback multiple times callback = -> else results[k] = args async.setImmediate taskComplete return requires = task.slice(0, Math.abs(task.length - 1)) or [] ready = -> _reduce(requires, (a, x) -> a and results.hasOwnProperty(x) , true) and not results.hasOwnProperty(k) if ready() task[task.length - 1] taskCallback, results else listener = -> if ready() removeListener listener task[task.length - 1] taskCallback, results return addListener listener return return async.retry = (times, task, callback) -> DEFAULT_TIMES = 5 attempts = [] # Use defaults if times not passed if typeof times is "function" callback = task task = times times = DEFAULT_TIMES # Make sure times is a number times = parseInt(times, 10) or DEFAULT_TIMES wrappedTask = (wrappedCallback, wrappedResults) -> retryAttempt = (task, finalAttempt) -> (seriesCallback) -> task ((err, result) -> seriesCallback not err or finalAttempt, err: err result: result return ), wrappedResults return attempts.push retryAttempt(task, not (times -= 1)) while times async.series attempts, (done, data) -> data = data[data.length - 1] (wrappedCallback or callback) data.err, data.result return return # If a callback is passed, run this as a controll flow (if callback then wrappedTask() else wrappedTask) async.waterfall = (tasks, callback) -> callback = callback or -> unless _isArray(tasks) err = new Error("First argument to waterfall must be an array of functions") return callback(err) return callback() unless tasks.length wrapIterator = (iterator) -> (err) -> if err callback.apply null, arguments callback = -> else args = Array::slice.call(arguments, 1) next = iterator.next() if next args.push wrapIterator(next) else args.push callback async.setImmediate -> iterator.apply null, args return return wrapIterator(async.iterator(tasks))() return _parallel = (eachfn, tasks, callback) -> callback = callback or -> if _isArray(tasks) eachfn.map tasks, ((fn, callback) -> if fn fn (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 callback.call null, err, args return return ), callback else results = {} eachfn.each _keys(tasks), ((k, callback) -> tasks[k] (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 results[k] = args callback err return return ), (err) -> callback err, results return return async.parallel = (tasks, callback) -> _parallel map: async.map each: async.each , tasks, callback return async.parallelLimit = (tasks, limit, callback) -> _parallel map: _mapLimit(limit) each: _eachLimit(limit) , tasks, callback return async.series = (tasks, callback) -> callback = callback or -> if _isArray(tasks) async.mapSeries tasks, ((fn, callback) -> if fn fn (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 callback.call null, err, args return return ), callback else results = {} async.eachSeries _keys(tasks), ((k, callback) -> tasks[k] (err) -> args = Array::slice.call(arguments, 1) args = args[0] if args.length <= 1 results[k] = args callback err return return ), (err) -> callback err, results return return async.iterator = (tasks) -> makeCallback = (index) -> fn = -> tasks[index].apply null, arguments if tasks.length fn.next() fn.next = -> (if (index < tasks.length - 1) then makeCallback(index + 1) else null) fn makeCallback 0 async.apply = (fn) -> args = Array::slice.call(arguments, 1) -> fn.apply null, args.concat(Array::slice.call(arguments)) _concat = (eachfn, arr, fn, callback) -> r = [] eachfn arr, ((x, cb) -> fn x, (err, y) -> r = r.concat(y or []) cb err return return ), (err) -> callback err, r return return async.concat = doParallel(_concat) async.concatSeries = doSeries(_concat) async.whilst = (test, iterator, callback) -> if test() iterator (err) -> return callback(err) if err async.whilst test, iterator, callback return else callback() return async.doWhilst = (iterator, test, callback) -> iterator (err) -> return callback(err) if err args = Array::slice.call(arguments, 1) if test.apply(null, args) async.doWhilst iterator, test, callback else callback() return return async.until = (test, iterator, callback) -> unless test() iterator (err) -> return callback(err) if err async.until test, iterator, callback return else callback() return async.doUntil = (iterator, test, callback) -> iterator (err) -> return callback(err) if err args = Array::slice.call(arguments, 1) unless test.apply(null, args) async.doUntil iterator, test, callback else callback() return return async.queue = (worker, concurrency) -> _insert = (q, data, pos, callback) -> q.started = true unless q.started data = [data] unless _isArray(data) if data.length is 0 # call drain immediately if there are no tasks return async.setImmediate(-> q.drain() if q.drain return ) _each data, (task) -> item = data: task callback: (if typeof callback is "function" then callback else null) if pos q.tasks.unshift item else q.tasks.push item q.saturated() if q.saturated and q.tasks.length is q.concurrency async.setImmediate q.process return return concurrency = 1 if concurrency is `undefined` workers = 0 q = tasks: [] concurrency: concurrency saturated: null empty: null drain: null started: false paused: false push: (data, callback) -> _insert q, data, false, callback return kill: -> q.drain = null q.tasks = [] return unshift: (data, callback) -> _insert q, data, true, callback return process: -> if not q.paused and workers < q.concurrency and q.tasks.length task = q.tasks.shift() q.empty() if q.empty and q.tasks.length is 0 workers += 1 next = -> workers -= 1 task.callback.apply task, arguments if task.callback q.drain() if q.drain and q.tasks.length + workers is 0 q.process() return cb = only_once(next) worker task.data, cb return length: -> q.tasks.length running: -> workers idle: -> q.tasks.length + workers is 0 pause: -> return if q.paused is true q.paused = true q.process() return resume: -> return if q.paused is false q.paused = false q.process() return q async.priorityQueue = (worker, concurrency) -> _compareTasks = (a, b) -> a.priority - b.priority _binarySearch = (sequence, item, compare) -> beg = -1 end = sequence.length - 1 while beg < end mid = beg + ((end - beg + 1) >>> 1) if compare(item, sequence[mid]) >= 0 beg = mid else end = mid - 1 beg _insert = (q, data, priority, callback) -> q.started = true unless q.started data = [data] unless _isArray(data) if data.length is 0 # call drain immediately if there are no tasks return async.setImmediate(-> q.drain() if q.drain return ) _each data, (task) -> item = data: task priority: priority callback: (if typeof callback is "function" then callback else null) q.tasks.splice _binarySearch(q.tasks, item, _compareTasks) + 1, 0, item q.saturated() if q.saturated and q.tasks.length is q.concurrency async.setImmediate q.process return return # Start with a normal queue q = async.queue(worker, concurrency) # Override push to accept second parameter representing priority q.push = (data, priority, callback) -> _insert q, data, priority, callback return # Remove unshift function delete q.unshift q async.cargo = (worker, payload) -> working = false tasks = [] cargo = tasks: tasks payload: payload saturated: null empty: null drain: null drained: true push: (data, callback) -> data = [data] unless _isArray(data) _each data, (task) -> tasks.push data: task callback: (if typeof callback is "function" then callback else null) cargo.drained = false cargo.saturated() if cargo.saturated and tasks.length is payload return async.setImmediate cargo.process return process: process = -> return if working if tasks.length is 0 cargo.drain() if cargo.drain and not cargo.drained cargo.drained = true return ts = (if typeof payload is "number" then tasks.splice(0, payload) else tasks.splice(0, tasks.length)) ds = _map(ts, (task) -> task.data ) cargo.empty() if cargo.empty working = true worker ds, -> working = false args = arguments _each ts, (data) -> data.callback.apply null, args if data.callback return process() return return length: -> tasks.length running: -> working cargo _console_fn = (name) -> (fn) -> args = Array::slice.call(arguments, 1) fn.apply null, args.concat([(err) -> args = Array::slice.call(arguments, 1) if typeof console isnt "undefined" if err console.error err if console.error else if console[name] _each args, (x) -> console[name] x return return ]) return async.log = _console_fn("log") async.dir = _console_fn("dir") #async.info = _console_fn('info'); # async.warn = _console_fn('warn'); # async.error = _console_fn('error'); async.memoize = (fn, hasher) -> memo = {} queues = {} hasher = hasher or (x) -> x memoized = -> args = Array::slice.call(arguments) callback = args.pop() key = hasher.apply(null, args) if key of memo async.nextTick -> callback.apply null, memo[key] return else if key of queues queues[key].push callback else queues[key] = [callback] fn.apply null, args.concat([-> memo[key] = arguments q = queues[key] delete queues[key] i = 0 l = q.length while i < l q[i].apply null, arguments i++ return ]) return memoized.memo = memo memoized.unmemoized = fn memoized async.unmemoize = (fn) -> -> (fn.unmemoized or fn).apply null, arguments async.times = (count, iterator, callback) -> counter = [] i = 0 while i < count counter.push i i++ async.map counter, iterator, callback async.timesSeries = (count, iterator, callback) -> counter = [] i = 0 while i < count counter.push i i++ async.mapSeries counter, iterator, callback async.seq = -> # functions... fns = arguments -> that = this args = Array::slice.call(arguments) callback = args.pop() async.reduce fns, args, ((newargs, fn, cb) -> fn.apply that, newargs.concat([-> err = arguments[0] nextargs = Array::slice.call(arguments, 1) cb err, nextargs return ]) return ), (err, results) -> callback.apply that, [err].concat(results) return return async.compose = -> # functions... async.seq.apply null, Array::reverse.call(arguments) _applyEach = (eachfn, fns) -> #args... go = -> that = this args = Array::slice.call(arguments) callback = args.pop() eachfn fns, ((fn, cb) -> fn.apply that, args.concat([cb]) return ), callback if arguments.length > 2 args = Array::slice.call(arguments, 2) go.apply this, args else go async.applyEach = doParallel(_applyEach) async.applyEachSeries = doSeries(_applyEach) async.forever = (fn, callback) -> next = (err) -> if err return callback(err) if callback throw err fn next return next() return # Node.js if typeof module isnt "undefined" and module.exports module.exports = async # AMD / RequireJS else if typeof define isnt "undefined" and define.amd define [], -> async # included directly via <script> tag else root.async = async return )()
[ { "context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed under the Apach", "end": 35, "score": 0.9998140931129456, "start": 24, "tag": "NAME", "value": "Dan Elliott" }, { "context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed under the Apache License, Version ", "end": 54, "score": 0.9998003840446472, "start": 37, "tag": "NAME", "value": "Russell Valentine" } ]
clients/www/src/coffee/handler/isadore_current_bl_filltab.coffee
bluthen/isadore_server
0
# Copyright 2010-2019 Dan Elliott, Russell Valentine # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class window.FillTab constructor: () -> self = this self.currentBin_ = null self.fill_ = null $('#bin_lightbox_fill_edit').click(() -> self.editClick_()) $('#bin_lightbox_fill_new').click(() -> self.newClick_()) reopenBinLightbox_: () -> self = this self.refresh(self.currentBin_) _getYear: (yfill) -> if yfill.filled_datetime? year = newDate(yfill.filled_datetime).getFullYear() else year = newDate(yfill.air_begin_datetime).getFullYear() return year; editClick_: () -> self = this lightboxHandlers.editFillLightbox.open({ year: self._getYear(self.fill), fill_id: self.fill.id, customCloseCallback: () -> self.reopenBinLightbox_() }) newClick_: () -> self = this lightboxHandlers.editFillLightbox.open({ year: new Date().getFullYear() bin_id: self.currentBin_.id customCloseCallback: () -> self.reopenBinLightbox_() }) refreshNonArrayForm_: () -> self = this $('#bin_lightbox_fillinfo_fillnumber').html(self.fill.fill_number) $('#bin_lightbox_fillinfo_fill_type').text(_.find(IsadoreData.fillTypes, {id: self.fill.fill_type_id}).name) $('#bin_lightbox_fillinfo_bin').html(self.fill.bin_id) if not IsadoreData.general.multiple_rolls $('#bin_lightbox_fillinfo_single_roll_option').show() $('#bin_lightbox_fill_info_multiple_rolls_option').hide() else $('#bin_lightbox_fillinfo_single_roll_option').hide() $('#bin_lightbox_fill_info_multiple_rolls_option').show() # Blank all the non-required fields $('#bin_lightbox_fillinfo_start, #bin_lightbox_fillinfo_end, #bin_lightbox_fillinfo_filled, #bin_lightbox_fillinfo_emptied, #bin_lightbox_fillinfo_rotationnumber, #bin_lightbox_fillinfo_hybridcode, #bin_lightbox_fillinfo_fieldcode, #bin_lightbox_fillinfo_truck, #bin_lightbox_fillinfo_lotnumber, #bin_lightbox_fillinfo_storagebinnumber, #bin_lightbox_fillinfo_storagebincode, #bin_lightbox_fillinfo_bushels, #bin_lightbox_fillinfo_single_roll').each( (index, value) -> $(value).html('') ) if self.fill.filled_datetime $('#bin_lightbox_fillinfo_filled').html( HTMLHelper.dateToReadableO2(newDate(self.fill.filled_datetime))) if self.fill.emptied_datetime $('#bin_lightbox_fillinfo_emptied').html( HTMLHelper.dateToReadableO2(newDate(self.fill.emptied_datetime))) if self.fill.air_begin_datetime $('#bin_lightbox_fillinfo_start').html( HTMLHelper.dateToReadableO2(newDate(self.fill.air_begin_datetime))) if self.fill.air_end_datetime $('#bin_lightbox_fillinfo_end').html( HTMLHelper.dateToReadableO2(newDate(self.fill.air_end_datetime))) if self.fill.roll_datetime && self.fill.roll_datetime.length > 0 $('#bin_lightbox_fillinfo_single_roll').html( HTMLHelper .dateToReadableO2(newDate(self.fill.roll_datetime[0]))) if self.fill.rotation_number $('#bin_lightbox_fillinfo_rotationnumber').html(self.fill.rotation_number) if self.fill.hybrid_code $('#bin_lightbox_fillinfo_hybridcode').html(self.fill.hybrid_code.replace("\n", '</br>')) if self.fill.field_code $('#bin_lightbox_fillinfo_fieldcode').html(self.fill.field_code.replace("\n", '</br>')) if self.fill.truck $('#bin_lightbox_fillinfo_truck').html(self.fill.truck.replace("\n", '</br>')) if self.fill.lot_number $('#bin_lightbox_fillinfo_lotnumber').html(self.fill.lot_number) if self.fill.storage_bin_number $('#bin_lightbox_fillinfo_storagebinnumber').html(self.fill.storage_bin_number) if self.fill.storage_bin_code $('#bin_lightbox_fillinfo_storagebincode').html(self.fill.storage_bin_code) if self.fill.bushels $('#bin_lightbox_fillinfo_bushels').html(self.fill.bushels) # Updates the page with current fill roll information. refreshRolls_: () -> self = this html = [] if self.fill.roll_datetime for rdt in self.fill.roll_datetime html.push('<li><span class="roll_date">'); html.push(HTMLHelper.dateToReadableO2(newDate(rdt))) html.push('</span>'); html.push('</li>'); ul = $('#bin_lightbox_fillinfo_rolls ul') ul.html(html.join('')) # Updates the page with current fill mc data. refreshMC_: () -> self = this labels = ["pre_mc", "post_mc"] if IsadoreData.general.during_mc labels.push("during_mc") for label in labels html = [] arr = self.fill[label] if arr for mc in arr html.push('<li><span class="mc_value">') if label == "during_mc" html.push(mc[0].toFixed(1)) html.push('%') html.push(" ") html.push(HTMLHelper.dateToReadableO2(newDate(mc[1]))); else html.push(mc.toFixed(1)) html.push('%') html.push('</span>') html.push('</li>') ul = $('#bin_lightbox_fillinfo_' + label) ul.html(html.join('')) _refresh2: (foundFill) -> self = this if self.currentBin_.name.split(' ')[0] != 'Bin' $('#bin_lightbox_fill_info_na_binname').html(self.currentBin_.name) $('#bin_lightbox_fillinfo_na').show() $('#bin_lightbox_fill_buttons').hide() $('#bin_lightbox_fillinfo_nonexist').hide() $('#bin_lightbox_fillinfo_exist').hide() $('#bin_lightbox_fill_spinner').hide() $('#bin_lightbox_fill_wrapper').show() return $('#bin_lightbox_fill_buttons').show() $('#bin_lightbox_fillinfo_na').hide() self.fill = foundFill if not self.fill $('#bin_lightbox_fillinfo_nonexist').show() $('#bin_lightbox_fillinfo_exist').hide() $('#bin_lightbox_fill_edit').hide() else self.refreshNonArrayForm_() self.refreshRolls_() self.refreshMC_() $('#bin_lightbox_fillinfo_nonexist').hide() $('#bin_lightbox_fillinfo_exist').show() $('#bin_lightbox_fill_edit').show() $('#bin_lightbox_fill_spinner').hide() $('#bin_lightbox_fill_wrapper').show() cbResize() refresh: (bin) -> self = this $('#bin_lightbox_fill_wrapper').hide() $('#bin_lightbox_fill_spinner').show() self.currentBin_ = bin self.fill = null DataManager.getFills({ year: new Date().getFullYear(), callback: (d) => fills = d.fills; fill = CurrentDataUtil.getBinFill(fills, bin.id, false) if _.isEmpty(fill) fill = null self._refresh2(fill) })
162080
# Copyright 2010-2019 <NAME>, <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class window.FillTab constructor: () -> self = this self.currentBin_ = null self.fill_ = null $('#bin_lightbox_fill_edit').click(() -> self.editClick_()) $('#bin_lightbox_fill_new').click(() -> self.newClick_()) reopenBinLightbox_: () -> self = this self.refresh(self.currentBin_) _getYear: (yfill) -> if yfill.filled_datetime? year = newDate(yfill.filled_datetime).getFullYear() else year = newDate(yfill.air_begin_datetime).getFullYear() return year; editClick_: () -> self = this lightboxHandlers.editFillLightbox.open({ year: self._getYear(self.fill), fill_id: self.fill.id, customCloseCallback: () -> self.reopenBinLightbox_() }) newClick_: () -> self = this lightboxHandlers.editFillLightbox.open({ year: new Date().getFullYear() bin_id: self.currentBin_.id customCloseCallback: () -> self.reopenBinLightbox_() }) refreshNonArrayForm_: () -> self = this $('#bin_lightbox_fillinfo_fillnumber').html(self.fill.fill_number) $('#bin_lightbox_fillinfo_fill_type').text(_.find(IsadoreData.fillTypes, {id: self.fill.fill_type_id}).name) $('#bin_lightbox_fillinfo_bin').html(self.fill.bin_id) if not IsadoreData.general.multiple_rolls $('#bin_lightbox_fillinfo_single_roll_option').show() $('#bin_lightbox_fill_info_multiple_rolls_option').hide() else $('#bin_lightbox_fillinfo_single_roll_option').hide() $('#bin_lightbox_fill_info_multiple_rolls_option').show() # Blank all the non-required fields $('#bin_lightbox_fillinfo_start, #bin_lightbox_fillinfo_end, #bin_lightbox_fillinfo_filled, #bin_lightbox_fillinfo_emptied, #bin_lightbox_fillinfo_rotationnumber, #bin_lightbox_fillinfo_hybridcode, #bin_lightbox_fillinfo_fieldcode, #bin_lightbox_fillinfo_truck, #bin_lightbox_fillinfo_lotnumber, #bin_lightbox_fillinfo_storagebinnumber, #bin_lightbox_fillinfo_storagebincode, #bin_lightbox_fillinfo_bushels, #bin_lightbox_fillinfo_single_roll').each( (index, value) -> $(value).html('') ) if self.fill.filled_datetime $('#bin_lightbox_fillinfo_filled').html( HTMLHelper.dateToReadableO2(newDate(self.fill.filled_datetime))) if self.fill.emptied_datetime $('#bin_lightbox_fillinfo_emptied').html( HTMLHelper.dateToReadableO2(newDate(self.fill.emptied_datetime))) if self.fill.air_begin_datetime $('#bin_lightbox_fillinfo_start').html( HTMLHelper.dateToReadableO2(newDate(self.fill.air_begin_datetime))) if self.fill.air_end_datetime $('#bin_lightbox_fillinfo_end').html( HTMLHelper.dateToReadableO2(newDate(self.fill.air_end_datetime))) if self.fill.roll_datetime && self.fill.roll_datetime.length > 0 $('#bin_lightbox_fillinfo_single_roll').html( HTMLHelper .dateToReadableO2(newDate(self.fill.roll_datetime[0]))) if self.fill.rotation_number $('#bin_lightbox_fillinfo_rotationnumber').html(self.fill.rotation_number) if self.fill.hybrid_code $('#bin_lightbox_fillinfo_hybridcode').html(self.fill.hybrid_code.replace("\n", '</br>')) if self.fill.field_code $('#bin_lightbox_fillinfo_fieldcode').html(self.fill.field_code.replace("\n", '</br>')) if self.fill.truck $('#bin_lightbox_fillinfo_truck').html(self.fill.truck.replace("\n", '</br>')) if self.fill.lot_number $('#bin_lightbox_fillinfo_lotnumber').html(self.fill.lot_number) if self.fill.storage_bin_number $('#bin_lightbox_fillinfo_storagebinnumber').html(self.fill.storage_bin_number) if self.fill.storage_bin_code $('#bin_lightbox_fillinfo_storagebincode').html(self.fill.storage_bin_code) if self.fill.bushels $('#bin_lightbox_fillinfo_bushels').html(self.fill.bushels) # Updates the page with current fill roll information. refreshRolls_: () -> self = this html = [] if self.fill.roll_datetime for rdt in self.fill.roll_datetime html.push('<li><span class="roll_date">'); html.push(HTMLHelper.dateToReadableO2(newDate(rdt))) html.push('</span>'); html.push('</li>'); ul = $('#bin_lightbox_fillinfo_rolls ul') ul.html(html.join('')) # Updates the page with current fill mc data. refreshMC_: () -> self = this labels = ["pre_mc", "post_mc"] if IsadoreData.general.during_mc labels.push("during_mc") for label in labels html = [] arr = self.fill[label] if arr for mc in arr html.push('<li><span class="mc_value">') if label == "during_mc" html.push(mc[0].toFixed(1)) html.push('%') html.push(" ") html.push(HTMLHelper.dateToReadableO2(newDate(mc[1]))); else html.push(mc.toFixed(1)) html.push('%') html.push('</span>') html.push('</li>') ul = $('#bin_lightbox_fillinfo_' + label) ul.html(html.join('')) _refresh2: (foundFill) -> self = this if self.currentBin_.name.split(' ')[0] != 'Bin' $('#bin_lightbox_fill_info_na_binname').html(self.currentBin_.name) $('#bin_lightbox_fillinfo_na').show() $('#bin_lightbox_fill_buttons').hide() $('#bin_lightbox_fillinfo_nonexist').hide() $('#bin_lightbox_fillinfo_exist').hide() $('#bin_lightbox_fill_spinner').hide() $('#bin_lightbox_fill_wrapper').show() return $('#bin_lightbox_fill_buttons').show() $('#bin_lightbox_fillinfo_na').hide() self.fill = foundFill if not self.fill $('#bin_lightbox_fillinfo_nonexist').show() $('#bin_lightbox_fillinfo_exist').hide() $('#bin_lightbox_fill_edit').hide() else self.refreshNonArrayForm_() self.refreshRolls_() self.refreshMC_() $('#bin_lightbox_fillinfo_nonexist').hide() $('#bin_lightbox_fillinfo_exist').show() $('#bin_lightbox_fill_edit').show() $('#bin_lightbox_fill_spinner').hide() $('#bin_lightbox_fill_wrapper').show() cbResize() refresh: (bin) -> self = this $('#bin_lightbox_fill_wrapper').hide() $('#bin_lightbox_fill_spinner').show() self.currentBin_ = bin self.fill = null DataManager.getFills({ year: new Date().getFullYear(), callback: (d) => fills = d.fills; fill = CurrentDataUtil.getBinFill(fills, bin.id, false) if _.isEmpty(fill) fill = null self._refresh2(fill) })
true
# Copyright 2010-2019 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class window.FillTab constructor: () -> self = this self.currentBin_ = null self.fill_ = null $('#bin_lightbox_fill_edit').click(() -> self.editClick_()) $('#bin_lightbox_fill_new').click(() -> self.newClick_()) reopenBinLightbox_: () -> self = this self.refresh(self.currentBin_) _getYear: (yfill) -> if yfill.filled_datetime? year = newDate(yfill.filled_datetime).getFullYear() else year = newDate(yfill.air_begin_datetime).getFullYear() return year; editClick_: () -> self = this lightboxHandlers.editFillLightbox.open({ year: self._getYear(self.fill), fill_id: self.fill.id, customCloseCallback: () -> self.reopenBinLightbox_() }) newClick_: () -> self = this lightboxHandlers.editFillLightbox.open({ year: new Date().getFullYear() bin_id: self.currentBin_.id customCloseCallback: () -> self.reopenBinLightbox_() }) refreshNonArrayForm_: () -> self = this $('#bin_lightbox_fillinfo_fillnumber').html(self.fill.fill_number) $('#bin_lightbox_fillinfo_fill_type').text(_.find(IsadoreData.fillTypes, {id: self.fill.fill_type_id}).name) $('#bin_lightbox_fillinfo_bin').html(self.fill.bin_id) if not IsadoreData.general.multiple_rolls $('#bin_lightbox_fillinfo_single_roll_option').show() $('#bin_lightbox_fill_info_multiple_rolls_option').hide() else $('#bin_lightbox_fillinfo_single_roll_option').hide() $('#bin_lightbox_fill_info_multiple_rolls_option').show() # Blank all the non-required fields $('#bin_lightbox_fillinfo_start, #bin_lightbox_fillinfo_end, #bin_lightbox_fillinfo_filled, #bin_lightbox_fillinfo_emptied, #bin_lightbox_fillinfo_rotationnumber, #bin_lightbox_fillinfo_hybridcode, #bin_lightbox_fillinfo_fieldcode, #bin_lightbox_fillinfo_truck, #bin_lightbox_fillinfo_lotnumber, #bin_lightbox_fillinfo_storagebinnumber, #bin_lightbox_fillinfo_storagebincode, #bin_lightbox_fillinfo_bushels, #bin_lightbox_fillinfo_single_roll').each( (index, value) -> $(value).html('') ) if self.fill.filled_datetime $('#bin_lightbox_fillinfo_filled').html( HTMLHelper.dateToReadableO2(newDate(self.fill.filled_datetime))) if self.fill.emptied_datetime $('#bin_lightbox_fillinfo_emptied').html( HTMLHelper.dateToReadableO2(newDate(self.fill.emptied_datetime))) if self.fill.air_begin_datetime $('#bin_lightbox_fillinfo_start').html( HTMLHelper.dateToReadableO2(newDate(self.fill.air_begin_datetime))) if self.fill.air_end_datetime $('#bin_lightbox_fillinfo_end').html( HTMLHelper.dateToReadableO2(newDate(self.fill.air_end_datetime))) if self.fill.roll_datetime && self.fill.roll_datetime.length > 0 $('#bin_lightbox_fillinfo_single_roll').html( HTMLHelper .dateToReadableO2(newDate(self.fill.roll_datetime[0]))) if self.fill.rotation_number $('#bin_lightbox_fillinfo_rotationnumber').html(self.fill.rotation_number) if self.fill.hybrid_code $('#bin_lightbox_fillinfo_hybridcode').html(self.fill.hybrid_code.replace("\n", '</br>')) if self.fill.field_code $('#bin_lightbox_fillinfo_fieldcode').html(self.fill.field_code.replace("\n", '</br>')) if self.fill.truck $('#bin_lightbox_fillinfo_truck').html(self.fill.truck.replace("\n", '</br>')) if self.fill.lot_number $('#bin_lightbox_fillinfo_lotnumber').html(self.fill.lot_number) if self.fill.storage_bin_number $('#bin_lightbox_fillinfo_storagebinnumber').html(self.fill.storage_bin_number) if self.fill.storage_bin_code $('#bin_lightbox_fillinfo_storagebincode').html(self.fill.storage_bin_code) if self.fill.bushels $('#bin_lightbox_fillinfo_bushels').html(self.fill.bushels) # Updates the page with current fill roll information. refreshRolls_: () -> self = this html = [] if self.fill.roll_datetime for rdt in self.fill.roll_datetime html.push('<li><span class="roll_date">'); html.push(HTMLHelper.dateToReadableO2(newDate(rdt))) html.push('</span>'); html.push('</li>'); ul = $('#bin_lightbox_fillinfo_rolls ul') ul.html(html.join('')) # Updates the page with current fill mc data. refreshMC_: () -> self = this labels = ["pre_mc", "post_mc"] if IsadoreData.general.during_mc labels.push("during_mc") for label in labels html = [] arr = self.fill[label] if arr for mc in arr html.push('<li><span class="mc_value">') if label == "during_mc" html.push(mc[0].toFixed(1)) html.push('%') html.push(" ") html.push(HTMLHelper.dateToReadableO2(newDate(mc[1]))); else html.push(mc.toFixed(1)) html.push('%') html.push('</span>') html.push('</li>') ul = $('#bin_lightbox_fillinfo_' + label) ul.html(html.join('')) _refresh2: (foundFill) -> self = this if self.currentBin_.name.split(' ')[0] != 'Bin' $('#bin_lightbox_fill_info_na_binname').html(self.currentBin_.name) $('#bin_lightbox_fillinfo_na').show() $('#bin_lightbox_fill_buttons').hide() $('#bin_lightbox_fillinfo_nonexist').hide() $('#bin_lightbox_fillinfo_exist').hide() $('#bin_lightbox_fill_spinner').hide() $('#bin_lightbox_fill_wrapper').show() return $('#bin_lightbox_fill_buttons').show() $('#bin_lightbox_fillinfo_na').hide() self.fill = foundFill if not self.fill $('#bin_lightbox_fillinfo_nonexist').show() $('#bin_lightbox_fillinfo_exist').hide() $('#bin_lightbox_fill_edit').hide() else self.refreshNonArrayForm_() self.refreshRolls_() self.refreshMC_() $('#bin_lightbox_fillinfo_nonexist').hide() $('#bin_lightbox_fillinfo_exist').show() $('#bin_lightbox_fill_edit').show() $('#bin_lightbox_fill_spinner').hide() $('#bin_lightbox_fill_wrapper').show() cbResize() refresh: (bin) -> self = this $('#bin_lightbox_fill_wrapper').hide() $('#bin_lightbox_fill_spinner').show() self.currentBin_ = bin self.fill = null DataManager.getFills({ year: new Date().getFullYear(), callback: (d) => fills = d.fills; fill = CurrentDataUtil.getBinFill(fills, bin.id, false) if _.isEmpty(fill) fill = null self._refresh2(fill) })
[ { "context": "ey can be used', ->\n flow = 'EXR'\n key = '.CHF+NOK.EUR..2'\n q = AvailabilityQuery.from({flow: flow, ke", "end": 2113, "score": 0.9984492063522339, "start": 2097, "tag": "KEY", "value": "'.CHF+NOK.EUR..2" }, { "context": " query.should.have.property('key').that.equals 'D.NOK+RUB+CHF.EUR..A'\n\n it 'a mixed array can be used to build the ", "end": 2647, "score": 0.9955073595046997, "start": 2627, "tag": "KEY", "value": "D.NOK+RUB+CHF.EUR..A" }, { "context": " query.should.have.property('key').that.equals 'D.NOK+RUB+CHF..SP00.'\n\n it 'an exotic array can be used to build the", "end": 3015, "score": 0.9864736199378967, "start": 2994, "tag": "KEY", "value": "D.NOK+RUB+CHF..SP00.'" }, { "context": " query.should.have.property('key').that.equals '.NOK+RUB+CHF.EUR..'\n\n it 'throws an exception if the value for th", "end": 3383, "score": 0.9920970797538757, "start": 3364, "tag": "KEY", "value": "'.NOK+RUB+CHF.EUR.." }, { "context": " = -> AvailabilityQuery.from({flow: 'EXR', key: '1%'})\n should.Throw(test, Error, 'Not a valid a", "end": 3516, "score": 0.5048392415046692, "start": 3515, "tag": "KEY", "value": "%" } ]
test/avail/availability-query.test.coffee
sosna/sdmx-rest.js
16
should = require('chai').should() {AvailabilityMode} = require '../../src/avail/availability-mode' {AvailabilityReferences} = require '../../src/avail/availability-references' {AvailabilityQuery} = require '../../src/avail/availability-query' describe 'Availability queries', -> it 'has the expected properties', -> q = AvailabilityQuery.from {flow: 'ICP'} q.should.be.an 'object' q.should.have.property 'flow' q.should.have.property 'key' q.should.have.property 'provider' q.should.have.property 'component' q.should.have.property 'start' q.should.have.property 'end' q.should.have.property 'updatedAfter' q.should.have.property 'mode' q.should.have.property 'references' it 'has the expected defaults', -> flow = 'EXR' q = AvailabilityQuery.from {flow: flow} q.should.have.property('flow').that.equals flow q.should.have.property('key').that.equals 'all' q.should.have.property('provider').that.equals 'all' q.should.have.property('component').that.equals 'all' q.should.have.property('start').that.is.undefined q.should.have.property('end').that.is.undefined q.should.have.property('updatedAfter').that.is.undefined q.should.have.property('mode').that.equals 'exact' q.should.have.property('references').that.equals 'none' it 'throws an exception when using an unknown property', -> test = -> AvailabilityQuery.from({flow: 'EXR', type: 'blah'}) describe 'when setting the flow', -> it 'throws an exception when the flow is not set', -> test = -> AvailabilityQuery.from({flow: ' '}) should.Throw(test, Error, 'Not a valid availability query') test = -> AvailabilityQuery.from({flow: undefined}) should.Throw(test, Error, 'Not a valid availability query') it 'throws an exception when the flow is invalid', -> test = -> AvailabilityQuery.from({flow: '1%'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the key', -> it 'a string representing the key can be used', -> flow = 'EXR' key = '.CHF+NOK.EUR..2' q = AvailabilityQuery.from({flow: flow, key: key}) q.should.have.property('flow').that.equals flow q.should.have.property('key').that.equals key it 'an array of arrays can be used to build the key', -> values = [ ['D'] ['NOK', 'RUB', 'CHF'] ['EUR'] [] ['A'] ] query = AvailabilityQuery.from({flow: 'EXR', key: values}) query.should.have.property('flow').that.equals 'EXR' query.should.have.property('key').that.equals 'D.NOK+RUB+CHF.EUR..A' it 'a mixed array can be used to build the key', -> values = [ 'D' ['NOK', 'RUB', 'CHF'] '' 'SP00' undefined ] query = AvailabilityQuery.from({flow: 'EXR', key: values}) query.should.have.property('flow').that.equals 'EXR' query.should.have.property('key').that.equals 'D.NOK+RUB+CHF..SP00.' it 'an exotic array can be used to build the key', -> values = [ '' ['NOK', 'RUB', 'CHF'] ['EUR'] undefined null ] query = AvailabilityQuery.from({flow: 'EXR', key: values}) query.should.have.property('flow').that.equals 'EXR' query.should.have.property('key').that.equals '.NOK+RUB+CHF.EUR..' it 'throws an exception if the value for the key is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', key: '1%'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the provider', -> it 'a string representing the provider can be used', -> flow = 'EXR' provider = 'ECB' q = AvailabilityQuery.from({flow: flow, provider: provider}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals provider provider = 'SDMX,ECB' q = AvailabilityQuery.from({flow: flow, provider: provider}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals provider it 'throws an exception if the value for provider is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', provider: 'SDMX,ECB,2.0'}) should.Throw(test, Error, 'Not a valid availability query') it 'a string representing multiple providers can be used', -> flow = 'EXR' provider = 'ECB+BIS' q = AvailabilityQuery.from({flow: flow, provider: provider}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals provider it 'an array representing multiple providers can be used', -> flow = 'EXR' providers = ['SDMX,ECB', 'BIS'] q = AvailabilityQuery.from({flow: flow, provider: providers}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals 'SDMX,ECB+BIS' describe 'when setting the start and end periods', -> it 'a string representing years can be passed', -> flow = 'EXR' start = '2000' end = '2004' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing months can be passed', -> flow = 'EXR' start = '2000-01' end = '2004-12' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing days can be passed', -> flow = 'EXR' start = '2000-01-01' end = '2004-12-31' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing quarters can be passed', -> flow = 'EXR' start = '2000-Q1' end = '2004-Q4' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing semesters can be passed', -> flow = 'EXR' start = '2000-S1' end = '2004-S4' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing weeks can be passed', -> flow = 'EXR' start = '2000-W01' end = '2004-W53' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'throws an exception if the value for start period is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', start: 'SDMX,ECB,2.0'}) should.Throw(test, Error, 'Not a valid availability query') it 'throws an exception if the value for end period is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', end: 'SDMX,ECB,2.0'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the updatedAfter timestamp', -> it 'a string representing a timestamp can be passed', -> flow = 'EXR' last = '2016-03-04T09:57:00Z' q = AvailabilityQuery.from({flow: flow, updatedAfter: last}) q.should.have.property('flow').that.equals flow q.should.have.property('updatedAfter').that.equals last it 'throws an exception if the value for updatedAfter is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', updatedAfter: 'now'}) should.Throw(test, Error, 'Not a valid availability query') test = -> AvailabilityQuery.from({flow: 'EXR', updatedAfter: '2000-Q1'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the component ID', -> it 'a string representing the component id can be passed', -> cp = 'A' query = AvailabilityQuery.from({flow: 'EXR', component: cp}) query.should.have.property('component').that.equals cp it 'throws an exception if the component id is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', component: ' '}) should.Throw(test, Error, 'Not a valid availability query') test = -> AvailabilityQuery.from({flow: 'EXR', component: 'A*'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the processing mode', -> it 'a string representing the amount of details can be passed', -> mode = AvailabilityMode.AVAILABLE query = AvailabilityQuery.from({flow: 'EXR', mode: mode}) query.should.have.property('mode').that.equals mode it 'throws an exception if the value for mode is unknown', -> test = -> AvailabilityQuery.from({flow: 'EXR', mode: 'test'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the references', -> it 'a string representing the references to be resolved can be passed', -> refs = AvailabilityReferences.CONCEPT_SCHEME query = AvailabilityQuery.from({flow: 'EXR', references: refs}) query.should.have.property('references').that.equals refs it 'throws an exception if the value for references is unknown', -> test = -> AvailabilityQuery.from({flow: 'dataflow', references: 'ref'}) should.Throw(test, Error, 'Not a valid availability query')
2865
should = require('chai').should() {AvailabilityMode} = require '../../src/avail/availability-mode' {AvailabilityReferences} = require '../../src/avail/availability-references' {AvailabilityQuery} = require '../../src/avail/availability-query' describe 'Availability queries', -> it 'has the expected properties', -> q = AvailabilityQuery.from {flow: 'ICP'} q.should.be.an 'object' q.should.have.property 'flow' q.should.have.property 'key' q.should.have.property 'provider' q.should.have.property 'component' q.should.have.property 'start' q.should.have.property 'end' q.should.have.property 'updatedAfter' q.should.have.property 'mode' q.should.have.property 'references' it 'has the expected defaults', -> flow = 'EXR' q = AvailabilityQuery.from {flow: flow} q.should.have.property('flow').that.equals flow q.should.have.property('key').that.equals 'all' q.should.have.property('provider').that.equals 'all' q.should.have.property('component').that.equals 'all' q.should.have.property('start').that.is.undefined q.should.have.property('end').that.is.undefined q.should.have.property('updatedAfter').that.is.undefined q.should.have.property('mode').that.equals 'exact' q.should.have.property('references').that.equals 'none' it 'throws an exception when using an unknown property', -> test = -> AvailabilityQuery.from({flow: 'EXR', type: 'blah'}) describe 'when setting the flow', -> it 'throws an exception when the flow is not set', -> test = -> AvailabilityQuery.from({flow: ' '}) should.Throw(test, Error, 'Not a valid availability query') test = -> AvailabilityQuery.from({flow: undefined}) should.Throw(test, Error, 'Not a valid availability query') it 'throws an exception when the flow is invalid', -> test = -> AvailabilityQuery.from({flow: '1%'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the key', -> it 'a string representing the key can be used', -> flow = 'EXR' key = <KEY>' q = AvailabilityQuery.from({flow: flow, key: key}) q.should.have.property('flow').that.equals flow q.should.have.property('key').that.equals key it 'an array of arrays can be used to build the key', -> values = [ ['D'] ['NOK', 'RUB', 'CHF'] ['EUR'] [] ['A'] ] query = AvailabilityQuery.from({flow: 'EXR', key: values}) query.should.have.property('flow').that.equals 'EXR' query.should.have.property('key').that.equals '<KEY>' it 'a mixed array can be used to build the key', -> values = [ 'D' ['NOK', 'RUB', 'CHF'] '' 'SP00' undefined ] query = AvailabilityQuery.from({flow: 'EXR', key: values}) query.should.have.property('flow').that.equals 'EXR' query.should.have.property('key').that.equals '<KEY> it 'an exotic array can be used to build the key', -> values = [ '' ['NOK', 'RUB', 'CHF'] ['EUR'] undefined null ] query = AvailabilityQuery.from({flow: 'EXR', key: values}) query.should.have.property('flow').that.equals 'EXR' query.should.have.property('key').that.equals <KEY>' it 'throws an exception if the value for the key is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', key: '1<KEY>'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the provider', -> it 'a string representing the provider can be used', -> flow = 'EXR' provider = 'ECB' q = AvailabilityQuery.from({flow: flow, provider: provider}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals provider provider = 'SDMX,ECB' q = AvailabilityQuery.from({flow: flow, provider: provider}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals provider it 'throws an exception if the value for provider is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', provider: 'SDMX,ECB,2.0'}) should.Throw(test, Error, 'Not a valid availability query') it 'a string representing multiple providers can be used', -> flow = 'EXR' provider = 'ECB+BIS' q = AvailabilityQuery.from({flow: flow, provider: provider}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals provider it 'an array representing multiple providers can be used', -> flow = 'EXR' providers = ['SDMX,ECB', 'BIS'] q = AvailabilityQuery.from({flow: flow, provider: providers}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals 'SDMX,ECB+BIS' describe 'when setting the start and end periods', -> it 'a string representing years can be passed', -> flow = 'EXR' start = '2000' end = '2004' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing months can be passed', -> flow = 'EXR' start = '2000-01' end = '2004-12' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing days can be passed', -> flow = 'EXR' start = '2000-01-01' end = '2004-12-31' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing quarters can be passed', -> flow = 'EXR' start = '2000-Q1' end = '2004-Q4' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing semesters can be passed', -> flow = 'EXR' start = '2000-S1' end = '2004-S4' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing weeks can be passed', -> flow = 'EXR' start = '2000-W01' end = '2004-W53' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'throws an exception if the value for start period is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', start: 'SDMX,ECB,2.0'}) should.Throw(test, Error, 'Not a valid availability query') it 'throws an exception if the value for end period is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', end: 'SDMX,ECB,2.0'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the updatedAfter timestamp', -> it 'a string representing a timestamp can be passed', -> flow = 'EXR' last = '2016-03-04T09:57:00Z' q = AvailabilityQuery.from({flow: flow, updatedAfter: last}) q.should.have.property('flow').that.equals flow q.should.have.property('updatedAfter').that.equals last it 'throws an exception if the value for updatedAfter is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', updatedAfter: 'now'}) should.Throw(test, Error, 'Not a valid availability query') test = -> AvailabilityQuery.from({flow: 'EXR', updatedAfter: '2000-Q1'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the component ID', -> it 'a string representing the component id can be passed', -> cp = 'A' query = AvailabilityQuery.from({flow: 'EXR', component: cp}) query.should.have.property('component').that.equals cp it 'throws an exception if the component id is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', component: ' '}) should.Throw(test, Error, 'Not a valid availability query') test = -> AvailabilityQuery.from({flow: 'EXR', component: 'A*'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the processing mode', -> it 'a string representing the amount of details can be passed', -> mode = AvailabilityMode.AVAILABLE query = AvailabilityQuery.from({flow: 'EXR', mode: mode}) query.should.have.property('mode').that.equals mode it 'throws an exception if the value for mode is unknown', -> test = -> AvailabilityQuery.from({flow: 'EXR', mode: 'test'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the references', -> it 'a string representing the references to be resolved can be passed', -> refs = AvailabilityReferences.CONCEPT_SCHEME query = AvailabilityQuery.from({flow: 'EXR', references: refs}) query.should.have.property('references').that.equals refs it 'throws an exception if the value for references is unknown', -> test = -> AvailabilityQuery.from({flow: 'dataflow', references: 'ref'}) should.Throw(test, Error, 'Not a valid availability query')
true
should = require('chai').should() {AvailabilityMode} = require '../../src/avail/availability-mode' {AvailabilityReferences} = require '../../src/avail/availability-references' {AvailabilityQuery} = require '../../src/avail/availability-query' describe 'Availability queries', -> it 'has the expected properties', -> q = AvailabilityQuery.from {flow: 'ICP'} q.should.be.an 'object' q.should.have.property 'flow' q.should.have.property 'key' q.should.have.property 'provider' q.should.have.property 'component' q.should.have.property 'start' q.should.have.property 'end' q.should.have.property 'updatedAfter' q.should.have.property 'mode' q.should.have.property 'references' it 'has the expected defaults', -> flow = 'EXR' q = AvailabilityQuery.from {flow: flow} q.should.have.property('flow').that.equals flow q.should.have.property('key').that.equals 'all' q.should.have.property('provider').that.equals 'all' q.should.have.property('component').that.equals 'all' q.should.have.property('start').that.is.undefined q.should.have.property('end').that.is.undefined q.should.have.property('updatedAfter').that.is.undefined q.should.have.property('mode').that.equals 'exact' q.should.have.property('references').that.equals 'none' it 'throws an exception when using an unknown property', -> test = -> AvailabilityQuery.from({flow: 'EXR', type: 'blah'}) describe 'when setting the flow', -> it 'throws an exception when the flow is not set', -> test = -> AvailabilityQuery.from({flow: ' '}) should.Throw(test, Error, 'Not a valid availability query') test = -> AvailabilityQuery.from({flow: undefined}) should.Throw(test, Error, 'Not a valid availability query') it 'throws an exception when the flow is invalid', -> test = -> AvailabilityQuery.from({flow: '1%'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the key', -> it 'a string representing the key can be used', -> flow = 'EXR' key = PI:KEY:<KEY>END_PI' q = AvailabilityQuery.from({flow: flow, key: key}) q.should.have.property('flow').that.equals flow q.should.have.property('key').that.equals key it 'an array of arrays can be used to build the key', -> values = [ ['D'] ['NOK', 'RUB', 'CHF'] ['EUR'] [] ['A'] ] query = AvailabilityQuery.from({flow: 'EXR', key: values}) query.should.have.property('flow').that.equals 'EXR' query.should.have.property('key').that.equals 'PI:KEY:<KEY>END_PI' it 'a mixed array can be used to build the key', -> values = [ 'D' ['NOK', 'RUB', 'CHF'] '' 'SP00' undefined ] query = AvailabilityQuery.from({flow: 'EXR', key: values}) query.should.have.property('flow').that.equals 'EXR' query.should.have.property('key').that.equals 'PI:KEY:<KEY>END_PI it 'an exotic array can be used to build the key', -> values = [ '' ['NOK', 'RUB', 'CHF'] ['EUR'] undefined null ] query = AvailabilityQuery.from({flow: 'EXR', key: values}) query.should.have.property('flow').that.equals 'EXR' query.should.have.property('key').that.equals PI:KEY:<KEY>END_PI' it 'throws an exception if the value for the key is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', key: '1PI:KEY:<KEY>END_PI'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the provider', -> it 'a string representing the provider can be used', -> flow = 'EXR' provider = 'ECB' q = AvailabilityQuery.from({flow: flow, provider: provider}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals provider provider = 'SDMX,ECB' q = AvailabilityQuery.from({flow: flow, provider: provider}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals provider it 'throws an exception if the value for provider is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', provider: 'SDMX,ECB,2.0'}) should.Throw(test, Error, 'Not a valid availability query') it 'a string representing multiple providers can be used', -> flow = 'EXR' provider = 'ECB+BIS' q = AvailabilityQuery.from({flow: flow, provider: provider}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals provider it 'an array representing multiple providers can be used', -> flow = 'EXR' providers = ['SDMX,ECB', 'BIS'] q = AvailabilityQuery.from({flow: flow, provider: providers}) q.should.have.property('flow').that.equals flow q.should.have.property('provider').that.equals 'SDMX,ECB+BIS' describe 'when setting the start and end periods', -> it 'a string representing years can be passed', -> flow = 'EXR' start = '2000' end = '2004' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing months can be passed', -> flow = 'EXR' start = '2000-01' end = '2004-12' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing days can be passed', -> flow = 'EXR' start = '2000-01-01' end = '2004-12-31' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing quarters can be passed', -> flow = 'EXR' start = '2000-Q1' end = '2004-Q4' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing semesters can be passed', -> flow = 'EXR' start = '2000-S1' end = '2004-S4' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'a string representing weeks can be passed', -> flow = 'EXR' start = '2000-W01' end = '2004-W53' q = AvailabilityQuery.from({flow: flow, start: start, end: end}) q.should.have.property('flow').that.equals flow q.should.have.property('start').that.equals start q.should.have.property('end').that.equals end it 'throws an exception if the value for start period is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', start: 'SDMX,ECB,2.0'}) should.Throw(test, Error, 'Not a valid availability query') it 'throws an exception if the value for end period is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', end: 'SDMX,ECB,2.0'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the updatedAfter timestamp', -> it 'a string representing a timestamp can be passed', -> flow = 'EXR' last = '2016-03-04T09:57:00Z' q = AvailabilityQuery.from({flow: flow, updatedAfter: last}) q.should.have.property('flow').that.equals flow q.should.have.property('updatedAfter').that.equals last it 'throws an exception if the value for updatedAfter is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', updatedAfter: 'now'}) should.Throw(test, Error, 'Not a valid availability query') test = -> AvailabilityQuery.from({flow: 'EXR', updatedAfter: '2000-Q1'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the component ID', -> it 'a string representing the component id can be passed', -> cp = 'A' query = AvailabilityQuery.from({flow: 'EXR', component: cp}) query.should.have.property('component').that.equals cp it 'throws an exception if the component id is invalid', -> test = -> AvailabilityQuery.from({flow: 'EXR', component: ' '}) should.Throw(test, Error, 'Not a valid availability query') test = -> AvailabilityQuery.from({flow: 'EXR', component: 'A*'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the processing mode', -> it 'a string representing the amount of details can be passed', -> mode = AvailabilityMode.AVAILABLE query = AvailabilityQuery.from({flow: 'EXR', mode: mode}) query.should.have.property('mode').that.equals mode it 'throws an exception if the value for mode is unknown', -> test = -> AvailabilityQuery.from({flow: 'EXR', mode: 'test'}) should.Throw(test, Error, 'Not a valid availability query') describe 'when setting the references', -> it 'a string representing the references to be resolved can be passed', -> refs = AvailabilityReferences.CONCEPT_SCHEME query = AvailabilityQuery.from({flow: 'EXR', references: refs}) query.should.have.property('references').that.equals refs it 'throws an exception if the value for references is unknown', -> test = -> AvailabilityQuery.from({flow: 'dataflow', references: 'ref'}) should.Throw(test, Error, 'Not a valid availability query')
[ { "context": "rtext password with the hash\n user.password = hash\n next()\n\n\nUserSchema.methods.comparePassword", "end": 828, "score": 0.6199815273284912, "start": 824, "tag": "PASSWORD", "value": "hash" } ]
app/models/user.coffee
kvchen/mizzen
1
bcrypt = require 'bcrypt' mongoose = require 'mongoose' UserSchema = new mongoose.Schema username: type: String required: true unique: true password: type: String required: true first: type: String required: true last: type: String required: true courses: [{type: mongoose.Schema.Types.ObjectId, ref: 'Course'}] # Middleware for hashing passwords UserSchema.pre 'save', (next) -> user = this # Hash the password if it is new return next() if !user.isModified 'password' # Generate a salt bcrypt.genSalt 12, (err, salt) -> return next err if err # Hash the password using our new salt bcrypt.hash user.password, salt, (err, hash) -> return next err if err # Override the cleartext password with the hash user.password = hash next() UserSchema.methods.comparePassword = (candidate, cb) -> bcrypt.compare candidate, this.password, (err, match) -> return cb err if err cb null, match User = mongoose.model 'User', UserSchema module.exports = User
202992
bcrypt = require 'bcrypt' mongoose = require 'mongoose' UserSchema = new mongoose.Schema username: type: String required: true unique: true password: type: String required: true first: type: String required: true last: type: String required: true courses: [{type: mongoose.Schema.Types.ObjectId, ref: 'Course'}] # Middleware for hashing passwords UserSchema.pre 'save', (next) -> user = this # Hash the password if it is new return next() if !user.isModified 'password' # Generate a salt bcrypt.genSalt 12, (err, salt) -> return next err if err # Hash the password using our new salt bcrypt.hash user.password, salt, (err, hash) -> return next err if err # Override the cleartext password with the hash user.password = <PASSWORD> next() UserSchema.methods.comparePassword = (candidate, cb) -> bcrypt.compare candidate, this.password, (err, match) -> return cb err if err cb null, match User = mongoose.model 'User', UserSchema module.exports = User
true
bcrypt = require 'bcrypt' mongoose = require 'mongoose' UserSchema = new mongoose.Schema username: type: String required: true unique: true password: type: String required: true first: type: String required: true last: type: String required: true courses: [{type: mongoose.Schema.Types.ObjectId, ref: 'Course'}] # Middleware for hashing passwords UserSchema.pre 'save', (next) -> user = this # Hash the password if it is new return next() if !user.isModified 'password' # Generate a salt bcrypt.genSalt 12, (err, salt) -> return next err if err # Hash the password using our new salt bcrypt.hash user.password, salt, (err, hash) -> return next err if err # Override the cleartext password with the hash user.password = PI:PASSWORD:<PASSWORD>END_PI next() UserSchema.methods.comparePassword = (candidate, cb) -> bcrypt.compare candidate, this.password, (err, match) -> return cb err if err cb null, match User = mongoose.model 'User', UserSchema module.exports = User
[ { "context": "ore installing/testing this plugin\n#\n# Author:\n# Ravikiran Janardhana <ravikiran.j.127@gmail.com>\n\nemoticonRegex = /\\([", "end": 362, "score": 0.9998880624771118, "start": 342, "tag": "NAME", "value": "Ravikiran Janardhana" }, { "context": "this plugin\n#\n# Author:\n# Ravikiran Janardhana <ravikiran.j.127@gmail.com>\n\nemoticonRegex = /\\([a-z0-9]+\\)/g\ntopRegex = /^\\", "end": 389, "score": 0.9999350309371948, "start": 364, "tag": "EMAIL", "value": "ravikiran.j.127@gmail.com" }, { "context": "msg.message.user\n if user.mention_name == 'hbot'\n return\n\n # Ignore messages st", "end": 2195, "score": 0.9959957599639893, "start": 2191, "tag": "USERNAME", "value": "hbot" }, { "context": "essage.user.reply_to\n if room_xmpp_jid != \"1_shire@conf.btf.hipchat.com\"\n return\n\n ", "end": 3562, "score": 0.5670995712280273, "start": 3555, "tag": "EMAIL", "value": "1_shire" }, { "context": "eply_to\n if room_xmpp_jid != \"1_shire@conf.btf.hipchat.com\"\n return\n\n op = [", "end": 3569, "score": 0.5058155059814453, "start": 3568, "tag": "EMAIL", "value": "b" } ]
src/emoticon-stats.coffee
ravikiranj/hubot-emoticon-stats
0
# Description # Emoticon Stats # # Configuration: # # Commands: # /emoticon top - lists top 10 emoticons used # /emoticon bottom - lists bottom 10 emoticons sorted by count # /emoticon (emoticon) - lists count of a particular emoticon # # Notes: # Please install a redis server before installing/testing this plugin # # Author: # Ravikiran Janardhana <ravikiran.j.127@gmail.com> emoticonRegex = /\([a-z0-9]+\)/g topRegex = /^\/emoticon top$/i bottomRegex = /^\/emoticon bottom$/i emoticonCountRegex = /^\/emoticon\s+(\([a-z0-9]+\))\s*$/i allRegex = /^\/emoticon all$/i class EmoticonCounts constructor: (@robot) -> @cache = emoticonCounts: {} @robot.brain.on 'loaded', => @robot.brain.data.emoticonCounts = @robot.brain.data.emoticonCounts || {} @cache.emoticonCounts = @robot.brain.data.emoticonCounts initCounts: (counts) -> @cache.emoticonCounts = counts getEmoticonCount: (emoticon) -> @cache.emoticonCounts[emoticon] = @cache.emoticonCounts[emoticon] || 0 return @cache.emoticonCounts[emoticon] getEmoticonCountWithoutDefaultWrite: (emoticon) -> return @cache.emoticonCounts[emoticon] || 0 saveEmoticonCount: (emoticon) -> @robot.brain.data.emoticonCounts[emoticon] = @cache.emoticonCounts[emoticon] @robot.brain.emit('save', @robot.brain.data) updateEmoticonCount: (emoticon) -> @cache.emoticonCounts[emoticon] = @getEmoticonCount(emoticon) + 1 @saveEmoticonCount(emoticon) return @cache.emoticonCounts[emoticon] top: (n) -> tops = [] for emoticon, count of @cache.emoticonCounts tops.push(emoticon: emoticon, count: count) return tops.sort((a,b) -> b.count - a.count).slice(0, n) bottom: (n) -> all = @top(@cache.emoticonCounts.length) return all.reverse().slice(0, n) all: -> return @top(@cache.emoticonCounts.length) module.exports = (robot) -> emoticonCounts = new EmoticonCounts(robot) robot.hear emoticonRegex, (msg) -> # Ignore hbot messages user = msg.message.user if user.mention_name == 'hbot' return # Ignore messages starting with '/emoticon' if msg.message.text.startsWith('/emoticon') return for input in msg.match result = emoticonRegex.exec(input) # See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#Description emoticonRegex.lastIndex = 0 if result? and result[0]? emoticon = result[0].trim() value = emoticonCounts.updateEmoticonCount(emoticon) robot.hear topRegex, (msg) -> op = [] n = 10 top = emoticonCounts.top(n) for i in [0..top.length - 1] op.push("#{top[i].count} #{top[i].emoticon}") msg.send op.join("\n") robot.hear bottomRegex, (msg) -> op = [] n = 10 bottom = emoticonCounts.bottom(n) for i in [0..bottom.length - 1] op.push("#{bottom[i].count} #{bottom[i].emoticon}") msg.send op.join("\n") robot.hear emoticonCountRegex, (msg) -> emoticon = msg.match[1] count = emoticonCounts.getEmoticonCountWithoutDefaultWrite(emoticon) msg.send "#{emoticon} = #{count}" robot.hear allRegex, (msg) -> # Only respond if in Shire room_xmpp_jid = msg.message.user.reply_to if room_xmpp_jid != "1_shire@conf.btf.hipchat.com" return op = [] all = emoticonCounts.all() for i in [0..all.length - 1] op.push("#{all[i].count} #{all[i].emoticon}") msg.send op.join("\n")
53611
# Description # Emoticon Stats # # Configuration: # # Commands: # /emoticon top - lists top 10 emoticons used # /emoticon bottom - lists bottom 10 emoticons sorted by count # /emoticon (emoticon) - lists count of a particular emoticon # # Notes: # Please install a redis server before installing/testing this plugin # # Author: # <NAME> <<EMAIL>> emoticonRegex = /\([a-z0-9]+\)/g topRegex = /^\/emoticon top$/i bottomRegex = /^\/emoticon bottom$/i emoticonCountRegex = /^\/emoticon\s+(\([a-z0-9]+\))\s*$/i allRegex = /^\/emoticon all$/i class EmoticonCounts constructor: (@robot) -> @cache = emoticonCounts: {} @robot.brain.on 'loaded', => @robot.brain.data.emoticonCounts = @robot.brain.data.emoticonCounts || {} @cache.emoticonCounts = @robot.brain.data.emoticonCounts initCounts: (counts) -> @cache.emoticonCounts = counts getEmoticonCount: (emoticon) -> @cache.emoticonCounts[emoticon] = @cache.emoticonCounts[emoticon] || 0 return @cache.emoticonCounts[emoticon] getEmoticonCountWithoutDefaultWrite: (emoticon) -> return @cache.emoticonCounts[emoticon] || 0 saveEmoticonCount: (emoticon) -> @robot.brain.data.emoticonCounts[emoticon] = @cache.emoticonCounts[emoticon] @robot.brain.emit('save', @robot.brain.data) updateEmoticonCount: (emoticon) -> @cache.emoticonCounts[emoticon] = @getEmoticonCount(emoticon) + 1 @saveEmoticonCount(emoticon) return @cache.emoticonCounts[emoticon] top: (n) -> tops = [] for emoticon, count of @cache.emoticonCounts tops.push(emoticon: emoticon, count: count) return tops.sort((a,b) -> b.count - a.count).slice(0, n) bottom: (n) -> all = @top(@cache.emoticonCounts.length) return all.reverse().slice(0, n) all: -> return @top(@cache.emoticonCounts.length) module.exports = (robot) -> emoticonCounts = new EmoticonCounts(robot) robot.hear emoticonRegex, (msg) -> # Ignore hbot messages user = msg.message.user if user.mention_name == 'hbot' return # Ignore messages starting with '/emoticon' if msg.message.text.startsWith('/emoticon') return for input in msg.match result = emoticonRegex.exec(input) # See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#Description emoticonRegex.lastIndex = 0 if result? and result[0]? emoticon = result[0].trim() value = emoticonCounts.updateEmoticonCount(emoticon) robot.hear topRegex, (msg) -> op = [] n = 10 top = emoticonCounts.top(n) for i in [0..top.length - 1] op.push("#{top[i].count} #{top[i].emoticon}") msg.send op.join("\n") robot.hear bottomRegex, (msg) -> op = [] n = 10 bottom = emoticonCounts.bottom(n) for i in [0..bottom.length - 1] op.push("#{bottom[i].count} #{bottom[i].emoticon}") msg.send op.join("\n") robot.hear emoticonCountRegex, (msg) -> emoticon = msg.match[1] count = emoticonCounts.getEmoticonCountWithoutDefaultWrite(emoticon) msg.send "#{emoticon} = #{count}" robot.hear allRegex, (msg) -> # Only respond if in Shire room_xmpp_jid = msg.message.user.reply_to if room_xmpp_jid != "<EMAIL>@conf.<EMAIL>tf.hipchat.com" return op = [] all = emoticonCounts.all() for i in [0..all.length - 1] op.push("#{all[i].count} #{all[i].emoticon}") msg.send op.join("\n")
true
# Description # Emoticon Stats # # Configuration: # # Commands: # /emoticon top - lists top 10 emoticons used # /emoticon bottom - lists bottom 10 emoticons sorted by count # /emoticon (emoticon) - lists count of a particular emoticon # # Notes: # Please install a redis server before installing/testing this plugin # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> emoticonRegex = /\([a-z0-9]+\)/g topRegex = /^\/emoticon top$/i bottomRegex = /^\/emoticon bottom$/i emoticonCountRegex = /^\/emoticon\s+(\([a-z0-9]+\))\s*$/i allRegex = /^\/emoticon all$/i class EmoticonCounts constructor: (@robot) -> @cache = emoticonCounts: {} @robot.brain.on 'loaded', => @robot.brain.data.emoticonCounts = @robot.brain.data.emoticonCounts || {} @cache.emoticonCounts = @robot.brain.data.emoticonCounts initCounts: (counts) -> @cache.emoticonCounts = counts getEmoticonCount: (emoticon) -> @cache.emoticonCounts[emoticon] = @cache.emoticonCounts[emoticon] || 0 return @cache.emoticonCounts[emoticon] getEmoticonCountWithoutDefaultWrite: (emoticon) -> return @cache.emoticonCounts[emoticon] || 0 saveEmoticonCount: (emoticon) -> @robot.brain.data.emoticonCounts[emoticon] = @cache.emoticonCounts[emoticon] @robot.brain.emit('save', @robot.brain.data) updateEmoticonCount: (emoticon) -> @cache.emoticonCounts[emoticon] = @getEmoticonCount(emoticon) + 1 @saveEmoticonCount(emoticon) return @cache.emoticonCounts[emoticon] top: (n) -> tops = [] for emoticon, count of @cache.emoticonCounts tops.push(emoticon: emoticon, count: count) return tops.sort((a,b) -> b.count - a.count).slice(0, n) bottom: (n) -> all = @top(@cache.emoticonCounts.length) return all.reverse().slice(0, n) all: -> return @top(@cache.emoticonCounts.length) module.exports = (robot) -> emoticonCounts = new EmoticonCounts(robot) robot.hear emoticonRegex, (msg) -> # Ignore hbot messages user = msg.message.user if user.mention_name == 'hbot' return # Ignore messages starting with '/emoticon' if msg.message.text.startsWith('/emoticon') return for input in msg.match result = emoticonRegex.exec(input) # See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#Description emoticonRegex.lastIndex = 0 if result? and result[0]? emoticon = result[0].trim() value = emoticonCounts.updateEmoticonCount(emoticon) robot.hear topRegex, (msg) -> op = [] n = 10 top = emoticonCounts.top(n) for i in [0..top.length - 1] op.push("#{top[i].count} #{top[i].emoticon}") msg.send op.join("\n") robot.hear bottomRegex, (msg) -> op = [] n = 10 bottom = emoticonCounts.bottom(n) for i in [0..bottom.length - 1] op.push("#{bottom[i].count} #{bottom[i].emoticon}") msg.send op.join("\n") robot.hear emoticonCountRegex, (msg) -> emoticon = msg.match[1] count = emoticonCounts.getEmoticonCountWithoutDefaultWrite(emoticon) msg.send "#{emoticon} = #{count}" robot.hear allRegex, (msg) -> # Only respond if in Shire room_xmpp_jid = msg.message.user.reply_to if room_xmpp_jid != "PI:EMAIL:<EMAIL>END_PI@conf.PI:EMAIL:<EMAIL>END_PItf.hipchat.com" return op = [] all = emoticonCounts.all() for i in [0..all.length - 1] op.push("#{all[i].count} #{all[i].emoticon}") msg.send op.join("\n")
[ { "context": " parentView: mockParent\n bodyPart: {subject: \"Greetings!\", value: \"Welcome to Vulcan!\"}\n overlayPa", "end": 1376, "score": 0.5044839382171631, "start": 1372, "tag": "NAME", "value": "reet" } ]
test/javascripts/components/inline_edit_email_test.js.coffee
johan--/tahi
1
moduleForComponent 'inline-edit-email', 'Unit: components/inline-edit-email', setup: -> setupApp() test '#sendEmail', -> targetObject = emailMock: (data) -> ok true, 'sends the sendEmail action to its target' ok data.subject == "Greetings!", "contains the subject" ok data.body == "Welcome to Vulcan!", "contains the body" mockParent = send: (arg) -> ok arg == 'save', "sends save to the parentView" emailSentStates: Ember.ArrayProxy.create(content: []) component = @subject() component.setProperties sendEmail: 'emailMock' bodyPart: {subject: "Greetings!", value: "Welcome to Vulcan!"} overlayParticipants: [Ember.Object.create(id: 5)] recipients: [Ember.Object.create(id: 5)] targetObject: targetObject parentView: mockParent showChooseReceivers: true component.send 'sendEmail' ok !component.get('showChooseReceivers'), 'turns off the receivers selector' ok component.get('emailSentStates').contains('Greetings!'), 'records itself as sent to the controller' test 'shows itelf as sent based on emailSentStates', -> mockParent = send: (arg) -> ok arg == 'save', "sends save to the parentView" emailSentStates: Ember.ArrayProxy.create(content: ['Greetings!']) component = @subject() component.setProperties parentView: mockParent bodyPart: {subject: "Greetings!", value: "Welcome to Vulcan!"} overlayParticipants: [Ember.Object.create(id: 5)] recipients: [Ember.Object.create(id: 5)] showChooseReceivers: true ok component.get('showSentMessage'), 'It shows up when its key is in emailSentStates' component.send 'clearEmailSent' ok !component.get('showSentMessage'), "It doesn't show up after clearing"
126127
moduleForComponent 'inline-edit-email', 'Unit: components/inline-edit-email', setup: -> setupApp() test '#sendEmail', -> targetObject = emailMock: (data) -> ok true, 'sends the sendEmail action to its target' ok data.subject == "Greetings!", "contains the subject" ok data.body == "Welcome to Vulcan!", "contains the body" mockParent = send: (arg) -> ok arg == 'save', "sends save to the parentView" emailSentStates: Ember.ArrayProxy.create(content: []) component = @subject() component.setProperties sendEmail: 'emailMock' bodyPart: {subject: "Greetings!", value: "Welcome to Vulcan!"} overlayParticipants: [Ember.Object.create(id: 5)] recipients: [Ember.Object.create(id: 5)] targetObject: targetObject parentView: mockParent showChooseReceivers: true component.send 'sendEmail' ok !component.get('showChooseReceivers'), 'turns off the receivers selector' ok component.get('emailSentStates').contains('Greetings!'), 'records itself as sent to the controller' test 'shows itelf as sent based on emailSentStates', -> mockParent = send: (arg) -> ok arg == 'save', "sends save to the parentView" emailSentStates: Ember.ArrayProxy.create(content: ['Greetings!']) component = @subject() component.setProperties parentView: mockParent bodyPart: {subject: "G<NAME>ings!", value: "Welcome to Vulcan!"} overlayParticipants: [Ember.Object.create(id: 5)] recipients: [Ember.Object.create(id: 5)] showChooseReceivers: true ok component.get('showSentMessage'), 'It shows up when its key is in emailSentStates' component.send 'clearEmailSent' ok !component.get('showSentMessage'), "It doesn't show up after clearing"
true
moduleForComponent 'inline-edit-email', 'Unit: components/inline-edit-email', setup: -> setupApp() test '#sendEmail', -> targetObject = emailMock: (data) -> ok true, 'sends the sendEmail action to its target' ok data.subject == "Greetings!", "contains the subject" ok data.body == "Welcome to Vulcan!", "contains the body" mockParent = send: (arg) -> ok arg == 'save', "sends save to the parentView" emailSentStates: Ember.ArrayProxy.create(content: []) component = @subject() component.setProperties sendEmail: 'emailMock' bodyPart: {subject: "Greetings!", value: "Welcome to Vulcan!"} overlayParticipants: [Ember.Object.create(id: 5)] recipients: [Ember.Object.create(id: 5)] targetObject: targetObject parentView: mockParent showChooseReceivers: true component.send 'sendEmail' ok !component.get('showChooseReceivers'), 'turns off the receivers selector' ok component.get('emailSentStates').contains('Greetings!'), 'records itself as sent to the controller' test 'shows itelf as sent based on emailSentStates', -> mockParent = send: (arg) -> ok arg == 'save', "sends save to the parentView" emailSentStates: Ember.ArrayProxy.create(content: ['Greetings!']) component = @subject() component.setProperties parentView: mockParent bodyPart: {subject: "GPI:NAME:<NAME>END_PIings!", value: "Welcome to Vulcan!"} overlayParticipants: [Ember.Object.create(id: 5)] recipients: [Ember.Object.create(id: 5)] showChooseReceivers: true ok component.get('showSentMessage'), 'It shows up when its key is in emailSentStates' component.send 'clearEmailSent' ok !component.get('showSentMessage'), "It doesn't show up after clearing"
[ { "context": "e keys in the data. Every key of the form:\n # `req123_xxx` will be used to populate its map.\n reg", "end": 12295, "score": 0.6132519841194153, "start": 12292, "tag": "KEY", "value": "req" }, { "context": " support watchFile. See:\n # https://github.com/josephg/node-browserchannel/pull/6\n fs.watch clientFil", "end": 15654, "score": 0.9996442794799805, "start": 15647, "tag": "USERNAME", "value": "josephg" }, { "context": " to be unique.\n # [node-hat]: https://github.com/substack/node-hat\n #\n # This method is synchronous, beca", "end": 34911, "score": 0.9941619634628296, "start": 34903, "tag": "USERNAME", "value": "substack" } ]
lib/server.coffee
adig/node-browserchannel
0
# # A BrowserChannel server. # # - Its still pretty young, so there's probably bugs lurking around and the API # will still change quickly. # - Its missing integration tests # # It works in all the browsers I've tried. # # I've written this using the literate programming style to try it out. So, thats why # there's a million comments everywhere. # # The server is implemented an express middleware. Its intended to be used like this: # # ``` # server = express(); # server.use(browserChannel(function(client) { client.send('hi'); })); # ``` # ## Dependancies, helper methods and constant data # `parse` helps us decode URLs in requests {parse} = require 'url' # `querystring` will help decode the URL-encoded forward channel data querystring = require 'querystring' # `fs` is used to read & serve the client library fs = require 'fs' # Client sessions are `EventEmitters` {EventEmitter} = require 'events' # Client session Ids are generated using `node-hat` hat = require('hat').rack(40, 36) # When sending messages to IE using a hidden iframe, UTF8-encoded characters # don't get processed correctly. This encodes unicode characters using the # \u2028 encoding style, which (thankfully) makes it through. asciijson = require 'ascii-json' # `randomInt(n)` generates and returns a random int smaller than n (0 <= k < n) randomInt = (n) -> Math.floor(Math.random() * n) # `randomArrayElement(array)` Selects and returns a random element from *array* randomArrayElement = (array) -> array[randomInt(array.length)] # For testing we'll override `setInterval`, etc with special testing stub versions (so # we don't have to actually wait for actual *time*. To do that, we need local variable # versions (I don't want to edit the global versions). ... and they'll just point to the # normal versions anyway. {setInterval, clearInterval, setTimeout, clearTimeout, Date} = global # The module is configurable defaultOptions = # An optional array of host prefixes. Each browserchannel client will # randomly pick from the list of host prefixes when it connects. This reduces # the impact of per-host connection limits. # # All host prefixes should point to the same server. Ie, if your server's # hostname is *example.com* and your hostPrefixes contains ['a', 'b', 'c'], # a.example.com, b.example.com and c.example.com should all point to the same # host as example.com. hostPrefixes: null # You can specify the base URL which browserchannel connects to. Change this # if you want to scope browserchannel in part of your app, or if you want # /channel to mean something else, or whatever. # # I really want to remove this parameter - express 4.0's router is now good # enough that you can just install the middleware anywhere using express. For # example: # app.use('/mycoolpath', browserchannel({base:''}, ...)); # # Unfortunately you have to force the base option to '' to do that (since it # defaults to /channel otherwise). What a pain. TODO browserchannel 3.0 base: '/channel' # We'll send keepalives every so often to make sure the http connection isn't # closed by eagar clients. The standard timeout is 30 seconds, so we'll # default to sending them every 20 seconds or so. keepAliveInterval: 20 * 1000 # After awhile (30 seconds or so) of not having a backchannel connected, # we'll evict the session completely. This will happen whenever a user closes # their browser. sessionTimeoutInterval: 30 * 1000 # By default, browsers don't allow access via javascript to foreign sites. # You can use the cors: option to set the Access-Control-Allow-Origin header # in responses, which tells browsers whether or not to allow cross domain # requests to be sent. # # See https://developer.mozilla.org/en/http_access_control for more information. # # Setting cors:'*' will enable javascript from any domain to access your # application. BE CAREFUL! If your application uses cookies to manage user # sessions, javascript on a foreign site could make requests as if it were # acting on behalf of one of your users. # # Setting cors:'X' is equivalent to adding # {headers: {'Access-Control-Allow-Origin':X}}. cors: null # Even with Access-Control-Allow-Origin enabled, browsers don't send their # cookies to different domains. You can set corsAllowCredentials to be true # to add the `Access-Control-Allow-Credentials: true` header to responses. # This tells browsers they are allowed to send credentialed requests (ie, # requests with cookies) to a foreign domain. If you do this, you must *also* # set {crossDomainXhr:true} in your BCSocket browser options to tell XHR # requests to send credentials. # # Also note that credentialed requests require explicitly mentioned domains # to work. You cannot use a wildcard cors header (`cors:*`) if you want # credentials. # # See: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Requests_with_credentials # # Setting corsAllowCredentials:true is equivalent to adding: # {headers: {'Access-Control-Allow-Credentials':true}}. corsAllowCredentials: false # A user can override all the headers if they want by setting the headers # option to an object. headers: null # All server responses set some standard HTTP headers. To be honest, I don't # know how many of these are necessary. I just copied them from google. # # The nocache headers in particular seem unnecessary since each client request # includes a randomized `zx=junk` query parameter. standardHeaders = 'Content-Type': 'text/plain' 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate' 'Pragma': 'no-cache' 'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT' 'X-Content-Type-Options': 'nosniff' # Gmail also sends this, though I'm not really sure what it does... # 'X-Xss-Protection': '1; mode=block' # The one exception to that is requests destined for iframes. They need to have # content-type: text/html set for IE to process the juicy JS inside. ieHeaders = {} ieHeaders[k] = v for k, v of standardHeaders ieHeaders['Content-Type'] = 'text/html' # Google's browserchannel server adds some junk after the first message data is # sent. I assume this stops some whole-page buffering in IE. I assume the data # used is noise so it doesn't compress. # # I don't really know why google does this. I'm assuming there's a good reason # to it though. ieJunk = "7cca69475363026330a0d99468e88d23ce95e222591126443015f5f462d9a177186c8701fb45a6ffe\ e0daf1a178fc0f58cd309308fba7e6f011ac38c9cdd4580760f1d4560a84d5ca0355ecbbed2ab715a3350fe0c47\ 9050640bd0e77acec90c58c4d3dd0f5cf8d4510e68c8b12e087bd88cad349aafd2ab16b07b0b1b8276091217a44\ a9fe92fedacffff48092ee693af\n" # If the user is using IE, instead of using XHR backchannel loaded using a # forever iframe. When data is sent, it is wrapped in <script></script> tags # which call functions in the browserchannel library. # # This method wraps the normal `.writeHead()`, `.write()` and `.end()` methods # by special versions which produce output based on the request's type. # # This **is not used** for: # # - The first channel test # - The first *bind* connection a client makes. The server sends arrays there, # but the connection is a POST and it returns immediately. So that request # happens using XHR/Trident like regular forward channel requests. messagingMethods = (options, query, res) -> type = query.TYPE if type == 'html' # IE encoding using messaging via a slowly loading script file junkSent = false methods = writeHead: -> res.writeHead 200, 'OK', ieHeaders res.write '<html><body>' domain = query.DOMAIN # If the iframe is making the request using a secondary domain, I think # we need to set the `domain` to the original domain so that we can # call the response methods. if domain and domain != '' # Make sure the domain doesn't contain anything by naughty by # `JSON.stringify()`-ing it before passing it to the client. There # are XSS vulnerabilities otherwise. res.write "<script>try{document.domain=#{asciijson.stringify domain};}catch(e){}</script>\n" write: (data) -> # The data is passed to `m()`, which is bound to *onTridentRpcMessage_* in the client. res.write "<script>try {parent.m(#{asciijson.stringify data})} catch(e) {}</script>\n" unless junkSent res.write ieJunk junkSent = true end: -> # Once the data has been received, the client needs to call `d()`, # which is bound to *onTridentDone_* with success=*true*. The weird # spacing of this is copied from browserchannel. Its really not # necessary. res.end "<script>try {parent.d(); }catch (e){}</script>\n" # This is a helper method for signalling an error in the request back to the client. writeError: (statusCode, message) -> # The HTML (iframe) handler has no way to discover that the embedded # script tag didn't complete successfully. To signal errors, we return # **200 OK** and call an exposed rpcClose() method on the page. methods.writeHead() res.end "<script>try {parent.rpcClose(#{asciijson.stringify message})} catch(e){}</script>\n" # For some reason, sending data during the second test (111112) works # slightly differently for XHR, but its identical for html encoding. We'll # use a writeRaw() method in that case, which is copied in the case of # html. methods.writeRaw = methods.write methods else # Encoding for modern browsers # For normal XHR requests, we send data normally. writeHead: -> res.writeHead 200, 'OK', options.headers write: (data) -> res.write "#{data.length}\n#{data}" writeRaw: (data) -> res.write data end: -> res.end() writeError: (statusCode, message) -> res.writeHead statusCode, options.headers res.end message # For telling the client its done bad. # # It turns out google's server isn't particularly fussy about signalling errors # using the proper html RPC stuff, so this is useful for html connections too. sendError = (res, statusCode, message, options) -> res.writeHead statusCode, message, options.headers res.end "<html><body><h1>#{message}</h1></body></html>" return # ## Parsing client maps from the forward channel # # The client sends data in a series of url-encoded maps. The data is encoded # like this: # # ``` # count=2&ofs=0&req0_x=3&req0_y=10&req1_abc=def # ``` # # First, we need to buffer up the request response and query string decode it. bufferPostData = (req, callback) -> data = [] req.on 'data', (chunk) -> data.push chunk.toString 'utf8' req.on 'end', -> data = data.join '' callback data # Next, we'll need to decode the incoming client data into an array of objects. # # The data could be in two different forms: # # - Classical browserchannel format, which is a bunch of string->string url-encoded maps # - A JSON object # # We can tell what format the data is in by inspecting the content-type header # # ## URL Encoded data # # Essentially, url encoded the data looks like this: # # ``` # { count: '2', # ofs: '0', # req0_x: '3', # req0_y: '10', # req1_abc: 'def' # } # ``` # # ... and we will return an object in the form of `[{x:'3', y:'10'}, {abc: 'def'}, ...]` # # ## JSON Encoded data # # JSON encoded the data looks like: # # ``` # { ofs: 0 # , data: [null, {...}, 1000.4, 'hi', ...] # } # ``` # # or `null` if there's no data. # # This function returns null if there's no data or {ofs, json:[...]} or {ofs, maps:[...]} transformData = (req, data) -> if req.headers['content-type'] == 'application/json' # We'll restructure it slightly to mark the data as JSON rather than maps. {ofs, data} = data {ofs, json:data} else count = parseInt data.count return null if count is 0 # ofs will be missing if count is zero ofs = parseInt data.ofs throw new Error 'invalid map data' if isNaN count or isNaN ofs throw new Error 'Invalid maps' unless count == 0 or (count > 0 and data.ofs?) maps = new Array count # Scan through all the keys in the data. Every key of the form: # `req123_xxx` will be used to populate its map. regex = /^req(\d+)_(.+)$/ for key, val of data match = regex.exec key if match id = match[1] mapKey = match[2] map = (maps[id] ||= {}) # The client uses `mapX_type=_badmap` to signify an error encoding a map. continue if id == 'type' and mapKey == '_badmap' map[mapKey] = val {ofs, maps} # Decode data string body and get an object back # Either a query string format or JSON depending on content type decodeData = (req, data) -> if req.headers['content-type'] == 'application/json' JSON.parse data else # Maps. Ugh. # # By default, querystring.parse only parses out the first 1000 keys from the data. # maxKeys:0 removes this restriction. querystring.parse data, '&', '=', maxKeys:0 # This is a helper method to order the handling of messages / requests / whatever. # # Use it like this: # inOrder = order 0 # # inOrder 1, -> console.log 'second' # inOrder 0, -> console.log 'first' # # Start is the ID of the first element we expect to receive. If we get data for # earlier elements, we'll play them anyway if playOld is truthy. order = (start, playOld) -> # Base is the ID of the (missing) element at the start of the queue base = start # The queue will start with about 10 elements. Elements of the queue are # undefined if we don't have data for that queue element. queue = new Array 10 (seq, callback) -> # Its important that all the cells of the array are truthy if we have data. # We'll use an empty function instead of null. callback or= -> # Ignore old messages, or play them back immediately if playOld=true if seq < base callback() if playOld else queue[seq - base] = callback while queue[0] callback = queue.shift() base++ callback() return # Host prefixes provide a way to skirt around connection limits. They're only # really important for old browsers. getHostPrefix = (options) -> if options.hostPrefixes randomArrayElement options.hostPrefixes else null # We need access to the client's sourcecode. I'm going to get it using a # synchronous file call (it'll be fast anyway, and only happen once). # # I'm also going to set an etag on the client data so the browser client will # be cached. I'm kind of uncomfortable about adding complexity here because its # not like this code hasn't been written before, but.. I think a lot of people # will use this API. # # I should probably look into hosting the client code as a javascript module # using that client-side npm thing. clientFile = "#{__dirname}/../dist/bcsocket.js" clientStats = fs.statSync clientFile try clientCode = fs.readFileSync clientFile, 'utf8' catch e console.error 'Could not load the client javascript. Run `cake client` to generate it.' throw e # This is mostly to help development, but if the client is recompiled, I'll # pull in a new version. This isn't tested by the unit tests - but its not a # big deal. # # The `readFileSync` call here will stop the whole server while the client is # reloaded. This will only happen during development so its not a big deal. if process.env.NODE_ENV != 'production' if process.platform is "win32" # Windows doesn't support watchFile. See: # https://github.com/josephg/node-browserchannel/pull/6 fs.watch clientFile, persistent: false, (event, filename) -> if event is "change" console.log "Reloading client JS" clientCode = fs.readFileSync clientFile, 'utf8' clientStats = curr else fs.watchFile clientFile, persistent: false, (curr, prev) -> if curr.mtime.getTime() isnt prev.mtime.getTime() console.log "Reloading client JS" clientCode = fs.readFileSync clientFile, 'utf8' clientStats = curr # This code was rewritten from closure-style to class style to make heap dumps # clearer and make the code run faster in V8 (v8 loves this code style). BCSession = (address, query, headers, options) -> EventEmitter.call this # The session's unique ID for this connection @id = hat() # The client stores its IP address and headers from when it first opened # the session. The handler can use this information for authentication or # something. @address = address @headers = headers # Add a reference to the query as users can send extra query string # information using the `extraParams` option on the Socket. @query = query # Options are passed in when creating the BrowserChannel middleware @options = options # The session is a little state machine. It has the following states: # # - **init**: The session has been created and its sessionId hasn't been # sent yet. The session moves to the **ok** state when the first data # chunk is sent to the client. # # - **ok**: The session is sitting pretty and ready to send and receive # data. The session will spend most of its time in this state. # # - **closed**: The session has been removed from the session list. It can # no longer be used for any reason. @state = 'init' # The client's reported application version, or null. This is sent when the # connection is first requested, so you can use it to make your application die / stay # compatible with people who don't close their browsers. @appVersion = query.CVER or null # The server sends messages to the client via a hanging GET request. Of course, # the client has to be the one to open that request. # # This is a handle to null, or {res, methods, chunk} # # - **res** is the http response object # - **methods** is a map of send(), etc methods for communicating properly with the backchannel - # this will be different if the request comes from IE or not. # - **chunk** specifies whether or not we're going to keep the connection open across multiple # messages. If there's a buffering proxy in the way of the connection, we can't respond a bit at # a time, so we close the backchannel after each data chunk. The client decides this during # testing and passes a CI= parameter to the server when the backchannel connection is established. # - **bytesSent** specifies how many bytes of data have been sent through the backchannel. We periodically # close the backchannel and let the client reopen it, so things like the chrome web inspector stay # usable. @_backChannel = null # The server sends data to the client by sending *arrays*. It seems a bit silly that # client->server messages are maps and server->client messages are arrays, but there it is. # # Each entry in this array is of the form [id, data]. @_outgoingArrays = [] # `lastArrayId` is the array ID of the last queued array @_lastArrayId = -1 # Every request from the client has an *AID* parameter which tells the server the ID # of the last request the client has received. We won't remove arrays from the outgoingArrays # list until the client has confirmed its received them. # # In `lastSentArrayId` we store the ID of the last array which we actually sent. @_lastSentArrayId = -1 # If we haven't sent anything for 15 seconds, we'll send a little `['noop']` to the # client so it knows we haven't forgotten it. (And to make sure the backchannel # connection doesn't time out.) @_heartbeat = null # The session will close if there's been no backchannel for awhile. @_sessionTimeout = null # Since the session doesn't start with a backchannel, we'll kick off the timeout timer as soon as its # created. @_refreshSessionTimeout() # The session has just been created. The first thing it needs to tell the client # is its session id and host prefix and stuff. # # It would be pretty easy to add a callback here setting the client status to 'ok' or # something, but its not really necessary. The client has already connected once the first # POST /bind has been received. @_queueArray ['c', @id, getHostPrefix(options), 8] # ### Maps # # The client sends maps to the server using POST requests. Its possible for the requests # to come in out of order, so sometimes we need to buffer up incoming maps and reorder them # before emitting them to the user. # # Each map has an ID (which starts at 0 when the session is first created). # We'll emit received data to the user immediately if they're in order, but if they're out of order # we'll use the little order helper above to order them. The order helper is instructed to not # emit any old messages twice. # # There's a potential DOS attack here whereby a client could just spam the server with # out-of-order maps until it runs out of memory. We should dump a session if there are # too many entries in this dictionary. @_mapBuffer = order 0, false # This method is called whenever we get maps from the client. Offset is the ID of the first # map. The data could either be maps or JSON data. If its maps, data contains {maps} and if its # JSON data, maps contains {JSON}. # # Browserchannel has 2 different mechanisms for consistantly ordering messages in the forward channel: # # - Each forward channel request contains a request ID (RID=X), which start at a random value # (set with the first session create packet). These increment by 1 with each request. # # If a request fails, it might be retried with the same RID as the previous message, and with extra # maps tacked on the end. We need to handle the maps in this case. # # - Each map has an ID, counting from 0. ofs= in the POST data tells the server the ID of the first # map in a request. # # As far as I can tell, the RID stuff can mostly be ignored. The one place it is important is in # handling disconnect messages. The session should only be disconnected by a disconnect message when # the preceeding messages have been received. # All requests are handled in order too, though if not for disconnecting I don't think it would matter. # Because of the funky retry-has-extra-maps logic, we'll allow processing requests twice. @_ridBuffer = order query.RID, true return # Sessions extend node's [EventEmitter][] so they # have access to goodies like `session.on(event, handler)`, # `session.emit('paarty')`, etc. # [EventEmitter]: http://nodejs.org/docs/v0.4.12/api/events.html do -> for name, method of EventEmitter:: BCSession::[name] = method return # The state is modified through this method. It emits events when the state # changes. (yay) BCSession::_changeState = (newState) -> oldState = @state @state = newState @emit 'state changed', @state, oldState BackChannel = (session, res, query) -> @res = res @methods = messagingMethods session.options, query, res @chunk = query.CI == '0' @bytesSent = 0 @listener = -> session._backChannel.listener = null session._clearBackChannel res return # I would like this method to be private or something, but it needs to be accessed from # the HTTP request code below. The _ at the start will hopefully make people think twice # before using it. BCSession::_setBackChannel = (res, query) -> @_clearBackChannel() @_backChannel = new BackChannel this, res, query # When the TCP connection underlying the backchannel request is closed, we'll stop using the # backchannel and start the session timeout clock. The listener is kept so the event handler # removed once the backchannel is closed. res.connection.once 'close', @_backChannel.listener # We'll start the heartbeat interval and clear out the session timeout. # The session timeout will be started again if the backchannel connection closes for # any reason. @_refreshHeartbeat() clearTimeout @_sessionTimeout # When a new backchannel is created, its possible that the old backchannel is dead. # In this case, its possible that previously sent arrays haven't been received. # By resetting lastSentArrayId, we're effectively rolling back the status of sent arrays # to only those arrays which have been acknowledged. if @_outgoingArrays.length > 0 @_lastSentArrayId = @_outgoingArrays[0].id - 1 # Send any arrays we've buffered now that we have a backchannel @flush() # This method removes the back channel and any state associated with it. It'll get called # when the backchannel closes naturally, is replaced or when the connection closes. BCSession::_clearBackChannel = (res) -> # clearBackChannel doesn't do anything if we call it repeatedly. return unless @_backChannel # Its important that we only delete the backchannel if the closed connection is actually # the backchannel we're currently using. return if res? and res != @_backChannel.res if @_backChannel.listener # The backchannel listener has been attached to the 'close' event of the underlying TCP # stream. We don't care about that anymore @_backChannel.res.connection.removeListener 'close', @_backChannel.listener @_backChannel.listener = null # Conveniently, clearTimeout has no effect if the argument is null. clearTimeout @_heartbeat @_backChannel.methods.end() @_backChannel = null # Whenever we don't have a backchannel, we run the session timeout timer. @_refreshSessionTimeout() # This method sets / resets the heartbeat timeout to the full 15 seconds. BCSession::_refreshHeartbeat = -> clearTimeout @_heartbeat session = this @_heartbeat = setInterval -> session.send ['noop'] , @options.keepAliveInterval BCSession::_refreshSessionTimeout = -> clearTimeout @_sessionTimeout session = this @_sessionTimeout = setTimeout -> session.close 'Timed out' , @options.sessionTimeoutInterval # The arrays get removed once they've been acknowledged BCSession::_acknowledgeArrays = (id) -> id = parseInt id if typeof id is 'string' while @_outgoingArrays.length > 0 and @_outgoingArrays[0].id <= id {confirmcallback} = @_outgoingArrays.shift() # I've got no idea what to do if we get an exception thrown here. The session will end up # in an inconsistant state... confirmcallback?() return OutgoingArray = (@id, @data, @sendcallback, @confirmcallback) -> # Queue an array to be sent. The optional callbacks notifies a caller when the array has been # sent, and then received by the client. # # If the session is already closed, we'll call the confirmation callback immediately with the # error. # # queueArray returns the ID of the queued data chunk. BCSession::_queueArray = (data, sendcallback, confirmcallback) -> return confirmcallback? new Error 'closed' if @state is 'closed' id = ++@_lastArrayId @_outgoingArrays.push new OutgoingArray(id, data, sendcallback, confirmcallback) return @_lastArrayId # Send the array data through the backchannel. This takes an optional callback which # will be called with no arguments when the client acknowledges the array, or called with an # error object if the client disconnects before the array is sent. # # queueArray can also take a callback argument which is called when the session sends the message # in the first place. I'm not sure if I should expose this through send - I can't tell if its # useful beyond the server code. BCSession::send = (arr, callback) -> id = @_queueArray arr, null, callback @flush() return id BCSession::_receivedData = (rid, data) -> session = this @_ridBuffer rid, -> return if data is null throw new Error 'Invalid data' unless data.maps? or data.json? session._ridBuffer rid id = data.ofs # First, classic browserchannel maps. if data.maps # If an exception is thrown during this loop, I'm not really sure what the behaviour should be. for map in data.maps # The funky do expression here is used to pass the map into the closure. # Another way to do it is to index into the data.maps array inside the function, but then I'd # need to pass the index to the closure anyway. session._mapBuffer id++, do (map) -> -> return if session.state is 'closed' session.emit 'map', map # If you specify the key as JSON, the server will try to decode JSON data from the map and emit # 'message'. This is a much nicer way to message the server. if map.JSON? try message = JSON.parse map.JSON catch e session.close 'Invalid JSON' return session.emit 'message', message # Raw string messages are embedded in a _S: property in a map. else if map._S? session.emit 'message', map._S else # We have data.json. We'll just emit it directly. for message in data.json session._mapBuffer id++, do (map) -> -> return if session.state is 'closed' session.emit 'message', message return BCSession::_disconnectAt = (rid) -> session = this @_ridBuffer rid, -> session.close 'Disconnected' # When we receive forwardchannel data, we reply with a special little 3-variable array to tell the # client if it should reopen the backchannel. # # This method returns what the forward channel should reply with. BCSession::_backChannelStatus = -> # Find the arrays have been sent over the wire but haven't been acknowledged yet numUnsentArrays = @_lastArrayId - @_lastSentArrayId unacknowledgedArrays = @_outgoingArrays[... @_outgoingArrays.length - numUnsentArrays] outstandingBytes = if unacknowledgedArrays.length == 0 0 else # We don't care about the length of the array IDs or callback functions. # I'm actually not sure what data the client expects here - the value is just used in a rough # heuristic to determine if the backchannel should be reopened. data = (a.data for a in unacknowledgedArrays) JSON.stringify(data).length return [ (if @_backChannel then 1 else 0) @_lastSentArrayId outstandingBytes ] # ## Encoding server arrays for the back channel # # The server sends data to the client in **chunks**. Each chunk is a *JSON* array prefixed # by its length in bytes. # # The array looks like this: # # ``` # [ # [100, ['message', 'one']], # [101, ['message', 'two']], # [102, ['message', 'three']] # ] # ``` # # Each individial message is prefixed by its *array id*, which is a counter starting at 0 # when the session is first created and incremented with each array. # This will actually send the arrays to the backchannel on the next tick if the backchannel # is alive. BCSession::flush = -> session = this process.nextTick -> session._flush() BCSession::_flush = -> return unless @_backChannel numUnsentArrays = @_lastArrayId - @_lastSentArrayId if numUnsentArrays > 0 arrays = @_outgoingArrays[@_outgoingArrays.length - numUnsentArrays ...] # I've abused outgoingArrays to also contain some callbacks. We only send [id, data] to # the client. data = ([id, data] for {id, data} in arrays) bytes = JSON.stringify(data) + "\n" # Stand back, pro hax! Ideally there is a general solution for escaping these characters # when converting to JSON. bytes = bytes.replace(/\u2028/g, "\\u2028") bytes = bytes.replace(/\u2029/g, "\\u2029") # **Away!** @_backChannel.methods.write bytes @_backChannel.bytesSent += bytes.length @_lastSentArrayId = @_lastArrayId # Fire any send callbacks on the messages. These callbacks should only be called once. # Again, not sure what to do if there are exceptions here. for a in arrays if a.sendcallback? a.sendcallback?() delete a.sendcallback # The send callback could have cleared the backchannel by calling close. if @_backChannel and (!@_backChannel.chunk or @_backChannel.bytesSent > 10 * 1024) @_clearBackChannel() # The first backchannel is the client's initial connection. Once we've sent the first # data chunk to the client, we've officially opened the connection. @_changeState 'ok' if @state == 'init' # Signal to a client that it should stop trying to connect. This has no other effect # on the server session. # # `stop` takes a callback which will be called once the message has been *sent* by the server. # Typically, you should call it like this: # # ``` # session.stop -> # session.close() # ``` # # I considered making this automatically close the connection after you've called it, or after # you've sent the stop message or something, but if I did that it wouldn't be obvious that you # can still receive messages after stop() has been called. (Because you can!). That would never # come up when you're testing locally, but it *would* come up in production. This is more obvious. BCSession::stop = (callback) -> return if @state is 'closed' @_queueArray ['stop'], callback, null @flush() # This closes a session and makes the server forget about it. # # The client might try and reconnect if you only call `close()`. It'll get a new session if it does so. # # close takes an optional message argument, which is passed to the send event handlers. BCSession::close = (message) -> # You can't double-close. return if @state == 'closed' @_changeState 'closed' @emit 'close', message @_clearBackChannel() clearTimeout @_sessionTimeout for {confirmcallback} in @_outgoingArrays confirmcallback? new Error(message || 'closed') return # --- # # # The server middleware # # The server module returns a function, which you can call with your # configuration options. It returns your configured connect middleware, which # is actually another function. module.exports = browserChannel = (options, onConnect) -> if typeof onConnect == 'undefined' onConnect = options options = {} options ||= {} options[option] ?= value for option, value of defaultOptions options.headers = {} unless options.headers options.headers[h] ||= v for h, v of standardHeaders options.headers['Access-Control-Allow-Origin'] = options.cors if options.cors options.headers['Access-Control-Allow-Credentials'] = true if options.corsAllowCredentials # Strip off a trailing slash in base. base = options.base base = base[... base.length - 1] if base.match /\/$/ # Add a leading slash back on base base = "/#{base}" if base.length > 0 and !base.match /^\// # map from sessionId -> session sessions = {} # # Create a new client session. # # This method will start a new client session. # # Session ids are generated by [node-hat]. They are guaranteed to be unique. # [node-hat]: https://github.com/substack/node-hat # # This method is synchronous, because a database will never be involved in # browserchannel session management. Browserchannel sessions only last as # long as the user's browser is open. If there's any connection turbulence, # the client will reconnect and get a new session id. # # Sometimes a client will specify an old session ID and old array ID. In this # case, the client is reconnecting and we should evict the named session (if # it exists). createSession = (address, query, headers) -> {OSID: oldSessionId, OAID: oldArrayId} = query if oldSessionId? and (oldSession = sessions[oldSessionId]) oldSession._acknowledgeArrays oldArrayId oldSession.close 'Reconnected' session = new BCSession address, query, headers, options sessions[session.id] = session session.on 'close', -> delete sessions[session.id] # console.log "closed #{@id}" return session # This is the returned middleware. Connect middleware is a function which # takes in an http request, an http response and a next method. # # The middleware can do one of two things: # # - Handle the request, sending data back to the server via the response # - Call `next()`, which allows the next middleware in the stack a chance to # handle the request. middleware = (req, res, next) -> {query, pathname} = parse req.url, true #console.warn req.method, req.url # If base is /foo, we don't match /foobar. (Currently no unit tests for this) return next() if pathname.substring(0, base.length + 1) != "#{base}/" {writeHead, write, writeRaw, end, writeError} = messagingMethods options, query, res # # Serving the client # # The browserchannel server hosts a usable web client library at /CHANNEL/bcsocket.js. # This library wraps the google closure library client implementation. # # If I have time, I would like to write my own version of the client to add a few features # (websockets, message acknowledgement callbacks) and do some manual optimisations for speed. # However, the current version works ok. if pathname is "#{base}/bcsocket.js" etag = "\"#{clientStats.size}-#{clientStats.mtime.getTime()}\"" res.writeHead 200, 'OK', 'Content-Type': 'application/javascript', 'ETag': etag, 'Content-Length': clientCode.length # This code is manually tested because it looks like its impossible to send HEAD requests # using nodejs's HTTP library at time of writing (0.4.12). (Yeah, I know, rite?) if req.method is 'HEAD' res.end() else res.end clientCode # # Connection testing # # Before the browserchannel client connects, it tests the connection to make # sure its working, and to look for buffering proxies. # # The server-side code for connection testing is completely stateless. else if pathname is "#{base}/test" # This server only supports browserchannel protocol version **8**. # I have no idea if 400 is the right error here. return sendError res, 400, 'Version 8 required', options unless query.VER is '8' #### Phase 1: Server info # The client is requests host prefixes. The server responds with an array of # ['hostprefix' or null, 'blockedprefix' or null]. # # > Actually, I think you might be able to return [] if neither hostPrefix nor blockedPrefix # > is defined. (Thats what google wave seems to do) # # - **hostprefix** is subdomain prepended onto the hostname of each request. # This gets around browser connection limits. Using this requires a bank of # configured DNS entries and SSL certificates if you're using HTTPS. # # - **blockedprefix** provides network admins a way to blacklist browserchannel # requests. It is not supported by node-browserchannel. if query.MODE == 'init' and req.method == 'GET' hostPrefix = getHostPrefix options blockedPrefix = null # Blocked prefixes aren't supported. # We add an extra special header to tell the client that this server likes # json-encoded forward channel data over form urlencoded channel data. # # It might be easier to put these headers in the response body or increment the # version, but that might conflict with future browserchannel versions. headers = {} headers[k] = v for k, v of options.headers headers['X-Accept'] = 'application/json; application/x-www-form-urlencoded' # This is a straight-up normal HTTP request like the forward channel requests. # We don't use the funny iframe write methods. res.writeHead 200, 'OK', headers res.end(JSON.stringify [hostPrefix, blockedPrefix]) else #### Phase 2: Buffering proxy detection # The client is trying to determine if their connection is buffered or unbuffered. # We reply with '11111', then 2 seconds later '2'. # # The client should get the data in 2 chunks - but they won't if there's a misbehaving # corporate proxy in the way or something. writeHead() writeRaw '11111' setTimeout (-> writeRaw '2'; end()), 2000 # # BrowserChannel connection # # Once a client has finished testing its connection, it connects. # # BrowserChannel communicates through two connections: # # - The **forward channel** is used for the client to send data to the server. # It uses a **POST** request for each message. # - The **back channel** is used to get data back from the server. This uses a # hanging **GET** request. If chunking is disallowed (ie, if the proxy buffers) # then the back channel is closed after each server message. else if pathname == "#{base}/bind" # I'm copying the behaviour of unknown SIDs below. I don't know how the client # is supposed to detect this error, but, eh. The other choice is to `return writeError ...` return sendError res, 400, 'Version 8 required', options unless query.VER is '8' # All browserchannel connections have an associated client object. A client # is created immediately if the connection is new. if query.SID session = sessions[query.SID] # This is a special error code for the client. It tells the client to abandon its # connection request and reconnect. # # For some reason, google replies with the same response on HTTP and HTML requests here. # I'll follow suit, though its a little weird. Maybe I should do the same with all client # errors? return sendError res, 400, 'Unknown SID', options unless session session._acknowledgeArrays query.AID if query.AID? and session # ### Forward Channel if req.method == 'POST' if session == undefined # The session is new! Make them a new session object and let the # application know. session = createSession req.connection.remoteAddress, query, req.headers onConnect? session, req # TODO Emit 'req' for subsequent requests associated with session session.emit 'req', req dataError = (e) -> console.warn 'Error parsing forward channel', e.stack return sendError res, 400, 'Bad data', options processData = (data) -> try data = transformData req, data session._receivedData query.RID, data catch e return dataError e if session.state is 'init' # The initial forward channel request is also used as a backchannel # for the server's initial data (session id, etc). This connection # is a little bit special - it is always encoded using # length-prefixed json encoding and it is closed as soon as the # first chunk is sent. res.writeHead 200, 'OK', options.headers session._setBackChannel res, CI:1, TYPE:'xmlhttp', RID:'rpc' session.flush() else if session.state is 'closed' # If the onConnect handler called close() immediately, # session.state can be already closed at this point. I'll assume # there was an authentication problem and treat this as a forbidden # connection attempt. sendError res, 403, 'Forbidden', options else # On normal forward channels, we reply to the request by telling # the session if our backchannel is still live and telling it how # many unconfirmed arrays we have. response = JSON.stringify session._backChannelStatus() res.writeHead 200, 'OK', options.headers res.end "#{response.length}\n#{response}" if req.body processData req.body else bufferPostData req, (data) -> try data = decodeData req, data catch e return dataError e processData data else if req.method is 'GET' # ### Back channel # # GET messages are usually backchannel requests (server->client). # Backchannel messages are handled by the session object. if query.TYPE in ['xmlhttp', 'html'] return sendError res, 400, 'Invalid SID', options if typeof query.SID != 'string' && query.SID.length < 5 return sendError res, 400, 'Expected RPC', options unless query.RID is 'rpc' writeHead() session._setBackChannel res, query # The client can manually disconnect by making a GET request with TYPE='terminate' else if query.TYPE is 'terminate' # We don't send any data in the response to the disconnect message. # # The client implements this using an img= appended to the page. session?._disconnectAt query.RID res.writeHead 200, 'OK', options.headers res.end() else res.writeHead 405, 'Method Not Allowed', options.headers res.end "Method not allowed" else # We'll 404 the user instead of letting another handler take care of it. # Users shouldn't be using the specified URL prefix for anything else. res.writeHead 404, 'Not Found', options.headers res.end "Not found" middleware.close = -> for id, session of sessions session.close() return # This is an undocumented, untested treat - if you pass the HTTP server / # connect server to browserchannel through the options object, it can attach # a close listener for you automatically. options.server?.on 'close', middleware.close middleware # This will override the timer methods (`setInterval`, etc) with the testing # stub versions, which are way faster. browserChannel._setTimerMethods = (methods) -> {setInterval, clearInterval, setTimeout, clearTimeout, Date} = methods
84661
# # A BrowserChannel server. # # - Its still pretty young, so there's probably bugs lurking around and the API # will still change quickly. # - Its missing integration tests # # It works in all the browsers I've tried. # # I've written this using the literate programming style to try it out. So, thats why # there's a million comments everywhere. # # The server is implemented an express middleware. Its intended to be used like this: # # ``` # server = express(); # server.use(browserChannel(function(client) { client.send('hi'); })); # ``` # ## Dependancies, helper methods and constant data # `parse` helps us decode URLs in requests {parse} = require 'url' # `querystring` will help decode the URL-encoded forward channel data querystring = require 'querystring' # `fs` is used to read & serve the client library fs = require 'fs' # Client sessions are `EventEmitters` {EventEmitter} = require 'events' # Client session Ids are generated using `node-hat` hat = require('hat').rack(40, 36) # When sending messages to IE using a hidden iframe, UTF8-encoded characters # don't get processed correctly. This encodes unicode characters using the # \u2028 encoding style, which (thankfully) makes it through. asciijson = require 'ascii-json' # `randomInt(n)` generates and returns a random int smaller than n (0 <= k < n) randomInt = (n) -> Math.floor(Math.random() * n) # `randomArrayElement(array)` Selects and returns a random element from *array* randomArrayElement = (array) -> array[randomInt(array.length)] # For testing we'll override `setInterval`, etc with special testing stub versions (so # we don't have to actually wait for actual *time*. To do that, we need local variable # versions (I don't want to edit the global versions). ... and they'll just point to the # normal versions anyway. {setInterval, clearInterval, setTimeout, clearTimeout, Date} = global # The module is configurable defaultOptions = # An optional array of host prefixes. Each browserchannel client will # randomly pick from the list of host prefixes when it connects. This reduces # the impact of per-host connection limits. # # All host prefixes should point to the same server. Ie, if your server's # hostname is *example.com* and your hostPrefixes contains ['a', 'b', 'c'], # a.example.com, b.example.com and c.example.com should all point to the same # host as example.com. hostPrefixes: null # You can specify the base URL which browserchannel connects to. Change this # if you want to scope browserchannel in part of your app, or if you want # /channel to mean something else, or whatever. # # I really want to remove this parameter - express 4.0's router is now good # enough that you can just install the middleware anywhere using express. For # example: # app.use('/mycoolpath', browserchannel({base:''}, ...)); # # Unfortunately you have to force the base option to '' to do that (since it # defaults to /channel otherwise). What a pain. TODO browserchannel 3.0 base: '/channel' # We'll send keepalives every so often to make sure the http connection isn't # closed by eagar clients. The standard timeout is 30 seconds, so we'll # default to sending them every 20 seconds or so. keepAliveInterval: 20 * 1000 # After awhile (30 seconds or so) of not having a backchannel connected, # we'll evict the session completely. This will happen whenever a user closes # their browser. sessionTimeoutInterval: 30 * 1000 # By default, browsers don't allow access via javascript to foreign sites. # You can use the cors: option to set the Access-Control-Allow-Origin header # in responses, which tells browsers whether or not to allow cross domain # requests to be sent. # # See https://developer.mozilla.org/en/http_access_control for more information. # # Setting cors:'*' will enable javascript from any domain to access your # application. BE CAREFUL! If your application uses cookies to manage user # sessions, javascript on a foreign site could make requests as if it were # acting on behalf of one of your users. # # Setting cors:'X' is equivalent to adding # {headers: {'Access-Control-Allow-Origin':X}}. cors: null # Even with Access-Control-Allow-Origin enabled, browsers don't send their # cookies to different domains. You can set corsAllowCredentials to be true # to add the `Access-Control-Allow-Credentials: true` header to responses. # This tells browsers they are allowed to send credentialed requests (ie, # requests with cookies) to a foreign domain. If you do this, you must *also* # set {crossDomainXhr:true} in your BCSocket browser options to tell XHR # requests to send credentials. # # Also note that credentialed requests require explicitly mentioned domains # to work. You cannot use a wildcard cors header (`cors:*`) if you want # credentials. # # See: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Requests_with_credentials # # Setting corsAllowCredentials:true is equivalent to adding: # {headers: {'Access-Control-Allow-Credentials':true}}. corsAllowCredentials: false # A user can override all the headers if they want by setting the headers # option to an object. headers: null # All server responses set some standard HTTP headers. To be honest, I don't # know how many of these are necessary. I just copied them from google. # # The nocache headers in particular seem unnecessary since each client request # includes a randomized `zx=junk` query parameter. standardHeaders = 'Content-Type': 'text/plain' 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate' 'Pragma': 'no-cache' 'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT' 'X-Content-Type-Options': 'nosniff' # Gmail also sends this, though I'm not really sure what it does... # 'X-Xss-Protection': '1; mode=block' # The one exception to that is requests destined for iframes. They need to have # content-type: text/html set for IE to process the juicy JS inside. ieHeaders = {} ieHeaders[k] = v for k, v of standardHeaders ieHeaders['Content-Type'] = 'text/html' # Google's browserchannel server adds some junk after the first message data is # sent. I assume this stops some whole-page buffering in IE. I assume the data # used is noise so it doesn't compress. # # I don't really know why google does this. I'm assuming there's a good reason # to it though. ieJunk = "7cca69475363026330a0d99468e88d23ce95e222591126443015f5f462d9a177186c8701fb45a6ffe\ e0daf1a178fc0f58cd309308fba7e6f011ac38c9cdd4580760f1d4560a84d5ca0355ecbbed2ab715a3350fe0c47\ 9050640bd0e77acec90c58c4d3dd0f5cf8d4510e68c8b12e087bd88cad349aafd2ab16b07b0b1b8276091217a44\ a9fe92fedacffff48092ee693af\n" # If the user is using IE, instead of using XHR backchannel loaded using a # forever iframe. When data is sent, it is wrapped in <script></script> tags # which call functions in the browserchannel library. # # This method wraps the normal `.writeHead()`, `.write()` and `.end()` methods # by special versions which produce output based on the request's type. # # This **is not used** for: # # - The first channel test # - The first *bind* connection a client makes. The server sends arrays there, # but the connection is a POST and it returns immediately. So that request # happens using XHR/Trident like regular forward channel requests. messagingMethods = (options, query, res) -> type = query.TYPE if type == 'html' # IE encoding using messaging via a slowly loading script file junkSent = false methods = writeHead: -> res.writeHead 200, 'OK', ieHeaders res.write '<html><body>' domain = query.DOMAIN # If the iframe is making the request using a secondary domain, I think # we need to set the `domain` to the original domain so that we can # call the response methods. if domain and domain != '' # Make sure the domain doesn't contain anything by naughty by # `JSON.stringify()`-ing it before passing it to the client. There # are XSS vulnerabilities otherwise. res.write "<script>try{document.domain=#{asciijson.stringify domain};}catch(e){}</script>\n" write: (data) -> # The data is passed to `m()`, which is bound to *onTridentRpcMessage_* in the client. res.write "<script>try {parent.m(#{asciijson.stringify data})} catch(e) {}</script>\n" unless junkSent res.write ieJunk junkSent = true end: -> # Once the data has been received, the client needs to call `d()`, # which is bound to *onTridentDone_* with success=*true*. The weird # spacing of this is copied from browserchannel. Its really not # necessary. res.end "<script>try {parent.d(); }catch (e){}</script>\n" # This is a helper method for signalling an error in the request back to the client. writeError: (statusCode, message) -> # The HTML (iframe) handler has no way to discover that the embedded # script tag didn't complete successfully. To signal errors, we return # **200 OK** and call an exposed rpcClose() method on the page. methods.writeHead() res.end "<script>try {parent.rpcClose(#{asciijson.stringify message})} catch(e){}</script>\n" # For some reason, sending data during the second test (111112) works # slightly differently for XHR, but its identical for html encoding. We'll # use a writeRaw() method in that case, which is copied in the case of # html. methods.writeRaw = methods.write methods else # Encoding for modern browsers # For normal XHR requests, we send data normally. writeHead: -> res.writeHead 200, 'OK', options.headers write: (data) -> res.write "#{data.length}\n#{data}" writeRaw: (data) -> res.write data end: -> res.end() writeError: (statusCode, message) -> res.writeHead statusCode, options.headers res.end message # For telling the client its done bad. # # It turns out google's server isn't particularly fussy about signalling errors # using the proper html RPC stuff, so this is useful for html connections too. sendError = (res, statusCode, message, options) -> res.writeHead statusCode, message, options.headers res.end "<html><body><h1>#{message}</h1></body></html>" return # ## Parsing client maps from the forward channel # # The client sends data in a series of url-encoded maps. The data is encoded # like this: # # ``` # count=2&ofs=0&req0_x=3&req0_y=10&req1_abc=def # ``` # # First, we need to buffer up the request response and query string decode it. bufferPostData = (req, callback) -> data = [] req.on 'data', (chunk) -> data.push chunk.toString 'utf8' req.on 'end', -> data = data.join '' callback data # Next, we'll need to decode the incoming client data into an array of objects. # # The data could be in two different forms: # # - Classical browserchannel format, which is a bunch of string->string url-encoded maps # - A JSON object # # We can tell what format the data is in by inspecting the content-type header # # ## URL Encoded data # # Essentially, url encoded the data looks like this: # # ``` # { count: '2', # ofs: '0', # req0_x: '3', # req0_y: '10', # req1_abc: 'def' # } # ``` # # ... and we will return an object in the form of `[{x:'3', y:'10'}, {abc: 'def'}, ...]` # # ## JSON Encoded data # # JSON encoded the data looks like: # # ``` # { ofs: 0 # , data: [null, {...}, 1000.4, 'hi', ...] # } # ``` # # or `null` if there's no data. # # This function returns null if there's no data or {ofs, json:[...]} or {ofs, maps:[...]} transformData = (req, data) -> if req.headers['content-type'] == 'application/json' # We'll restructure it slightly to mark the data as JSON rather than maps. {ofs, data} = data {ofs, json:data} else count = parseInt data.count return null if count is 0 # ofs will be missing if count is zero ofs = parseInt data.ofs throw new Error 'invalid map data' if isNaN count or isNaN ofs throw new Error 'Invalid maps' unless count == 0 or (count > 0 and data.ofs?) maps = new Array count # Scan through all the keys in the data. Every key of the form: # `<KEY>123_xxx` will be used to populate its map. regex = /^req(\d+)_(.+)$/ for key, val of data match = regex.exec key if match id = match[1] mapKey = match[2] map = (maps[id] ||= {}) # The client uses `mapX_type=_badmap` to signify an error encoding a map. continue if id == 'type' and mapKey == '_badmap' map[mapKey] = val {ofs, maps} # Decode data string body and get an object back # Either a query string format or JSON depending on content type decodeData = (req, data) -> if req.headers['content-type'] == 'application/json' JSON.parse data else # Maps. Ugh. # # By default, querystring.parse only parses out the first 1000 keys from the data. # maxKeys:0 removes this restriction. querystring.parse data, '&', '=', maxKeys:0 # This is a helper method to order the handling of messages / requests / whatever. # # Use it like this: # inOrder = order 0 # # inOrder 1, -> console.log 'second' # inOrder 0, -> console.log 'first' # # Start is the ID of the first element we expect to receive. If we get data for # earlier elements, we'll play them anyway if playOld is truthy. order = (start, playOld) -> # Base is the ID of the (missing) element at the start of the queue base = start # The queue will start with about 10 elements. Elements of the queue are # undefined if we don't have data for that queue element. queue = new Array 10 (seq, callback) -> # Its important that all the cells of the array are truthy if we have data. # We'll use an empty function instead of null. callback or= -> # Ignore old messages, or play them back immediately if playOld=true if seq < base callback() if playOld else queue[seq - base] = callback while queue[0] callback = queue.shift() base++ callback() return # Host prefixes provide a way to skirt around connection limits. They're only # really important for old browsers. getHostPrefix = (options) -> if options.hostPrefixes randomArrayElement options.hostPrefixes else null # We need access to the client's sourcecode. I'm going to get it using a # synchronous file call (it'll be fast anyway, and only happen once). # # I'm also going to set an etag on the client data so the browser client will # be cached. I'm kind of uncomfortable about adding complexity here because its # not like this code hasn't been written before, but.. I think a lot of people # will use this API. # # I should probably look into hosting the client code as a javascript module # using that client-side npm thing. clientFile = "#{__dirname}/../dist/bcsocket.js" clientStats = fs.statSync clientFile try clientCode = fs.readFileSync clientFile, 'utf8' catch e console.error 'Could not load the client javascript. Run `cake client` to generate it.' throw e # This is mostly to help development, but if the client is recompiled, I'll # pull in a new version. This isn't tested by the unit tests - but its not a # big deal. # # The `readFileSync` call here will stop the whole server while the client is # reloaded. This will only happen during development so its not a big deal. if process.env.NODE_ENV != 'production' if process.platform is "win32" # Windows doesn't support watchFile. See: # https://github.com/josephg/node-browserchannel/pull/6 fs.watch clientFile, persistent: false, (event, filename) -> if event is "change" console.log "Reloading client JS" clientCode = fs.readFileSync clientFile, 'utf8' clientStats = curr else fs.watchFile clientFile, persistent: false, (curr, prev) -> if curr.mtime.getTime() isnt prev.mtime.getTime() console.log "Reloading client JS" clientCode = fs.readFileSync clientFile, 'utf8' clientStats = curr # This code was rewritten from closure-style to class style to make heap dumps # clearer and make the code run faster in V8 (v8 loves this code style). BCSession = (address, query, headers, options) -> EventEmitter.call this # The session's unique ID for this connection @id = hat() # The client stores its IP address and headers from when it first opened # the session. The handler can use this information for authentication or # something. @address = address @headers = headers # Add a reference to the query as users can send extra query string # information using the `extraParams` option on the Socket. @query = query # Options are passed in when creating the BrowserChannel middleware @options = options # The session is a little state machine. It has the following states: # # - **init**: The session has been created and its sessionId hasn't been # sent yet. The session moves to the **ok** state when the first data # chunk is sent to the client. # # - **ok**: The session is sitting pretty and ready to send and receive # data. The session will spend most of its time in this state. # # - **closed**: The session has been removed from the session list. It can # no longer be used for any reason. @state = 'init' # The client's reported application version, or null. This is sent when the # connection is first requested, so you can use it to make your application die / stay # compatible with people who don't close their browsers. @appVersion = query.CVER or null # The server sends messages to the client via a hanging GET request. Of course, # the client has to be the one to open that request. # # This is a handle to null, or {res, methods, chunk} # # - **res** is the http response object # - **methods** is a map of send(), etc methods for communicating properly with the backchannel - # this will be different if the request comes from IE or not. # - **chunk** specifies whether or not we're going to keep the connection open across multiple # messages. If there's a buffering proxy in the way of the connection, we can't respond a bit at # a time, so we close the backchannel after each data chunk. The client decides this during # testing and passes a CI= parameter to the server when the backchannel connection is established. # - **bytesSent** specifies how many bytes of data have been sent through the backchannel. We periodically # close the backchannel and let the client reopen it, so things like the chrome web inspector stay # usable. @_backChannel = null # The server sends data to the client by sending *arrays*. It seems a bit silly that # client->server messages are maps and server->client messages are arrays, but there it is. # # Each entry in this array is of the form [id, data]. @_outgoingArrays = [] # `lastArrayId` is the array ID of the last queued array @_lastArrayId = -1 # Every request from the client has an *AID* parameter which tells the server the ID # of the last request the client has received. We won't remove arrays from the outgoingArrays # list until the client has confirmed its received them. # # In `lastSentArrayId` we store the ID of the last array which we actually sent. @_lastSentArrayId = -1 # If we haven't sent anything for 15 seconds, we'll send a little `['noop']` to the # client so it knows we haven't forgotten it. (And to make sure the backchannel # connection doesn't time out.) @_heartbeat = null # The session will close if there's been no backchannel for awhile. @_sessionTimeout = null # Since the session doesn't start with a backchannel, we'll kick off the timeout timer as soon as its # created. @_refreshSessionTimeout() # The session has just been created. The first thing it needs to tell the client # is its session id and host prefix and stuff. # # It would be pretty easy to add a callback here setting the client status to 'ok' or # something, but its not really necessary. The client has already connected once the first # POST /bind has been received. @_queueArray ['c', @id, getHostPrefix(options), 8] # ### Maps # # The client sends maps to the server using POST requests. Its possible for the requests # to come in out of order, so sometimes we need to buffer up incoming maps and reorder them # before emitting them to the user. # # Each map has an ID (which starts at 0 when the session is first created). # We'll emit received data to the user immediately if they're in order, but if they're out of order # we'll use the little order helper above to order them. The order helper is instructed to not # emit any old messages twice. # # There's a potential DOS attack here whereby a client could just spam the server with # out-of-order maps until it runs out of memory. We should dump a session if there are # too many entries in this dictionary. @_mapBuffer = order 0, false # This method is called whenever we get maps from the client. Offset is the ID of the first # map. The data could either be maps or JSON data. If its maps, data contains {maps} and if its # JSON data, maps contains {JSON}. # # Browserchannel has 2 different mechanisms for consistantly ordering messages in the forward channel: # # - Each forward channel request contains a request ID (RID=X), which start at a random value # (set with the first session create packet). These increment by 1 with each request. # # If a request fails, it might be retried with the same RID as the previous message, and with extra # maps tacked on the end. We need to handle the maps in this case. # # - Each map has an ID, counting from 0. ofs= in the POST data tells the server the ID of the first # map in a request. # # As far as I can tell, the RID stuff can mostly be ignored. The one place it is important is in # handling disconnect messages. The session should only be disconnected by a disconnect message when # the preceeding messages have been received. # All requests are handled in order too, though if not for disconnecting I don't think it would matter. # Because of the funky retry-has-extra-maps logic, we'll allow processing requests twice. @_ridBuffer = order query.RID, true return # Sessions extend node's [EventEmitter][] so they # have access to goodies like `session.on(event, handler)`, # `session.emit('paarty')`, etc. # [EventEmitter]: http://nodejs.org/docs/v0.4.12/api/events.html do -> for name, method of EventEmitter:: BCSession::[name] = method return # The state is modified through this method. It emits events when the state # changes. (yay) BCSession::_changeState = (newState) -> oldState = @state @state = newState @emit 'state changed', @state, oldState BackChannel = (session, res, query) -> @res = res @methods = messagingMethods session.options, query, res @chunk = query.CI == '0' @bytesSent = 0 @listener = -> session._backChannel.listener = null session._clearBackChannel res return # I would like this method to be private or something, but it needs to be accessed from # the HTTP request code below. The _ at the start will hopefully make people think twice # before using it. BCSession::_setBackChannel = (res, query) -> @_clearBackChannel() @_backChannel = new BackChannel this, res, query # When the TCP connection underlying the backchannel request is closed, we'll stop using the # backchannel and start the session timeout clock. The listener is kept so the event handler # removed once the backchannel is closed. res.connection.once 'close', @_backChannel.listener # We'll start the heartbeat interval and clear out the session timeout. # The session timeout will be started again if the backchannel connection closes for # any reason. @_refreshHeartbeat() clearTimeout @_sessionTimeout # When a new backchannel is created, its possible that the old backchannel is dead. # In this case, its possible that previously sent arrays haven't been received. # By resetting lastSentArrayId, we're effectively rolling back the status of sent arrays # to only those arrays which have been acknowledged. if @_outgoingArrays.length > 0 @_lastSentArrayId = @_outgoingArrays[0].id - 1 # Send any arrays we've buffered now that we have a backchannel @flush() # This method removes the back channel and any state associated with it. It'll get called # when the backchannel closes naturally, is replaced or when the connection closes. BCSession::_clearBackChannel = (res) -> # clearBackChannel doesn't do anything if we call it repeatedly. return unless @_backChannel # Its important that we only delete the backchannel if the closed connection is actually # the backchannel we're currently using. return if res? and res != @_backChannel.res if @_backChannel.listener # The backchannel listener has been attached to the 'close' event of the underlying TCP # stream. We don't care about that anymore @_backChannel.res.connection.removeListener 'close', @_backChannel.listener @_backChannel.listener = null # Conveniently, clearTimeout has no effect if the argument is null. clearTimeout @_heartbeat @_backChannel.methods.end() @_backChannel = null # Whenever we don't have a backchannel, we run the session timeout timer. @_refreshSessionTimeout() # This method sets / resets the heartbeat timeout to the full 15 seconds. BCSession::_refreshHeartbeat = -> clearTimeout @_heartbeat session = this @_heartbeat = setInterval -> session.send ['noop'] , @options.keepAliveInterval BCSession::_refreshSessionTimeout = -> clearTimeout @_sessionTimeout session = this @_sessionTimeout = setTimeout -> session.close 'Timed out' , @options.sessionTimeoutInterval # The arrays get removed once they've been acknowledged BCSession::_acknowledgeArrays = (id) -> id = parseInt id if typeof id is 'string' while @_outgoingArrays.length > 0 and @_outgoingArrays[0].id <= id {confirmcallback} = @_outgoingArrays.shift() # I've got no idea what to do if we get an exception thrown here. The session will end up # in an inconsistant state... confirmcallback?() return OutgoingArray = (@id, @data, @sendcallback, @confirmcallback) -> # Queue an array to be sent. The optional callbacks notifies a caller when the array has been # sent, and then received by the client. # # If the session is already closed, we'll call the confirmation callback immediately with the # error. # # queueArray returns the ID of the queued data chunk. BCSession::_queueArray = (data, sendcallback, confirmcallback) -> return confirmcallback? new Error 'closed' if @state is 'closed' id = ++@_lastArrayId @_outgoingArrays.push new OutgoingArray(id, data, sendcallback, confirmcallback) return @_lastArrayId # Send the array data through the backchannel. This takes an optional callback which # will be called with no arguments when the client acknowledges the array, or called with an # error object if the client disconnects before the array is sent. # # queueArray can also take a callback argument which is called when the session sends the message # in the first place. I'm not sure if I should expose this through send - I can't tell if its # useful beyond the server code. BCSession::send = (arr, callback) -> id = @_queueArray arr, null, callback @flush() return id BCSession::_receivedData = (rid, data) -> session = this @_ridBuffer rid, -> return if data is null throw new Error 'Invalid data' unless data.maps? or data.json? session._ridBuffer rid id = data.ofs # First, classic browserchannel maps. if data.maps # If an exception is thrown during this loop, I'm not really sure what the behaviour should be. for map in data.maps # The funky do expression here is used to pass the map into the closure. # Another way to do it is to index into the data.maps array inside the function, but then I'd # need to pass the index to the closure anyway. session._mapBuffer id++, do (map) -> -> return if session.state is 'closed' session.emit 'map', map # If you specify the key as JSON, the server will try to decode JSON data from the map and emit # 'message'. This is a much nicer way to message the server. if map.JSON? try message = JSON.parse map.JSON catch e session.close 'Invalid JSON' return session.emit 'message', message # Raw string messages are embedded in a _S: property in a map. else if map._S? session.emit 'message', map._S else # We have data.json. We'll just emit it directly. for message in data.json session._mapBuffer id++, do (map) -> -> return if session.state is 'closed' session.emit 'message', message return BCSession::_disconnectAt = (rid) -> session = this @_ridBuffer rid, -> session.close 'Disconnected' # When we receive forwardchannel data, we reply with a special little 3-variable array to tell the # client if it should reopen the backchannel. # # This method returns what the forward channel should reply with. BCSession::_backChannelStatus = -> # Find the arrays have been sent over the wire but haven't been acknowledged yet numUnsentArrays = @_lastArrayId - @_lastSentArrayId unacknowledgedArrays = @_outgoingArrays[... @_outgoingArrays.length - numUnsentArrays] outstandingBytes = if unacknowledgedArrays.length == 0 0 else # We don't care about the length of the array IDs or callback functions. # I'm actually not sure what data the client expects here - the value is just used in a rough # heuristic to determine if the backchannel should be reopened. data = (a.data for a in unacknowledgedArrays) JSON.stringify(data).length return [ (if @_backChannel then 1 else 0) @_lastSentArrayId outstandingBytes ] # ## Encoding server arrays for the back channel # # The server sends data to the client in **chunks**. Each chunk is a *JSON* array prefixed # by its length in bytes. # # The array looks like this: # # ``` # [ # [100, ['message', 'one']], # [101, ['message', 'two']], # [102, ['message', 'three']] # ] # ``` # # Each individial message is prefixed by its *array id*, which is a counter starting at 0 # when the session is first created and incremented with each array. # This will actually send the arrays to the backchannel on the next tick if the backchannel # is alive. BCSession::flush = -> session = this process.nextTick -> session._flush() BCSession::_flush = -> return unless @_backChannel numUnsentArrays = @_lastArrayId - @_lastSentArrayId if numUnsentArrays > 0 arrays = @_outgoingArrays[@_outgoingArrays.length - numUnsentArrays ...] # I've abused outgoingArrays to also contain some callbacks. We only send [id, data] to # the client. data = ([id, data] for {id, data} in arrays) bytes = JSON.stringify(data) + "\n" # Stand back, pro hax! Ideally there is a general solution for escaping these characters # when converting to JSON. bytes = bytes.replace(/\u2028/g, "\\u2028") bytes = bytes.replace(/\u2029/g, "\\u2029") # **Away!** @_backChannel.methods.write bytes @_backChannel.bytesSent += bytes.length @_lastSentArrayId = @_lastArrayId # Fire any send callbacks on the messages. These callbacks should only be called once. # Again, not sure what to do if there are exceptions here. for a in arrays if a.sendcallback? a.sendcallback?() delete a.sendcallback # The send callback could have cleared the backchannel by calling close. if @_backChannel and (!@_backChannel.chunk or @_backChannel.bytesSent > 10 * 1024) @_clearBackChannel() # The first backchannel is the client's initial connection. Once we've sent the first # data chunk to the client, we've officially opened the connection. @_changeState 'ok' if @state == 'init' # Signal to a client that it should stop trying to connect. This has no other effect # on the server session. # # `stop` takes a callback which will be called once the message has been *sent* by the server. # Typically, you should call it like this: # # ``` # session.stop -> # session.close() # ``` # # I considered making this automatically close the connection after you've called it, or after # you've sent the stop message or something, but if I did that it wouldn't be obvious that you # can still receive messages after stop() has been called. (Because you can!). That would never # come up when you're testing locally, but it *would* come up in production. This is more obvious. BCSession::stop = (callback) -> return if @state is 'closed' @_queueArray ['stop'], callback, null @flush() # This closes a session and makes the server forget about it. # # The client might try and reconnect if you only call `close()`. It'll get a new session if it does so. # # close takes an optional message argument, which is passed to the send event handlers. BCSession::close = (message) -> # You can't double-close. return if @state == 'closed' @_changeState 'closed' @emit 'close', message @_clearBackChannel() clearTimeout @_sessionTimeout for {confirmcallback} in @_outgoingArrays confirmcallback? new Error(message || 'closed') return # --- # # # The server middleware # # The server module returns a function, which you can call with your # configuration options. It returns your configured connect middleware, which # is actually another function. module.exports = browserChannel = (options, onConnect) -> if typeof onConnect == 'undefined' onConnect = options options = {} options ||= {} options[option] ?= value for option, value of defaultOptions options.headers = {} unless options.headers options.headers[h] ||= v for h, v of standardHeaders options.headers['Access-Control-Allow-Origin'] = options.cors if options.cors options.headers['Access-Control-Allow-Credentials'] = true if options.corsAllowCredentials # Strip off a trailing slash in base. base = options.base base = base[... base.length - 1] if base.match /\/$/ # Add a leading slash back on base base = "/#{base}" if base.length > 0 and !base.match /^\// # map from sessionId -> session sessions = {} # # Create a new client session. # # This method will start a new client session. # # Session ids are generated by [node-hat]. They are guaranteed to be unique. # [node-hat]: https://github.com/substack/node-hat # # This method is synchronous, because a database will never be involved in # browserchannel session management. Browserchannel sessions only last as # long as the user's browser is open. If there's any connection turbulence, # the client will reconnect and get a new session id. # # Sometimes a client will specify an old session ID and old array ID. In this # case, the client is reconnecting and we should evict the named session (if # it exists). createSession = (address, query, headers) -> {OSID: oldSessionId, OAID: oldArrayId} = query if oldSessionId? and (oldSession = sessions[oldSessionId]) oldSession._acknowledgeArrays oldArrayId oldSession.close 'Reconnected' session = new BCSession address, query, headers, options sessions[session.id] = session session.on 'close', -> delete sessions[session.id] # console.log "closed #{@id}" return session # This is the returned middleware. Connect middleware is a function which # takes in an http request, an http response and a next method. # # The middleware can do one of two things: # # - Handle the request, sending data back to the server via the response # - Call `next()`, which allows the next middleware in the stack a chance to # handle the request. middleware = (req, res, next) -> {query, pathname} = parse req.url, true #console.warn req.method, req.url # If base is /foo, we don't match /foobar. (Currently no unit tests for this) return next() if pathname.substring(0, base.length + 1) != "#{base}/" {writeHead, write, writeRaw, end, writeError} = messagingMethods options, query, res # # Serving the client # # The browserchannel server hosts a usable web client library at /CHANNEL/bcsocket.js. # This library wraps the google closure library client implementation. # # If I have time, I would like to write my own version of the client to add a few features # (websockets, message acknowledgement callbacks) and do some manual optimisations for speed. # However, the current version works ok. if pathname is "#{base}/bcsocket.js" etag = "\"#{clientStats.size}-#{clientStats.mtime.getTime()}\"" res.writeHead 200, 'OK', 'Content-Type': 'application/javascript', 'ETag': etag, 'Content-Length': clientCode.length # This code is manually tested because it looks like its impossible to send HEAD requests # using nodejs's HTTP library at time of writing (0.4.12). (Yeah, I know, rite?) if req.method is 'HEAD' res.end() else res.end clientCode # # Connection testing # # Before the browserchannel client connects, it tests the connection to make # sure its working, and to look for buffering proxies. # # The server-side code for connection testing is completely stateless. else if pathname is "#{base}/test" # This server only supports browserchannel protocol version **8**. # I have no idea if 400 is the right error here. return sendError res, 400, 'Version 8 required', options unless query.VER is '8' #### Phase 1: Server info # The client is requests host prefixes. The server responds with an array of # ['hostprefix' or null, 'blockedprefix' or null]. # # > Actually, I think you might be able to return [] if neither hostPrefix nor blockedPrefix # > is defined. (Thats what google wave seems to do) # # - **hostprefix** is subdomain prepended onto the hostname of each request. # This gets around browser connection limits. Using this requires a bank of # configured DNS entries and SSL certificates if you're using HTTPS. # # - **blockedprefix** provides network admins a way to blacklist browserchannel # requests. It is not supported by node-browserchannel. if query.MODE == 'init' and req.method == 'GET' hostPrefix = getHostPrefix options blockedPrefix = null # Blocked prefixes aren't supported. # We add an extra special header to tell the client that this server likes # json-encoded forward channel data over form urlencoded channel data. # # It might be easier to put these headers in the response body or increment the # version, but that might conflict with future browserchannel versions. headers = {} headers[k] = v for k, v of options.headers headers['X-Accept'] = 'application/json; application/x-www-form-urlencoded' # This is a straight-up normal HTTP request like the forward channel requests. # We don't use the funny iframe write methods. res.writeHead 200, 'OK', headers res.end(JSON.stringify [hostPrefix, blockedPrefix]) else #### Phase 2: Buffering proxy detection # The client is trying to determine if their connection is buffered or unbuffered. # We reply with '11111', then 2 seconds later '2'. # # The client should get the data in 2 chunks - but they won't if there's a misbehaving # corporate proxy in the way or something. writeHead() writeRaw '11111' setTimeout (-> writeRaw '2'; end()), 2000 # # BrowserChannel connection # # Once a client has finished testing its connection, it connects. # # BrowserChannel communicates through two connections: # # - The **forward channel** is used for the client to send data to the server. # It uses a **POST** request for each message. # - The **back channel** is used to get data back from the server. This uses a # hanging **GET** request. If chunking is disallowed (ie, if the proxy buffers) # then the back channel is closed after each server message. else if pathname == "#{base}/bind" # I'm copying the behaviour of unknown SIDs below. I don't know how the client # is supposed to detect this error, but, eh. The other choice is to `return writeError ...` return sendError res, 400, 'Version 8 required', options unless query.VER is '8' # All browserchannel connections have an associated client object. A client # is created immediately if the connection is new. if query.SID session = sessions[query.SID] # This is a special error code for the client. It tells the client to abandon its # connection request and reconnect. # # For some reason, google replies with the same response on HTTP and HTML requests here. # I'll follow suit, though its a little weird. Maybe I should do the same with all client # errors? return sendError res, 400, 'Unknown SID', options unless session session._acknowledgeArrays query.AID if query.AID? and session # ### Forward Channel if req.method == 'POST' if session == undefined # The session is new! Make them a new session object and let the # application know. session = createSession req.connection.remoteAddress, query, req.headers onConnect? session, req # TODO Emit 'req' for subsequent requests associated with session session.emit 'req', req dataError = (e) -> console.warn 'Error parsing forward channel', e.stack return sendError res, 400, 'Bad data', options processData = (data) -> try data = transformData req, data session._receivedData query.RID, data catch e return dataError e if session.state is 'init' # The initial forward channel request is also used as a backchannel # for the server's initial data (session id, etc). This connection # is a little bit special - it is always encoded using # length-prefixed json encoding and it is closed as soon as the # first chunk is sent. res.writeHead 200, 'OK', options.headers session._setBackChannel res, CI:1, TYPE:'xmlhttp', RID:'rpc' session.flush() else if session.state is 'closed' # If the onConnect handler called close() immediately, # session.state can be already closed at this point. I'll assume # there was an authentication problem and treat this as a forbidden # connection attempt. sendError res, 403, 'Forbidden', options else # On normal forward channels, we reply to the request by telling # the session if our backchannel is still live and telling it how # many unconfirmed arrays we have. response = JSON.stringify session._backChannelStatus() res.writeHead 200, 'OK', options.headers res.end "#{response.length}\n#{response}" if req.body processData req.body else bufferPostData req, (data) -> try data = decodeData req, data catch e return dataError e processData data else if req.method is 'GET' # ### Back channel # # GET messages are usually backchannel requests (server->client). # Backchannel messages are handled by the session object. if query.TYPE in ['xmlhttp', 'html'] return sendError res, 400, 'Invalid SID', options if typeof query.SID != 'string' && query.SID.length < 5 return sendError res, 400, 'Expected RPC', options unless query.RID is 'rpc' writeHead() session._setBackChannel res, query # The client can manually disconnect by making a GET request with TYPE='terminate' else if query.TYPE is 'terminate' # We don't send any data in the response to the disconnect message. # # The client implements this using an img= appended to the page. session?._disconnectAt query.RID res.writeHead 200, 'OK', options.headers res.end() else res.writeHead 405, 'Method Not Allowed', options.headers res.end "Method not allowed" else # We'll 404 the user instead of letting another handler take care of it. # Users shouldn't be using the specified URL prefix for anything else. res.writeHead 404, 'Not Found', options.headers res.end "Not found" middleware.close = -> for id, session of sessions session.close() return # This is an undocumented, untested treat - if you pass the HTTP server / # connect server to browserchannel through the options object, it can attach # a close listener for you automatically. options.server?.on 'close', middleware.close middleware # This will override the timer methods (`setInterval`, etc) with the testing # stub versions, which are way faster. browserChannel._setTimerMethods = (methods) -> {setInterval, clearInterval, setTimeout, clearTimeout, Date} = methods
true
# # A BrowserChannel server. # # - Its still pretty young, so there's probably bugs lurking around and the API # will still change quickly. # - Its missing integration tests # # It works in all the browsers I've tried. # # I've written this using the literate programming style to try it out. So, thats why # there's a million comments everywhere. # # The server is implemented an express middleware. Its intended to be used like this: # # ``` # server = express(); # server.use(browserChannel(function(client) { client.send('hi'); })); # ``` # ## Dependancies, helper methods and constant data # `parse` helps us decode URLs in requests {parse} = require 'url' # `querystring` will help decode the URL-encoded forward channel data querystring = require 'querystring' # `fs` is used to read & serve the client library fs = require 'fs' # Client sessions are `EventEmitters` {EventEmitter} = require 'events' # Client session Ids are generated using `node-hat` hat = require('hat').rack(40, 36) # When sending messages to IE using a hidden iframe, UTF8-encoded characters # don't get processed correctly. This encodes unicode characters using the # \u2028 encoding style, which (thankfully) makes it through. asciijson = require 'ascii-json' # `randomInt(n)` generates and returns a random int smaller than n (0 <= k < n) randomInt = (n) -> Math.floor(Math.random() * n) # `randomArrayElement(array)` Selects and returns a random element from *array* randomArrayElement = (array) -> array[randomInt(array.length)] # For testing we'll override `setInterval`, etc with special testing stub versions (so # we don't have to actually wait for actual *time*. To do that, we need local variable # versions (I don't want to edit the global versions). ... and they'll just point to the # normal versions anyway. {setInterval, clearInterval, setTimeout, clearTimeout, Date} = global # The module is configurable defaultOptions = # An optional array of host prefixes. Each browserchannel client will # randomly pick from the list of host prefixes when it connects. This reduces # the impact of per-host connection limits. # # All host prefixes should point to the same server. Ie, if your server's # hostname is *example.com* and your hostPrefixes contains ['a', 'b', 'c'], # a.example.com, b.example.com and c.example.com should all point to the same # host as example.com. hostPrefixes: null # You can specify the base URL which browserchannel connects to. Change this # if you want to scope browserchannel in part of your app, or if you want # /channel to mean something else, or whatever. # # I really want to remove this parameter - express 4.0's router is now good # enough that you can just install the middleware anywhere using express. For # example: # app.use('/mycoolpath', browserchannel({base:''}, ...)); # # Unfortunately you have to force the base option to '' to do that (since it # defaults to /channel otherwise). What a pain. TODO browserchannel 3.0 base: '/channel' # We'll send keepalives every so often to make sure the http connection isn't # closed by eagar clients. The standard timeout is 30 seconds, so we'll # default to sending them every 20 seconds or so. keepAliveInterval: 20 * 1000 # After awhile (30 seconds or so) of not having a backchannel connected, # we'll evict the session completely. This will happen whenever a user closes # their browser. sessionTimeoutInterval: 30 * 1000 # By default, browsers don't allow access via javascript to foreign sites. # You can use the cors: option to set the Access-Control-Allow-Origin header # in responses, which tells browsers whether or not to allow cross domain # requests to be sent. # # See https://developer.mozilla.org/en/http_access_control for more information. # # Setting cors:'*' will enable javascript from any domain to access your # application. BE CAREFUL! If your application uses cookies to manage user # sessions, javascript on a foreign site could make requests as if it were # acting on behalf of one of your users. # # Setting cors:'X' is equivalent to adding # {headers: {'Access-Control-Allow-Origin':X}}. cors: null # Even with Access-Control-Allow-Origin enabled, browsers don't send their # cookies to different domains. You can set corsAllowCredentials to be true # to add the `Access-Control-Allow-Credentials: true` header to responses. # This tells browsers they are allowed to send credentialed requests (ie, # requests with cookies) to a foreign domain. If you do this, you must *also* # set {crossDomainXhr:true} in your BCSocket browser options to tell XHR # requests to send credentials. # # Also note that credentialed requests require explicitly mentioned domains # to work. You cannot use a wildcard cors header (`cors:*`) if you want # credentials. # # See: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Requests_with_credentials # # Setting corsAllowCredentials:true is equivalent to adding: # {headers: {'Access-Control-Allow-Credentials':true}}. corsAllowCredentials: false # A user can override all the headers if they want by setting the headers # option to an object. headers: null # All server responses set some standard HTTP headers. To be honest, I don't # know how many of these are necessary. I just copied them from google. # # The nocache headers in particular seem unnecessary since each client request # includes a randomized `zx=junk` query parameter. standardHeaders = 'Content-Type': 'text/plain' 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate' 'Pragma': 'no-cache' 'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT' 'X-Content-Type-Options': 'nosniff' # Gmail also sends this, though I'm not really sure what it does... # 'X-Xss-Protection': '1; mode=block' # The one exception to that is requests destined for iframes. They need to have # content-type: text/html set for IE to process the juicy JS inside. ieHeaders = {} ieHeaders[k] = v for k, v of standardHeaders ieHeaders['Content-Type'] = 'text/html' # Google's browserchannel server adds some junk after the first message data is # sent. I assume this stops some whole-page buffering in IE. I assume the data # used is noise so it doesn't compress. # # I don't really know why google does this. I'm assuming there's a good reason # to it though. ieJunk = "7cca69475363026330a0d99468e88d23ce95e222591126443015f5f462d9a177186c8701fb45a6ffe\ e0daf1a178fc0f58cd309308fba7e6f011ac38c9cdd4580760f1d4560a84d5ca0355ecbbed2ab715a3350fe0c47\ 9050640bd0e77acec90c58c4d3dd0f5cf8d4510e68c8b12e087bd88cad349aafd2ab16b07b0b1b8276091217a44\ a9fe92fedacffff48092ee693af\n" # If the user is using IE, instead of using XHR backchannel loaded using a # forever iframe. When data is sent, it is wrapped in <script></script> tags # which call functions in the browserchannel library. # # This method wraps the normal `.writeHead()`, `.write()` and `.end()` methods # by special versions which produce output based on the request's type. # # This **is not used** for: # # - The first channel test # - The first *bind* connection a client makes. The server sends arrays there, # but the connection is a POST and it returns immediately. So that request # happens using XHR/Trident like regular forward channel requests. messagingMethods = (options, query, res) -> type = query.TYPE if type == 'html' # IE encoding using messaging via a slowly loading script file junkSent = false methods = writeHead: -> res.writeHead 200, 'OK', ieHeaders res.write '<html><body>' domain = query.DOMAIN # If the iframe is making the request using a secondary domain, I think # we need to set the `domain` to the original domain so that we can # call the response methods. if domain and domain != '' # Make sure the domain doesn't contain anything by naughty by # `JSON.stringify()`-ing it before passing it to the client. There # are XSS vulnerabilities otherwise. res.write "<script>try{document.domain=#{asciijson.stringify domain};}catch(e){}</script>\n" write: (data) -> # The data is passed to `m()`, which is bound to *onTridentRpcMessage_* in the client. res.write "<script>try {parent.m(#{asciijson.stringify data})} catch(e) {}</script>\n" unless junkSent res.write ieJunk junkSent = true end: -> # Once the data has been received, the client needs to call `d()`, # which is bound to *onTridentDone_* with success=*true*. The weird # spacing of this is copied from browserchannel. Its really not # necessary. res.end "<script>try {parent.d(); }catch (e){}</script>\n" # This is a helper method for signalling an error in the request back to the client. writeError: (statusCode, message) -> # The HTML (iframe) handler has no way to discover that the embedded # script tag didn't complete successfully. To signal errors, we return # **200 OK** and call an exposed rpcClose() method on the page. methods.writeHead() res.end "<script>try {parent.rpcClose(#{asciijson.stringify message})} catch(e){}</script>\n" # For some reason, sending data during the second test (111112) works # slightly differently for XHR, but its identical for html encoding. We'll # use a writeRaw() method in that case, which is copied in the case of # html. methods.writeRaw = methods.write methods else # Encoding for modern browsers # For normal XHR requests, we send data normally. writeHead: -> res.writeHead 200, 'OK', options.headers write: (data) -> res.write "#{data.length}\n#{data}" writeRaw: (data) -> res.write data end: -> res.end() writeError: (statusCode, message) -> res.writeHead statusCode, options.headers res.end message # For telling the client its done bad. # # It turns out google's server isn't particularly fussy about signalling errors # using the proper html RPC stuff, so this is useful for html connections too. sendError = (res, statusCode, message, options) -> res.writeHead statusCode, message, options.headers res.end "<html><body><h1>#{message}</h1></body></html>" return # ## Parsing client maps from the forward channel # # The client sends data in a series of url-encoded maps. The data is encoded # like this: # # ``` # count=2&ofs=0&req0_x=3&req0_y=10&req1_abc=def # ``` # # First, we need to buffer up the request response and query string decode it. bufferPostData = (req, callback) -> data = [] req.on 'data', (chunk) -> data.push chunk.toString 'utf8' req.on 'end', -> data = data.join '' callback data # Next, we'll need to decode the incoming client data into an array of objects. # # The data could be in two different forms: # # - Classical browserchannel format, which is a bunch of string->string url-encoded maps # - A JSON object # # We can tell what format the data is in by inspecting the content-type header # # ## URL Encoded data # # Essentially, url encoded the data looks like this: # # ``` # { count: '2', # ofs: '0', # req0_x: '3', # req0_y: '10', # req1_abc: 'def' # } # ``` # # ... and we will return an object in the form of `[{x:'3', y:'10'}, {abc: 'def'}, ...]` # # ## JSON Encoded data # # JSON encoded the data looks like: # # ``` # { ofs: 0 # , data: [null, {...}, 1000.4, 'hi', ...] # } # ``` # # or `null` if there's no data. # # This function returns null if there's no data or {ofs, json:[...]} or {ofs, maps:[...]} transformData = (req, data) -> if req.headers['content-type'] == 'application/json' # We'll restructure it slightly to mark the data as JSON rather than maps. {ofs, data} = data {ofs, json:data} else count = parseInt data.count return null if count is 0 # ofs will be missing if count is zero ofs = parseInt data.ofs throw new Error 'invalid map data' if isNaN count or isNaN ofs throw new Error 'Invalid maps' unless count == 0 or (count > 0 and data.ofs?) maps = new Array count # Scan through all the keys in the data. Every key of the form: # `PI:KEY:<KEY>END_PI123_xxx` will be used to populate its map. regex = /^req(\d+)_(.+)$/ for key, val of data match = regex.exec key if match id = match[1] mapKey = match[2] map = (maps[id] ||= {}) # The client uses `mapX_type=_badmap` to signify an error encoding a map. continue if id == 'type' and mapKey == '_badmap' map[mapKey] = val {ofs, maps} # Decode data string body and get an object back # Either a query string format or JSON depending on content type decodeData = (req, data) -> if req.headers['content-type'] == 'application/json' JSON.parse data else # Maps. Ugh. # # By default, querystring.parse only parses out the first 1000 keys from the data. # maxKeys:0 removes this restriction. querystring.parse data, '&', '=', maxKeys:0 # This is a helper method to order the handling of messages / requests / whatever. # # Use it like this: # inOrder = order 0 # # inOrder 1, -> console.log 'second' # inOrder 0, -> console.log 'first' # # Start is the ID of the first element we expect to receive. If we get data for # earlier elements, we'll play them anyway if playOld is truthy. order = (start, playOld) -> # Base is the ID of the (missing) element at the start of the queue base = start # The queue will start with about 10 elements. Elements of the queue are # undefined if we don't have data for that queue element. queue = new Array 10 (seq, callback) -> # Its important that all the cells of the array are truthy if we have data. # We'll use an empty function instead of null. callback or= -> # Ignore old messages, or play them back immediately if playOld=true if seq < base callback() if playOld else queue[seq - base] = callback while queue[0] callback = queue.shift() base++ callback() return # Host prefixes provide a way to skirt around connection limits. They're only # really important for old browsers. getHostPrefix = (options) -> if options.hostPrefixes randomArrayElement options.hostPrefixes else null # We need access to the client's sourcecode. I'm going to get it using a # synchronous file call (it'll be fast anyway, and only happen once). # # I'm also going to set an etag on the client data so the browser client will # be cached. I'm kind of uncomfortable about adding complexity here because its # not like this code hasn't been written before, but.. I think a lot of people # will use this API. # # I should probably look into hosting the client code as a javascript module # using that client-side npm thing. clientFile = "#{__dirname}/../dist/bcsocket.js" clientStats = fs.statSync clientFile try clientCode = fs.readFileSync clientFile, 'utf8' catch e console.error 'Could not load the client javascript. Run `cake client` to generate it.' throw e # This is mostly to help development, but if the client is recompiled, I'll # pull in a new version. This isn't tested by the unit tests - but its not a # big deal. # # The `readFileSync` call here will stop the whole server while the client is # reloaded. This will only happen during development so its not a big deal. if process.env.NODE_ENV != 'production' if process.platform is "win32" # Windows doesn't support watchFile. See: # https://github.com/josephg/node-browserchannel/pull/6 fs.watch clientFile, persistent: false, (event, filename) -> if event is "change" console.log "Reloading client JS" clientCode = fs.readFileSync clientFile, 'utf8' clientStats = curr else fs.watchFile clientFile, persistent: false, (curr, prev) -> if curr.mtime.getTime() isnt prev.mtime.getTime() console.log "Reloading client JS" clientCode = fs.readFileSync clientFile, 'utf8' clientStats = curr # This code was rewritten from closure-style to class style to make heap dumps # clearer and make the code run faster in V8 (v8 loves this code style). BCSession = (address, query, headers, options) -> EventEmitter.call this # The session's unique ID for this connection @id = hat() # The client stores its IP address and headers from when it first opened # the session. The handler can use this information for authentication or # something. @address = address @headers = headers # Add a reference to the query as users can send extra query string # information using the `extraParams` option on the Socket. @query = query # Options are passed in when creating the BrowserChannel middleware @options = options # The session is a little state machine. It has the following states: # # - **init**: The session has been created and its sessionId hasn't been # sent yet. The session moves to the **ok** state when the first data # chunk is sent to the client. # # - **ok**: The session is sitting pretty and ready to send and receive # data. The session will spend most of its time in this state. # # - **closed**: The session has been removed from the session list. It can # no longer be used for any reason. @state = 'init' # The client's reported application version, or null. This is sent when the # connection is first requested, so you can use it to make your application die / stay # compatible with people who don't close their browsers. @appVersion = query.CVER or null # The server sends messages to the client via a hanging GET request. Of course, # the client has to be the one to open that request. # # This is a handle to null, or {res, methods, chunk} # # - **res** is the http response object # - **methods** is a map of send(), etc methods for communicating properly with the backchannel - # this will be different if the request comes from IE or not. # - **chunk** specifies whether or not we're going to keep the connection open across multiple # messages. If there's a buffering proxy in the way of the connection, we can't respond a bit at # a time, so we close the backchannel after each data chunk. The client decides this during # testing and passes a CI= parameter to the server when the backchannel connection is established. # - **bytesSent** specifies how many bytes of data have been sent through the backchannel. We periodically # close the backchannel and let the client reopen it, so things like the chrome web inspector stay # usable. @_backChannel = null # The server sends data to the client by sending *arrays*. It seems a bit silly that # client->server messages are maps and server->client messages are arrays, but there it is. # # Each entry in this array is of the form [id, data]. @_outgoingArrays = [] # `lastArrayId` is the array ID of the last queued array @_lastArrayId = -1 # Every request from the client has an *AID* parameter which tells the server the ID # of the last request the client has received. We won't remove arrays from the outgoingArrays # list until the client has confirmed its received them. # # In `lastSentArrayId` we store the ID of the last array which we actually sent. @_lastSentArrayId = -1 # If we haven't sent anything for 15 seconds, we'll send a little `['noop']` to the # client so it knows we haven't forgotten it. (And to make sure the backchannel # connection doesn't time out.) @_heartbeat = null # The session will close if there's been no backchannel for awhile. @_sessionTimeout = null # Since the session doesn't start with a backchannel, we'll kick off the timeout timer as soon as its # created. @_refreshSessionTimeout() # The session has just been created. The first thing it needs to tell the client # is its session id and host prefix and stuff. # # It would be pretty easy to add a callback here setting the client status to 'ok' or # something, but its not really necessary. The client has already connected once the first # POST /bind has been received. @_queueArray ['c', @id, getHostPrefix(options), 8] # ### Maps # # The client sends maps to the server using POST requests. Its possible for the requests # to come in out of order, so sometimes we need to buffer up incoming maps and reorder them # before emitting them to the user. # # Each map has an ID (which starts at 0 when the session is first created). # We'll emit received data to the user immediately if they're in order, but if they're out of order # we'll use the little order helper above to order them. The order helper is instructed to not # emit any old messages twice. # # There's a potential DOS attack here whereby a client could just spam the server with # out-of-order maps until it runs out of memory. We should dump a session if there are # too many entries in this dictionary. @_mapBuffer = order 0, false # This method is called whenever we get maps from the client. Offset is the ID of the first # map. The data could either be maps or JSON data. If its maps, data contains {maps} and if its # JSON data, maps contains {JSON}. # # Browserchannel has 2 different mechanisms for consistantly ordering messages in the forward channel: # # - Each forward channel request contains a request ID (RID=X), which start at a random value # (set with the first session create packet). These increment by 1 with each request. # # If a request fails, it might be retried with the same RID as the previous message, and with extra # maps tacked on the end. We need to handle the maps in this case. # # - Each map has an ID, counting from 0. ofs= in the POST data tells the server the ID of the first # map in a request. # # As far as I can tell, the RID stuff can mostly be ignored. The one place it is important is in # handling disconnect messages. The session should only be disconnected by a disconnect message when # the preceeding messages have been received. # All requests are handled in order too, though if not for disconnecting I don't think it would matter. # Because of the funky retry-has-extra-maps logic, we'll allow processing requests twice. @_ridBuffer = order query.RID, true return # Sessions extend node's [EventEmitter][] so they # have access to goodies like `session.on(event, handler)`, # `session.emit('paarty')`, etc. # [EventEmitter]: http://nodejs.org/docs/v0.4.12/api/events.html do -> for name, method of EventEmitter:: BCSession::[name] = method return # The state is modified through this method. It emits events when the state # changes. (yay) BCSession::_changeState = (newState) -> oldState = @state @state = newState @emit 'state changed', @state, oldState BackChannel = (session, res, query) -> @res = res @methods = messagingMethods session.options, query, res @chunk = query.CI == '0' @bytesSent = 0 @listener = -> session._backChannel.listener = null session._clearBackChannel res return # I would like this method to be private or something, but it needs to be accessed from # the HTTP request code below. The _ at the start will hopefully make people think twice # before using it. BCSession::_setBackChannel = (res, query) -> @_clearBackChannel() @_backChannel = new BackChannel this, res, query # When the TCP connection underlying the backchannel request is closed, we'll stop using the # backchannel and start the session timeout clock. The listener is kept so the event handler # removed once the backchannel is closed. res.connection.once 'close', @_backChannel.listener # We'll start the heartbeat interval and clear out the session timeout. # The session timeout will be started again if the backchannel connection closes for # any reason. @_refreshHeartbeat() clearTimeout @_sessionTimeout # When a new backchannel is created, its possible that the old backchannel is dead. # In this case, its possible that previously sent arrays haven't been received. # By resetting lastSentArrayId, we're effectively rolling back the status of sent arrays # to only those arrays which have been acknowledged. if @_outgoingArrays.length > 0 @_lastSentArrayId = @_outgoingArrays[0].id - 1 # Send any arrays we've buffered now that we have a backchannel @flush() # This method removes the back channel and any state associated with it. It'll get called # when the backchannel closes naturally, is replaced or when the connection closes. BCSession::_clearBackChannel = (res) -> # clearBackChannel doesn't do anything if we call it repeatedly. return unless @_backChannel # Its important that we only delete the backchannel if the closed connection is actually # the backchannel we're currently using. return if res? and res != @_backChannel.res if @_backChannel.listener # The backchannel listener has been attached to the 'close' event of the underlying TCP # stream. We don't care about that anymore @_backChannel.res.connection.removeListener 'close', @_backChannel.listener @_backChannel.listener = null # Conveniently, clearTimeout has no effect if the argument is null. clearTimeout @_heartbeat @_backChannel.methods.end() @_backChannel = null # Whenever we don't have a backchannel, we run the session timeout timer. @_refreshSessionTimeout() # This method sets / resets the heartbeat timeout to the full 15 seconds. BCSession::_refreshHeartbeat = -> clearTimeout @_heartbeat session = this @_heartbeat = setInterval -> session.send ['noop'] , @options.keepAliveInterval BCSession::_refreshSessionTimeout = -> clearTimeout @_sessionTimeout session = this @_sessionTimeout = setTimeout -> session.close 'Timed out' , @options.sessionTimeoutInterval # The arrays get removed once they've been acknowledged BCSession::_acknowledgeArrays = (id) -> id = parseInt id if typeof id is 'string' while @_outgoingArrays.length > 0 and @_outgoingArrays[0].id <= id {confirmcallback} = @_outgoingArrays.shift() # I've got no idea what to do if we get an exception thrown here. The session will end up # in an inconsistant state... confirmcallback?() return OutgoingArray = (@id, @data, @sendcallback, @confirmcallback) -> # Queue an array to be sent. The optional callbacks notifies a caller when the array has been # sent, and then received by the client. # # If the session is already closed, we'll call the confirmation callback immediately with the # error. # # queueArray returns the ID of the queued data chunk. BCSession::_queueArray = (data, sendcallback, confirmcallback) -> return confirmcallback? new Error 'closed' if @state is 'closed' id = ++@_lastArrayId @_outgoingArrays.push new OutgoingArray(id, data, sendcallback, confirmcallback) return @_lastArrayId # Send the array data through the backchannel. This takes an optional callback which # will be called with no arguments when the client acknowledges the array, or called with an # error object if the client disconnects before the array is sent. # # queueArray can also take a callback argument which is called when the session sends the message # in the first place. I'm not sure if I should expose this through send - I can't tell if its # useful beyond the server code. BCSession::send = (arr, callback) -> id = @_queueArray arr, null, callback @flush() return id BCSession::_receivedData = (rid, data) -> session = this @_ridBuffer rid, -> return if data is null throw new Error 'Invalid data' unless data.maps? or data.json? session._ridBuffer rid id = data.ofs # First, classic browserchannel maps. if data.maps # If an exception is thrown during this loop, I'm not really sure what the behaviour should be. for map in data.maps # The funky do expression here is used to pass the map into the closure. # Another way to do it is to index into the data.maps array inside the function, but then I'd # need to pass the index to the closure anyway. session._mapBuffer id++, do (map) -> -> return if session.state is 'closed' session.emit 'map', map # If you specify the key as JSON, the server will try to decode JSON data from the map and emit # 'message'. This is a much nicer way to message the server. if map.JSON? try message = JSON.parse map.JSON catch e session.close 'Invalid JSON' return session.emit 'message', message # Raw string messages are embedded in a _S: property in a map. else if map._S? session.emit 'message', map._S else # We have data.json. We'll just emit it directly. for message in data.json session._mapBuffer id++, do (map) -> -> return if session.state is 'closed' session.emit 'message', message return BCSession::_disconnectAt = (rid) -> session = this @_ridBuffer rid, -> session.close 'Disconnected' # When we receive forwardchannel data, we reply with a special little 3-variable array to tell the # client if it should reopen the backchannel. # # This method returns what the forward channel should reply with. BCSession::_backChannelStatus = -> # Find the arrays have been sent over the wire but haven't been acknowledged yet numUnsentArrays = @_lastArrayId - @_lastSentArrayId unacknowledgedArrays = @_outgoingArrays[... @_outgoingArrays.length - numUnsentArrays] outstandingBytes = if unacknowledgedArrays.length == 0 0 else # We don't care about the length of the array IDs or callback functions. # I'm actually not sure what data the client expects here - the value is just used in a rough # heuristic to determine if the backchannel should be reopened. data = (a.data for a in unacknowledgedArrays) JSON.stringify(data).length return [ (if @_backChannel then 1 else 0) @_lastSentArrayId outstandingBytes ] # ## Encoding server arrays for the back channel # # The server sends data to the client in **chunks**. Each chunk is a *JSON* array prefixed # by its length in bytes. # # The array looks like this: # # ``` # [ # [100, ['message', 'one']], # [101, ['message', 'two']], # [102, ['message', 'three']] # ] # ``` # # Each individial message is prefixed by its *array id*, which is a counter starting at 0 # when the session is first created and incremented with each array. # This will actually send the arrays to the backchannel on the next tick if the backchannel # is alive. BCSession::flush = -> session = this process.nextTick -> session._flush() BCSession::_flush = -> return unless @_backChannel numUnsentArrays = @_lastArrayId - @_lastSentArrayId if numUnsentArrays > 0 arrays = @_outgoingArrays[@_outgoingArrays.length - numUnsentArrays ...] # I've abused outgoingArrays to also contain some callbacks. We only send [id, data] to # the client. data = ([id, data] for {id, data} in arrays) bytes = JSON.stringify(data) + "\n" # Stand back, pro hax! Ideally there is a general solution for escaping these characters # when converting to JSON. bytes = bytes.replace(/\u2028/g, "\\u2028") bytes = bytes.replace(/\u2029/g, "\\u2029") # **Away!** @_backChannel.methods.write bytes @_backChannel.bytesSent += bytes.length @_lastSentArrayId = @_lastArrayId # Fire any send callbacks on the messages. These callbacks should only be called once. # Again, not sure what to do if there are exceptions here. for a in arrays if a.sendcallback? a.sendcallback?() delete a.sendcallback # The send callback could have cleared the backchannel by calling close. if @_backChannel and (!@_backChannel.chunk or @_backChannel.bytesSent > 10 * 1024) @_clearBackChannel() # The first backchannel is the client's initial connection. Once we've sent the first # data chunk to the client, we've officially opened the connection. @_changeState 'ok' if @state == 'init' # Signal to a client that it should stop trying to connect. This has no other effect # on the server session. # # `stop` takes a callback which will be called once the message has been *sent* by the server. # Typically, you should call it like this: # # ``` # session.stop -> # session.close() # ``` # # I considered making this automatically close the connection after you've called it, or after # you've sent the stop message or something, but if I did that it wouldn't be obvious that you # can still receive messages after stop() has been called. (Because you can!). That would never # come up when you're testing locally, but it *would* come up in production. This is more obvious. BCSession::stop = (callback) -> return if @state is 'closed' @_queueArray ['stop'], callback, null @flush() # This closes a session and makes the server forget about it. # # The client might try and reconnect if you only call `close()`. It'll get a new session if it does so. # # close takes an optional message argument, which is passed to the send event handlers. BCSession::close = (message) -> # You can't double-close. return if @state == 'closed' @_changeState 'closed' @emit 'close', message @_clearBackChannel() clearTimeout @_sessionTimeout for {confirmcallback} in @_outgoingArrays confirmcallback? new Error(message || 'closed') return # --- # # # The server middleware # # The server module returns a function, which you can call with your # configuration options. It returns your configured connect middleware, which # is actually another function. module.exports = browserChannel = (options, onConnect) -> if typeof onConnect == 'undefined' onConnect = options options = {} options ||= {} options[option] ?= value for option, value of defaultOptions options.headers = {} unless options.headers options.headers[h] ||= v for h, v of standardHeaders options.headers['Access-Control-Allow-Origin'] = options.cors if options.cors options.headers['Access-Control-Allow-Credentials'] = true if options.corsAllowCredentials # Strip off a trailing slash in base. base = options.base base = base[... base.length - 1] if base.match /\/$/ # Add a leading slash back on base base = "/#{base}" if base.length > 0 and !base.match /^\// # map from sessionId -> session sessions = {} # # Create a new client session. # # This method will start a new client session. # # Session ids are generated by [node-hat]. They are guaranteed to be unique. # [node-hat]: https://github.com/substack/node-hat # # This method is synchronous, because a database will never be involved in # browserchannel session management. Browserchannel sessions only last as # long as the user's browser is open. If there's any connection turbulence, # the client will reconnect and get a new session id. # # Sometimes a client will specify an old session ID and old array ID. In this # case, the client is reconnecting and we should evict the named session (if # it exists). createSession = (address, query, headers) -> {OSID: oldSessionId, OAID: oldArrayId} = query if oldSessionId? and (oldSession = sessions[oldSessionId]) oldSession._acknowledgeArrays oldArrayId oldSession.close 'Reconnected' session = new BCSession address, query, headers, options sessions[session.id] = session session.on 'close', -> delete sessions[session.id] # console.log "closed #{@id}" return session # This is the returned middleware. Connect middleware is a function which # takes in an http request, an http response and a next method. # # The middleware can do one of two things: # # - Handle the request, sending data back to the server via the response # - Call `next()`, which allows the next middleware in the stack a chance to # handle the request. middleware = (req, res, next) -> {query, pathname} = parse req.url, true #console.warn req.method, req.url # If base is /foo, we don't match /foobar. (Currently no unit tests for this) return next() if pathname.substring(0, base.length + 1) != "#{base}/" {writeHead, write, writeRaw, end, writeError} = messagingMethods options, query, res # # Serving the client # # The browserchannel server hosts a usable web client library at /CHANNEL/bcsocket.js. # This library wraps the google closure library client implementation. # # If I have time, I would like to write my own version of the client to add a few features # (websockets, message acknowledgement callbacks) and do some manual optimisations for speed. # However, the current version works ok. if pathname is "#{base}/bcsocket.js" etag = "\"#{clientStats.size}-#{clientStats.mtime.getTime()}\"" res.writeHead 200, 'OK', 'Content-Type': 'application/javascript', 'ETag': etag, 'Content-Length': clientCode.length # This code is manually tested because it looks like its impossible to send HEAD requests # using nodejs's HTTP library at time of writing (0.4.12). (Yeah, I know, rite?) if req.method is 'HEAD' res.end() else res.end clientCode # # Connection testing # # Before the browserchannel client connects, it tests the connection to make # sure its working, and to look for buffering proxies. # # The server-side code for connection testing is completely stateless. else if pathname is "#{base}/test" # This server only supports browserchannel protocol version **8**. # I have no idea if 400 is the right error here. return sendError res, 400, 'Version 8 required', options unless query.VER is '8' #### Phase 1: Server info # The client is requests host prefixes. The server responds with an array of # ['hostprefix' or null, 'blockedprefix' or null]. # # > Actually, I think you might be able to return [] if neither hostPrefix nor blockedPrefix # > is defined. (Thats what google wave seems to do) # # - **hostprefix** is subdomain prepended onto the hostname of each request. # This gets around browser connection limits. Using this requires a bank of # configured DNS entries and SSL certificates if you're using HTTPS. # # - **blockedprefix** provides network admins a way to blacklist browserchannel # requests. It is not supported by node-browserchannel. if query.MODE == 'init' and req.method == 'GET' hostPrefix = getHostPrefix options blockedPrefix = null # Blocked prefixes aren't supported. # We add an extra special header to tell the client that this server likes # json-encoded forward channel data over form urlencoded channel data. # # It might be easier to put these headers in the response body or increment the # version, but that might conflict with future browserchannel versions. headers = {} headers[k] = v for k, v of options.headers headers['X-Accept'] = 'application/json; application/x-www-form-urlencoded' # This is a straight-up normal HTTP request like the forward channel requests. # We don't use the funny iframe write methods. res.writeHead 200, 'OK', headers res.end(JSON.stringify [hostPrefix, blockedPrefix]) else #### Phase 2: Buffering proxy detection # The client is trying to determine if their connection is buffered or unbuffered. # We reply with '11111', then 2 seconds later '2'. # # The client should get the data in 2 chunks - but they won't if there's a misbehaving # corporate proxy in the way or something. writeHead() writeRaw '11111' setTimeout (-> writeRaw '2'; end()), 2000 # # BrowserChannel connection # # Once a client has finished testing its connection, it connects. # # BrowserChannel communicates through two connections: # # - The **forward channel** is used for the client to send data to the server. # It uses a **POST** request for each message. # - The **back channel** is used to get data back from the server. This uses a # hanging **GET** request. If chunking is disallowed (ie, if the proxy buffers) # then the back channel is closed after each server message. else if pathname == "#{base}/bind" # I'm copying the behaviour of unknown SIDs below. I don't know how the client # is supposed to detect this error, but, eh. The other choice is to `return writeError ...` return sendError res, 400, 'Version 8 required', options unless query.VER is '8' # All browserchannel connections have an associated client object. A client # is created immediately if the connection is new. if query.SID session = sessions[query.SID] # This is a special error code for the client. It tells the client to abandon its # connection request and reconnect. # # For some reason, google replies with the same response on HTTP and HTML requests here. # I'll follow suit, though its a little weird. Maybe I should do the same with all client # errors? return sendError res, 400, 'Unknown SID', options unless session session._acknowledgeArrays query.AID if query.AID? and session # ### Forward Channel if req.method == 'POST' if session == undefined # The session is new! Make them a new session object and let the # application know. session = createSession req.connection.remoteAddress, query, req.headers onConnect? session, req # TODO Emit 'req' for subsequent requests associated with session session.emit 'req', req dataError = (e) -> console.warn 'Error parsing forward channel', e.stack return sendError res, 400, 'Bad data', options processData = (data) -> try data = transformData req, data session._receivedData query.RID, data catch e return dataError e if session.state is 'init' # The initial forward channel request is also used as a backchannel # for the server's initial data (session id, etc). This connection # is a little bit special - it is always encoded using # length-prefixed json encoding and it is closed as soon as the # first chunk is sent. res.writeHead 200, 'OK', options.headers session._setBackChannel res, CI:1, TYPE:'xmlhttp', RID:'rpc' session.flush() else if session.state is 'closed' # If the onConnect handler called close() immediately, # session.state can be already closed at this point. I'll assume # there was an authentication problem and treat this as a forbidden # connection attempt. sendError res, 403, 'Forbidden', options else # On normal forward channels, we reply to the request by telling # the session if our backchannel is still live and telling it how # many unconfirmed arrays we have. response = JSON.stringify session._backChannelStatus() res.writeHead 200, 'OK', options.headers res.end "#{response.length}\n#{response}" if req.body processData req.body else bufferPostData req, (data) -> try data = decodeData req, data catch e return dataError e processData data else if req.method is 'GET' # ### Back channel # # GET messages are usually backchannel requests (server->client). # Backchannel messages are handled by the session object. if query.TYPE in ['xmlhttp', 'html'] return sendError res, 400, 'Invalid SID', options if typeof query.SID != 'string' && query.SID.length < 5 return sendError res, 400, 'Expected RPC', options unless query.RID is 'rpc' writeHead() session._setBackChannel res, query # The client can manually disconnect by making a GET request with TYPE='terminate' else if query.TYPE is 'terminate' # We don't send any data in the response to the disconnect message. # # The client implements this using an img= appended to the page. session?._disconnectAt query.RID res.writeHead 200, 'OK', options.headers res.end() else res.writeHead 405, 'Method Not Allowed', options.headers res.end "Method not allowed" else # We'll 404 the user instead of letting another handler take care of it. # Users shouldn't be using the specified URL prefix for anything else. res.writeHead 404, 'Not Found', options.headers res.end "Not found" middleware.close = -> for id, session of sessions session.close() return # This is an undocumented, untested treat - if you pass the HTTP server / # connect server to browserchannel through the options object, it can attach # a close listener for you automatically. options.server?.on 'close', middleware.close middleware # This will override the timer methods (`setInterval`, etc) with the testing # stub versions, which are way faster. browserChannel._setTimerMethods = (methods) -> {setInterval, clearInterval, setTimeout, clearTimeout, Date} = methods
[ { "context": "\n# @fileoverview Tests for new-cap rule.\n# @author Nicholas C. Zakas\n###\n\n'use strict'\n\n#-----------------------------", "end": 72, "score": 0.9998176097869873, "start": 55, "tag": "NAME", "value": "Nicholas C. Zakas" } ]
src/tests/rules/new-cap.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for new-cap rule. # @author Nicholas C. Zakas ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/new-cap' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'new-cap', rule, valid: [ 'x = new Constructor()' 'x = new a.b.Constructor()' "x = new a.b['Constructor']()" 'x = new a.b[Constructor]()' 'x = new a.b[constructor]()' 'x = new ->' 'x = new _' 'x = new $' 'x = new Σ' 'x = new _x' 'x = new $x' 'x = new this' 'x = Array(42)' 'x = Boolean(42)' 'x = Date(42)' 'x = Date.UTC(2000, 0)' "x = Error('error')" "x = Function('return 0')" 'x = Number(42)' 'x = Object(null)' 'x = RegExp(42)' 'x = String(42)' "x = Symbol('symbol')" 'x = _()' 'x = $()' , code: 'x = Foo(42)', options: [capIsNew: no] , code: 'x = bar.Foo(42)', options: [capIsNew: no] , code: 'x = Foo.bar(42)', options: [capIsNew: no] , 'x = bar[Foo](42)' , code: "x = bar['Foo'](42)", options: [capIsNew: no] , 'x = Foo.bar(42)' , code: 'x = new foo(42)', options: [newIsCap: no] , ''' o = { 1: -> } o[1]() ''' ''' o = { 1: -> } new o[1]() ''' , code: 'x = Foo(42)' options: [capIsNew: yes, capIsNewExceptions: ['Foo']] , code: 'x = Foo(42)', options: [capIsNewExceptionPattern: '^Foo'] , code: 'x = new foo(42)' options: [newIsCap: yes, newIsCapExceptions: ['foo']] , code: 'x = new foo(42)', options: [newIsCapExceptionPattern: '^foo'] , code: 'x = Object(42)', options: [capIsNewExceptions: ['Foo']] , code: 'x = Foo.Bar(42)', options: [capIsNewExceptions: ['Bar']] , code: 'x = Foo.Bar(42)', options: [capIsNewExceptions: ['Foo.Bar']] , code: 'x = Foo.Bar(42)' options: [capIsNewExceptionPattern: '^Foo\\..'] , code: 'x = new foo.bar(42)', options: [newIsCapExceptions: ['bar']] , code: 'x = new foo.bar(42)' options: [newIsCapExceptions: ['foo.bar']] , code: 'x = new foo.bar(42)' options: [newIsCapExceptionPattern: '^foo\\..'] , code: 'x = new foo.bar(42)', options: [properties: no] , code: 'x = Foo.bar(42)', options: [properties: no] , code: 'x = foo.Bar(42)', options: [capIsNew: no, properties: no] ] invalid: [ code: 'x = new c()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: 'x = new φ' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: 'x = new a.b.c' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: "x = new a.b['c']" errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: 'b = Foo()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'b = a.Foo()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: "b = a['Foo']()" errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'b = a.Date.UTC()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'b = UTC()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'a = B.C()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' line: 1 column: 7 ] , code: 'a = B\n.C()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' line: 2 column: 2 ] , code: 'a = new B.c()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' line: 1 column: 11 ] , code: 'a = new B.\nc()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' line: 2 column: 1 ] , code: 'a = new c()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' line: 1 column: 9 ] , code: 'x = Foo.Bar(42)' options: [capIsNewExceptions: ['Foo']] errors: [ type: 'CallExpression' message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' ] , code: 'x = Bar.Foo(42)' options: [capIsNewExceptionPattern: '^Foo\\..'] errors: [ type: 'CallExpression' message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' ] , code: 'x = new foo.bar(42)' options: [newIsCapExceptions: ['foo']] errors: [ type: 'NewExpression' message: 'A constructor name should not start with a lowercase letter.' ] , code: 'x = new bar.foo(42)' options: [newIsCapExceptionPattern: '^foo\\..'] errors: [ type: 'NewExpression' message: 'A constructor name should not start with a lowercase letter.' ] ]
48413
###* # @fileoverview Tests for new-cap rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/new-cap' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'new-cap', rule, valid: [ 'x = new Constructor()' 'x = new a.b.Constructor()' "x = new a.b['Constructor']()" 'x = new a.b[Constructor]()' 'x = new a.b[constructor]()' 'x = new ->' 'x = new _' 'x = new $' 'x = new Σ' 'x = new _x' 'x = new $x' 'x = new this' 'x = Array(42)' 'x = Boolean(42)' 'x = Date(42)' 'x = Date.UTC(2000, 0)' "x = Error('error')" "x = Function('return 0')" 'x = Number(42)' 'x = Object(null)' 'x = RegExp(42)' 'x = String(42)' "x = Symbol('symbol')" 'x = _()' 'x = $()' , code: 'x = Foo(42)', options: [capIsNew: no] , code: 'x = bar.Foo(42)', options: [capIsNew: no] , code: 'x = Foo.bar(42)', options: [capIsNew: no] , 'x = bar[Foo](42)' , code: "x = bar['Foo'](42)", options: [capIsNew: no] , 'x = Foo.bar(42)' , code: 'x = new foo(42)', options: [newIsCap: no] , ''' o = { 1: -> } o[1]() ''' ''' o = { 1: -> } new o[1]() ''' , code: 'x = Foo(42)' options: [capIsNew: yes, capIsNewExceptions: ['Foo']] , code: 'x = Foo(42)', options: [capIsNewExceptionPattern: '^Foo'] , code: 'x = new foo(42)' options: [newIsCap: yes, newIsCapExceptions: ['foo']] , code: 'x = new foo(42)', options: [newIsCapExceptionPattern: '^foo'] , code: 'x = Object(42)', options: [capIsNewExceptions: ['Foo']] , code: 'x = Foo.Bar(42)', options: [capIsNewExceptions: ['Bar']] , code: 'x = Foo.Bar(42)', options: [capIsNewExceptions: ['Foo.Bar']] , code: 'x = Foo.Bar(42)' options: [capIsNewExceptionPattern: '^Foo\\..'] , code: 'x = new foo.bar(42)', options: [newIsCapExceptions: ['bar']] , code: 'x = new foo.bar(42)' options: [newIsCapExceptions: ['foo.bar']] , code: 'x = new foo.bar(42)' options: [newIsCapExceptionPattern: '^foo\\..'] , code: 'x = new foo.bar(42)', options: [properties: no] , code: 'x = Foo.bar(42)', options: [properties: no] , code: 'x = foo.Bar(42)', options: [capIsNew: no, properties: no] ] invalid: [ code: 'x = new c()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: 'x = new φ' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: 'x = new a.b.c' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: "x = new a.b['c']" errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: 'b = Foo()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'b = a.Foo()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: "b = a['Foo']()" errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'b = a.Date.UTC()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'b = UTC()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'a = B.C()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' line: 1 column: 7 ] , code: 'a = B\n.C()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' line: 2 column: 2 ] , code: 'a = new B.c()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' line: 1 column: 11 ] , code: 'a = new B.\nc()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' line: 2 column: 1 ] , code: 'a = new c()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' line: 1 column: 9 ] , code: 'x = Foo.Bar(42)' options: [capIsNewExceptions: ['Foo']] errors: [ type: 'CallExpression' message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' ] , code: 'x = Bar.Foo(42)' options: [capIsNewExceptionPattern: '^Foo\\..'] errors: [ type: 'CallExpression' message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' ] , code: 'x = new foo.bar(42)' options: [newIsCapExceptions: ['foo']] errors: [ type: 'NewExpression' message: 'A constructor name should not start with a lowercase letter.' ] , code: 'x = new bar.foo(42)' options: [newIsCapExceptionPattern: '^foo\\..'] errors: [ type: 'NewExpression' message: 'A constructor name should not start with a lowercase letter.' ] ]
true
###* # @fileoverview Tests for new-cap rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/new-cap' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'new-cap', rule, valid: [ 'x = new Constructor()' 'x = new a.b.Constructor()' "x = new a.b['Constructor']()" 'x = new a.b[Constructor]()' 'x = new a.b[constructor]()' 'x = new ->' 'x = new _' 'x = new $' 'x = new Σ' 'x = new _x' 'x = new $x' 'x = new this' 'x = Array(42)' 'x = Boolean(42)' 'x = Date(42)' 'x = Date.UTC(2000, 0)' "x = Error('error')" "x = Function('return 0')" 'x = Number(42)' 'x = Object(null)' 'x = RegExp(42)' 'x = String(42)' "x = Symbol('symbol')" 'x = _()' 'x = $()' , code: 'x = Foo(42)', options: [capIsNew: no] , code: 'x = bar.Foo(42)', options: [capIsNew: no] , code: 'x = Foo.bar(42)', options: [capIsNew: no] , 'x = bar[Foo](42)' , code: "x = bar['Foo'](42)", options: [capIsNew: no] , 'x = Foo.bar(42)' , code: 'x = new foo(42)', options: [newIsCap: no] , ''' o = { 1: -> } o[1]() ''' ''' o = { 1: -> } new o[1]() ''' , code: 'x = Foo(42)' options: [capIsNew: yes, capIsNewExceptions: ['Foo']] , code: 'x = Foo(42)', options: [capIsNewExceptionPattern: '^Foo'] , code: 'x = new foo(42)' options: [newIsCap: yes, newIsCapExceptions: ['foo']] , code: 'x = new foo(42)', options: [newIsCapExceptionPattern: '^foo'] , code: 'x = Object(42)', options: [capIsNewExceptions: ['Foo']] , code: 'x = Foo.Bar(42)', options: [capIsNewExceptions: ['Bar']] , code: 'x = Foo.Bar(42)', options: [capIsNewExceptions: ['Foo.Bar']] , code: 'x = Foo.Bar(42)' options: [capIsNewExceptionPattern: '^Foo\\..'] , code: 'x = new foo.bar(42)', options: [newIsCapExceptions: ['bar']] , code: 'x = new foo.bar(42)' options: [newIsCapExceptions: ['foo.bar']] , code: 'x = new foo.bar(42)' options: [newIsCapExceptionPattern: '^foo\\..'] , code: 'x = new foo.bar(42)', options: [properties: no] , code: 'x = Foo.bar(42)', options: [properties: no] , code: 'x = foo.Bar(42)', options: [capIsNew: no, properties: no] ] invalid: [ code: 'x = new c()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: 'x = new φ' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: 'x = new a.b.c' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: "x = new a.b['c']" errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' ] , code: 'b = Foo()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'b = a.Foo()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: "b = a['Foo']()" errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'b = a.Date.UTC()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'b = UTC()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' ] , code: 'a = B.C()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' line: 1 column: 7 ] , code: 'a = B\n.C()' errors: [ message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' type: 'CallExpression' line: 2 column: 2 ] , code: 'a = new B.c()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' line: 1 column: 11 ] , code: 'a = new B.\nc()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' line: 2 column: 1 ] , code: 'a = new c()' errors: [ message: 'A constructor name should not start with a lowercase letter.' type: 'NewExpression' line: 1 column: 9 ] , code: 'x = Foo.Bar(42)' options: [capIsNewExceptions: ['Foo']] errors: [ type: 'CallExpression' message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' ] , code: 'x = Bar.Foo(42)' options: [capIsNewExceptionPattern: '^Foo\\..'] errors: [ type: 'CallExpression' message: 'A function with a name starting with an uppercase letter should only be used as a constructor.' ] , code: 'x = new foo.bar(42)' options: [newIsCapExceptions: ['foo']] errors: [ type: 'NewExpression' message: 'A constructor name should not start with a lowercase letter.' ] , code: 'x = new bar.foo(42)' options: [newIsCapExceptionPattern: '^foo\\..'] errors: [ type: 'NewExpression' message: 'A constructor name should not start with a lowercase letter.' ] ]
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9991995692253113, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-timers.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") inputs = [ `undefined` null true false "" [] { {} } NaN +Infinity -Infinity 1.0 / 0.0 # sanity check parseFloat("x") # NaN -10 -1 -0.5 -0.0 0 0.0 0.5 1 1.0 10 2147483648 # browser behaviour: timeouts > 2^31-1 run on next tick 12345678901234 # ditto ] timeouts = [] intervals = [] inputs.forEach (value, index) -> setTimeout (-> timeouts[index] = true return ), value handle = setInterval(-> clearInterval handle # disarm timer or we'll never finish intervals[index] = true return , value) return process.on "exit", -> # assert that all timers have run inputs.forEach (value, index) -> assert.equal true, timeouts[index] assert.equal true, intervals[index] return return
159546
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") inputs = [ `undefined` null true false "" [] { {} } NaN +Infinity -Infinity 1.0 / 0.0 # sanity check parseFloat("x") # NaN -10 -1 -0.5 -0.0 0 0.0 0.5 1 1.0 10 2147483648 # browser behaviour: timeouts > 2^31-1 run on next tick 12345678901234 # ditto ] timeouts = [] intervals = [] inputs.forEach (value, index) -> setTimeout (-> timeouts[index] = true return ), value handle = setInterval(-> clearInterval handle # disarm timer or we'll never finish intervals[index] = true return , value) return process.on "exit", -> # assert that all timers have run inputs.forEach (value, index) -> assert.equal true, timeouts[index] assert.equal true, intervals[index] return return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") inputs = [ `undefined` null true false "" [] { {} } NaN +Infinity -Infinity 1.0 / 0.0 # sanity check parseFloat("x") # NaN -10 -1 -0.5 -0.0 0 0.0 0.5 1 1.0 10 2147483648 # browser behaviour: timeouts > 2^31-1 run on next tick 12345678901234 # ditto ] timeouts = [] intervals = [] inputs.forEach (value, index) -> setTimeout (-> timeouts[index] = true return ), value handle = setInterval(-> clearInterval handle # disarm timer or we'll never finish intervals[index] = true return , value) return process.on "exit", -> # assert that all timers have run inputs.forEach (value, index) -> assert.equal true, timeouts[index] assert.equal true, intervals[index] return return
[ { "context": " @_name = sourceUser.name\n @setPassword(sourceUser.password)\n @setConfirmKey(sourceUser.confirmKey)\n\n ", "end": 869, "score": 0.9600814580917358, "start": 850, "tag": "PASSWORD", "value": "sourceUser.password" } ]
src/server/auth/password/model.coffee
LaPingvino/rizzoma
88
crypto = require('crypto') {AuthModel} = require('../model') {IdUtils} = require('../../utils/id_utils') {UserUtils} = require('../../user/utils') {DateUtils} = require('../../utils/date_utils') PASSWORD_SALT_DELIMITER = '$' # разделяет в поле документа соль и соленый им хеш пароля CONFIRM_KEY_EXPIRATION_TIMEOUT = 86400 *2 # время протухания ключа подтверждения регистрации в секундах 48 часов FORGOT_PASSWORD_KEY_EXPIRATION_TIMEOUT = 86400 *2 # время протухания ключа сброса пароля в секундах 48 часов class PasswordAuth extends AuthModel ### Модель авторизации по паролю ### constructor: (sourceUser) -> return super('password') if not sourceUser super("password", sourceUser, UserUtils.normalizeEmail(sourceUser.email)) @_email = sourceUser.email @_name = sourceUser.name @setPassword(sourceUser.password) @setConfirmKey(sourceUser.confirmKey) getPasswordHash: () -> return @_extra.passwordHash setPasswordHash: (passwordHash) -> @_extra.passwordHash = passwordHash isPasswordValid: (password) -> return false if not @_extra.passwordHash [salt, hash] = @_extra.passwordHash.split(PASSWORD_SALT_DELIMITER) return false if not salt or not hash return @_makeSaltedPasswordHash(password, salt) is hash setPassword: (pass) -> salt = @_generatePasswordSalt() hash = @_makeSaltedPasswordHash(pass, salt) @setPasswordHash([salt,hash].join(PASSWORD_SALT_DELIMITER)) _makeSaltedPasswordHash: (pass, salt) -> return crypto.createHash("md5").update(pass + salt).digest("hex") _generatePasswordSalt: () -> return IdUtils.getRandomId(16) generateConfirmKey: () -> @setConfirmKey(IdUtils.getRandomId(16)) getConfirmKey: () -> @_extra.confirmKey setConfirmKey: (key, expiration=null) -> ### Чтоб удалять ### @setConfirmKeyExpirationTime(expiration) @_extra.confirmKey = key setConfirmKeyExpirationTime: (timestamp=null) -> ### Устанавливает дату протухания ключа подтверждения ### timestamp = DateUtils.getCurrentTimestamp() + CONFIRM_KEY_EXPIRATION_TIMEOUT if not timestamp? @_extra.confirmKeyExpirationTime = timestamp getConfirmKeyExpirationTime: () -> @_extra.confirmKeyExpirationTime isConfirmed: () -> return not @getConfirmKey() isConfirmKeyExpired: () -> return true if @isConfirmed() return DateUtils.getCurrentTimestamp() > @getConfirmKeyExpirationTime() generateForgotPasswordKey: () -> @setForgotPasswordKey(IdUtils.getRandomId(16)) getForgotPasswordKey: () -> @_extra.forgotPasswordKey setForgotPasswordKey: (key, expiration=null) -> ### Чтоб удалять ### @_extra.forgotPasswordKey = key expiration = DateUtils.getCurrentTimestamp() + FORGOT_PASSWORD_KEY_EXPIRATION_TIMEOUT if not expiration? @_extra.forgotPasswordKeyExpirationTime = expiration isForgotPasswordKeyExpired: () -> ### Проверяет не протух ли ключ скидывания пароля ### return true if not @getForgotPasswordKey() return DateUtils.getCurrentTimestamp() > @_extra.forgotPasswordKeyExpirationTime module.exports.PasswordAuth = PasswordAuth
202919
crypto = require('crypto') {AuthModel} = require('../model') {IdUtils} = require('../../utils/id_utils') {UserUtils} = require('../../user/utils') {DateUtils} = require('../../utils/date_utils') PASSWORD_SALT_DELIMITER = '$' # разделяет в поле документа соль и соленый им хеш пароля CONFIRM_KEY_EXPIRATION_TIMEOUT = 86400 *2 # время протухания ключа подтверждения регистрации в секундах 48 часов FORGOT_PASSWORD_KEY_EXPIRATION_TIMEOUT = 86400 *2 # время протухания ключа сброса пароля в секундах 48 часов class PasswordAuth extends AuthModel ### Модель авторизации по паролю ### constructor: (sourceUser) -> return super('password') if not sourceUser super("password", sourceUser, UserUtils.normalizeEmail(sourceUser.email)) @_email = sourceUser.email @_name = sourceUser.name @setPassword(<PASSWORD>) @setConfirmKey(sourceUser.confirmKey) getPasswordHash: () -> return @_extra.passwordHash setPasswordHash: (passwordHash) -> @_extra.passwordHash = passwordHash isPasswordValid: (password) -> return false if not @_extra.passwordHash [salt, hash] = @_extra.passwordHash.split(PASSWORD_SALT_DELIMITER) return false if not salt or not hash return @_makeSaltedPasswordHash(password, salt) is hash setPassword: (pass) -> salt = @_generatePasswordSalt() hash = @_makeSaltedPasswordHash(pass, salt) @setPasswordHash([salt,hash].join(PASSWORD_SALT_DELIMITER)) _makeSaltedPasswordHash: (pass, salt) -> return crypto.createHash("md5").update(pass + salt).digest("hex") _generatePasswordSalt: () -> return IdUtils.getRandomId(16) generateConfirmKey: () -> @setConfirmKey(IdUtils.getRandomId(16)) getConfirmKey: () -> @_extra.confirmKey setConfirmKey: (key, expiration=null) -> ### Чтоб удалять ### @setConfirmKeyExpirationTime(expiration) @_extra.confirmKey = key setConfirmKeyExpirationTime: (timestamp=null) -> ### Устанавливает дату протухания ключа подтверждения ### timestamp = DateUtils.getCurrentTimestamp() + CONFIRM_KEY_EXPIRATION_TIMEOUT if not timestamp? @_extra.confirmKeyExpirationTime = timestamp getConfirmKeyExpirationTime: () -> @_extra.confirmKeyExpirationTime isConfirmed: () -> return not @getConfirmKey() isConfirmKeyExpired: () -> return true if @isConfirmed() return DateUtils.getCurrentTimestamp() > @getConfirmKeyExpirationTime() generateForgotPasswordKey: () -> @setForgotPasswordKey(IdUtils.getRandomId(16)) getForgotPasswordKey: () -> @_extra.forgotPasswordKey setForgotPasswordKey: (key, expiration=null) -> ### Чтоб удалять ### @_extra.forgotPasswordKey = key expiration = DateUtils.getCurrentTimestamp() + FORGOT_PASSWORD_KEY_EXPIRATION_TIMEOUT if not expiration? @_extra.forgotPasswordKeyExpirationTime = expiration isForgotPasswordKeyExpired: () -> ### Проверяет не протух ли ключ скидывания пароля ### return true if not @getForgotPasswordKey() return DateUtils.getCurrentTimestamp() > @_extra.forgotPasswordKeyExpirationTime module.exports.PasswordAuth = PasswordAuth
true
crypto = require('crypto') {AuthModel} = require('../model') {IdUtils} = require('../../utils/id_utils') {UserUtils} = require('../../user/utils') {DateUtils} = require('../../utils/date_utils') PASSWORD_SALT_DELIMITER = '$' # разделяет в поле документа соль и соленый им хеш пароля CONFIRM_KEY_EXPIRATION_TIMEOUT = 86400 *2 # время протухания ключа подтверждения регистрации в секундах 48 часов FORGOT_PASSWORD_KEY_EXPIRATION_TIMEOUT = 86400 *2 # время протухания ключа сброса пароля в секундах 48 часов class PasswordAuth extends AuthModel ### Модель авторизации по паролю ### constructor: (sourceUser) -> return super('password') if not sourceUser super("password", sourceUser, UserUtils.normalizeEmail(sourceUser.email)) @_email = sourceUser.email @_name = sourceUser.name @setPassword(PI:PASSWORD:<PASSWORD>END_PI) @setConfirmKey(sourceUser.confirmKey) getPasswordHash: () -> return @_extra.passwordHash setPasswordHash: (passwordHash) -> @_extra.passwordHash = passwordHash isPasswordValid: (password) -> return false if not @_extra.passwordHash [salt, hash] = @_extra.passwordHash.split(PASSWORD_SALT_DELIMITER) return false if not salt or not hash return @_makeSaltedPasswordHash(password, salt) is hash setPassword: (pass) -> salt = @_generatePasswordSalt() hash = @_makeSaltedPasswordHash(pass, salt) @setPasswordHash([salt,hash].join(PASSWORD_SALT_DELIMITER)) _makeSaltedPasswordHash: (pass, salt) -> return crypto.createHash("md5").update(pass + salt).digest("hex") _generatePasswordSalt: () -> return IdUtils.getRandomId(16) generateConfirmKey: () -> @setConfirmKey(IdUtils.getRandomId(16)) getConfirmKey: () -> @_extra.confirmKey setConfirmKey: (key, expiration=null) -> ### Чтоб удалять ### @setConfirmKeyExpirationTime(expiration) @_extra.confirmKey = key setConfirmKeyExpirationTime: (timestamp=null) -> ### Устанавливает дату протухания ключа подтверждения ### timestamp = DateUtils.getCurrentTimestamp() + CONFIRM_KEY_EXPIRATION_TIMEOUT if not timestamp? @_extra.confirmKeyExpirationTime = timestamp getConfirmKeyExpirationTime: () -> @_extra.confirmKeyExpirationTime isConfirmed: () -> return not @getConfirmKey() isConfirmKeyExpired: () -> return true if @isConfirmed() return DateUtils.getCurrentTimestamp() > @getConfirmKeyExpirationTime() generateForgotPasswordKey: () -> @setForgotPasswordKey(IdUtils.getRandomId(16)) getForgotPasswordKey: () -> @_extra.forgotPasswordKey setForgotPasswordKey: (key, expiration=null) -> ### Чтоб удалять ### @_extra.forgotPasswordKey = key expiration = DateUtils.getCurrentTimestamp() + FORGOT_PASSWORD_KEY_EXPIRATION_TIMEOUT if not expiration? @_extra.forgotPasswordKeyExpirationTime = expiration isForgotPasswordKeyExpired: () -> ### Проверяет не протух ли ключ скидывания пароля ### return true if not @getForgotPasswordKey() return DateUtils.getCurrentTimestamp() > @_extra.forgotPasswordKeyExpirationTime module.exports.PasswordAuth = PasswordAuth
[ { "context": " \"application/json\"\n \"trakt-api-key\": \"6a858663eb2b89454c785ce93981f7726b90f33169ac454004d33d8837c4d0e8\"\n \"trakt-api-version\": \"2\"\n\n\n #", "end": 686, "score": 0.9997210502624512, "start": 622, "tag": "KEY", "value": "6a858663eb2b89454c785ce93981f7726b90f33169ac454004d33d8837c4d0e8" } ]
app/scripts/providers/trakt.coffee
dackmin/Gummy
3
'use strict' ###* # @ngdoc function # @name gummyApp.provider:$trakt # @description # # $trakt # Trakt TV API provider ### angular .module 'gummyApp' .service '$trakt', ($http, $q) -> ###* # Api method # @attribute API_METHOD ### @API_METHOD = "https://" ###* # Api root url # @attribute API_ROOT ### @API_ROOT = "api-v2launch.trakt.tv" ###* # API custom headers # @attribute HEADERS ### @HEADERS = "Content-Type": "application/json" "trakt-api-key": "6a858663eb2b89454c785ce93981f7726b90f33169ac454004d33d8837c4d0e8" "trakt-api-version": "2" ###* # Find a movie # @method search # @param {String} name - Movie name ### @search = (name) -> q = $q.defer() $http method: "GET" url: "#{@API_METHOD}#{@API_ROOT}/search" params: query: name type: "movie" headers: @HEADERS .success (data) => movies = [] movies.push @toSimpleJSON(obj) for key, obj of data q.resolve movies .error (e) -> q.reject e q.promise ###* # Get movie infos # @method get # @param {String|int} id - Movie id/slug # @param {Object} infos - Additional infos # @return {Object} - $q promise ### @get = (id, infos) -> q = $q.defer() # Get cast members @cast id .then (cast) => # Compile raw data raw = infos: infos cast: cast # Return parsed data q.resolve @toJSON(raw) .catch (e) -> q.reject e q.promise ###* # Get cast members # @method cast # @param {String|int} id - Movie slug/id # @return {Object} - $q promise ### @cast = (id) -> q = $q.defer() $http method: "GET" url: "#{@API_METHOD}#{@API_ROOT}/movies/#{id}/people" headers: @HEADERS .success (data) -> cast = [] cast.push item.person.name for item in data.cast q.resolve cast .error (e) -> q.reject e q.promise ###* # Return movie as simple json object # @method toSimpleJSON # @param {Object} raw - Raw data from movie # @return {Object} - simply parsed json object ### @toSimpleJSON = (raw) -> id: raw.movie.ids.slug rating: raw.score title: raw.movie.title synopsis: raw.movie.overview year: raw.movie.year cover: small: raw.movie.images.poster.thumb medium: raw.movie.images.poster.medium large: raw.movie.images.poster.full background: small: raw.movie.images.fanart.thumb medium: raw.movie.images.fanart.medium large: raw.movie.images.fanart.full raw: raw ###* # Return movie as a normal json object # @method toJSON # @param {Object} raw - Raw movie data # @return {Object} - parsed json object ### @toJSON = (raw) -> id: raw.infos.raw.movie.ids.slug rating: raw.infos.raw.movie.rating * 10 title: raw.infos.raw.movie.title synopsis: raw.infos.raw.movie.overview year: raw.infos.raw.movie.year cast: raw.cast.slice(0, 3).join ", " cover: small: raw.infos.raw.movie.images.poster.thumb medium: raw.infos.raw.movie.images.poster.medium large: raw.infos.raw.movie.images.poster.full background: small: raw.infos.raw.movie.images.fanart.thumb medium: raw.infos.raw.movie.images.fanart.medium large: raw.infos.raw.movie.images.fanart.full ###* # Generate an empty object when movie is not recognized # @method toEmpty # @param {String} filename - Sanitized filename (the.best.movie.ever.720p.HDTV.mkv becomes "The best movie ever") # @param {String} path - original filepath # @return {Object} ### @toEmpty = (filename, path) -> id: "" rating: 0 title: filename path: path synopsis: "" year: (new Date()).getFullYear() cover: small: "" medium: "" large: "" background: small: "" medium: "" large: "" raw: {} @
126666
'use strict' ###* # @ngdoc function # @name gummyApp.provider:$trakt # @description # # $trakt # Trakt TV API provider ### angular .module 'gummyApp' .service '$trakt', ($http, $q) -> ###* # Api method # @attribute API_METHOD ### @API_METHOD = "https://" ###* # Api root url # @attribute API_ROOT ### @API_ROOT = "api-v2launch.trakt.tv" ###* # API custom headers # @attribute HEADERS ### @HEADERS = "Content-Type": "application/json" "trakt-api-key": "<KEY>" "trakt-api-version": "2" ###* # Find a movie # @method search # @param {String} name - Movie name ### @search = (name) -> q = $q.defer() $http method: "GET" url: "#{@API_METHOD}#{@API_ROOT}/search" params: query: name type: "movie" headers: @HEADERS .success (data) => movies = [] movies.push @toSimpleJSON(obj) for key, obj of data q.resolve movies .error (e) -> q.reject e q.promise ###* # Get movie infos # @method get # @param {String|int} id - Movie id/slug # @param {Object} infos - Additional infos # @return {Object} - $q promise ### @get = (id, infos) -> q = $q.defer() # Get cast members @cast id .then (cast) => # Compile raw data raw = infos: infos cast: cast # Return parsed data q.resolve @toJSON(raw) .catch (e) -> q.reject e q.promise ###* # Get cast members # @method cast # @param {String|int} id - Movie slug/id # @return {Object} - $q promise ### @cast = (id) -> q = $q.defer() $http method: "GET" url: "#{@API_METHOD}#{@API_ROOT}/movies/#{id}/people" headers: @HEADERS .success (data) -> cast = [] cast.push item.person.name for item in data.cast q.resolve cast .error (e) -> q.reject e q.promise ###* # Return movie as simple json object # @method toSimpleJSON # @param {Object} raw - Raw data from movie # @return {Object} - simply parsed json object ### @toSimpleJSON = (raw) -> id: raw.movie.ids.slug rating: raw.score title: raw.movie.title synopsis: raw.movie.overview year: raw.movie.year cover: small: raw.movie.images.poster.thumb medium: raw.movie.images.poster.medium large: raw.movie.images.poster.full background: small: raw.movie.images.fanart.thumb medium: raw.movie.images.fanart.medium large: raw.movie.images.fanart.full raw: raw ###* # Return movie as a normal json object # @method toJSON # @param {Object} raw - Raw movie data # @return {Object} - parsed json object ### @toJSON = (raw) -> id: raw.infos.raw.movie.ids.slug rating: raw.infos.raw.movie.rating * 10 title: raw.infos.raw.movie.title synopsis: raw.infos.raw.movie.overview year: raw.infos.raw.movie.year cast: raw.cast.slice(0, 3).join ", " cover: small: raw.infos.raw.movie.images.poster.thumb medium: raw.infos.raw.movie.images.poster.medium large: raw.infos.raw.movie.images.poster.full background: small: raw.infos.raw.movie.images.fanart.thumb medium: raw.infos.raw.movie.images.fanart.medium large: raw.infos.raw.movie.images.fanart.full ###* # Generate an empty object when movie is not recognized # @method toEmpty # @param {String} filename - Sanitized filename (the.best.movie.ever.720p.HDTV.mkv becomes "The best movie ever") # @param {String} path - original filepath # @return {Object} ### @toEmpty = (filename, path) -> id: "" rating: 0 title: filename path: path synopsis: "" year: (new Date()).getFullYear() cover: small: "" medium: "" large: "" background: small: "" medium: "" large: "" raw: {} @
true
'use strict' ###* # @ngdoc function # @name gummyApp.provider:$trakt # @description # # $trakt # Trakt TV API provider ### angular .module 'gummyApp' .service '$trakt', ($http, $q) -> ###* # Api method # @attribute API_METHOD ### @API_METHOD = "https://" ###* # Api root url # @attribute API_ROOT ### @API_ROOT = "api-v2launch.trakt.tv" ###* # API custom headers # @attribute HEADERS ### @HEADERS = "Content-Type": "application/json" "trakt-api-key": "PI:KEY:<KEY>END_PI" "trakt-api-version": "2" ###* # Find a movie # @method search # @param {String} name - Movie name ### @search = (name) -> q = $q.defer() $http method: "GET" url: "#{@API_METHOD}#{@API_ROOT}/search" params: query: name type: "movie" headers: @HEADERS .success (data) => movies = [] movies.push @toSimpleJSON(obj) for key, obj of data q.resolve movies .error (e) -> q.reject e q.promise ###* # Get movie infos # @method get # @param {String|int} id - Movie id/slug # @param {Object} infos - Additional infos # @return {Object} - $q promise ### @get = (id, infos) -> q = $q.defer() # Get cast members @cast id .then (cast) => # Compile raw data raw = infos: infos cast: cast # Return parsed data q.resolve @toJSON(raw) .catch (e) -> q.reject e q.promise ###* # Get cast members # @method cast # @param {String|int} id - Movie slug/id # @return {Object} - $q promise ### @cast = (id) -> q = $q.defer() $http method: "GET" url: "#{@API_METHOD}#{@API_ROOT}/movies/#{id}/people" headers: @HEADERS .success (data) -> cast = [] cast.push item.person.name for item in data.cast q.resolve cast .error (e) -> q.reject e q.promise ###* # Return movie as simple json object # @method toSimpleJSON # @param {Object} raw - Raw data from movie # @return {Object} - simply parsed json object ### @toSimpleJSON = (raw) -> id: raw.movie.ids.slug rating: raw.score title: raw.movie.title synopsis: raw.movie.overview year: raw.movie.year cover: small: raw.movie.images.poster.thumb medium: raw.movie.images.poster.medium large: raw.movie.images.poster.full background: small: raw.movie.images.fanart.thumb medium: raw.movie.images.fanart.medium large: raw.movie.images.fanart.full raw: raw ###* # Return movie as a normal json object # @method toJSON # @param {Object} raw - Raw movie data # @return {Object} - parsed json object ### @toJSON = (raw) -> id: raw.infos.raw.movie.ids.slug rating: raw.infos.raw.movie.rating * 10 title: raw.infos.raw.movie.title synopsis: raw.infos.raw.movie.overview year: raw.infos.raw.movie.year cast: raw.cast.slice(0, 3).join ", " cover: small: raw.infos.raw.movie.images.poster.thumb medium: raw.infos.raw.movie.images.poster.medium large: raw.infos.raw.movie.images.poster.full background: small: raw.infos.raw.movie.images.fanart.thumb medium: raw.infos.raw.movie.images.fanart.medium large: raw.infos.raw.movie.images.fanart.full ###* # Generate an empty object when movie is not recognized # @method toEmpty # @param {String} filename - Sanitized filename (the.best.movie.ever.720p.HDTV.mkv becomes "The best movie ever") # @param {String} path - original filepath # @return {Object} ### @toEmpty = (filename, path) -> id: "" rating: 0 title: filename path: path synopsis: "" year: (new Date()).getFullYear() cover: small: "" medium: "" large: "" background: small: "" medium: "" large: "" raw: {} @