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": "###\n@authors\nNicolas Laplante - https://plus.google.com/108189012221374960701\nN",
"end": 29,
"score": 0.9998853802680969,
"start": 13,
"tag": "NAME",
"value": "Nicolas Laplante"
},
{
"context": "e - https://plus.google.com/108189012221374960701\nNicholas McCready - h... | SafetyNet_Mobile/www/lib/angular-google-maps-master/src/coffee/directives/rectangle.coffee | donh/pheonix | 1 | ###
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Chentsu Lin - https://github.com/ChenTsuLin
###
angular.module("uiGmapgoogle-maps").directive "uiGmapRectangle", [
"uiGmapLogger"
"uiGmapRectangle"
($log, Rectangle) -> Rectangle
]
| 109944 | ###
@authors
<NAME> - https://plus.google.com/108189012221374960701
<NAME> - https://twitter.com/nmccready
<NAME> - https://github.com/ChenTsuLin
###
angular.module("uiGmapgoogle-maps").directive "uiGmapRectangle", [
"uiGmapLogger"
"uiGmapRectangle"
($log, Rectangle) -> Rectangle
]
| true | ###
@authors
PI:NAME:<NAME>END_PI - https://plus.google.com/108189012221374960701
PI:NAME:<NAME>END_PI - https://twitter.com/nmccready
PI:NAME:<NAME>END_PI - https://github.com/ChenTsuLin
###
angular.module("uiGmapgoogle-maps").directive "uiGmapRectangle", [
"uiGmapLogger"
"uiGmapRectangle"
($log, Rectangle) -> Rectangle
]
|
[
{
"context": " {\n getName: () ->\n \"Dezo\"\n }\n guildManager:\n ",
"end": 1771,
"score": 0.7272554636001587,
"start": 1767,
"tag": "NAME",
"value": "Dezo"
},
{
"context": ": {}\n }\n expect(str).to.equal(\"<player.nam... | test/system/handlers/MessageCreatorTest.coffee | jawsome/IdleLands | 3 | basedir = "../../../src/"
chai = require "chai"
mocha = require "mocha"
sinon = require "sinon"
proxyquire = require "proxyquire"
expect = chai.expect
describe = mocha.describe
class API
@gameInstance = {
petManager: {
pets: {}
activePets: {}
},
playerManager: {
players: {}
},
guildManager: {
guilds: {}
},
world: {
maps: {}
},
componentDatabase: {
generatorCache: [] #[placeholder: ["an ordinary potato"], deity: ["Zeus"]]
insertString: (type, string) ->
API.gameInstance.componentDatabase.generatorCache[type] = [] if not @generatorCache[type]
API.gameInstance.componentDatabase.generatorCache[type].push string
}
}
API.gameInstance.componentDatabase.insertString "placeholder", "an ordinary potato"
describe "MessageCreator", () ->
messageCreator = proxyquire(basedir + 'system/handlers/MessageCreator', {
"chance":
class Chance
constructor: () ->
, "./../accessibility/API":
API
}, '@noCallThru': true )
it "Should replace %player", () ->
str = messageCreator.doStringReplace "%player %player", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("<player.name>Wabber</player.name> <player.name>Wabber</player.name>")
it "Should replace %pet", () ->
str = messageCreator.doStringReplace "%pet %pet", {
getGender: () ->
"male"
getName: () ->
"Wabber"
playerManager:
game:
petManager:
getActivePetFor: (player) ->
if player.getName() isnt "Wabber"
throw new Error "Player #{player.getName()} is not Wabber"
{
getName: () ->
"Dezo"
}
guildManager:
getGuildByName: (guild) ->
{}
guild: {}
}
expect(str).to.equal("<player.name>Dezo</player.name> <player.name>Dezo</player.name>")
it "Should replace %guild", () ->
str = messageCreator.doStringReplace "%guild %guild", {
getGender: () ->
"male"
getName: () ->
"Wabber"
playerManager:
game:
petManager:
getActivePetFor: (player) ->
if player.getName() isnt "Wabber"
throw new Error "Player #{player.getName()} is not Wabber"
{
getName: () ->
"Dezo"
}
guildManager:
getGuildByName: (guild) ->
if guild isnt "Styx"
throw new Error "Guild #{guild} is not Styx"
{}
guild: "Styx"
}
expect(str).to.equal("<event.guildName>Styx</event.guildName> <event.guildName>Styx</event.guildName>")
it "Should replace %guildMember", () ->
str = messageCreator.doStringReplace "%guildMember %guildMember", {
getGender: () ->
"male"
getName: () ->
"Wabber"
name: "Wabber"
playerManager:
players: ["Wubbaloo"]
game:
petManager:
getActivePetFor: (player) ->
if player.getName() isnt "Wabber"
throw new Error "Player #{player.getName()} is not Wabber"
{
getName: () ->
"Dezo"
}
guildManager:
getGuildByName: (guild) ->
if guild isnt "Styx"
throw new Error "Guild #{guild} is not Styx"
{members: [{name: "Wubbaloo"}, {name: "Wabber"}]}
guild: "Styx"
}
expect(str).to.equal("<player.name>Wubbaloo</player.name> <player.name>Wubbaloo</player.name>")
it "Should replace %hishers", () ->
str = messageCreator.doStringReplace "%hishers %hishers", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("his his")
str = messageCreator.doStringReplace "%hishers %hishers", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
expect(str).to.equal("hers hers")
str = messageCreator.doStringReplace "%hishers %hishers", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
expect(str).to.equal("theirs theirs")
str = messageCreator.doStringReplace "%Hishers %Hishers", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("His His")
str = messageCreator.doStringReplace "%Hishers %Hishers", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
expect(str).to.equal("Hers Hers")
str = messageCreator.doStringReplace "%Hishers %Hishers", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
expect(str).to.equal("Theirs Theirs")
it "Should replace %hisher", () ->
str = messageCreator.doStringReplace "%hisher %hisher", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("his his")
str = messageCreator.doStringReplace "%hisher %hisher", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
expect(str).to.equal("her her")
str = messageCreator.doStringReplace "%hisher %hisher", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
expect(str).to.equal("their their")
str = messageCreator.doStringReplace "%Hisher %Hisher", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("His His")
str = messageCreator.doStringReplace "%Hisher %Hisher", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
expect(str).to.equal("Her Her")
str = messageCreator.doStringReplace "%Hisher %Hisher", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
expect(str).to.equal("Their Their")
it "Should replace %himher", () ->
str = messageCreator.doStringReplace "%himher %himher", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("him him")
str = messageCreator.doStringReplace "%himher %himher", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
expect(str).to.equal("her her")
str = messageCreator.doStringReplace "%himher %himher", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
expect(str).to.equal("them them")
str = messageCreator.doStringReplace "%Himher %Himher", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("Him Him")
str = messageCreator.doStringReplace "%Himher %Himher", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
expect(str).to.equal("Her Her")
str = messageCreator.doStringReplace "%Himher %Himher", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
expect(str).to.equal("Them Them")
it "Should replace %heshe", () ->
str = messageCreator.doStringReplace "%heshe %heshe", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%she %she", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("he he")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%heshe %heshe", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%she %she", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
expect(str).to.equal("she she")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%heshe %heshe", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%she %she", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
expect(str).to.equal("they they")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%Heshe %Heshe", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%She %She", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("He He")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%Heshe %Heshe", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%She %She", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
expect(str).to.equal("She She")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%Heshe %Heshe", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%She %She", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
expect(str).to.equal("They They")
expect(str).to.equal(str2) | 179315 | basedir = "../../../src/"
chai = require "chai"
mocha = require "mocha"
sinon = require "sinon"
proxyquire = require "proxyquire"
expect = chai.expect
describe = mocha.describe
class API
@gameInstance = {
petManager: {
pets: {}
activePets: {}
},
playerManager: {
players: {}
},
guildManager: {
guilds: {}
},
world: {
maps: {}
},
componentDatabase: {
generatorCache: [] #[placeholder: ["an ordinary potato"], deity: ["Zeus"]]
insertString: (type, string) ->
API.gameInstance.componentDatabase.generatorCache[type] = [] if not @generatorCache[type]
API.gameInstance.componentDatabase.generatorCache[type].push string
}
}
API.gameInstance.componentDatabase.insertString "placeholder", "an ordinary potato"
describe "MessageCreator", () ->
messageCreator = proxyquire(basedir + 'system/handlers/MessageCreator', {
"chance":
class Chance
constructor: () ->
, "./../accessibility/API":
API
}, '@noCallThru': true )
it "Should replace %player", () ->
str = messageCreator.doStringReplace "%player %player", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("<player.name>Wabber</player.name> <player.name>Wabber</player.name>")
it "Should replace %pet", () ->
str = messageCreator.doStringReplace "%pet %pet", {
getGender: () ->
"male"
getName: () ->
"Wabber"
playerManager:
game:
petManager:
getActivePetFor: (player) ->
if player.getName() isnt "Wabber"
throw new Error "Player #{player.getName()} is not Wabber"
{
getName: () ->
"<NAME>"
}
guildManager:
getGuildByName: (guild) ->
{}
guild: {}
}
expect(str).to.equal("<player.name><NAME></player.name> <player.name>Dezo</player.name>")
it "Should replace %guild", () ->
str = messageCreator.doStringReplace "%guild %guild", {
getGender: () ->
"male"
getName: () ->
"W<NAME>"
playerManager:
game:
petManager:
getActivePetFor: (player) ->
if player.getName() isnt "Wabber"
throw new Error "Player #{player.getName()} is not Wabber"
{
getName: () ->
"De<NAME>"
}
guildManager:
getGuildByName: (guild) ->
if guild isnt "Styx"
throw new Error "Guild #{guild} is not Styx"
{}
guild: "Styx"
}
expect(str).to.equal("<event.guildName>Styx</event.guildName> <event.guildName>Styx</event.guildName>")
it "Should replace %guildMember", () ->
str = messageCreator.doStringReplace "%guildMember %guildMember", {
getGender: () ->
"male"
getName: () ->
"<NAME>"
name: "<NAME>"
playerManager:
players: ["Wubbaloo"]
game:
petManager:
getActivePetFor: (player) ->
if player.getName() isnt "Wabber"
throw new Error "Player #{player.getName()} is not Wabber"
{
getName: () ->
"<NAME>"
}
guildManager:
getGuildByName: (guild) ->
if guild isnt "Styx"
throw new Error "Guild #{guild} is not Styx"
{members: [{name: "Wubbaloo"}, {name: "Wabber"}]}
guild: "Styx"
}
expect(str).to.equal("<player.name>Wubbaloo</player.name> <player.name>Wubbaloo</player.name>")
it "Should replace %hishers", () ->
str = messageCreator.doStringReplace "%hishers %hishers", {
getGender: () ->
"male"
getName: () ->
"W<NAME>"
}
expect(str).to.equal("his his")
str = messageCreator.doStringReplace "%hishers %hishers", {
getGender: () ->
"female"
getName: () ->
"<NAME>"
}
expect(str).to.equal("hers hers")
str = messageCreator.doStringReplace "%hishers %hishers", {
getGender: () ->
"Android"
getName: () ->
"<NAME>"
}
expect(str).to.equal("theirs theirs")
str = messageCreator.doStringReplace "%Hishers %Hishers", {
getGender: () ->
"male"
getName: () ->
"<NAME>"
}
expect(str).to.equal("His His")
str = messageCreator.doStringReplace "%Hishers %Hishers", {
getGender: () ->
"female"
getName: () ->
"<NAME>"
}
expect(str).to.equal("Hers Hers")
str = messageCreator.doStringReplace "%Hishers %Hishers", {
getGender: () ->
"Android"
getName: () ->
"<NAME>"
}
expect(str).to.equal("Theirs Theirs")
it "Should replace %hisher", () ->
str = messageCreator.doStringReplace "%hisher %hisher", {
getGender: () ->
"male"
getName: () ->
"<NAME>"
}
expect(str).to.equal("his his")
str = messageCreator.doStringReplace "%hisher %hisher", {
getGender: () ->
"female"
getName: () ->
"<NAME>"
}
expect(str).to.equal("her her")
str = messageCreator.doStringReplace "%hisher %hisher", {
getGender: () ->
"Android"
getName: () ->
"<NAME>"
}
expect(str).to.equal("their their")
str = messageCreator.doStringReplace "%Hisher %Hisher", {
getGender: () ->
"male"
getName: () ->
"<NAME>"
}
expect(str).to.equal("His His")
str = messageCreator.doStringReplace "%Hisher %Hish<NAME>", {
getGender: () ->
"female"
getName: () ->
"<NAME>"
}
expect(str).to.equal("Her Her")
str = messageCreator.doStringReplace "%Hisher %Hisher", {
getGender: () ->
"Android"
getName: () ->
"<NAME>"
}
expect(str).to.equal("Their Their")
it "Should replace %himher", () ->
str = messageCreator.doStringReplace "%himher %himher", {
getGender: () ->
"male"
getName: () ->
"<NAME>"
}
expect(str).to.equal("him him")
str = messageCreator.doStringReplace "%himher %himher", {
getGender: () ->
"female"
getName: () ->
"W<NAME>ber"
}
expect(str).to.equal("her her")
str = messageCreator.doStringReplace "%himher %himher", {
getGender: () ->
"Android"
getName: () ->
"<NAME>"
}
expect(str).to.equal("them them")
str = messageCreator.doStringReplace "%Himher %Himher", {
getGender: () ->
"male"
getName: () ->
"<NAME>"
}
expect(str).to.equal("Him Him")
str = messageCreator.doStringReplace "%Himher %Himher", {
getGender: () ->
"female"
getName: () ->
"<NAME>"
}
expect(str).to.equal("Her Her")
str = messageCreator.doStringReplace "%Himher %Himher", {
getGender: () ->
"Android"
getName: () ->
"<NAME>"
}
expect(str).to.equal("Them Them")
it "Should replace %heshe", () ->
str = messageCreator.doStringReplace "%heshe %heshe", {
getGender: () ->
"male"
getName: () ->
"<NAME>"
}
str2 = messageCreator.doStringReplace "%she %she", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("he he")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%heshe %heshe", {
getGender: () ->
"female"
getName: () ->
"<NAME>"
}
str2 = messageCreator.doStringReplace "%she %she", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
expect(str).to.equal("she she")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%heshe %heshe", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%she %she", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
expect(str).to.equal("they they")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%Heshe %Heshe", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%She %She", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("He He")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%Heshe %Heshe", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%She %She", {
getGender: () ->
"female"
getName: () ->
"W<NAME>ber"
}
expect(str).to.equal("She She")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%Heshe %Heshe", {
getGender: () ->
"Android"
getName: () ->
"W<NAME>ber"
}
str2 = messageCreator.doStringReplace "%She %She", {
getGender: () ->
"Android"
getName: () ->
"<NAME>"
}
expect(str).to.equal("They They")
expect(str).to.equal(str2) | true | basedir = "../../../src/"
chai = require "chai"
mocha = require "mocha"
sinon = require "sinon"
proxyquire = require "proxyquire"
expect = chai.expect
describe = mocha.describe
class API
@gameInstance = {
petManager: {
pets: {}
activePets: {}
},
playerManager: {
players: {}
},
guildManager: {
guilds: {}
},
world: {
maps: {}
},
componentDatabase: {
generatorCache: [] #[placeholder: ["an ordinary potato"], deity: ["Zeus"]]
insertString: (type, string) ->
API.gameInstance.componentDatabase.generatorCache[type] = [] if not @generatorCache[type]
API.gameInstance.componentDatabase.generatorCache[type].push string
}
}
API.gameInstance.componentDatabase.insertString "placeholder", "an ordinary potato"
describe "MessageCreator", () ->
messageCreator = proxyquire(basedir + 'system/handlers/MessageCreator', {
"chance":
class Chance
constructor: () ->
, "./../accessibility/API":
API
}, '@noCallThru': true )
it "Should replace %player", () ->
str = messageCreator.doStringReplace "%player %player", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("<player.name>Wabber</player.name> <player.name>Wabber</player.name>")
it "Should replace %pet", () ->
str = messageCreator.doStringReplace "%pet %pet", {
getGender: () ->
"male"
getName: () ->
"Wabber"
playerManager:
game:
petManager:
getActivePetFor: (player) ->
if player.getName() isnt "Wabber"
throw new Error "Player #{player.getName()} is not Wabber"
{
getName: () ->
"PI:NAME:<NAME>END_PI"
}
guildManager:
getGuildByName: (guild) ->
{}
guild: {}
}
expect(str).to.equal("<player.name>PI:NAME:<NAME>END_PI</player.name> <player.name>Dezo</player.name>")
it "Should replace %guild", () ->
str = messageCreator.doStringReplace "%guild %guild", {
getGender: () ->
"male"
getName: () ->
"WPI:NAME:<NAME>END_PI"
playerManager:
game:
petManager:
getActivePetFor: (player) ->
if player.getName() isnt "Wabber"
throw new Error "Player #{player.getName()} is not Wabber"
{
getName: () ->
"DePI:NAME:<NAME>END_PI"
}
guildManager:
getGuildByName: (guild) ->
if guild isnt "Styx"
throw new Error "Guild #{guild} is not Styx"
{}
guild: "Styx"
}
expect(str).to.equal("<event.guildName>Styx</event.guildName> <event.guildName>Styx</event.guildName>")
it "Should replace %guildMember", () ->
str = messageCreator.doStringReplace "%guildMember %guildMember", {
getGender: () ->
"male"
getName: () ->
"PI:NAME:<NAME>END_PI"
name: "PI:NAME:<NAME>END_PI"
playerManager:
players: ["Wubbaloo"]
game:
petManager:
getActivePetFor: (player) ->
if player.getName() isnt "Wabber"
throw new Error "Player #{player.getName()} is not Wabber"
{
getName: () ->
"PI:NAME:<NAME>END_PI"
}
guildManager:
getGuildByName: (guild) ->
if guild isnt "Styx"
throw new Error "Guild #{guild} is not Styx"
{members: [{name: "Wubbaloo"}, {name: "Wabber"}]}
guild: "Styx"
}
expect(str).to.equal("<player.name>Wubbaloo</player.name> <player.name>Wubbaloo</player.name>")
it "Should replace %hishers", () ->
str = messageCreator.doStringReplace "%hishers %hishers", {
getGender: () ->
"male"
getName: () ->
"WPI:NAME:<NAME>END_PI"
}
expect(str).to.equal("his his")
str = messageCreator.doStringReplace "%hishers %hishers", {
getGender: () ->
"female"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("hers hers")
str = messageCreator.doStringReplace "%hishers %hishers", {
getGender: () ->
"Android"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("theirs theirs")
str = messageCreator.doStringReplace "%Hishers %Hishers", {
getGender: () ->
"male"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("His His")
str = messageCreator.doStringReplace "%Hishers %Hishers", {
getGender: () ->
"female"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("Hers Hers")
str = messageCreator.doStringReplace "%Hishers %Hishers", {
getGender: () ->
"Android"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("Theirs Theirs")
it "Should replace %hisher", () ->
str = messageCreator.doStringReplace "%hisher %hisher", {
getGender: () ->
"male"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("his his")
str = messageCreator.doStringReplace "%hisher %hisher", {
getGender: () ->
"female"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("her her")
str = messageCreator.doStringReplace "%hisher %hisher", {
getGender: () ->
"Android"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("their their")
str = messageCreator.doStringReplace "%Hisher %Hisher", {
getGender: () ->
"male"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("His His")
str = messageCreator.doStringReplace "%Hisher %HishPI:NAME:<NAME>END_PI", {
getGender: () ->
"female"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("Her Her")
str = messageCreator.doStringReplace "%Hisher %Hisher", {
getGender: () ->
"Android"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("Their Their")
it "Should replace %himher", () ->
str = messageCreator.doStringReplace "%himher %himher", {
getGender: () ->
"male"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("him him")
str = messageCreator.doStringReplace "%himher %himher", {
getGender: () ->
"female"
getName: () ->
"WPI:NAME:<NAME>END_PIber"
}
expect(str).to.equal("her her")
str = messageCreator.doStringReplace "%himher %himher", {
getGender: () ->
"Android"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("them them")
str = messageCreator.doStringReplace "%Himher %Himher", {
getGender: () ->
"male"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("Him Him")
str = messageCreator.doStringReplace "%Himher %Himher", {
getGender: () ->
"female"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("Her Her")
str = messageCreator.doStringReplace "%Himher %Himher", {
getGender: () ->
"Android"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("Them Them")
it "Should replace %heshe", () ->
str = messageCreator.doStringReplace "%heshe %heshe", {
getGender: () ->
"male"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
str2 = messageCreator.doStringReplace "%she %she", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("he he")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%heshe %heshe", {
getGender: () ->
"female"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
str2 = messageCreator.doStringReplace "%she %she", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
expect(str).to.equal("she she")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%heshe %heshe", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%she %she", {
getGender: () ->
"Android"
getName: () ->
"Wabber"
}
expect(str).to.equal("they they")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%Heshe %Heshe", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%She %She", {
getGender: () ->
"male"
getName: () ->
"Wabber"
}
expect(str).to.equal("He He")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%Heshe %Heshe", {
getGender: () ->
"female"
getName: () ->
"Wabber"
}
str2 = messageCreator.doStringReplace "%She %She", {
getGender: () ->
"female"
getName: () ->
"WPI:NAME:<NAME>END_PIber"
}
expect(str).to.equal("She She")
expect(str).to.equal(str2)
str = messageCreator.doStringReplace "%Heshe %Heshe", {
getGender: () ->
"Android"
getName: () ->
"WPI:NAME:<NAME>END_PIber"
}
str2 = messageCreator.doStringReplace "%She %She", {
getGender: () ->
"Android"
getName: () ->
"PI:NAME:<NAME>END_PI"
}
expect(str).to.equal("They They")
expect(str).to.equal(str2) |
[
{
"context": " @alarm.metadoctype.displayName.should.equal 'Alarme'\n @alarm.metadoctype.identificatio",
"end": 5131,
"score": 0.9994484782218933,
"start": 5125,
"tag": "NAME",
"value": "Alarme"
}
] | tests/doctypelist.coffee | aenario/cozy-databrowser | 0 | Client = require('request-json').JsonClient
should = require 'should'
fixtures = require 'cozy-fixtures'
path = require 'path'
helpers = require './helpers'
helpers.options =
serverHost: 'localhost'
serverPort: '8888'
client = new Client "http://#{helpers.options.serverHost}:#{helpers.options.serverPort}/"
fixtures.setDefaultValues
dirPath: path.resolve __dirname, './fixtures/'
silent: true
removeBeforeLoad: false # useless because we clean the DB before tests
describe "Doctype list management", ->
before helpers.cleanDB
before helpers.startApp
after helpers.stopApp
after helpers.cleanDB
describe "When the database is empty", ->
it "There shouldn't be items in doctypes list", (done) ->
client.get 'doctypes', (err, res, body) ->
should.exist res
res.should.have.property 'statusCode'
res.statusCode.should.equal 200
body.length.should.equal 0
done()
describe "When we add 2 documents of one doctype (Alarm)", ->
before helpers.cleanDB
before (done) -> fixtures.load doctypeTarget: 'alarm', callback: done
after helpers.cleanDB
describe "When we request the doctypes list", (done) =>
@err = null
@res = null
@body = null
before (done) =>
client.get 'doctypes', (err, res, body) =>
@err = err
@res = res
@body = body
done()
it "The response shouldn't be an error", =>
should.not.exist @err
should.exist @res
@res.should.have.property 'statusCode'
@res.statusCode.should.equal 200
should.exist @body
it "And should only have the doctype Alarm in the list", =>
@body.length.should.equal 1
element = @body[0]
element.should.have.properties ['name', 'sum', 'app']
element.name.should.equal 'alarm'
it "And this doctype should only have 2 documents", =>
element = @body[0]
element.sum.should.equal 2
it "And no application should use this doctype", =>
element = @body[0]
element.app.should.be.an.instanceOf(Array).and.empty
describe "When we add documents of multiple doctypes with the metadoctype information", ->
# load all the fixtures
before helpers.cleanDB
before (done) -> fixtures.load doctypeTarget: 'alarm', callback: done
before (done) -> fixtures.load doctypeTarget: 'metadoctype', callback: done
before (done) -> fixtures.load doctypeTarget: 'contact', callback: done
before (done) -> fixtures.load doctypeTarget: 'application', callback: done
after helpers.cleanDB
describe "When we request the doctypes list", (done) =>
@err = null
@res = null
@body = null
before (done) =>
client.get 'doctypes', (err, res, body) =>
@err = err
@res = res
@body = body
done()
it "The response shouldn't be an error", =>
should.not.exist @err
should.exist @res
@res.should.have.property 'statusCode'
@res.statusCode.should.equal 200
should.exist @body
it "And should have 4 doctypes: metadoctype, application, alarm and contact", =>
@body.length.should.equal 4
@alarm = null
@metadoctype = null
@contact = null
@application = null
expectedDoctypes = ['alarm', 'metadoctype', 'contact', 'application']
for doctypeInfo in @body
if doctypeInfo.name is 'alarm'
@alarm = doctypeInfo
else if doctypeInfo.name is 'metadoctype'
@metadoctype = doctypeInfo
else if doctypeInfo.name is 'contact'
@contact = doctypeInfo
else if doctypeInfo.name is 'application'
@application = doctypeInfo
else
expectedDoctypes.should.contain doctypeInfo.name
should.exist @alarm
should.exist @metadoctype
should.exist @contact
should.exist @application
it "And alarm should be well formed", =>
@alarm.should.have.properties ['name', 'sum', 'app']
it "And alarm should have its meta information", =>
@alarm.should.have.property 'metadoctype'
@alarm.metadoctype.should.have.properties ['related', 'displayName', 'identificationField', 'fields']
@alarm.metadoctype.related.should.equal 'Alarm'
@alarm.metadoctype.displayName.should.equal 'Alarme'
@alarm.metadoctype.identificationField.should.equal 'description'
it "And alarm should have the application 'photos' in its app list", =>
@alarm.should.have.property 'app'
@alarm.app.should.have.lengthOf 2
@alarm.app[1].should.equal 'photos'
it "And contact should be well formed", =>
@contact.should.have.properties ['name', 'sum', 'app']
it "And contact should have the application 'photos' in its apps list", =>
@contact.should.have.property 'app'
@contact.app.should.have.lengthOf 2
@contact.app[1].should.equal 'photos'
it "And contact should have its meta information", =>
@contact.should.have.property 'metadoctype'
it "And metadoctype should be well formed", =>
@metadoctype.should.have.properties ['name', 'sum', 'app']
it "And metadoctype shouldn't have its meta information", =>
@metadoctype.should.not.have.property 'metadoctype'
it "And application should be well formed", =>
@application.should.have.properties ['name', 'sum', 'app']
it "And application shouldn't have its meta information", =>
@application.should.not.have.property 'metadoctype'
| 144906 | Client = require('request-json').JsonClient
should = require 'should'
fixtures = require 'cozy-fixtures'
path = require 'path'
helpers = require './helpers'
helpers.options =
serverHost: 'localhost'
serverPort: '8888'
client = new Client "http://#{helpers.options.serverHost}:#{helpers.options.serverPort}/"
fixtures.setDefaultValues
dirPath: path.resolve __dirname, './fixtures/'
silent: true
removeBeforeLoad: false # useless because we clean the DB before tests
describe "Doctype list management", ->
before helpers.cleanDB
before helpers.startApp
after helpers.stopApp
after helpers.cleanDB
describe "When the database is empty", ->
it "There shouldn't be items in doctypes list", (done) ->
client.get 'doctypes', (err, res, body) ->
should.exist res
res.should.have.property 'statusCode'
res.statusCode.should.equal 200
body.length.should.equal 0
done()
describe "When we add 2 documents of one doctype (Alarm)", ->
before helpers.cleanDB
before (done) -> fixtures.load doctypeTarget: 'alarm', callback: done
after helpers.cleanDB
describe "When we request the doctypes list", (done) =>
@err = null
@res = null
@body = null
before (done) =>
client.get 'doctypes', (err, res, body) =>
@err = err
@res = res
@body = body
done()
it "The response shouldn't be an error", =>
should.not.exist @err
should.exist @res
@res.should.have.property 'statusCode'
@res.statusCode.should.equal 200
should.exist @body
it "And should only have the doctype Alarm in the list", =>
@body.length.should.equal 1
element = @body[0]
element.should.have.properties ['name', 'sum', 'app']
element.name.should.equal 'alarm'
it "And this doctype should only have 2 documents", =>
element = @body[0]
element.sum.should.equal 2
it "And no application should use this doctype", =>
element = @body[0]
element.app.should.be.an.instanceOf(Array).and.empty
describe "When we add documents of multiple doctypes with the metadoctype information", ->
# load all the fixtures
before helpers.cleanDB
before (done) -> fixtures.load doctypeTarget: 'alarm', callback: done
before (done) -> fixtures.load doctypeTarget: 'metadoctype', callback: done
before (done) -> fixtures.load doctypeTarget: 'contact', callback: done
before (done) -> fixtures.load doctypeTarget: 'application', callback: done
after helpers.cleanDB
describe "When we request the doctypes list", (done) =>
@err = null
@res = null
@body = null
before (done) =>
client.get 'doctypes', (err, res, body) =>
@err = err
@res = res
@body = body
done()
it "The response shouldn't be an error", =>
should.not.exist @err
should.exist @res
@res.should.have.property 'statusCode'
@res.statusCode.should.equal 200
should.exist @body
it "And should have 4 doctypes: metadoctype, application, alarm and contact", =>
@body.length.should.equal 4
@alarm = null
@metadoctype = null
@contact = null
@application = null
expectedDoctypes = ['alarm', 'metadoctype', 'contact', 'application']
for doctypeInfo in @body
if doctypeInfo.name is 'alarm'
@alarm = doctypeInfo
else if doctypeInfo.name is 'metadoctype'
@metadoctype = doctypeInfo
else if doctypeInfo.name is 'contact'
@contact = doctypeInfo
else if doctypeInfo.name is 'application'
@application = doctypeInfo
else
expectedDoctypes.should.contain doctypeInfo.name
should.exist @alarm
should.exist @metadoctype
should.exist @contact
should.exist @application
it "And alarm should be well formed", =>
@alarm.should.have.properties ['name', 'sum', 'app']
it "And alarm should have its meta information", =>
@alarm.should.have.property 'metadoctype'
@alarm.metadoctype.should.have.properties ['related', 'displayName', 'identificationField', 'fields']
@alarm.metadoctype.related.should.equal 'Alarm'
@alarm.metadoctype.displayName.should.equal '<NAME>'
@alarm.metadoctype.identificationField.should.equal 'description'
it "And alarm should have the application 'photos' in its app list", =>
@alarm.should.have.property 'app'
@alarm.app.should.have.lengthOf 2
@alarm.app[1].should.equal 'photos'
it "And contact should be well formed", =>
@contact.should.have.properties ['name', 'sum', 'app']
it "And contact should have the application 'photos' in its apps list", =>
@contact.should.have.property 'app'
@contact.app.should.have.lengthOf 2
@contact.app[1].should.equal 'photos'
it "And contact should have its meta information", =>
@contact.should.have.property 'metadoctype'
it "And metadoctype should be well formed", =>
@metadoctype.should.have.properties ['name', 'sum', 'app']
it "And metadoctype shouldn't have its meta information", =>
@metadoctype.should.not.have.property 'metadoctype'
it "And application should be well formed", =>
@application.should.have.properties ['name', 'sum', 'app']
it "And application shouldn't have its meta information", =>
@application.should.not.have.property 'metadoctype'
| true | Client = require('request-json').JsonClient
should = require 'should'
fixtures = require 'cozy-fixtures'
path = require 'path'
helpers = require './helpers'
helpers.options =
serverHost: 'localhost'
serverPort: '8888'
client = new Client "http://#{helpers.options.serverHost}:#{helpers.options.serverPort}/"
fixtures.setDefaultValues
dirPath: path.resolve __dirname, './fixtures/'
silent: true
removeBeforeLoad: false # useless because we clean the DB before tests
describe "Doctype list management", ->
before helpers.cleanDB
before helpers.startApp
after helpers.stopApp
after helpers.cleanDB
describe "When the database is empty", ->
it "There shouldn't be items in doctypes list", (done) ->
client.get 'doctypes', (err, res, body) ->
should.exist res
res.should.have.property 'statusCode'
res.statusCode.should.equal 200
body.length.should.equal 0
done()
describe "When we add 2 documents of one doctype (Alarm)", ->
before helpers.cleanDB
before (done) -> fixtures.load doctypeTarget: 'alarm', callback: done
after helpers.cleanDB
describe "When we request the doctypes list", (done) =>
@err = null
@res = null
@body = null
before (done) =>
client.get 'doctypes', (err, res, body) =>
@err = err
@res = res
@body = body
done()
it "The response shouldn't be an error", =>
should.not.exist @err
should.exist @res
@res.should.have.property 'statusCode'
@res.statusCode.should.equal 200
should.exist @body
it "And should only have the doctype Alarm in the list", =>
@body.length.should.equal 1
element = @body[0]
element.should.have.properties ['name', 'sum', 'app']
element.name.should.equal 'alarm'
it "And this doctype should only have 2 documents", =>
element = @body[0]
element.sum.should.equal 2
it "And no application should use this doctype", =>
element = @body[0]
element.app.should.be.an.instanceOf(Array).and.empty
describe "When we add documents of multiple doctypes with the metadoctype information", ->
# load all the fixtures
before helpers.cleanDB
before (done) -> fixtures.load doctypeTarget: 'alarm', callback: done
before (done) -> fixtures.load doctypeTarget: 'metadoctype', callback: done
before (done) -> fixtures.load doctypeTarget: 'contact', callback: done
before (done) -> fixtures.load doctypeTarget: 'application', callback: done
after helpers.cleanDB
describe "When we request the doctypes list", (done) =>
@err = null
@res = null
@body = null
before (done) =>
client.get 'doctypes', (err, res, body) =>
@err = err
@res = res
@body = body
done()
it "The response shouldn't be an error", =>
should.not.exist @err
should.exist @res
@res.should.have.property 'statusCode'
@res.statusCode.should.equal 200
should.exist @body
it "And should have 4 doctypes: metadoctype, application, alarm and contact", =>
@body.length.should.equal 4
@alarm = null
@metadoctype = null
@contact = null
@application = null
expectedDoctypes = ['alarm', 'metadoctype', 'contact', 'application']
for doctypeInfo in @body
if doctypeInfo.name is 'alarm'
@alarm = doctypeInfo
else if doctypeInfo.name is 'metadoctype'
@metadoctype = doctypeInfo
else if doctypeInfo.name is 'contact'
@contact = doctypeInfo
else if doctypeInfo.name is 'application'
@application = doctypeInfo
else
expectedDoctypes.should.contain doctypeInfo.name
should.exist @alarm
should.exist @metadoctype
should.exist @contact
should.exist @application
it "And alarm should be well formed", =>
@alarm.should.have.properties ['name', 'sum', 'app']
it "And alarm should have its meta information", =>
@alarm.should.have.property 'metadoctype'
@alarm.metadoctype.should.have.properties ['related', 'displayName', 'identificationField', 'fields']
@alarm.metadoctype.related.should.equal 'Alarm'
@alarm.metadoctype.displayName.should.equal 'PI:NAME:<NAME>END_PI'
@alarm.metadoctype.identificationField.should.equal 'description'
it "And alarm should have the application 'photos' in its app list", =>
@alarm.should.have.property 'app'
@alarm.app.should.have.lengthOf 2
@alarm.app[1].should.equal 'photos'
it "And contact should be well formed", =>
@contact.should.have.properties ['name', 'sum', 'app']
it "And contact should have the application 'photos' in its apps list", =>
@contact.should.have.property 'app'
@contact.app.should.have.lengthOf 2
@contact.app[1].should.equal 'photos'
it "And contact should have its meta information", =>
@contact.should.have.property 'metadoctype'
it "And metadoctype should be well formed", =>
@metadoctype.should.have.properties ['name', 'sum', 'app']
it "And metadoctype shouldn't have its meta information", =>
@metadoctype.should.not.have.property 'metadoctype'
it "And application should be well formed", =>
@application.should.have.properties ['name', 'sum', 'app']
it "And application shouldn't have its meta information", =>
@application.should.not.have.property 'metadoctype'
|
[
{
"context": "login', { login: $('#login').val(), password: $('#password').val() }, (data) ->\n context.log data\n ",
"end": 2121,
"score": 0.6385889053344727,
"start": 2113,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "al()\n $.post '/post-reply', {\n u... | frontend/javascripts/agora.coffee | fasterthanlime/agora2 | 0 | # Simple sammy test in CS :)
showdown = new Showdown.converter()
app = $.sammy '#main', ->
@use 'Template'
@use 'Storage'
@use 'Session'
getUser = (username, cb) ->
user = @session('user/' + username)
if user
cb(user)
else
$.get('/user/' + username, {}, (data) -> cb(data))
formatDate = (timestamp) ->
pad = (number) ->
if number < 10
'0' + number
else
'' + number
date = new Date(timestamp)
pad(date.getDate()) + " " + ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"][date.getMonth()] + " " + date.getFullYear() + " à " + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds())
@before (context) ->
@user = @session('user')
@getUser = (username, data) -> getUser.apply(@, [username, data])
if context.path != '#/login'
if !@user
$('.user-info').fadeOut()
@redirect('#/login')
return false
$('.nickname').text(@user.nickname)
$('.avatar').attr('src', @user.avatar)
$('.user-info').fadeIn()
@bind 'render-all', (event, args) ->
@load('/' + args.path, { json: true }).then (content) ->
@renderEach(args.template, args.name, content).appendTo(args.target)
# Others' profile pages
@get '#/u/:username', { token: @session( 'token' ) }, (context) ->
username = @params.username
$.get '/user/' + username, { token: @session( 'token' ) }, (user) ->
context.partial('templates/profile.template', { user: user, date: formatDate(user.joindate) })
# Own profile page
@get '#/u', (context) ->
$.get '/user/' + @user.username, { token: @session( 'token' ) }, (user) ->
context.partial('templates/profile.template', { user: user, date: formatDate(user.joindate) })
# Login box
@get '#/login', (context) ->
@partial('templates/login.template').then ->
$('#password').keypress (event) ->
return unless event.which == 13
event.preventDefault()
$.post '/login', { login: $('#login').val(), password: $('#password').val() }, (data) ->
context.log data
switch data.result
when "failure"
context.log "Log-in failed!"
when "success"
context.log "Log-in succeeded!"
context.session('user', data.user)
context.session('token', data.session_token)
context.redirect('#/')
@get '#/logout', (context) ->
$('.user-info').fadeOut()
$.post '/logout', { token: @session('token') }, (data) ->
context.log 'Logged out gracefully!'
# Note that if we don't, it's no biggie. Token
# will end up expiring anyways.
@session('user', null)
@session('token', null)
# Couldn't find a good way to clear, nulling works just as fine
@redirect('#/login')
# Category list
@get '#/', (context) ->
@partial('templates/home.template')
@trigger 'render-all', {
path: 'categories?token=' + @session('token')
template: 'templates/category-summary.template'
name: 'category'
target: '.categories'
}
# Thread list in a category
@get '#/r/:slug', (context) ->
@slug = @params['slug']
$.get '/category/' + @slug, { token: @session('token') }, (category) ->
context.partial 'templates/category.template', { category: category }
context.render('templates/new-thread.template', { post: { user: context.user, category: category._id }}).prependTo('.threads').then ->
@trigger 'setup-thread-opener'
@trigger 'setup-post-editor'
render0 = (index) ->
if index < category.threads.length
thread = category.threads[category.threads.length - 1 - index]
thread.category = category
context.render('templates/thread-summary.template', { thread: thread }).then (threadnode) ->
$(threadnode).appendTo('.threads')
render0(index + 1)
render0(0)
# Message list in a thread
@get '#/r/:slug/:tid', (context) ->
tid = @params['tid']
$.ajax({
url: '/thread/' + tid
data: { token: @session( 'token' ) }
dataType: 'json'
success: (thread) ->
context.partial('templates/thread.template', {thread: thread}).then ->
render0 = (index) ->
if index < thread.posts.length
post = thread.posts[index]
content = showdown.makeHtml(post.source)
context.getUser post.username, (postUser) ->
context.render('templates/post.template', {post: {content: content, date: formatDate(post.date), user: postUser}}).then (post) ->
$(post).appendTo('.thread')
render0(index + 1)
else
context.render('templates/post-reply.template', {post: {user: context.user, tid: tid}}).then (post) ->
$(post).appendTo('.thread')
@trigger 'setup-post-editor'
$('.submit-post').click ->
context.trigger 'post-reply', { context: context }
render0(0)
})
@bind 'setup-thread-opener', ->
context = @
$('.post-title').blur ->
if $(this).val() == ""
$('.new-post').slideUp()
$('.post-title').focus ->
newpost = $('.new-post')
if newpost.css('display') == 'none'
$('.new-post').hide().css('height', '0px').show().animate({height: '191px'})
$('.submit-post').click ->
context.trigger 'new-thread'
@bind 'setup-post-editor', ->
context = @
$('.post-source').blur ->
source = $(this)
source.hide()
preview = source.parent().children('.post-preview')
preview.html(showdown.makeHtml(source.val())).show()
$('.post-preview').click ->
preview = $(this)
preview.hide()
source = preview.parent().children('.post-source')
source.show().focus()
@bind 'post-reply', (context) ->
context = @
tid = $('.reply-thread').val()
$.post '/post-reply', {
username: @user.username
tid: tid
source: $('.post-source').val()
token: @session('token')
}, (data) ->
content = showdown.makeHtml($('.post-source').val())
context.render('templates/post.template', {post: {content: content, user: context.user, date: formatDate(data.date)}}).then (postnode) ->
$(postnode).hide().appendTo('.thread').slideDown()
$('.new-post').detach().appendTo('.thread')
$('.post-preview').click()
$('.post-source').val('')
@bind 'new-thread', (context) ->
context = @
category = $('.post-category').val()
title = $('.post-title').val()
$.post '/new-thread', {
username: @user.username
category: category
title: title
source: $('.post-source').val()
token: @session( 'token' )
}, (data) ->
title = $('.new-header .post-title').val()
context.log title
$('.new-header, .new-post').remove()
context.render('templates/thread-summary.template', { thread: { category: { slug: context.slug }, _id: data.id, title: title } }).then (postnode) ->
$(postnode).hide().prependTo('.threads').slideDown()
context.render('templates/new-thread.template', { post: { user: context.user, category: category }}).prependTo('.threads').then ->
@trigger 'setup-thread-opener'
@trigger 'setup-post-editor'
$ -> app.run '#/'
| 70966 | # Simple sammy test in CS :)
showdown = new Showdown.converter()
app = $.sammy '#main', ->
@use 'Template'
@use 'Storage'
@use 'Session'
getUser = (username, cb) ->
user = @session('user/' + username)
if user
cb(user)
else
$.get('/user/' + username, {}, (data) -> cb(data))
formatDate = (timestamp) ->
pad = (number) ->
if number < 10
'0' + number
else
'' + number
date = new Date(timestamp)
pad(date.getDate()) + " " + ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"][date.getMonth()] + " " + date.getFullYear() + " à " + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds())
@before (context) ->
@user = @session('user')
@getUser = (username, data) -> getUser.apply(@, [username, data])
if context.path != '#/login'
if !@user
$('.user-info').fadeOut()
@redirect('#/login')
return false
$('.nickname').text(@user.nickname)
$('.avatar').attr('src', @user.avatar)
$('.user-info').fadeIn()
@bind 'render-all', (event, args) ->
@load('/' + args.path, { json: true }).then (content) ->
@renderEach(args.template, args.name, content).appendTo(args.target)
# Others' profile pages
@get '#/u/:username', { token: @session( 'token' ) }, (context) ->
username = @params.username
$.get '/user/' + username, { token: @session( 'token' ) }, (user) ->
context.partial('templates/profile.template', { user: user, date: formatDate(user.joindate) })
# Own profile page
@get '#/u', (context) ->
$.get '/user/' + @user.username, { token: @session( 'token' ) }, (user) ->
context.partial('templates/profile.template', { user: user, date: formatDate(user.joindate) })
# Login box
@get '#/login', (context) ->
@partial('templates/login.template').then ->
$('#password').keypress (event) ->
return unless event.which == 13
event.preventDefault()
$.post '/login', { login: $('#login').val(), password: $('#<PASSWORD>').val() }, (data) ->
context.log data
switch data.result
when "failure"
context.log "Log-in failed!"
when "success"
context.log "Log-in succeeded!"
context.session('user', data.user)
context.session('token', data.session_token)
context.redirect('#/')
@get '#/logout', (context) ->
$('.user-info').fadeOut()
$.post '/logout', { token: @session('token') }, (data) ->
context.log 'Logged out gracefully!'
# Note that if we don't, it's no biggie. Token
# will end up expiring anyways.
@session('user', null)
@session('token', null)
# Couldn't find a good way to clear, nulling works just as fine
@redirect('#/login')
# Category list
@get '#/', (context) ->
@partial('templates/home.template')
@trigger 'render-all', {
path: 'categories?token=' + @session('token')
template: 'templates/category-summary.template'
name: 'category'
target: '.categories'
}
# Thread list in a category
@get '#/r/:slug', (context) ->
@slug = @params['slug']
$.get '/category/' + @slug, { token: @session('token') }, (category) ->
context.partial 'templates/category.template', { category: category }
context.render('templates/new-thread.template', { post: { user: context.user, category: category._id }}).prependTo('.threads').then ->
@trigger 'setup-thread-opener'
@trigger 'setup-post-editor'
render0 = (index) ->
if index < category.threads.length
thread = category.threads[category.threads.length - 1 - index]
thread.category = category
context.render('templates/thread-summary.template', { thread: thread }).then (threadnode) ->
$(threadnode).appendTo('.threads')
render0(index + 1)
render0(0)
# Message list in a thread
@get '#/r/:slug/:tid', (context) ->
tid = @params['tid']
$.ajax({
url: '/thread/' + tid
data: { token: @session( 'token' ) }
dataType: 'json'
success: (thread) ->
context.partial('templates/thread.template', {thread: thread}).then ->
render0 = (index) ->
if index < thread.posts.length
post = thread.posts[index]
content = showdown.makeHtml(post.source)
context.getUser post.username, (postUser) ->
context.render('templates/post.template', {post: {content: content, date: formatDate(post.date), user: postUser}}).then (post) ->
$(post).appendTo('.thread')
render0(index + 1)
else
context.render('templates/post-reply.template', {post: {user: context.user, tid: tid}}).then (post) ->
$(post).appendTo('.thread')
@trigger 'setup-post-editor'
$('.submit-post').click ->
context.trigger 'post-reply', { context: context }
render0(0)
})
@bind 'setup-thread-opener', ->
context = @
$('.post-title').blur ->
if $(this).val() == ""
$('.new-post').slideUp()
$('.post-title').focus ->
newpost = $('.new-post')
if newpost.css('display') == 'none'
$('.new-post').hide().css('height', '0px').show().animate({height: '191px'})
$('.submit-post').click ->
context.trigger 'new-thread'
@bind 'setup-post-editor', ->
context = @
$('.post-source').blur ->
source = $(this)
source.hide()
preview = source.parent().children('.post-preview')
preview.html(showdown.makeHtml(source.val())).show()
$('.post-preview').click ->
preview = $(this)
preview.hide()
source = preview.parent().children('.post-source')
source.show().focus()
@bind 'post-reply', (context) ->
context = @
tid = $('.reply-thread').val()
$.post '/post-reply', {
username: @user.username
tid: tid
source: $('.post-source').val()
token: @session('token')
}, (data) ->
content = showdown.makeHtml($('.post-source').val())
context.render('templates/post.template', {post: {content: content, user: context.user, date: formatDate(data.date)}}).then (postnode) ->
$(postnode).hide().appendTo('.thread').slideDown()
$('.new-post').detach().appendTo('.thread')
$('.post-preview').click()
$('.post-source').val('')
@bind 'new-thread', (context) ->
context = @
category = $('.post-category').val()
title = $('.post-title').val()
$.post '/new-thread', {
username: @user.username
category: category
title: title
source: $('.post-source').val()
token: @session( 'token' )
}, (data) ->
title = $('.new-header .post-title').val()
context.log title
$('.new-header, .new-post').remove()
context.render('templates/thread-summary.template', { thread: { category: { slug: context.slug }, _id: data.id, title: title } }).then (postnode) ->
$(postnode).hide().prependTo('.threads').slideDown()
context.render('templates/new-thread.template', { post: { user: context.user, category: category }}).prependTo('.threads').then ->
@trigger 'setup-thread-opener'
@trigger 'setup-post-editor'
$ -> app.run '#/'
| true | # Simple sammy test in CS :)
showdown = new Showdown.converter()
app = $.sammy '#main', ->
@use 'Template'
@use 'Storage'
@use 'Session'
getUser = (username, cb) ->
user = @session('user/' + username)
if user
cb(user)
else
$.get('/user/' + username, {}, (data) -> cb(data))
formatDate = (timestamp) ->
pad = (number) ->
if number < 10
'0' + number
else
'' + number
date = new Date(timestamp)
pad(date.getDate()) + " " + ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"][date.getMonth()] + " " + date.getFullYear() + " à " + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds())
@before (context) ->
@user = @session('user')
@getUser = (username, data) -> getUser.apply(@, [username, data])
if context.path != '#/login'
if !@user
$('.user-info').fadeOut()
@redirect('#/login')
return false
$('.nickname').text(@user.nickname)
$('.avatar').attr('src', @user.avatar)
$('.user-info').fadeIn()
@bind 'render-all', (event, args) ->
@load('/' + args.path, { json: true }).then (content) ->
@renderEach(args.template, args.name, content).appendTo(args.target)
# Others' profile pages
@get '#/u/:username', { token: @session( 'token' ) }, (context) ->
username = @params.username
$.get '/user/' + username, { token: @session( 'token' ) }, (user) ->
context.partial('templates/profile.template', { user: user, date: formatDate(user.joindate) })
# Own profile page
@get '#/u', (context) ->
$.get '/user/' + @user.username, { token: @session( 'token' ) }, (user) ->
context.partial('templates/profile.template', { user: user, date: formatDate(user.joindate) })
# Login box
@get '#/login', (context) ->
@partial('templates/login.template').then ->
$('#password').keypress (event) ->
return unless event.which == 13
event.preventDefault()
$.post '/login', { login: $('#login').val(), password: $('#PI:PASSWORD:<PASSWORD>END_PI').val() }, (data) ->
context.log data
switch data.result
when "failure"
context.log "Log-in failed!"
when "success"
context.log "Log-in succeeded!"
context.session('user', data.user)
context.session('token', data.session_token)
context.redirect('#/')
@get '#/logout', (context) ->
$('.user-info').fadeOut()
$.post '/logout', { token: @session('token') }, (data) ->
context.log 'Logged out gracefully!'
# Note that if we don't, it's no biggie. Token
# will end up expiring anyways.
@session('user', null)
@session('token', null)
# Couldn't find a good way to clear, nulling works just as fine
@redirect('#/login')
# Category list
@get '#/', (context) ->
@partial('templates/home.template')
@trigger 'render-all', {
path: 'categories?token=' + @session('token')
template: 'templates/category-summary.template'
name: 'category'
target: '.categories'
}
# Thread list in a category
@get '#/r/:slug', (context) ->
@slug = @params['slug']
$.get '/category/' + @slug, { token: @session('token') }, (category) ->
context.partial 'templates/category.template', { category: category }
context.render('templates/new-thread.template', { post: { user: context.user, category: category._id }}).prependTo('.threads').then ->
@trigger 'setup-thread-opener'
@trigger 'setup-post-editor'
render0 = (index) ->
if index < category.threads.length
thread = category.threads[category.threads.length - 1 - index]
thread.category = category
context.render('templates/thread-summary.template', { thread: thread }).then (threadnode) ->
$(threadnode).appendTo('.threads')
render0(index + 1)
render0(0)
# Message list in a thread
@get '#/r/:slug/:tid', (context) ->
tid = @params['tid']
$.ajax({
url: '/thread/' + tid
data: { token: @session( 'token' ) }
dataType: 'json'
success: (thread) ->
context.partial('templates/thread.template', {thread: thread}).then ->
render0 = (index) ->
if index < thread.posts.length
post = thread.posts[index]
content = showdown.makeHtml(post.source)
context.getUser post.username, (postUser) ->
context.render('templates/post.template', {post: {content: content, date: formatDate(post.date), user: postUser}}).then (post) ->
$(post).appendTo('.thread')
render0(index + 1)
else
context.render('templates/post-reply.template', {post: {user: context.user, tid: tid}}).then (post) ->
$(post).appendTo('.thread')
@trigger 'setup-post-editor'
$('.submit-post').click ->
context.trigger 'post-reply', { context: context }
render0(0)
})
@bind 'setup-thread-opener', ->
context = @
$('.post-title').blur ->
if $(this).val() == ""
$('.new-post').slideUp()
$('.post-title').focus ->
newpost = $('.new-post')
if newpost.css('display') == 'none'
$('.new-post').hide().css('height', '0px').show().animate({height: '191px'})
$('.submit-post').click ->
context.trigger 'new-thread'
@bind 'setup-post-editor', ->
context = @
$('.post-source').blur ->
source = $(this)
source.hide()
preview = source.parent().children('.post-preview')
preview.html(showdown.makeHtml(source.val())).show()
$('.post-preview').click ->
preview = $(this)
preview.hide()
source = preview.parent().children('.post-source')
source.show().focus()
@bind 'post-reply', (context) ->
context = @
tid = $('.reply-thread').val()
$.post '/post-reply', {
username: @user.username
tid: tid
source: $('.post-source').val()
token: @session('token')
}, (data) ->
content = showdown.makeHtml($('.post-source').val())
context.render('templates/post.template', {post: {content: content, user: context.user, date: formatDate(data.date)}}).then (postnode) ->
$(postnode).hide().appendTo('.thread').slideDown()
$('.new-post').detach().appendTo('.thread')
$('.post-preview').click()
$('.post-source').val('')
@bind 'new-thread', (context) ->
context = @
category = $('.post-category').val()
title = $('.post-title').val()
$.post '/new-thread', {
username: @user.username
category: category
title: title
source: $('.post-source').val()
token: @session( 'token' )
}, (data) ->
title = $('.new-header .post-title').val()
context.log title
$('.new-header, .new-post').remove()
context.render('templates/thread-summary.template', { thread: { category: { slug: context.slug }, _id: data.id, title: title } }).then (postnode) ->
$(postnode).hide().prependTo('.threads').slideDown()
context.render('templates/new-thread.template', { post: { user: context.user, category: category }}).prependTo('.threads').then ->
@trigger 'setup-thread-opener'
@trigger 'setup-post-editor'
$ -> app.run '#/'
|
[
{
"context": " repo: repo\n user:\n name: 'JsJob bot'\n email: 'bot@thegrid.io'\n ",
"end": 1046,
"score": 0.7413568496704102,
"start": 1044,
"tag": "NAME",
"value": "Js"
},
{
"context": " repo: repo\n user:\n name: 'JsJob bo... | Gruntfile.coffee | flowhubio/jsjob | 10 | module.exports = ->
pkg = @file.readJSON 'package.json'
repo = pkg.repository.url.replace 'git://', 'https://'+process.env.GH_TOKEN+'@'
# Project configuration
@initConfig
pkg: @file.readJSON 'package.json'
# BDD tests on Node.js
mochaTest:
nodejs:
src: ['spec/*.coffee']
options:
reporter: 'spec'
grep: process.env.TESTS
# Coding standards
coffeelint:
components:
files:
src: [
'components/*.coffee'
'lib/*.coffee'
]
options:
max_line_length:
value: 120
level: 'warn'
# Web server serving design systems used by ExternalSolver
connect:
server:
options:
port: 8001
exec:
sudoku: './node_modules/.bin/webpack examples/sudoku.js dist/examples/sudoku.js'
'gh-pages':
options:
base: 'dist'
clone: 'gh-pages'
message: 'Deploying dist/ to gh-pages'
repo: repo
user:
name: 'JsJob bot'
email: 'bot@thegrid.io'
silent: true
src: '**/*'
# Grunt plugins used for building
@loadNpmTasks 'grunt-exec'
# Grunt plugins used for testing
@loadNpmTasks 'grunt-mocha-test'
@loadNpmTasks 'grunt-coffeelint'
@loadNpmTasks 'grunt-contrib-connect'
# Grunt plugins used for deploying
@loadNpmTasks 'grunt-gh-pages'
# Our local tasks
@registerTask 'build', ['exec']
@registerTask 'test', 'Build and run automated tests', (target = 'all') =>
@task.run 'build'
@task.run 'coffeelint'
@task.run 'connect'
@task.run 'mochaTest'
@registerTask 'default', ['test']
| 188473 | module.exports = ->
pkg = @file.readJSON 'package.json'
repo = pkg.repository.url.replace 'git://', 'https://'+process.env.GH_TOKEN+'@'
# Project configuration
@initConfig
pkg: @file.readJSON 'package.json'
# BDD tests on Node.js
mochaTest:
nodejs:
src: ['spec/*.coffee']
options:
reporter: 'spec'
grep: process.env.TESTS
# Coding standards
coffeelint:
components:
files:
src: [
'components/*.coffee'
'lib/*.coffee'
]
options:
max_line_length:
value: 120
level: 'warn'
# Web server serving design systems used by ExternalSolver
connect:
server:
options:
port: 8001
exec:
sudoku: './node_modules/.bin/webpack examples/sudoku.js dist/examples/sudoku.js'
'gh-pages':
options:
base: 'dist'
clone: 'gh-pages'
message: 'Deploying dist/ to gh-pages'
repo: repo
user:
name: '<NAME>Job bot'
email: '<EMAIL>'
silent: true
src: '**/*'
# Grunt plugins used for building
@loadNpmTasks 'grunt-exec'
# Grunt plugins used for testing
@loadNpmTasks 'grunt-mocha-test'
@loadNpmTasks 'grunt-coffeelint'
@loadNpmTasks 'grunt-contrib-connect'
# Grunt plugins used for deploying
@loadNpmTasks 'grunt-gh-pages'
# Our local tasks
@registerTask 'build', ['exec']
@registerTask 'test', 'Build and run automated tests', (target = 'all') =>
@task.run 'build'
@task.run 'coffeelint'
@task.run 'connect'
@task.run 'mochaTest'
@registerTask 'default', ['test']
| true | module.exports = ->
pkg = @file.readJSON 'package.json'
repo = pkg.repository.url.replace 'git://', 'https://'+process.env.GH_TOKEN+'@'
# Project configuration
@initConfig
pkg: @file.readJSON 'package.json'
# BDD tests on Node.js
mochaTest:
nodejs:
src: ['spec/*.coffee']
options:
reporter: 'spec'
grep: process.env.TESTS
# Coding standards
coffeelint:
components:
files:
src: [
'components/*.coffee'
'lib/*.coffee'
]
options:
max_line_length:
value: 120
level: 'warn'
# Web server serving design systems used by ExternalSolver
connect:
server:
options:
port: 8001
exec:
sudoku: './node_modules/.bin/webpack examples/sudoku.js dist/examples/sudoku.js'
'gh-pages':
options:
base: 'dist'
clone: 'gh-pages'
message: 'Deploying dist/ to gh-pages'
repo: repo
user:
name: 'PI:NAME:<NAME>END_PIJob bot'
email: 'PI:EMAIL:<EMAIL>END_PI'
silent: true
src: '**/*'
# Grunt plugins used for building
@loadNpmTasks 'grunt-exec'
# Grunt plugins used for testing
@loadNpmTasks 'grunt-mocha-test'
@loadNpmTasks 'grunt-coffeelint'
@loadNpmTasks 'grunt-contrib-connect'
# Grunt plugins used for deploying
@loadNpmTasks 'grunt-gh-pages'
# Our local tasks
@registerTask 'build', ['exec']
@registerTask 'test', 'Build and run automated tests', (target = 'all') =>
@task.run 'build'
@task.run 'coffeelint'
@task.run 'connect'
@task.run 'mochaTest'
@registerTask 'default', ['test']
|
[
{
"context": "res) ->\n email = req.body?.email\n password = req.body?.password\n if not email? or not password?\n res.json",
"end": 678,
"score": 0.9258362054824829,
"start": 660,
"tag": "PASSWORD",
"value": "req.body?.password"
},
{
"context": "ser.findOne\n em... | src/routes/index.coffee | ArmedGuy/sharecal | 0 | token = require 'rand-token'
user = require './user'
event = require './event'
module.exports = (app) ->
# Models
User = app.locals.model.users
# Update user info on every request
app.use (req, res, next) ->
if req.session.loggedIn and req.session.userId?
User.findOne _id: req.session.userId, (err, user) ->
req.session.user = user if not err? and user?
next()
else
next()
# Public endpoints
# return session
app.get '/session', (req, res) ->
res.json loggedIn: req.session.loggedIn? and req.session.loggedIn
# Login user
app.post '/login', (req, res) ->
email = req.body?.email
password = req.body?.password
if not email? or not password?
res.json error: true, message: "Missing email or password"
else
User.findOne
email: email
password: password,
(err, user) ->
if err or not user
res.json error: true, message: "Failed to log in, please try again"
else
req.session.loggedIn = true
req.session.userId = user._id
res.json loggedIn: true
# Log user out
app.post '/logout', (req, res) ->
if req.session.loggedIn
req.session.destroy (err) ->
res.json loggedOut: not err?
else
res.json error: true, message: "Must be logged in to log out"
# Register new user
app.post '/register', (req, res) ->
if req.body?
u = new User req.body
u.token = token.generate(16)
u.save (err) ->
if err
res.json error: true, message: err.message
else
req.session.loggedIn = true
req.session.userId = u._id
res.json registered: true
else
res.json error: true, message: "Missing information to register"
# Everything below this is private
app.use (req, res, next) ->
return next() if req.method == 'GET' # allow all get requests for now
if req.session.loggedIn then next() else res.json error: true, message: "Not logged in"
# Router files
user app
event app
# Get ICal
app.get '/share/:cal_ident.ics', (req, res) ->
raw = req.params.cal_ident.replace(/_/g, '/') + "=="
data = (new Buffer raw, 'base64').toString()
res.end data
| 157269 | token = require 'rand-token'
user = require './user'
event = require './event'
module.exports = (app) ->
# Models
User = app.locals.model.users
# Update user info on every request
app.use (req, res, next) ->
if req.session.loggedIn and req.session.userId?
User.findOne _id: req.session.userId, (err, user) ->
req.session.user = user if not err? and user?
next()
else
next()
# Public endpoints
# return session
app.get '/session', (req, res) ->
res.json loggedIn: req.session.loggedIn? and req.session.loggedIn
# Login user
app.post '/login', (req, res) ->
email = req.body?.email
password = <PASSWORD>
if not email? or not password?
res.json error: true, message: "Missing email or password"
else
User.findOne
email: email
password: <PASSWORD>,
(err, user) ->
if err or not user
res.json error: true, message: "Failed to log in, please try again"
else
req.session.loggedIn = true
req.session.userId = user._id
res.json loggedIn: true
# Log user out
app.post '/logout', (req, res) ->
if req.session.loggedIn
req.session.destroy (err) ->
res.json loggedOut: not err?
else
res.json error: true, message: "Must be logged in to log out"
# Register new user
app.post '/register', (req, res) ->
if req.body?
u = new User req.body
u.token = token.generate(16)
u.save (err) ->
if err
res.json error: true, message: err.message
else
req.session.loggedIn = true
req.session.userId = u._id
res.json registered: true
else
res.json error: true, message: "Missing information to register"
# Everything below this is private
app.use (req, res, next) ->
return next() if req.method == 'GET' # allow all get requests for now
if req.session.loggedIn then next() else res.json error: true, message: "Not logged in"
# Router files
user app
event app
# Get ICal
app.get '/share/:cal_ident.ics', (req, res) ->
raw = req.params.cal_ident.replace(/_/g, '/') + "=="
data = (new Buffer raw, 'base64').toString()
res.end data
| true | token = require 'rand-token'
user = require './user'
event = require './event'
module.exports = (app) ->
# Models
User = app.locals.model.users
# Update user info on every request
app.use (req, res, next) ->
if req.session.loggedIn and req.session.userId?
User.findOne _id: req.session.userId, (err, user) ->
req.session.user = user if not err? and user?
next()
else
next()
# Public endpoints
# return session
app.get '/session', (req, res) ->
res.json loggedIn: req.session.loggedIn? and req.session.loggedIn
# Login user
app.post '/login', (req, res) ->
email = req.body?.email
password = PI:PASSWORD:<PASSWORD>END_PI
if not email? or not password?
res.json error: true, message: "Missing email or password"
else
User.findOne
email: email
password: PI:PASSWORD:<PASSWORD>END_PI,
(err, user) ->
if err or not user
res.json error: true, message: "Failed to log in, please try again"
else
req.session.loggedIn = true
req.session.userId = user._id
res.json loggedIn: true
# Log user out
app.post '/logout', (req, res) ->
if req.session.loggedIn
req.session.destroy (err) ->
res.json loggedOut: not err?
else
res.json error: true, message: "Must be logged in to log out"
# Register new user
app.post '/register', (req, res) ->
if req.body?
u = new User req.body
u.token = token.generate(16)
u.save (err) ->
if err
res.json error: true, message: err.message
else
req.session.loggedIn = true
req.session.userId = u._id
res.json registered: true
else
res.json error: true, message: "Missing information to register"
# Everything below this is private
app.use (req, res, next) ->
return next() if req.method == 'GET' # allow all get requests for now
if req.session.loggedIn then next() else res.json error: true, message: "Not logged in"
# Router files
user app
event app
# Get ICal
app.get '/share/:cal_ident.ics', (req, res) ->
raw = req.params.cal_ident.replace(/_/g, '/') + "=="
data = (new Buffer raw, 'base64').toString()
res.end data
|
[
{
"context": "e...'\n\nfps = parseInt process.argv[2], 10\n\ntoken = \"#{new Date().getTime()}\"\n\nopt = {\n method: 'POST'\n host: 'localhost'\n ",
"end": 184,
"score": 0.9774345755577087,
"start": 161,
"tag": "KEY",
"value": "\"#{new Date().getTime()"
}
] | upload.coffee | andrewschaaf/media-client-mac | 1 |
fs = require 'fs'
http = require 'http'
{spawn} = require 'child_process'
console.log 'Starting upload.coffee...'
fps = parseInt process.argv[2], 10
token = "#{new Date().getTime()}"
opt = {
method: 'POST'
host: 'localhost'
port: 3000
path: "/stream/#{token}/upload/"
}
req = http.request opt, (res) ->
console.log 'got upload response'
p = spawn '/usr/local/bin/ffmpeg', [
'-r', "#{fps}",
'-f', 'image2pipe',
'-vcodec', 'ppm',
'-i', '-',
'-vcodec', 'libx264',
'-f', 'mpegts',
'-'
]
console.log "*** PID #{p.pid}"
process.stdin.resume()
process.stdin.pipe p.stdin
p.on 'exit', () ->
console.log '**** ffmpeg exited'
console.log 'Started.'
p.stdout.pipe req
| 111617 |
fs = require 'fs'
http = require 'http'
{spawn} = require 'child_process'
console.log 'Starting upload.coffee...'
fps = parseInt process.argv[2], 10
token = <KEY>}"
opt = {
method: 'POST'
host: 'localhost'
port: 3000
path: "/stream/#{token}/upload/"
}
req = http.request opt, (res) ->
console.log 'got upload response'
p = spawn '/usr/local/bin/ffmpeg', [
'-r', "#{fps}",
'-f', 'image2pipe',
'-vcodec', 'ppm',
'-i', '-',
'-vcodec', 'libx264',
'-f', 'mpegts',
'-'
]
console.log "*** PID #{p.pid}"
process.stdin.resume()
process.stdin.pipe p.stdin
p.on 'exit', () ->
console.log '**** ffmpeg exited'
console.log 'Started.'
p.stdout.pipe req
| true |
fs = require 'fs'
http = require 'http'
{spawn} = require 'child_process'
console.log 'Starting upload.coffee...'
fps = parseInt process.argv[2], 10
token = PI:KEY:<KEY>END_PI}"
opt = {
method: 'POST'
host: 'localhost'
port: 3000
path: "/stream/#{token}/upload/"
}
req = http.request opt, (res) ->
console.log 'got upload response'
p = spawn '/usr/local/bin/ffmpeg', [
'-r', "#{fps}",
'-f', 'image2pipe',
'-vcodec', 'ppm',
'-i', '-',
'-vcodec', 'libx264',
'-f', 'mpegts',
'-'
]
console.log "*** PID #{p.pid}"
process.stdin.resume()
process.stdin.pipe p.stdin
p.on 'exit', () ->
console.log '**** ffmpeg exited'
console.log 'Started.'
p.stdout.pipe req
|
[
{
"context": "###:\n * @plugindesc Unity Ads Plugin\n * @author Dan Yamamoto\n * @license MIT\n *\n * @param gameID\n * @desc Game",
"end": 60,
"score": 0.9998752474784851,
"start": 48,
"tag": "NAME",
"value": "Dan Yamamoto"
}
] | js/plugins/UnityAdsMV.coffee | dan5/tkoolmv | 1 | ###:
* @plugindesc Unity Ads Plugin
* @author Dan Yamamoto
* @license MIT
*
* @param gameID
* @desc Game ID
* @default 42517
*
* @param videoAdPlacementId
* @desc Video Ad Placement Id
* @default defaultZone
*
* @param rewardedVideoAdPlacementId
* @desc Rewarded Video Ad Placement Id
* @default rewardedVideoZone
*
* @param isTest
* @desc Ipunt 'true' or 'false'
* @default true
*
####
parameters = PluginManager.parameters('UnityAdsMV')
gameId = String(parameters['gameId'] || '42517')
videoAdPlacementId = String(parameters['videoAdPlacementId'] || 'defaultZone')
rewardedVideoAdPlacementId = String(parameters['rewardedVideoAdPlacementId'] || 'rewardedVideoZone')
isTest = !parameters['isTest'].match(/^\s*(0|off|false)?\s*$/i)
unless window.unityads?
window.unityads =
showVideoAd: ->
showRewardedVideoAd: ->
loadedVideoAd: -> false
loadedRewardedVideoAd: -> false
isShowingVideoAd: -> false
isShowingRewardedVideoAd: -> false
class CordovaUnityAdsMV
constructor: ->
@status = null
@has_reward = false
showVideoAd: ->
if @loadedVideoAd()
window.unityads.showVideoAd()
@status = 'isReady'
else
console.log 'not loadedVideoAd'
showRewardedVideoAd: ->
unless window.unityads?
window.unityads =
showVideoAd: ->
showRewardedVideoAd: ->
loadedVideoAd: -> false
loadedRewardedVideoAd: -> false
isShowingVideoAd: -> false
isShowingRewardedVideoAd: -> false
class CordovaUnityAdsMV
constructor: ->
@status = null
@has_reward = false
isShowing: -> @status != null
hasReward: -> @has_reward
clearReward: -> @has_reward = false
showVideoAd: ->
if @loadedVideoAd()
window.unityads.showVideoAd()
@status = 'isReady'
else
console.log 'not loadedVideoAd'
showRewardedVideoAd: ->
if @loadedRewardedVideoAd()
window.unityads.showRewardedVideoAd()
@status = 'isReady'
else
console.log 'not loadedRewardedVideoAd'
loadedVideoAd: -> window.unityads.loadedVideoAd()
loadedRewardedVideoAd: -> window.unityads.loadedRewardedVideoAd()
isShowingVideoAd: -> window.unityads.isShowingVideoAd()
isShowingRewardedVideoAd: -> window.unityads.isShowingRewardedVideoAd()
window.UnityAdsMV = new CordovaUnityAdsMV()
setup = ->
window.unityads.setUp gameId, videoAdPlacementId, rewardedVideoAdPlacementId, isTest
window.unityads.onVideoAdLoaded = ->
isTest and console.log 'onVideoAdLoaded'
window.unityads.onVideoAdShown = ->
window.UnityAdsMV.status = 'isShowing'
isTest and console.log 'onVideoAdShown'
window.unityads.onVideoAdHidden = ->
window.UnityAdsMV.status = null
isTest and console.log 'onVideoAdHidden'
window.unityads.onRewardedVideoAdLoaded = ->
isTest and console.log 'onRewardedVideoAdLoaded'
window.unityads.onRewardedVideoAdShown = ->
window.UnityAdsMV.status = 'isShowing'
isTest and console.log 'onRewardedVideoAdShown'
window.unityads.onRewardedVideoAdHidden = ->
window.UnityAdsMV.status = null
isTest and console.log 'onRewardedVideoAdHidden'
window.unityads.onRewardedVideoAdCompleted = ->
@has_reward = true
isTest and console.log 'onRewardedVideoAdCompleted'
document.addEventListener "deviceready", setup, false
| 197578 | ###:
* @plugindesc Unity Ads Plugin
* @author <NAME>
* @license MIT
*
* @param gameID
* @desc Game ID
* @default 42517
*
* @param videoAdPlacementId
* @desc Video Ad Placement Id
* @default defaultZone
*
* @param rewardedVideoAdPlacementId
* @desc Rewarded Video Ad Placement Id
* @default rewardedVideoZone
*
* @param isTest
* @desc Ipunt 'true' or 'false'
* @default true
*
####
parameters = PluginManager.parameters('UnityAdsMV')
gameId = String(parameters['gameId'] || '42517')
videoAdPlacementId = String(parameters['videoAdPlacementId'] || 'defaultZone')
rewardedVideoAdPlacementId = String(parameters['rewardedVideoAdPlacementId'] || 'rewardedVideoZone')
isTest = !parameters['isTest'].match(/^\s*(0|off|false)?\s*$/i)
unless window.unityads?
window.unityads =
showVideoAd: ->
showRewardedVideoAd: ->
loadedVideoAd: -> false
loadedRewardedVideoAd: -> false
isShowingVideoAd: -> false
isShowingRewardedVideoAd: -> false
class CordovaUnityAdsMV
constructor: ->
@status = null
@has_reward = false
showVideoAd: ->
if @loadedVideoAd()
window.unityads.showVideoAd()
@status = 'isReady'
else
console.log 'not loadedVideoAd'
showRewardedVideoAd: ->
unless window.unityads?
window.unityads =
showVideoAd: ->
showRewardedVideoAd: ->
loadedVideoAd: -> false
loadedRewardedVideoAd: -> false
isShowingVideoAd: -> false
isShowingRewardedVideoAd: -> false
class CordovaUnityAdsMV
constructor: ->
@status = null
@has_reward = false
isShowing: -> @status != null
hasReward: -> @has_reward
clearReward: -> @has_reward = false
showVideoAd: ->
if @loadedVideoAd()
window.unityads.showVideoAd()
@status = 'isReady'
else
console.log 'not loadedVideoAd'
showRewardedVideoAd: ->
if @loadedRewardedVideoAd()
window.unityads.showRewardedVideoAd()
@status = 'isReady'
else
console.log 'not loadedRewardedVideoAd'
loadedVideoAd: -> window.unityads.loadedVideoAd()
loadedRewardedVideoAd: -> window.unityads.loadedRewardedVideoAd()
isShowingVideoAd: -> window.unityads.isShowingVideoAd()
isShowingRewardedVideoAd: -> window.unityads.isShowingRewardedVideoAd()
window.UnityAdsMV = new CordovaUnityAdsMV()
setup = ->
window.unityads.setUp gameId, videoAdPlacementId, rewardedVideoAdPlacementId, isTest
window.unityads.onVideoAdLoaded = ->
isTest and console.log 'onVideoAdLoaded'
window.unityads.onVideoAdShown = ->
window.UnityAdsMV.status = 'isShowing'
isTest and console.log 'onVideoAdShown'
window.unityads.onVideoAdHidden = ->
window.UnityAdsMV.status = null
isTest and console.log 'onVideoAdHidden'
window.unityads.onRewardedVideoAdLoaded = ->
isTest and console.log 'onRewardedVideoAdLoaded'
window.unityads.onRewardedVideoAdShown = ->
window.UnityAdsMV.status = 'isShowing'
isTest and console.log 'onRewardedVideoAdShown'
window.unityads.onRewardedVideoAdHidden = ->
window.UnityAdsMV.status = null
isTest and console.log 'onRewardedVideoAdHidden'
window.unityads.onRewardedVideoAdCompleted = ->
@has_reward = true
isTest and console.log 'onRewardedVideoAdCompleted'
document.addEventListener "deviceready", setup, false
| true | ###:
* @plugindesc Unity Ads Plugin
* @author PI:NAME:<NAME>END_PI
* @license MIT
*
* @param gameID
* @desc Game ID
* @default 42517
*
* @param videoAdPlacementId
* @desc Video Ad Placement Id
* @default defaultZone
*
* @param rewardedVideoAdPlacementId
* @desc Rewarded Video Ad Placement Id
* @default rewardedVideoZone
*
* @param isTest
* @desc Ipunt 'true' or 'false'
* @default true
*
####
parameters = PluginManager.parameters('UnityAdsMV')
gameId = String(parameters['gameId'] || '42517')
videoAdPlacementId = String(parameters['videoAdPlacementId'] || 'defaultZone')
rewardedVideoAdPlacementId = String(parameters['rewardedVideoAdPlacementId'] || 'rewardedVideoZone')
isTest = !parameters['isTest'].match(/^\s*(0|off|false)?\s*$/i)
unless window.unityads?
window.unityads =
showVideoAd: ->
showRewardedVideoAd: ->
loadedVideoAd: -> false
loadedRewardedVideoAd: -> false
isShowingVideoAd: -> false
isShowingRewardedVideoAd: -> false
class CordovaUnityAdsMV
constructor: ->
@status = null
@has_reward = false
showVideoAd: ->
if @loadedVideoAd()
window.unityads.showVideoAd()
@status = 'isReady'
else
console.log 'not loadedVideoAd'
showRewardedVideoAd: ->
unless window.unityads?
window.unityads =
showVideoAd: ->
showRewardedVideoAd: ->
loadedVideoAd: -> false
loadedRewardedVideoAd: -> false
isShowingVideoAd: -> false
isShowingRewardedVideoAd: -> false
class CordovaUnityAdsMV
constructor: ->
@status = null
@has_reward = false
isShowing: -> @status != null
hasReward: -> @has_reward
clearReward: -> @has_reward = false
showVideoAd: ->
if @loadedVideoAd()
window.unityads.showVideoAd()
@status = 'isReady'
else
console.log 'not loadedVideoAd'
showRewardedVideoAd: ->
if @loadedRewardedVideoAd()
window.unityads.showRewardedVideoAd()
@status = 'isReady'
else
console.log 'not loadedRewardedVideoAd'
loadedVideoAd: -> window.unityads.loadedVideoAd()
loadedRewardedVideoAd: -> window.unityads.loadedRewardedVideoAd()
isShowingVideoAd: -> window.unityads.isShowingVideoAd()
isShowingRewardedVideoAd: -> window.unityads.isShowingRewardedVideoAd()
window.UnityAdsMV = new CordovaUnityAdsMV()
setup = ->
window.unityads.setUp gameId, videoAdPlacementId, rewardedVideoAdPlacementId, isTest
window.unityads.onVideoAdLoaded = ->
isTest and console.log 'onVideoAdLoaded'
window.unityads.onVideoAdShown = ->
window.UnityAdsMV.status = 'isShowing'
isTest and console.log 'onVideoAdShown'
window.unityads.onVideoAdHidden = ->
window.UnityAdsMV.status = null
isTest and console.log 'onVideoAdHidden'
window.unityads.onRewardedVideoAdLoaded = ->
isTest and console.log 'onRewardedVideoAdLoaded'
window.unityads.onRewardedVideoAdShown = ->
window.UnityAdsMV.status = 'isShowing'
isTest and console.log 'onRewardedVideoAdShown'
window.unityads.onRewardedVideoAdHidden = ->
window.UnityAdsMV.status = null
isTest and console.log 'onRewardedVideoAdHidden'
window.unityads.onRewardedVideoAdCompleted = ->
@has_reward = true
isTest and console.log 'onRewardedVideoAdCompleted'
document.addEventListener "deviceready", setup, false
|
[
{
"context": "# Copyright (c) 2018 Natalie Marleny\n# Casing - UI framework for Framer\n# License: MIT",
"end": 36,
"score": 0.9998876452445984,
"start": 21,
"tag": "NAME",
"value": "Natalie Marleny"
},
{
"context": "r Framer\n# License: MIT\n# URL: https://github.com/nataliemarleny/... | FrmrDatePicker.coffee | nataliemarleny/Casing | 84 | # Copyright (c) 2018 Natalie Marleny
# Casing - UI framework for Framer
# License: MIT
# URL: https://github.com/nataliemarleny/Casing
Utils.loadWebFont("Rubik")
# Utility functinos for manipulating dates
Date.prototype.addDays = (deltaDays) ->
return new Date(
@getFullYear(),
@getMonth(),
@getDate() + deltaDays,
)
Date.prototype.addMonths = (deltaMonths) ->
return new Date(
@getFullYear(),
@getMonth() + deltaMonths,
)
# Utility arrays
monthNames = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
]
exports.monthNames = monthNames
monthNamesUppercase = [
"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
]
exports.monthNamesUppercase = monthNamesUppercase
monthAbbrevsUppercase = [
"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
]
exports.monthAbbrevsUppercase = monthAbbrevsUppercase
monthAbbrevsLowercase = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]
exports.monthAbbrevsLowercase = monthAbbrevsLowercase
dayAbbrevs = [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
]
exports.dayAbbrevs = dayAbbrevs
class exports.FrmrDatePicker extends Layer
constructor: (options = {}) ->
# CONFIGURATION
defaults =
enabled: true
numberOfMonthsShow: 1
firstColumnDay: 1
startDateShow: new Date(Date.now())
dateRangeSelectedStart: undefined
dateRangeSelectedEnd: undefined
hoverEnabled: true
dateRangeSelectable: false # if false only single date is selectable
outsideMonthDatesShow: false
buttonNextShow: true
buttonPrevShow: true
highlightDateRanges: [
# {
# dateRangeStart: new Date(2018, 5, 5)
# dateRangeEnd: new Date(2018, 5, 8)
# dateExtraStyle:
# backgroundColor: "red"
# color: "white"
# }
]
handleMonthsShowChange: (previousStartDateShow, currentStartDateShow) ->
undefined
handleDateRangeSelectedChange: (
previousDateRangeSelectedStart
previousDateRangeSelectedEnd
currentDateRangeSelectedStart
currentDateRangeSelectedEnd
) ->
undefined
monthsBoxStyle:
backgroundColor: "#ffffff"
width: 277 * (options.numberOfMonthsShow or 1)
height: 285
borderWidth: 1
borderRadius: 6
borderColor: "#E9ECF0"
padding:
top: 3
bottom: 0
left: 15
right: 15
monthHeaderStyle:
height: 36
backgroundColor: "transparent"
color: "#3C444D"
textAlign: "center"
fontSize: 18
fontStyle: "bold"
fontFamily: "-apple-system"
padding:
vertical: 0
left: 3
right: 3
weekHeaderStyle:
height: 36
backgroundColor: "transparent"
color: "#3C444D"
textAlign: "center"
fontSize: 12
fontFamily: "-apple-system"
padding:
vertical: 1
datesBoxStyle:
backgroundColor: "transparent"
color: "#3C444D"
padding:
top: 3
bottom: 0
left: 20
right: 20
buttonsStyle:
fontSize: 12
dateBaseStyle:
color: "#3C444D"
backgroundColor: "transparent"
borderColor: "#e6e6e6"
borderWidth: 1
borderRadius: 1
textAlign: "center"
fontSize: 12
fontFamily: "-apple-system"
padding:
vertical: 6
margin:
top: 0
bottom: -1
left: 0
right: -1
dateSelectedExtraStyle:
backgroundColor: "#3C444D"
color: "white"
dateHoveredExtraStyle:
backgroundColor: "#cccccc"
color: "white"
dateOutsideMonthExtraStyle:
opacity: 0.25
# assign all configuration to the object as properties
configs_passed = _.pick options, _.keys defaults
_.assign @, (_.merge {}, defaults, configs_passed)
# FIXED STYLES
options.backgroundColor = @monthsBoxStyle.backgroundColor
options.width = @monthsBoxStyle.width
options.height = @monthsBoxStyle.height
super options
# LAYER STORAGE
@dateCellBoxLayerDict = {}
@topContainerLayer = new Layer(
_.merge(
{}
@monthsBoxStyle
{parent: @}
)
)
# RENDERING
@_clean()
@_render()
_render: () ->
@isolatorLayer = new Layer(
_.merge(
{}
@topContainerLayer.frame
{
backgroundColor: "transparent"
parent: @topContainerLayer
}
)
)
monthsBoxLayer = new Layer
backgroundColor: "transparent"
parent: @isolatorLayer
x: @monthsBoxStyle.padding.left
y: @monthsBoxStyle.padding.top
width: (
@isolatorLayer.width +
(-@monthsBoxStyle.padding.left) +
(-@monthsBoxStyle.padding.right)
)
height: (
@isolatorLayer.height +
(-@monthsBoxStyle.padding.top) +
(- @monthsBoxStyle.padding.bottom)
)
for monthIndex in [0...@numberOfMonthsShow]
# SECTION: month
monthLayer = new Layer(
_.merge(
{}
@datesBoxStyle,
{
parent: monthsBoxLayer
x: monthIndex * (monthsBoxLayer.width / @numberOfMonthsShow)
y: 0
width: (monthsBoxLayer.width / @numberOfMonthsShow)
height: monthsBoxLayer.height
}
)
)
contentBoxLayer = new Layer
parent: monthLayer
backgroundColor: "transparent"
x: @datesBoxStyle.padding.left
y: @datesBoxStyle.padding.top
width: (
monthLayer.width +
(-@datesBoxStyle.padding.left) +
(-@datesBoxStyle.padding.right)
)
height: (
monthLayer.height +
(-@datesBoxStyle.padding.top) +
(-@datesBoxStyle.padding.bottom)
)
# SECTION: days rendering pre-calc
firstOfMonth = new Date(
@startDateShow.getFullYear(),
@startDateShow.getMonth() + monthIndex,
1
)
firstGridDate = new Date(firstOfMonth)
while firstGridDate.getDay() != @firstColumnDay
firstGridDate = firstGridDate.addDays(-1)
# SECTION: headers
monthHeaderLayer = new TextLayer(
_.merge(
{}
@monthHeaderStyle,
{
parent: contentBoxLayer
x: 0
y: 0
width: contentBoxLayer.width
text: "#{monthNamesUppercase[firstOfMonth.getMonth()]} #{firstOfMonth.getFullYear()}"
truncate: true
}
)
)
if (
monthIndex == 0 and
@buttonPrevShow
)
@btnPrevBoxLayer = new Layer
parent: monthHeaderLayer
backgroundColor: "transparent"
x: 0
y: 0
width: monthHeaderLayer.width / 4
height: monthHeaderLayer.height
btnPrevArrowLayer = new TextLayer
parent: @btnPrevBoxLayer
backgroundColor: "transparent"
x: 0
y: 0
width: @btnPrevBoxLayer.width / 3
height: @btnPrevBoxLayer.height
text: "<"
textAlign: "left"
color: "#3C444D"
# hacky...
fontSize: @buttonsStyle.fontSize * 2
fontFamily: "-apple-system"
padding:
vertical: (@btnPrevBoxLayer.height - 3*@buttonsStyle.fontSize) / 2
btnPrevLabelLayer = new TextLayer(
_.merge(
{}
@buttonsStyle
{
parent: @btnPrevBoxLayer
x: @btnPrevBoxLayer.width / 3
y: 0
width: @btnPrevBoxLayer.width * 2 / 3
height: @btnPrevBoxLayer.height
text: "#{monthAbbrevsUppercase[(firstOfMonth.getMonth() + 12 - 1) % 12]}"
textAlign: "left"
color: "#3C444D"
# hacky ...
padding:
vertical: (@btnPrevBoxLayer.height - 1.5*@buttonsStyle.fontSize) / 2
}
)
)
@btnPrevBoxLayer.onTap =>
@setStartDateShow @startDateShow.addMonths(-1)
if (
monthIndex == @numberOfMonthsShow - 1 and
@buttonNextShow
)
@btnNextBoxLayer = new Layer
parent: monthHeaderLayer
backgroundColor: "transparent"
x: monthHeaderLayer.width * 3 / 4
y: 0
width: monthHeaderLayer.width / 4
height: monthHeaderLayer.height
btnNextArrowLayer = new TextLayer
parent: @btnNextBoxLayer
backgroundColor: "transparent"
x: @btnNextBoxLayer.width * 2 / 3
y: 0
width: @btnNextBoxLayer.width / 3
height: @btnNextBoxLayer.height
text: ">"
color: "#3C444D"
textAlign: "right"
# hacky...
fontSize: @buttonsStyle.fontSize * 2
fontFamily: "-apple-system"
padding:
vertical: (@btnNextBoxLayer.height - 3*@buttonsStyle.fontSize) / 2
btnNextLabelLayer = new TextLayer(
_.merge(
{}
@buttonsStyle
{
parent: @btnNextBoxLayer
x: 0
y: 0
width: @btnNextBoxLayer.width * 2 / 3
height: @btnNextBoxLayer.height
text: "#{monthAbbrevsUppercase[(firstOfMonth.getMonth() + 1) % 12]}"
textAlign: "right"
color: "#3C444D"
# hacky ...
padding:
vertical: (@btnNextBoxLayer.height - 1.5*@buttonsStyle.fontSize) / 2
}
)
)
@btnNextBoxLayer.onTap =>
@setStartDateShow @startDateShow.addMonths(1)
weekHeaderLayer = new Layer
backgroundColor: "transparent"
x: 0
y: monthHeaderLayer.y + monthHeaderLayer.height
width: contentBoxLayer.width
height: @weekHeaderStyle.height
parent: contentBoxLayer
# Styling for weekHeaderLayer intentionally used for its children...
for dayIndex in [0...7]
new TextLayer(
_.merge(
{}
@weekHeaderStyle
{
x: dayIndex * (contentBoxLayer.width / 7)
y: 0
width: contentBoxLayer.width / 7
height: weekHeaderLayer.height
parent: weekHeaderLayer
text: "#{dayAbbrevs[(dayIndex + @firstColumnDay) % 7]}"
truncate: true
}
)
)
# SECTION: date cells
daysGridLayer = new Layer
backgroundColor: "transparent"
x: 0
y: weekHeaderLayer.y + weekHeaderLayer.height
width: contentBoxLayer.width
height: (
contentBoxLayer.height +
(-monthHeaderLayer.height) +
(-weekHeaderLayer.height) +
(-@datesBoxStyle.padding.top) +
(-@datesBoxStyle.padding.bottom)
)
parent: contentBoxLayer
dateRendering = firstGridDate
for row in [0...6]
for column in [0...7]
if (
@outsideMonthDatesShow or
dateRendering.getMonth() == firstOfMonth.getMonth()
)
isOutsideMonth = dateRendering.getMonth() != firstOfMonth.getMonth()
dateCellBoxLayer = new Layer
parent: daysGridLayer
backgroundColor: "transparent"
y: row * daysGridLayer.height / 6
x: column * daysGridLayer.width / 7
height: daysGridLayer.height / 6
width: daysGridLayer.width / 7
extraStyle = {}
if not isOutsideMonth
# add to the map addressable by date
@dateCellBoxLayerDict[dateRendering] = dateCellBoxLayer
# extra styles for highlight ranges
for highlighRange in @highlightDateRanges
if (
highlighRange.dateRangeStart <= dateRendering and
dateRendering <= highlighRange.dateRangeEnd
)
_.merge extraStyle, highlighRange.dateExtraStyle
else
# extra style for outside-month dates
extraStyle = @dateOutsideMonthExtraStyle
dateCellLayer = new TextLayer(
_.merge(
{}
@dateBaseStyle
{
parent: dateCellBoxLayer
x: @dateBaseStyle.margin.left
y: @dateBaseStyle.margin.top
width: (
dateCellBoxLayer.width +
(-@dateBaseStyle.margin.left) +
(-@dateBaseStyle.margin.right)
)
height: (
dateCellBoxLayer.height +
(-@dateBaseStyle.margin.top) +
(-@dateBaseStyle.margin.bottom)
)
text: "#{dateRendering.getDate()}"
}
extraStyle
)
)
dateCellBoxLayer.date = dateRendering
dateCellBoxLayer.dateCellLayer = dateCellLayer
if not isOutsideMonth
self = @
# Handle selecting
dateCellLayer.yesSelectedStyle = @dateSelectedExtraStyle
dateCellLayer.noSelectedStyle = _.pick dateCellLayer, _.keys @dateSelectedExtraStyle
do (dateCellBoxLayer, self) ->
dateCellBoxLayer.onTap () ->
if not self.enabled
return
if (
self.dateRangeSelectedStart == undefined or
not self.dateRangeSelectable
)
self.setDateRangeSelected(dateCellBoxLayer.date, dateCellBoxLayer.date)
return
if (self._nextChangeDateRangeStart or false)
self.setDateRangeSelected(self.dateRangeSelectedStart, dateCellBoxLayer.date)
else
self.setDateRangeSelected(dateCellBoxLayer.date, self.dateRangeSelectedEnd)
self._nextChangeDateRangeStart = not (self._nextChangeDateRangeStart or false)
# Handle hovering
if @hoverEnabled
dateCellLayer.yesHoveredStyle = @dateHoveredExtraStyle
dateCellLayer.noHoveredStyle = _.pick dateCellLayer, _.keys @dateHoveredExtraStyle
do (dateCellBoxLayer, dateCellLayer, self) ->
dateCellBoxLayer.on Events.MouseOver, (event, layer) ->
_.assign dateCellLayer, dateCellLayer.yesHoveredStyle
dateCellBoxLayer.on Events.MouseOut, (event, layer) ->
_.assign dateCellLayer, dateCellLayer.noHoveredStyle
if (self._isDateSelected(dateCellBoxLayer.date))
_.assign dateCellLayer, dateCellLayer.yesSelectedStyle
dateRendering = dateRendering.addDays(1)
# After the rendering, set the initial selected range
@setDateRangeSelected(@dateRangeSelectedStart, @dateRangeSelectedEnd, false)
_isDateSelected: (date) ->
return (
@dateRangeSelectedStart <= date and
date <= @dateRangeSelectedEnd
)
_clean: () ->
@isolatorLayer?.destroy()
# INTERFACE METHODS
getStartDateShow: () ->
return @startDateShow
setStartDateShow: (currentStartDateShow) ->
previousStartDateShow = @startDateShow
@startDateShow = currentStartDateShow
@_clean()
@_render()
@handleMonthsShowChange(previousStartDateShow, currentStartDateShow)
getDateRangeSelectedStart: () ->
return @dateRangeSelectedStart
getDateRangeSelectedEnd: () ->
return @dateRangeSelectedEnd
setDateRangeSelected: (currentDateRangeSelectedStart, currentDateRangeSelectedEnd, triggerHandler = true) ->
if currentDateRangeSelectedStart > currentDateRangeSelectedEnd
[currentDateRangeSelectedStart, currentDateRangeSelectedEnd] =
[currentDateRangeSelectedEnd, currentDateRangeSelectedStart]
previousDateRangeSelectedStart = @dateRangeSelectedStart
previousDateRangeSelectedEnd = @dateRangeSelectedEnd
# ... unselect previously selected
if (
previousDateRangeSelectedStart != undefined and
previousDateRangeSelectedEnd != undefined
)
currentDate = previousDateRangeSelectedStart
while currentDate <= previousDateRangeSelectedEnd
dateCellLayer = @dateCellBoxLayerDict[currentDate].dateCellLayer
_.assign dateCellLayer, dateCellLayer.noSelectedStyle
currentDate = currentDate.addDays(1)
# ... select currently selected
if (
currentDateRangeSelectedStart != undefined and
currentDateRangeSelectedEnd != undefined
)
currentDate = currentDateRangeSelectedStart
while currentDate <= currentDateRangeSelectedEnd
dateCellLayer = @dateCellBoxLayerDict[currentDate].dateCellLayer
_.assign dateCellLayer, dateCellLayer.yesSelectedStyle
currentDate = currentDate.addDays(1)
# ... update the newest state
@dateRangeSelectedStart = currentDateRangeSelectedStart
@dateRangeSelectedEnd = currentDateRangeSelectedEnd
# ... call the handler
if triggerHandler
@handleDateRangeSelectedChange(
previousDateRangeSelectedStart
previousDateRangeSelectedEnd
currentDateRangeSelectedStart
currentDateRangeSelectedEnd
)
getHighlightDateRanges: () ->
return @highlightDateRanges
setHighlightDateRanges: (highlightDateRanges) ->
@highlightDateRanges = highlightDateRanges
@_clean()
@_render()
setHandleMonthsShowChange: (handler) ->
@handleMonthsShowChange = handler
setHandleDateRangeSelectedChange: (handler) ->
@handleDateRangeSelectedChange = handler
| 147017 | # Copyright (c) 2018 <NAME>
# Casing - UI framework for Framer
# License: MIT
# URL: https://github.com/nataliemarleny/Casing
Utils.loadWebFont("Rubik")
# Utility functinos for manipulating dates
Date.prototype.addDays = (deltaDays) ->
return new Date(
@getFullYear(),
@getMonth(),
@getDate() + deltaDays,
)
Date.prototype.addMonths = (deltaMonths) ->
return new Date(
@getFullYear(),
@getMonth() + deltaMonths,
)
# Utility arrays
monthNames = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
]
exports.monthNames = monthNames
monthNamesUppercase = [
"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
]
exports.monthNamesUppercase = monthNamesUppercase
monthAbbrevsUppercase = [
"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
]
exports.monthAbbrevsUppercase = monthAbbrevsUppercase
monthAbbrevsLowercase = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]
exports.monthAbbrevsLowercase = monthAbbrevsLowercase
dayAbbrevs = [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
]
exports.dayAbbrevs = dayAbbrevs
class exports.FrmrDatePicker extends Layer
constructor: (options = {}) ->
# CONFIGURATION
defaults =
enabled: true
numberOfMonthsShow: 1
firstColumnDay: 1
startDateShow: new Date(Date.now())
dateRangeSelectedStart: undefined
dateRangeSelectedEnd: undefined
hoverEnabled: true
dateRangeSelectable: false # if false only single date is selectable
outsideMonthDatesShow: false
buttonNextShow: true
buttonPrevShow: true
highlightDateRanges: [
# {
# dateRangeStart: new Date(2018, 5, 5)
# dateRangeEnd: new Date(2018, 5, 8)
# dateExtraStyle:
# backgroundColor: "red"
# color: "white"
# }
]
handleMonthsShowChange: (previousStartDateShow, currentStartDateShow) ->
undefined
handleDateRangeSelectedChange: (
previousDateRangeSelectedStart
previousDateRangeSelectedEnd
currentDateRangeSelectedStart
currentDateRangeSelectedEnd
) ->
undefined
monthsBoxStyle:
backgroundColor: "#ffffff"
width: 277 * (options.numberOfMonthsShow or 1)
height: 285
borderWidth: 1
borderRadius: 6
borderColor: "#E9ECF0"
padding:
top: 3
bottom: 0
left: 15
right: 15
monthHeaderStyle:
height: 36
backgroundColor: "transparent"
color: "#3C444D"
textAlign: "center"
fontSize: 18
fontStyle: "bold"
fontFamily: "-apple-system"
padding:
vertical: 0
left: 3
right: 3
weekHeaderStyle:
height: 36
backgroundColor: "transparent"
color: "#3C444D"
textAlign: "center"
fontSize: 12
fontFamily: "-apple-system"
padding:
vertical: 1
datesBoxStyle:
backgroundColor: "transparent"
color: "#3C444D"
padding:
top: 3
bottom: 0
left: 20
right: 20
buttonsStyle:
fontSize: 12
dateBaseStyle:
color: "#3C444D"
backgroundColor: "transparent"
borderColor: "#e6e6e6"
borderWidth: 1
borderRadius: 1
textAlign: "center"
fontSize: 12
fontFamily: "-apple-system"
padding:
vertical: 6
margin:
top: 0
bottom: -1
left: 0
right: -1
dateSelectedExtraStyle:
backgroundColor: "#3C444D"
color: "white"
dateHoveredExtraStyle:
backgroundColor: "#cccccc"
color: "white"
dateOutsideMonthExtraStyle:
opacity: 0.25
# assign all configuration to the object as properties
configs_passed = _.pick options, _.keys defaults
_.assign @, (_.merge {}, defaults, configs_passed)
# FIXED STYLES
options.backgroundColor = @monthsBoxStyle.backgroundColor
options.width = @monthsBoxStyle.width
options.height = @monthsBoxStyle.height
super options
# LAYER STORAGE
@dateCellBoxLayerDict = {}
@topContainerLayer = new Layer(
_.merge(
{}
@monthsBoxStyle
{parent: @}
)
)
# RENDERING
@_clean()
@_render()
_render: () ->
@isolatorLayer = new Layer(
_.merge(
{}
@topContainerLayer.frame
{
backgroundColor: "transparent"
parent: @topContainerLayer
}
)
)
monthsBoxLayer = new Layer
backgroundColor: "transparent"
parent: @isolatorLayer
x: @monthsBoxStyle.padding.left
y: @monthsBoxStyle.padding.top
width: (
@isolatorLayer.width +
(-@monthsBoxStyle.padding.left) +
(-@monthsBoxStyle.padding.right)
)
height: (
@isolatorLayer.height +
(-@monthsBoxStyle.padding.top) +
(- @monthsBoxStyle.padding.bottom)
)
for monthIndex in [0...@numberOfMonthsShow]
# SECTION: month
monthLayer = new Layer(
_.merge(
{}
@datesBoxStyle,
{
parent: monthsBoxLayer
x: monthIndex * (monthsBoxLayer.width / @numberOfMonthsShow)
y: 0
width: (monthsBoxLayer.width / @numberOfMonthsShow)
height: monthsBoxLayer.height
}
)
)
contentBoxLayer = new Layer
parent: monthLayer
backgroundColor: "transparent"
x: @datesBoxStyle.padding.left
y: @datesBoxStyle.padding.top
width: (
monthLayer.width +
(-@datesBoxStyle.padding.left) +
(-@datesBoxStyle.padding.right)
)
height: (
monthLayer.height +
(-@datesBoxStyle.padding.top) +
(-@datesBoxStyle.padding.bottom)
)
# SECTION: days rendering pre-calc
firstOfMonth = new Date(
@startDateShow.getFullYear(),
@startDateShow.getMonth() + monthIndex,
1
)
firstGridDate = new Date(firstOfMonth)
while firstGridDate.getDay() != @firstColumnDay
firstGridDate = firstGridDate.addDays(-1)
# SECTION: headers
monthHeaderLayer = new TextLayer(
_.merge(
{}
@monthHeaderStyle,
{
parent: contentBoxLayer
x: 0
y: 0
width: contentBoxLayer.width
text: "#{monthNamesUppercase[firstOfMonth.getMonth()]} #{firstOfMonth.getFullYear()}"
truncate: true
}
)
)
if (
monthIndex == 0 and
@buttonPrevShow
)
@btnPrevBoxLayer = new Layer
parent: monthHeaderLayer
backgroundColor: "transparent"
x: 0
y: 0
width: monthHeaderLayer.width / 4
height: monthHeaderLayer.height
btnPrevArrowLayer = new TextLayer
parent: @btnPrevBoxLayer
backgroundColor: "transparent"
x: 0
y: 0
width: @btnPrevBoxLayer.width / 3
height: @btnPrevBoxLayer.height
text: "<"
textAlign: "left"
color: "#3C444D"
# hacky...
fontSize: @buttonsStyle.fontSize * 2
fontFamily: "-apple-system"
padding:
vertical: (@btnPrevBoxLayer.height - 3*@buttonsStyle.fontSize) / 2
btnPrevLabelLayer = new TextLayer(
_.merge(
{}
@buttonsStyle
{
parent: @btnPrevBoxLayer
x: @btnPrevBoxLayer.width / 3
y: 0
width: @btnPrevBoxLayer.width * 2 / 3
height: @btnPrevBoxLayer.height
text: "#{monthAbbrevsUppercase[(firstOfMonth.getMonth() + 12 - 1) % 12]}"
textAlign: "left"
color: "#3C444D"
# hacky ...
padding:
vertical: (@btnPrevBoxLayer.height - 1.5*@buttonsStyle.fontSize) / 2
}
)
)
@btnPrevBoxLayer.onTap =>
@setStartDateShow @startDateShow.addMonths(-1)
if (
monthIndex == @numberOfMonthsShow - 1 and
@buttonNextShow
)
@btnNextBoxLayer = new Layer
parent: monthHeaderLayer
backgroundColor: "transparent"
x: monthHeaderLayer.width * 3 / 4
y: 0
width: monthHeaderLayer.width / 4
height: monthHeaderLayer.height
btnNextArrowLayer = new TextLayer
parent: @btnNextBoxLayer
backgroundColor: "transparent"
x: @btnNextBoxLayer.width * 2 / 3
y: 0
width: @btnNextBoxLayer.width / 3
height: @btnNextBoxLayer.height
text: ">"
color: "#3C444D"
textAlign: "right"
# hacky...
fontSize: @buttonsStyle.fontSize * 2
fontFamily: "-apple-system"
padding:
vertical: (@btnNextBoxLayer.height - 3*@buttonsStyle.fontSize) / 2
btnNextLabelLayer = new TextLayer(
_.merge(
{}
@buttonsStyle
{
parent: @btnNextBoxLayer
x: 0
y: 0
width: @btnNextBoxLayer.width * 2 / 3
height: @btnNextBoxLayer.height
text: "#{monthAbbrevsUppercase[(firstOfMonth.getMonth() + 1) % 12]}"
textAlign: "right"
color: "#3C444D"
# hacky ...
padding:
vertical: (@btnNextBoxLayer.height - 1.5*@buttonsStyle.fontSize) / 2
}
)
)
@btnNextBoxLayer.onTap =>
@setStartDateShow @startDateShow.addMonths(1)
weekHeaderLayer = new Layer
backgroundColor: "transparent"
x: 0
y: monthHeaderLayer.y + monthHeaderLayer.height
width: contentBoxLayer.width
height: @weekHeaderStyle.height
parent: contentBoxLayer
# Styling for weekHeaderLayer intentionally used for its children...
for dayIndex in [0...7]
new TextLayer(
_.merge(
{}
@weekHeaderStyle
{
x: dayIndex * (contentBoxLayer.width / 7)
y: 0
width: contentBoxLayer.width / 7
height: weekHeaderLayer.height
parent: weekHeaderLayer
text: "#{dayAbbrevs[(dayIndex + @firstColumnDay) % 7]}"
truncate: true
}
)
)
# SECTION: date cells
daysGridLayer = new Layer
backgroundColor: "transparent"
x: 0
y: weekHeaderLayer.y + weekHeaderLayer.height
width: contentBoxLayer.width
height: (
contentBoxLayer.height +
(-monthHeaderLayer.height) +
(-weekHeaderLayer.height) +
(-@datesBoxStyle.padding<EMAIL>.top) +
(-@datesBoxStyle.padding.bottom)
)
parent: contentBoxLayer
dateRendering = firstGridDate
for row in [0...6]
for column in [0...7]
if (
@outsideMonthDatesShow or
dateRendering.getMonth() == firstOfMonth.getMonth()
)
isOutsideMonth = dateRendering.getMonth() != firstOfMonth.getMonth()
dateCellBoxLayer = new Layer
parent: daysGridLayer
backgroundColor: "transparent"
y: row * daysGridLayer.height / 6
x: column * daysGridLayer.width / 7
height: daysGridLayer.height / 6
width: daysGridLayer.width / 7
extraStyle = {}
if not isOutsideMonth
# add to the map addressable by date
@dateCellBoxLayerDict[dateRendering] = dateCellBoxLayer
# extra styles for highlight ranges
for highlighRange in @highlightDateRanges
if (
highlighRange.dateRangeStart <= dateRendering and
dateRendering <= highlighRange.dateRangeEnd
)
_.merge extraStyle, highlighRange.dateExtraStyle
else
# extra style for outside-month dates
extraStyle = @dateOutsideMonthExtraStyle
dateCellLayer = new TextLayer(
_.merge(
{}
@dateBaseStyle
{
parent: dateCellBoxLayer
x: @dateBaseStyle.margin.left
y: @dateBaseStyle.margin.top
width: (
dateCellBoxLayer.width +
(-@dateBaseStyle.margin.left) +
(-@dateBaseStyle.margin.right)
)
height: (
dateCellBoxLayer.height +
(-@dateBaseStyle.margin.top) +
(-@dateBaseStyle.margin.bottom)
)
text: "#{dateRendering.getDate()}"
}
extraStyle
)
)
dateCellBoxLayer.date = dateRendering
dateCellBoxLayer.dateCellLayer = dateCellLayer
if not isOutsideMonth
self = @
# Handle selecting
dateCellLayer.yesSelectedStyle = @dateSelectedExtraStyle
dateCellLayer.noSelectedStyle = _.pick dateCellLayer, _.keys @dateSelectedExtraStyle
do (dateCellBoxLayer, self) ->
dateCellBoxLayer.onTap () ->
if not self.enabled
return
if (
self.dateRangeSelectedStart == undefined or
not self.dateRangeSelectable
)
self.setDateRangeSelected(dateCellBoxLayer.date, dateCellBoxLayer.date)
return
if (self._nextChangeDateRangeStart or false)
self.setDateRangeSelected(self.dateRangeSelectedStart, dateCellBoxLayer.date)
else
self.setDateRangeSelected(dateCellBoxLayer.date, self.dateRangeSelectedEnd)
self._nextChangeDateRangeStart = not (self._nextChangeDateRangeStart or false)
# Handle hovering
if @hoverEnabled
dateCellLayer.yesHoveredStyle = @dateHoveredExtraStyle
dateCellLayer.noHoveredStyle = _.pick dateCellLayer, _.keys @dateHoveredExtraStyle
do (dateCellBoxLayer, dateCellLayer, self) ->
dateCellBoxLayer.on Events.MouseOver, (event, layer) ->
_.assign dateCellLayer, dateCellLayer.yesHoveredStyle
dateCellBoxLayer.on Events.MouseOut, (event, layer) ->
_.assign dateCellLayer, dateCellLayer.noHoveredStyle
if (self._isDateSelected(dateCellBoxLayer.date))
_.assign dateCellLayer, dateCellLayer.yesSelectedStyle
dateRendering = dateRendering.addDays(1)
# After the rendering, set the initial selected range
@setDateRangeSelected(@dateRangeSelectedStart, @dateRangeSelectedEnd, false)
_isDateSelected: (date) ->
return (
@dateRangeSelectedStart <= date and
date <= @dateRangeSelectedEnd
)
_clean: () ->
@isolatorLayer?.destroy()
# INTERFACE METHODS
getStartDateShow: () ->
return @startDateShow
setStartDateShow: (currentStartDateShow) ->
previousStartDateShow = @startDateShow
@startDateShow = currentStartDateShow
@_clean()
@_render()
@handleMonthsShowChange(previousStartDateShow, currentStartDateShow)
getDateRangeSelectedStart: () ->
return @dateRangeSelectedStart
getDateRangeSelectedEnd: () ->
return @dateRangeSelectedEnd
setDateRangeSelected: (currentDateRangeSelectedStart, currentDateRangeSelectedEnd, triggerHandler = true) ->
if currentDateRangeSelectedStart > currentDateRangeSelectedEnd
[currentDateRangeSelectedStart, currentDateRangeSelectedEnd] =
[currentDateRangeSelectedEnd, currentDateRangeSelectedStart]
previousDateRangeSelectedStart = @dateRangeSelectedStart
previousDateRangeSelectedEnd = @dateRangeSelectedEnd
# ... unselect previously selected
if (
previousDateRangeSelectedStart != undefined and
previousDateRangeSelectedEnd != undefined
)
currentDate = previousDateRangeSelectedStart
while currentDate <= previousDateRangeSelectedEnd
dateCellLayer = @dateCellBoxLayerDict[currentDate].dateCellLayer
_.assign dateCellLayer, dateCellLayer.noSelectedStyle
currentDate = currentDate.addDays(1)
# ... select currently selected
if (
currentDateRangeSelectedStart != undefined and
currentDateRangeSelectedEnd != undefined
)
currentDate = currentDateRangeSelectedStart
while currentDate <= currentDateRangeSelectedEnd
dateCellLayer = @dateCellBoxLayerDict[currentDate].dateCellLayer
_.assign dateCellLayer, dateCellLayer.yesSelectedStyle
currentDate = currentDate.addDays(1)
# ... update the newest state
@dateRangeSelectedStart = currentDateRangeSelectedStart
@dateRangeSelectedEnd = currentDateRangeSelectedEnd
# ... call the handler
if triggerHandler
@handleDateRangeSelectedChange(
previousDateRangeSelectedStart
previousDateRangeSelectedEnd
currentDateRangeSelectedStart
currentDateRangeSelectedEnd
)
getHighlightDateRanges: () ->
return @highlightDateRanges
setHighlightDateRanges: (highlightDateRanges) ->
@highlightDateRanges = highlightDateRanges
@_clean()
@_render()
setHandleMonthsShowChange: (handler) ->
@handleMonthsShowChange = handler
setHandleDateRangeSelectedChange: (handler) ->
@handleDateRangeSelectedChange = handler
| true | # Copyright (c) 2018 PI:NAME:<NAME>END_PI
# Casing - UI framework for Framer
# License: MIT
# URL: https://github.com/nataliemarleny/Casing
Utils.loadWebFont("Rubik")
# Utility functinos for manipulating dates
Date.prototype.addDays = (deltaDays) ->
return new Date(
@getFullYear(),
@getMonth(),
@getDate() + deltaDays,
)
Date.prototype.addMonths = (deltaMonths) ->
return new Date(
@getFullYear(),
@getMonth() + deltaMonths,
)
# Utility arrays
monthNames = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
]
exports.monthNames = monthNames
monthNamesUppercase = [
"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
]
exports.monthNamesUppercase = monthNamesUppercase
monthAbbrevsUppercase = [
"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
]
exports.monthAbbrevsUppercase = monthAbbrevsUppercase
monthAbbrevsLowercase = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]
exports.monthAbbrevsLowercase = monthAbbrevsLowercase
dayAbbrevs = [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
]
exports.dayAbbrevs = dayAbbrevs
class exports.FrmrDatePicker extends Layer
constructor: (options = {}) ->
# CONFIGURATION
defaults =
enabled: true
numberOfMonthsShow: 1
firstColumnDay: 1
startDateShow: new Date(Date.now())
dateRangeSelectedStart: undefined
dateRangeSelectedEnd: undefined
hoverEnabled: true
dateRangeSelectable: false # if false only single date is selectable
outsideMonthDatesShow: false
buttonNextShow: true
buttonPrevShow: true
highlightDateRanges: [
# {
# dateRangeStart: new Date(2018, 5, 5)
# dateRangeEnd: new Date(2018, 5, 8)
# dateExtraStyle:
# backgroundColor: "red"
# color: "white"
# }
]
handleMonthsShowChange: (previousStartDateShow, currentStartDateShow) ->
undefined
handleDateRangeSelectedChange: (
previousDateRangeSelectedStart
previousDateRangeSelectedEnd
currentDateRangeSelectedStart
currentDateRangeSelectedEnd
) ->
undefined
monthsBoxStyle:
backgroundColor: "#ffffff"
width: 277 * (options.numberOfMonthsShow or 1)
height: 285
borderWidth: 1
borderRadius: 6
borderColor: "#E9ECF0"
padding:
top: 3
bottom: 0
left: 15
right: 15
monthHeaderStyle:
height: 36
backgroundColor: "transparent"
color: "#3C444D"
textAlign: "center"
fontSize: 18
fontStyle: "bold"
fontFamily: "-apple-system"
padding:
vertical: 0
left: 3
right: 3
weekHeaderStyle:
height: 36
backgroundColor: "transparent"
color: "#3C444D"
textAlign: "center"
fontSize: 12
fontFamily: "-apple-system"
padding:
vertical: 1
datesBoxStyle:
backgroundColor: "transparent"
color: "#3C444D"
padding:
top: 3
bottom: 0
left: 20
right: 20
buttonsStyle:
fontSize: 12
dateBaseStyle:
color: "#3C444D"
backgroundColor: "transparent"
borderColor: "#e6e6e6"
borderWidth: 1
borderRadius: 1
textAlign: "center"
fontSize: 12
fontFamily: "-apple-system"
padding:
vertical: 6
margin:
top: 0
bottom: -1
left: 0
right: -1
dateSelectedExtraStyle:
backgroundColor: "#3C444D"
color: "white"
dateHoveredExtraStyle:
backgroundColor: "#cccccc"
color: "white"
dateOutsideMonthExtraStyle:
opacity: 0.25
# assign all configuration to the object as properties
configs_passed = _.pick options, _.keys defaults
_.assign @, (_.merge {}, defaults, configs_passed)
# FIXED STYLES
options.backgroundColor = @monthsBoxStyle.backgroundColor
options.width = @monthsBoxStyle.width
options.height = @monthsBoxStyle.height
super options
# LAYER STORAGE
@dateCellBoxLayerDict = {}
@topContainerLayer = new Layer(
_.merge(
{}
@monthsBoxStyle
{parent: @}
)
)
# RENDERING
@_clean()
@_render()
_render: () ->
@isolatorLayer = new Layer(
_.merge(
{}
@topContainerLayer.frame
{
backgroundColor: "transparent"
parent: @topContainerLayer
}
)
)
monthsBoxLayer = new Layer
backgroundColor: "transparent"
parent: @isolatorLayer
x: @monthsBoxStyle.padding.left
y: @monthsBoxStyle.padding.top
width: (
@isolatorLayer.width +
(-@monthsBoxStyle.padding.left) +
(-@monthsBoxStyle.padding.right)
)
height: (
@isolatorLayer.height +
(-@monthsBoxStyle.padding.top) +
(- @monthsBoxStyle.padding.bottom)
)
for monthIndex in [0...@numberOfMonthsShow]
# SECTION: month
monthLayer = new Layer(
_.merge(
{}
@datesBoxStyle,
{
parent: monthsBoxLayer
x: monthIndex * (monthsBoxLayer.width / @numberOfMonthsShow)
y: 0
width: (monthsBoxLayer.width / @numberOfMonthsShow)
height: monthsBoxLayer.height
}
)
)
contentBoxLayer = new Layer
parent: monthLayer
backgroundColor: "transparent"
x: @datesBoxStyle.padding.left
y: @datesBoxStyle.padding.top
width: (
monthLayer.width +
(-@datesBoxStyle.padding.left) +
(-@datesBoxStyle.padding.right)
)
height: (
monthLayer.height +
(-@datesBoxStyle.padding.top) +
(-@datesBoxStyle.padding.bottom)
)
# SECTION: days rendering pre-calc
firstOfMonth = new Date(
@startDateShow.getFullYear(),
@startDateShow.getMonth() + monthIndex,
1
)
firstGridDate = new Date(firstOfMonth)
while firstGridDate.getDay() != @firstColumnDay
firstGridDate = firstGridDate.addDays(-1)
# SECTION: headers
monthHeaderLayer = new TextLayer(
_.merge(
{}
@monthHeaderStyle,
{
parent: contentBoxLayer
x: 0
y: 0
width: contentBoxLayer.width
text: "#{monthNamesUppercase[firstOfMonth.getMonth()]} #{firstOfMonth.getFullYear()}"
truncate: true
}
)
)
if (
monthIndex == 0 and
@buttonPrevShow
)
@btnPrevBoxLayer = new Layer
parent: monthHeaderLayer
backgroundColor: "transparent"
x: 0
y: 0
width: monthHeaderLayer.width / 4
height: monthHeaderLayer.height
btnPrevArrowLayer = new TextLayer
parent: @btnPrevBoxLayer
backgroundColor: "transparent"
x: 0
y: 0
width: @btnPrevBoxLayer.width / 3
height: @btnPrevBoxLayer.height
text: "<"
textAlign: "left"
color: "#3C444D"
# hacky...
fontSize: @buttonsStyle.fontSize * 2
fontFamily: "-apple-system"
padding:
vertical: (@btnPrevBoxLayer.height - 3*@buttonsStyle.fontSize) / 2
btnPrevLabelLayer = new TextLayer(
_.merge(
{}
@buttonsStyle
{
parent: @btnPrevBoxLayer
x: @btnPrevBoxLayer.width / 3
y: 0
width: @btnPrevBoxLayer.width * 2 / 3
height: @btnPrevBoxLayer.height
text: "#{monthAbbrevsUppercase[(firstOfMonth.getMonth() + 12 - 1) % 12]}"
textAlign: "left"
color: "#3C444D"
# hacky ...
padding:
vertical: (@btnPrevBoxLayer.height - 1.5*@buttonsStyle.fontSize) / 2
}
)
)
@btnPrevBoxLayer.onTap =>
@setStartDateShow @startDateShow.addMonths(-1)
if (
monthIndex == @numberOfMonthsShow - 1 and
@buttonNextShow
)
@btnNextBoxLayer = new Layer
parent: monthHeaderLayer
backgroundColor: "transparent"
x: monthHeaderLayer.width * 3 / 4
y: 0
width: monthHeaderLayer.width / 4
height: monthHeaderLayer.height
btnNextArrowLayer = new TextLayer
parent: @btnNextBoxLayer
backgroundColor: "transparent"
x: @btnNextBoxLayer.width * 2 / 3
y: 0
width: @btnNextBoxLayer.width / 3
height: @btnNextBoxLayer.height
text: ">"
color: "#3C444D"
textAlign: "right"
# hacky...
fontSize: @buttonsStyle.fontSize * 2
fontFamily: "-apple-system"
padding:
vertical: (@btnNextBoxLayer.height - 3*@buttonsStyle.fontSize) / 2
btnNextLabelLayer = new TextLayer(
_.merge(
{}
@buttonsStyle
{
parent: @btnNextBoxLayer
x: 0
y: 0
width: @btnNextBoxLayer.width * 2 / 3
height: @btnNextBoxLayer.height
text: "#{monthAbbrevsUppercase[(firstOfMonth.getMonth() + 1) % 12]}"
textAlign: "right"
color: "#3C444D"
# hacky ...
padding:
vertical: (@btnNextBoxLayer.height - 1.5*@buttonsStyle.fontSize) / 2
}
)
)
@btnNextBoxLayer.onTap =>
@setStartDateShow @startDateShow.addMonths(1)
weekHeaderLayer = new Layer
backgroundColor: "transparent"
x: 0
y: monthHeaderLayer.y + monthHeaderLayer.height
width: contentBoxLayer.width
height: @weekHeaderStyle.height
parent: contentBoxLayer
# Styling for weekHeaderLayer intentionally used for its children...
for dayIndex in [0...7]
new TextLayer(
_.merge(
{}
@weekHeaderStyle
{
x: dayIndex * (contentBoxLayer.width / 7)
y: 0
width: contentBoxLayer.width / 7
height: weekHeaderLayer.height
parent: weekHeaderLayer
text: "#{dayAbbrevs[(dayIndex + @firstColumnDay) % 7]}"
truncate: true
}
)
)
# SECTION: date cells
daysGridLayer = new Layer
backgroundColor: "transparent"
x: 0
y: weekHeaderLayer.y + weekHeaderLayer.height
width: contentBoxLayer.width
height: (
contentBoxLayer.height +
(-monthHeaderLayer.height) +
(-weekHeaderLayer.height) +
(-@datesBoxStyle.paddingPI:EMAIL:<EMAIL>END_PI.top) +
(-@datesBoxStyle.padding.bottom)
)
parent: contentBoxLayer
dateRendering = firstGridDate
for row in [0...6]
for column in [0...7]
if (
@outsideMonthDatesShow or
dateRendering.getMonth() == firstOfMonth.getMonth()
)
isOutsideMonth = dateRendering.getMonth() != firstOfMonth.getMonth()
dateCellBoxLayer = new Layer
parent: daysGridLayer
backgroundColor: "transparent"
y: row * daysGridLayer.height / 6
x: column * daysGridLayer.width / 7
height: daysGridLayer.height / 6
width: daysGridLayer.width / 7
extraStyle = {}
if not isOutsideMonth
# add to the map addressable by date
@dateCellBoxLayerDict[dateRendering] = dateCellBoxLayer
# extra styles for highlight ranges
for highlighRange in @highlightDateRanges
if (
highlighRange.dateRangeStart <= dateRendering and
dateRendering <= highlighRange.dateRangeEnd
)
_.merge extraStyle, highlighRange.dateExtraStyle
else
# extra style for outside-month dates
extraStyle = @dateOutsideMonthExtraStyle
dateCellLayer = new TextLayer(
_.merge(
{}
@dateBaseStyle
{
parent: dateCellBoxLayer
x: @dateBaseStyle.margin.left
y: @dateBaseStyle.margin.top
width: (
dateCellBoxLayer.width +
(-@dateBaseStyle.margin.left) +
(-@dateBaseStyle.margin.right)
)
height: (
dateCellBoxLayer.height +
(-@dateBaseStyle.margin.top) +
(-@dateBaseStyle.margin.bottom)
)
text: "#{dateRendering.getDate()}"
}
extraStyle
)
)
dateCellBoxLayer.date = dateRendering
dateCellBoxLayer.dateCellLayer = dateCellLayer
if not isOutsideMonth
self = @
# Handle selecting
dateCellLayer.yesSelectedStyle = @dateSelectedExtraStyle
dateCellLayer.noSelectedStyle = _.pick dateCellLayer, _.keys @dateSelectedExtraStyle
do (dateCellBoxLayer, self) ->
dateCellBoxLayer.onTap () ->
if not self.enabled
return
if (
self.dateRangeSelectedStart == undefined or
not self.dateRangeSelectable
)
self.setDateRangeSelected(dateCellBoxLayer.date, dateCellBoxLayer.date)
return
if (self._nextChangeDateRangeStart or false)
self.setDateRangeSelected(self.dateRangeSelectedStart, dateCellBoxLayer.date)
else
self.setDateRangeSelected(dateCellBoxLayer.date, self.dateRangeSelectedEnd)
self._nextChangeDateRangeStart = not (self._nextChangeDateRangeStart or false)
# Handle hovering
if @hoverEnabled
dateCellLayer.yesHoveredStyle = @dateHoveredExtraStyle
dateCellLayer.noHoveredStyle = _.pick dateCellLayer, _.keys @dateHoveredExtraStyle
do (dateCellBoxLayer, dateCellLayer, self) ->
dateCellBoxLayer.on Events.MouseOver, (event, layer) ->
_.assign dateCellLayer, dateCellLayer.yesHoveredStyle
dateCellBoxLayer.on Events.MouseOut, (event, layer) ->
_.assign dateCellLayer, dateCellLayer.noHoveredStyle
if (self._isDateSelected(dateCellBoxLayer.date))
_.assign dateCellLayer, dateCellLayer.yesSelectedStyle
dateRendering = dateRendering.addDays(1)
# After the rendering, set the initial selected range
@setDateRangeSelected(@dateRangeSelectedStart, @dateRangeSelectedEnd, false)
_isDateSelected: (date) ->
return (
@dateRangeSelectedStart <= date and
date <= @dateRangeSelectedEnd
)
_clean: () ->
@isolatorLayer?.destroy()
# INTERFACE METHODS
getStartDateShow: () ->
return @startDateShow
setStartDateShow: (currentStartDateShow) ->
previousStartDateShow = @startDateShow
@startDateShow = currentStartDateShow
@_clean()
@_render()
@handleMonthsShowChange(previousStartDateShow, currentStartDateShow)
getDateRangeSelectedStart: () ->
return @dateRangeSelectedStart
getDateRangeSelectedEnd: () ->
return @dateRangeSelectedEnd
setDateRangeSelected: (currentDateRangeSelectedStart, currentDateRangeSelectedEnd, triggerHandler = true) ->
if currentDateRangeSelectedStart > currentDateRangeSelectedEnd
[currentDateRangeSelectedStart, currentDateRangeSelectedEnd] =
[currentDateRangeSelectedEnd, currentDateRangeSelectedStart]
previousDateRangeSelectedStart = @dateRangeSelectedStart
previousDateRangeSelectedEnd = @dateRangeSelectedEnd
# ... unselect previously selected
if (
previousDateRangeSelectedStart != undefined and
previousDateRangeSelectedEnd != undefined
)
currentDate = previousDateRangeSelectedStart
while currentDate <= previousDateRangeSelectedEnd
dateCellLayer = @dateCellBoxLayerDict[currentDate].dateCellLayer
_.assign dateCellLayer, dateCellLayer.noSelectedStyle
currentDate = currentDate.addDays(1)
# ... select currently selected
if (
currentDateRangeSelectedStart != undefined and
currentDateRangeSelectedEnd != undefined
)
currentDate = currentDateRangeSelectedStart
while currentDate <= currentDateRangeSelectedEnd
dateCellLayer = @dateCellBoxLayerDict[currentDate].dateCellLayer
_.assign dateCellLayer, dateCellLayer.yesSelectedStyle
currentDate = currentDate.addDays(1)
# ... update the newest state
@dateRangeSelectedStart = currentDateRangeSelectedStart
@dateRangeSelectedEnd = currentDateRangeSelectedEnd
# ... call the handler
if triggerHandler
@handleDateRangeSelectedChange(
previousDateRangeSelectedStart
previousDateRangeSelectedEnd
currentDateRangeSelectedStart
currentDateRangeSelectedEnd
)
getHighlightDateRanges: () ->
return @highlightDateRanges
setHighlightDateRanges: (highlightDateRanges) ->
@highlightDateRanges = highlightDateRanges
@_clean()
@_render()
setHandleMonthsShowChange: (handler) ->
@handleMonthsShowChange = handler
setHandleDateRangeSelectedChange: (handler) ->
@handleDateRangeSelectedChange = handler
|
[
{
"context": "oGLib\n# Module | Stat methods\n# Author | Sherif Emabrak\n# Description | mode for set of elements\n# ------",
"end": 163,
"score": 0.9998776316642761,
"start": 149,
"tag": "NAME",
"value": "Sherif Emabrak"
}
] | src/lib/statistics/summary/mode.coffee | Sherif-Embarak/gp-test | 0 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat methods
# Author | Sherif Emabrak
# Description | mode for set of elements
# ------------------------------------------------------------------------------
mode = () -> | 125655 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat methods
# Author | <NAME>
# Description | mode for set of elements
# ------------------------------------------------------------------------------
mode = () -> | true | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat methods
# Author | PI:NAME:<NAME>END_PI
# Description | mode for set of elements
# ------------------------------------------------------------------------------
mode = () -> |
[
{
"context": "scribe 'jasmine.Suite#let', ->\n @let 'name', -> 'Bob'\n\n it 'creates a property on the spec with the r",
"end": 2308,
"score": 0.9995163083076477,
"start": 2305,
"tag": "NAME",
"value": "Bob"
},
{
"context": "th the right name', ->\n expect(@name).toEqual('Bob')\... | spec/javascripts/helpers/lets.js.coffee | beeflamian/shuttle | 327 | # Copyright 2014 Square Inc.
#
# 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.
# We need to memoize the values returned by the let functions,
# but only for the current spec. This will ensure that all registered
# lets do not have an already-memoized value.
clearMemoizedLets = (suite) ->
if suite.parentSuite
clearMemoizedLets suite.parentSuite
if suite.lets_
for own name, getter of suite.lets_
delete getter.memoizedValue
# This defines getters on the spec named by the let calls.
defineGettersOnSpec = (spec, suite) ->
if suite.parentSuite
defineGettersOnSpec spec, suite.parentSuite
for own name, getter of suite.lets_
spec.__defineGetter__ name, getter
# Global beforeEach to clear memoized values.
beforeEach ->
clearMemoizedLets @suite
withRunLoop = Ember?.run? or (fn) -> fn()
# Defines an overridable getter on all specs in this Suite.
jasmine.Suite.prototype.let = (name, getter) ->
lets = (@lets_ ||= {})
if typeof getter is 'function'
# getter function, wrap it to memoize
lets[name] = ->
return lets[name].memoizedValue if 'memoizedValue' of lets[name]
value = withRunLoop => getter.call(this)
lets[name].memoizedValue = value
else
# constant, no need to memoize
lets[name] = -> getter
jasmine.Suite.prototype.set = (name, getter) ->
@let name, getter
beforeEach -> @[name]
jasmine.Suite.prototype.helper = (name, helper) ->
@let name, -> helper
# Hook into spec declaration that lets us define let getters on them.
jasmine_Suite_prototype_add = jasmine.Suite.prototype.add
jasmine.Suite.prototype.add = (spec, args...) ->
defineGettersOnSpec spec, this
jasmine_Suite_prototype_add.call(this, spec, args...)
## EXAMPLES
describe 'jasmine.Suite#let', ->
@let 'name', -> 'Bob'
it 'creates a property on the spec with the right name', ->
expect(@name).toEqual('Bob')
describe 'with a sub-suite', ->
@let 'name', -> 'Joe'
it 'allows overriding the parent suite value', ->
expect(@name).toEqual('Joe')
describe 'with a dependent value', ->
@let 'person', -> {@name, @age}
it 'allows chaining let value', ->
expect(@person.name).toEqual('Bob')
it 'allows chaining normal property values', ->
@age = 20
expect(@person.age).toEqual(20)
describe 'jasmine.Suite#set', ->
setName = null
letName = null
@set 'setName', -> setName
@let 'letName', -> letName
it 'reads the value before running the spec', ->
setName = 'Joy'
letName = 'Joy'
expect(@setName).toBeNull()
expect(@letName).toEqual('Joy')
describe 'jasmine.Suite#helper', ->
@helper 'addNumbers', (a, b) -> a + b
it 'creates a property that contains the helper function', ->
expect(typeof @addNumbers).toEqual('function')
it 'allows calling the function', ->
expect(@addNumbers 1, 2).toEqual(3)
describe 'with a sub-suite', ->
@helper 'addNumbers', (a, b) -> a + a
it 'allows overriding the parent suite value', ->
expect(@addNumbers 1, 2).toEqual(2)
describe 'with lets', ->
@let 'a', 1
@let 'b', 2
@helper 'addNumbers', -> @a + @b
it 'can interact with let values', ->
expect(@addNumbers()).toEqual(3)
| 82455 | # Copyright 2014 Square Inc.
#
# 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.
# We need to memoize the values returned by the let functions,
# but only for the current spec. This will ensure that all registered
# lets do not have an already-memoized value.
clearMemoizedLets = (suite) ->
if suite.parentSuite
clearMemoizedLets suite.parentSuite
if suite.lets_
for own name, getter of suite.lets_
delete getter.memoizedValue
# This defines getters on the spec named by the let calls.
defineGettersOnSpec = (spec, suite) ->
if suite.parentSuite
defineGettersOnSpec spec, suite.parentSuite
for own name, getter of suite.lets_
spec.__defineGetter__ name, getter
# Global beforeEach to clear memoized values.
beforeEach ->
clearMemoizedLets @suite
withRunLoop = Ember?.run? or (fn) -> fn()
# Defines an overridable getter on all specs in this Suite.
jasmine.Suite.prototype.let = (name, getter) ->
lets = (@lets_ ||= {})
if typeof getter is 'function'
# getter function, wrap it to memoize
lets[name] = ->
return lets[name].memoizedValue if 'memoizedValue' of lets[name]
value = withRunLoop => getter.call(this)
lets[name].memoizedValue = value
else
# constant, no need to memoize
lets[name] = -> getter
jasmine.Suite.prototype.set = (name, getter) ->
@let name, getter
beforeEach -> @[name]
jasmine.Suite.prototype.helper = (name, helper) ->
@let name, -> helper
# Hook into spec declaration that lets us define let getters on them.
jasmine_Suite_prototype_add = jasmine.Suite.prototype.add
jasmine.Suite.prototype.add = (spec, args...) ->
defineGettersOnSpec spec, this
jasmine_Suite_prototype_add.call(this, spec, args...)
## EXAMPLES
describe 'jasmine.Suite#let', ->
@let 'name', -> '<NAME>'
it 'creates a property on the spec with the right name', ->
expect(@name).toEqual('<NAME>')
describe 'with a sub-suite', ->
@let 'name', -> '<NAME>'
it 'allows overriding the parent suite value', ->
expect(@name).toEqual('<NAME>')
describe 'with a dependent value', ->
@let 'person', -> {@name, @age}
it 'allows chaining let value', ->
expect(@person.name).toEqual('<NAME>')
it 'allows chaining normal property values', ->
@age = 20
expect(@person.age).toEqual(20)
describe 'jasmine.Suite#set', ->
setName = null
letName = null
@set 'setName', -> setName
@let 'letName', -> letName
it 'reads the value before running the spec', ->
setName = '<NAME>'
letName = '<NAME>'
expect(@setName).toBeNull()
expect(@letName).toEqual('<NAME>')
describe 'jasmine.Suite#helper', ->
@helper 'addNumbers', (a, b) -> a + b
it 'creates a property that contains the helper function', ->
expect(typeof @addNumbers).toEqual('function')
it 'allows calling the function', ->
expect(@addNumbers 1, 2).toEqual(3)
describe 'with a sub-suite', ->
@helper 'addNumbers', (a, b) -> a + a
it 'allows overriding the parent suite value', ->
expect(@addNumbers 1, 2).toEqual(2)
describe 'with lets', ->
@let 'a', 1
@let 'b', 2
@helper 'addNumbers', -> @a + @b
it 'can interact with let values', ->
expect(@addNumbers()).toEqual(3)
| true | # Copyright 2014 Square Inc.
#
# 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.
# We need to memoize the values returned by the let functions,
# but only for the current spec. This will ensure that all registered
# lets do not have an already-memoized value.
clearMemoizedLets = (suite) ->
if suite.parentSuite
clearMemoizedLets suite.parentSuite
if suite.lets_
for own name, getter of suite.lets_
delete getter.memoizedValue
# This defines getters on the spec named by the let calls.
defineGettersOnSpec = (spec, suite) ->
if suite.parentSuite
defineGettersOnSpec spec, suite.parentSuite
for own name, getter of suite.lets_
spec.__defineGetter__ name, getter
# Global beforeEach to clear memoized values.
beforeEach ->
clearMemoizedLets @suite
withRunLoop = Ember?.run? or (fn) -> fn()
# Defines an overridable getter on all specs in this Suite.
jasmine.Suite.prototype.let = (name, getter) ->
lets = (@lets_ ||= {})
if typeof getter is 'function'
# getter function, wrap it to memoize
lets[name] = ->
return lets[name].memoizedValue if 'memoizedValue' of lets[name]
value = withRunLoop => getter.call(this)
lets[name].memoizedValue = value
else
# constant, no need to memoize
lets[name] = -> getter
jasmine.Suite.prototype.set = (name, getter) ->
@let name, getter
beforeEach -> @[name]
jasmine.Suite.prototype.helper = (name, helper) ->
@let name, -> helper
# Hook into spec declaration that lets us define let getters on them.
jasmine_Suite_prototype_add = jasmine.Suite.prototype.add
jasmine.Suite.prototype.add = (spec, args...) ->
defineGettersOnSpec spec, this
jasmine_Suite_prototype_add.call(this, spec, args...)
## EXAMPLES
describe 'jasmine.Suite#let', ->
@let 'name', -> 'PI:NAME:<NAME>END_PI'
it 'creates a property on the spec with the right name', ->
expect(@name).toEqual('PI:NAME:<NAME>END_PI')
describe 'with a sub-suite', ->
@let 'name', -> 'PI:NAME:<NAME>END_PI'
it 'allows overriding the parent suite value', ->
expect(@name).toEqual('PI:NAME:<NAME>END_PI')
describe 'with a dependent value', ->
@let 'person', -> {@name, @age}
it 'allows chaining let value', ->
expect(@person.name).toEqual('PI:NAME:<NAME>END_PI')
it 'allows chaining normal property values', ->
@age = 20
expect(@person.age).toEqual(20)
describe 'jasmine.Suite#set', ->
setName = null
letName = null
@set 'setName', -> setName
@let 'letName', -> letName
it 'reads the value before running the spec', ->
setName = 'PI:NAME:<NAME>END_PI'
letName = 'PI:NAME:<NAME>END_PI'
expect(@setName).toBeNull()
expect(@letName).toEqual('PI:NAME:<NAME>END_PI')
describe 'jasmine.Suite#helper', ->
@helper 'addNumbers', (a, b) -> a + b
it 'creates a property that contains the helper function', ->
expect(typeof @addNumbers).toEqual('function')
it 'allows calling the function', ->
expect(@addNumbers 1, 2).toEqual(3)
describe 'with a sub-suite', ->
@helper 'addNumbers', (a, b) -> a + a
it 'allows overriding the parent suite value', ->
expect(@addNumbers 1, 2).toEqual(2)
describe 'with lets', ->
@let 'a', 1
@let 'b', 2
@helper 'addNumbers', -> @a + @b
it 'can interact with let values', ->
expect(@addNumbers()).toEqual(3)
|
[
{
"context": "-id')\n unique_key = { position: target.index() + 1 }\n payload = $.param(id: id, unique_ke",
"end": 685,
"score": 0.6009629964828491,
"start": 674,
"tag": "KEY",
"value": "index() + 1"
},
{
"context": " $.post(url, payload)\n\n\n # https://git... | app/assets/javascripts/rails_admin_cms/cms.js.coffee | Loubz/rails_admin_cms | 0 | $.fn.extend
data_js: (name = null) ->
if name?
$(this).data("js-#{ name }")
else
for key, value of $(this).data()
if key.match /^js/
return value
class CMS
@start: =>
@ready =>
@clear_event_handlers()
@flash_messages()
@validate_mailchimp()
@ready_with_scope 'cms-forms', =>
@validate()
@ready_with_scope 'cms-edit-mode', =>
@data_js('cms-sortable').each ->
$(this).sortable
update: (event, ui) ->
url = $(this).data_js()['url']
target = $(ui.item)
id = target.data_js('cms-sortable-id')
unique_key = { position: target.index() + 1 }
payload = $.param(id: id, unique_key: unique_key)
$.post(url, payload)
# https://github.com/gemgento/rails_script/blob/master/lib/generators/rails_script/install/templates/base.js.coffee
@clear_event_handlers: =>
$(document).on 'page:before-change', ->
for element in [window, document]
for event, handlers of ($._data(element, 'events') || {})
for handler in handlers
if handler? && handler.namespace == ''
$(element).off event, handler.handler
@flash_messages: =>
@data_js('cms-flash').fadeIn().delay(3500).fadeOut(800)
@validate: =>
$.validate({ modules: 'security', validateOnBlur: false})
@validate_mailchimp: =>
$.validate(form: '#mailchimp_form', validateOnBlur: false)
@with_scope_any: (body_classes..., handler) =>
for body_class in body_classes
if @with_scope(body_class, handler)
return
@with_scope_all: (body_classes..., handler) =>
for body_class in body_classes
if !$('body').hasClass(body_class)
return
handler()
@with_scope_none: (body_classes..., handler) =>
without_scope = true
for body_class in body_classes
if $('body').hasClass(body_class)
without_scope = false
if without_scope
handler()
@with_scope: (body_class, handler) =>
if $('body').hasClass(body_class)
handler()
true
else
false
@ready_with_scope_any: (body_classes..., handler) =>
@ready =>
@with_scope_any(body_classes..., handler)
@ready_with_scope_all: (body_classes..., handler) =>
@ready =>
@with_scope_all(body_classes..., handler)
@ready_with_scope_none: (body_classes..., handler) =>
@ready =>
@with_scope_none(body_classes..., handler)
@ready_with_scope: (body_class, handler) =>
@ready =>
@with_scope(body_class, handler)
@ready: (handler) =>
$(document).on 'ready, page:change', ->
handler()
@data_js_on: (name, events, handler) =>
$(document).on(events, "[data-js-#{ name }]", handler)
@data_js: (name) =>
$("[data-js-#{ name }]")
window.CMS = CMS
| 173585 | $.fn.extend
data_js: (name = null) ->
if name?
$(this).data("js-#{ name }")
else
for key, value of $(this).data()
if key.match /^js/
return value
class CMS
@start: =>
@ready =>
@clear_event_handlers()
@flash_messages()
@validate_mailchimp()
@ready_with_scope 'cms-forms', =>
@validate()
@ready_with_scope 'cms-edit-mode', =>
@data_js('cms-sortable').each ->
$(this).sortable
update: (event, ui) ->
url = $(this).data_js()['url']
target = $(ui.item)
id = target.data_js('cms-sortable-id')
unique_key = { position: target.<KEY> }
payload = $.param(id: id, unique_key: unique_key)
$.post(url, payload)
# https://github.com/gemgento/rails_script/blob/master/lib/generators/rails_script/install/templates/base.js.coffee
@clear_event_handlers: =>
$(document).on 'page:before-change', ->
for element in [window, document]
for event, handlers of ($._data(element, 'events') || {})
for handler in handlers
if handler? && handler.namespace == ''
$(element).off event, handler.handler
@flash_messages: =>
@data_js('cms-flash').fadeIn().delay(3500).fadeOut(800)
@validate: =>
$.validate({ modules: 'security', validateOnBlur: false})
@validate_mailchimp: =>
$.validate(form: '#mailchimp_form', validateOnBlur: false)
@with_scope_any: (body_classes..., handler) =>
for body_class in body_classes
if @with_scope(body_class, handler)
return
@with_scope_all: (body_classes..., handler) =>
for body_class in body_classes
if !$('body').hasClass(body_class)
return
handler()
@with_scope_none: (body_classes..., handler) =>
without_scope = true
for body_class in body_classes
if $('body').hasClass(body_class)
without_scope = false
if without_scope
handler()
@with_scope: (body_class, handler) =>
if $('body').hasClass(body_class)
handler()
true
else
false
@ready_with_scope_any: (body_classes..., handler) =>
@ready =>
@with_scope_any(body_classes..., handler)
@ready_with_scope_all: (body_classes..., handler) =>
@ready =>
@with_scope_all(body_classes..., handler)
@ready_with_scope_none: (body_classes..., handler) =>
@ready =>
@with_scope_none(body_classes..., handler)
@ready_with_scope: (body_class, handler) =>
@ready =>
@with_scope(body_class, handler)
@ready: (handler) =>
$(document).on 'ready, page:change', ->
handler()
@data_js_on: (name, events, handler) =>
$(document).on(events, "[data-js-#{ name }]", handler)
@data_js: (name) =>
$("[data-js-#{ name }]")
window.CMS = CMS
| true | $.fn.extend
data_js: (name = null) ->
if name?
$(this).data("js-#{ name }")
else
for key, value of $(this).data()
if key.match /^js/
return value
class CMS
@start: =>
@ready =>
@clear_event_handlers()
@flash_messages()
@validate_mailchimp()
@ready_with_scope 'cms-forms', =>
@validate()
@ready_with_scope 'cms-edit-mode', =>
@data_js('cms-sortable').each ->
$(this).sortable
update: (event, ui) ->
url = $(this).data_js()['url']
target = $(ui.item)
id = target.data_js('cms-sortable-id')
unique_key = { position: target.PI:KEY:<KEY>END_PI }
payload = $.param(id: id, unique_key: unique_key)
$.post(url, payload)
# https://github.com/gemgento/rails_script/blob/master/lib/generators/rails_script/install/templates/base.js.coffee
@clear_event_handlers: =>
$(document).on 'page:before-change', ->
for element in [window, document]
for event, handlers of ($._data(element, 'events') || {})
for handler in handlers
if handler? && handler.namespace == ''
$(element).off event, handler.handler
@flash_messages: =>
@data_js('cms-flash').fadeIn().delay(3500).fadeOut(800)
@validate: =>
$.validate({ modules: 'security', validateOnBlur: false})
@validate_mailchimp: =>
$.validate(form: '#mailchimp_form', validateOnBlur: false)
@with_scope_any: (body_classes..., handler) =>
for body_class in body_classes
if @with_scope(body_class, handler)
return
@with_scope_all: (body_classes..., handler) =>
for body_class in body_classes
if !$('body').hasClass(body_class)
return
handler()
@with_scope_none: (body_classes..., handler) =>
without_scope = true
for body_class in body_classes
if $('body').hasClass(body_class)
without_scope = false
if without_scope
handler()
@with_scope: (body_class, handler) =>
if $('body').hasClass(body_class)
handler()
true
else
false
@ready_with_scope_any: (body_classes..., handler) =>
@ready =>
@with_scope_any(body_classes..., handler)
@ready_with_scope_all: (body_classes..., handler) =>
@ready =>
@with_scope_all(body_classes..., handler)
@ready_with_scope_none: (body_classes..., handler) =>
@ready =>
@with_scope_none(body_classes..., handler)
@ready_with_scope: (body_class, handler) =>
@ready =>
@with_scope(body_class, handler)
@ready: (handler) =>
$(document).on 'ready, page:change', ->
handler()
@data_js_on: (name, events, handler) =>
$(document).on(events, "[data-js-#{ name }]", handler)
@data_js: (name) =>
$("[data-js-#{ name }]")
window.CMS = CMS
|
[
{
"context": "describe \"Martrix\", ->\n\n it \"is a function\", ->\n expect(t",
"end": 17,
"score": 0.6256194114685059,
"start": 10,
"tag": "NAME",
"value": "Martrix"
}
] | tests/jasmine/spec/matrix.coffee | DmitryMyadzelets/embrion | 0 | describe "Martrix", ->
it "is a function", ->
expect(typeof Matrix).toBe('function')
describe "new Matrix()", ->
matrix = new Matrix()
it "returns an matrix object of default size [1, 1]", ->
expect(typeof matrix).toBe('object')
it "matrix.rows() returns '1'", ->
expect(matrix.rows()).toBe(1)
it "matrix.cols() returns '1'", ->
expect(matrix.cols()).toBe(1)
it "matrix.set(0, 0, 8) and matrix.get(0, 0) allow to set and get value 8", ->
matrix.set(0, 0, 8);
expect(matrix.get(0, 0)).toBe(8)
it "outrange access matrix.get(1, 0) returns undefined", ->
expect(matrix.get(1, 0)).toBe(undefined)
describe "new Matrix(5, 3)", ->
matrix = new Matrix(5, 3)
it "matrix.size returns array [5, 3]", ->
size = matrix.size()
expect(size[0]).toBe(5)
expect(size[1]).toBe(3)
it "matrix.rows() returns 5", ->
expect(matrix.rows()).toBe(5)
it "matrix.cols() returns 3", ->
expect(matrix.cols()).toBe(3)
it "matrix.each(function foo) invokes the function (rows * cols) times", ->
matrix = new Matrix(2, 3)
cells = 0
matrix.each((row, col)->
cells += 1
)
expect(cells).toBe(6)
it "matrix.zeros() fills the matrix with 0", ->
matrix = new Matrix(2, 3)
matrix.zeros()
ok = true
v = null
matrix.each((row, col)->
v = this.get(row, col);
ok &&= (v == 0)
)
expect(ok).toBe(true)
it "with matrix.each() we can fill the matrix with 1", ->
matrix = new Matrix(2, 3)
matrix.each(() -> 1)
ok = true
v = null
matrix.each((row, col) ->
v = this.get(row, col);
ok &&= (v == 1)
)
expect(ok).toBe(true)
it "... or even with objects", ->
matrix = new Matrix(2, 3)
matrix.each((row, col) -> { row:row, col:col })
ok = true
v = null
matrix.each((row, col) ->
v = this.get(row, col)
ok &&= (typeof v == 'object' && v.row == row && v.col == col)
)
expect(ok).toBe(true)
| 44028 | describe "<NAME>", ->
it "is a function", ->
expect(typeof Matrix).toBe('function')
describe "new Matrix()", ->
matrix = new Matrix()
it "returns an matrix object of default size [1, 1]", ->
expect(typeof matrix).toBe('object')
it "matrix.rows() returns '1'", ->
expect(matrix.rows()).toBe(1)
it "matrix.cols() returns '1'", ->
expect(matrix.cols()).toBe(1)
it "matrix.set(0, 0, 8) and matrix.get(0, 0) allow to set and get value 8", ->
matrix.set(0, 0, 8);
expect(matrix.get(0, 0)).toBe(8)
it "outrange access matrix.get(1, 0) returns undefined", ->
expect(matrix.get(1, 0)).toBe(undefined)
describe "new Matrix(5, 3)", ->
matrix = new Matrix(5, 3)
it "matrix.size returns array [5, 3]", ->
size = matrix.size()
expect(size[0]).toBe(5)
expect(size[1]).toBe(3)
it "matrix.rows() returns 5", ->
expect(matrix.rows()).toBe(5)
it "matrix.cols() returns 3", ->
expect(matrix.cols()).toBe(3)
it "matrix.each(function foo) invokes the function (rows * cols) times", ->
matrix = new Matrix(2, 3)
cells = 0
matrix.each((row, col)->
cells += 1
)
expect(cells).toBe(6)
it "matrix.zeros() fills the matrix with 0", ->
matrix = new Matrix(2, 3)
matrix.zeros()
ok = true
v = null
matrix.each((row, col)->
v = this.get(row, col);
ok &&= (v == 0)
)
expect(ok).toBe(true)
it "with matrix.each() we can fill the matrix with 1", ->
matrix = new Matrix(2, 3)
matrix.each(() -> 1)
ok = true
v = null
matrix.each((row, col) ->
v = this.get(row, col);
ok &&= (v == 1)
)
expect(ok).toBe(true)
it "... or even with objects", ->
matrix = new Matrix(2, 3)
matrix.each((row, col) -> { row:row, col:col })
ok = true
v = null
matrix.each((row, col) ->
v = this.get(row, col)
ok &&= (typeof v == 'object' && v.row == row && v.col == col)
)
expect(ok).toBe(true)
| true | describe "PI:NAME:<NAME>END_PI", ->
it "is a function", ->
expect(typeof Matrix).toBe('function')
describe "new Matrix()", ->
matrix = new Matrix()
it "returns an matrix object of default size [1, 1]", ->
expect(typeof matrix).toBe('object')
it "matrix.rows() returns '1'", ->
expect(matrix.rows()).toBe(1)
it "matrix.cols() returns '1'", ->
expect(matrix.cols()).toBe(1)
it "matrix.set(0, 0, 8) and matrix.get(0, 0) allow to set and get value 8", ->
matrix.set(0, 0, 8);
expect(matrix.get(0, 0)).toBe(8)
it "outrange access matrix.get(1, 0) returns undefined", ->
expect(matrix.get(1, 0)).toBe(undefined)
describe "new Matrix(5, 3)", ->
matrix = new Matrix(5, 3)
it "matrix.size returns array [5, 3]", ->
size = matrix.size()
expect(size[0]).toBe(5)
expect(size[1]).toBe(3)
it "matrix.rows() returns 5", ->
expect(matrix.rows()).toBe(5)
it "matrix.cols() returns 3", ->
expect(matrix.cols()).toBe(3)
it "matrix.each(function foo) invokes the function (rows * cols) times", ->
matrix = new Matrix(2, 3)
cells = 0
matrix.each((row, col)->
cells += 1
)
expect(cells).toBe(6)
it "matrix.zeros() fills the matrix with 0", ->
matrix = new Matrix(2, 3)
matrix.zeros()
ok = true
v = null
matrix.each((row, col)->
v = this.get(row, col);
ok &&= (v == 0)
)
expect(ok).toBe(true)
it "with matrix.each() we can fill the matrix with 1", ->
matrix = new Matrix(2, 3)
matrix.each(() -> 1)
ok = true
v = null
matrix.each((row, col) ->
v = this.get(row, col);
ok &&= (v == 1)
)
expect(ok).toBe(true)
it "... or even with objects", ->
matrix = new Matrix(2, 3)
matrix.each((row, col) -> { row:row, col:col })
ok = true
v = null
matrix.each((row, col) ->
v = this.get(row, col)
ok &&= (typeof v == 'object' && v.row == row && v.col == col)
)
expect(ok).toBe(true)
|
[
{
"context": "#Copyright (c) 2012 Elf M. Sternberg\n#\n# Much of the code here I would never have unde",
"end": 36,
"score": 0.9998660087585449,
"start": 20,
"tag": "NAME",
"value": "Elf M. Sternberg"
},
{
"context": "rstood if it hadn't\n# been for the patient work of Caleb Helbling... | src/sat.coffee | elfsternberg/fridgemagnets | 0 | #Copyright (c) 2012 Elf M. Sternberg
#
# Much of the code here I would never have understood if it hadn't
# been for the patient work of Caleb Helbling
# (http://www.propulsionjs.com/), as well as the Wikipedia pages for
# the Separating Axis Theorem. It took me a week to wrap my head
# around these ideas.
#
#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.
Math.vector =
add: (v1, v2) -> {x: (v1.x + v2.x), y: (v1.y + v2.y)}
# Scale a given vector.
scalar: (v, s) -> {x: (v.x * s), y: (v.y * s)}
dot: (v1, v2) -> v1.x * v2.x + v1.y * v2.y
magnitude2: (v) ->
x = v.x
y = v.y
x * x + y * y
magnitude: (v) -> Math.sqrt(Math.vector.magnitude2(v))
normalize: (v) ->
mag = Math.vector.magnitude(v)
{x: (v.x / mag), y: (v.y / mag)}
leftNormal: (v) -> {x: -v.y, y: v.x}
this.colliding = (shape1, shape2) ->
# Return the axes of a shape. In a polygon, each potential
# separating axis is the normal to each edge. For our purposes, a
# "shape" is an array of points with the structure [{x: 0, y: 0}, .. ]
# We assume that the final edge is from the last point back to the
# first.
genAxes = (shape) ->
throw "Cannot handle non-polygons" if shape.length < 3
# Calculate the normal of a single pair of points in the
# shape.
axis = (shape, pi) ->
p1 = shape[pi]
p2 = shape[if pi == (shape.length - 1) then 0 else pi + 1]
edge = {x: p1.x - p2.x, y: p1.y - p2.y}
Math.vector.normalize(Math.vector.leftNormal(edge))
(axis(shape, i) for i in [0...shape.length])
# Calculate the extremis of the shape "above" a given axis
genProjection = (shape, axis) ->
min = Math.vector.dot(axis, shape[0])
max = min
for i in [1...shape.length]
p = Math.vector.dot(axis, shape[i])
min = p if p < min
max = p if p > max
{min: min, max: max}
axes1 = genAxes(shape1)
axes2 = genAxes(shape2)
axes = axes1.concat axes2
for axis in axes
proj1 = genProjection(shape1, axis)
proj2 = genProjection(shape2, axis)
if not ( \
(proj1.min >= proj2.min and proj1.min <= proj2.max) or \
(proj1.max >= proj2.min and proj1.max <= proj2.max) or \
(proj2.min >= proj1.min and proj2.min <= proj1.max) or \
(proj2.max >= proj1.min and proj2.max <= proj1.max))
return false
return true
| 95606 | #Copyright (c) 2012 <NAME>
#
# Much of the code here I would never have understood if it hadn't
# been for the patient work of <NAME>
# (http://www.propulsionjs.com/), as well as the Wikipedia pages for
# the Separating Axis Theorem. It took me a week to wrap my head
# around these ideas.
#
#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.
Math.vector =
add: (v1, v2) -> {x: (v1.x + v2.x), y: (v1.y + v2.y)}
# Scale a given vector.
scalar: (v, s) -> {x: (v.x * s), y: (v.y * s)}
dot: (v1, v2) -> v1.x * v2.x + v1.y * v2.y
magnitude2: (v) ->
x = v.x
y = v.y
x * x + y * y
magnitude: (v) -> Math.sqrt(Math.vector.magnitude2(v))
normalize: (v) ->
mag = Math.vector.magnitude(v)
{x: (v.x / mag), y: (v.y / mag)}
leftNormal: (v) -> {x: -v.y, y: v.x}
this.colliding = (shape1, shape2) ->
# Return the axes of a shape. In a polygon, each potential
# separating axis is the normal to each edge. For our purposes, a
# "shape" is an array of points with the structure [{x: 0, y: 0}, .. ]
# We assume that the final edge is from the last point back to the
# first.
genAxes = (shape) ->
throw "Cannot handle non-polygons" if shape.length < 3
# Calculate the normal of a single pair of points in the
# shape.
axis = (shape, pi) ->
p1 = shape[pi]
p2 = shape[if pi == (shape.length - 1) then 0 else pi + 1]
edge = {x: p1.x - p2.x, y: p1.y - p2.y}
Math.vector.normalize(Math.vector.leftNormal(edge))
(axis(shape, i) for i in [0...shape.length])
# Calculate the extremis of the shape "above" a given axis
genProjection = (shape, axis) ->
min = Math.vector.dot(axis, shape[0])
max = min
for i in [1...shape.length]
p = Math.vector.dot(axis, shape[i])
min = p if p < min
max = p if p > max
{min: min, max: max}
axes1 = genAxes(shape1)
axes2 = genAxes(shape2)
axes = axes1.concat axes2
for axis in axes
proj1 = genProjection(shape1, axis)
proj2 = genProjection(shape2, axis)
if not ( \
(proj1.min >= proj2.min and proj1.min <= proj2.max) or \
(proj1.max >= proj2.min and proj1.max <= proj2.max) or \
(proj2.min >= proj1.min and proj2.min <= proj1.max) or \
(proj2.max >= proj1.min and proj2.max <= proj1.max))
return false
return true
| true | #Copyright (c) 2012 PI:NAME:<NAME>END_PI
#
# Much of the code here I would never have understood if it hadn't
# been for the patient work of PI:NAME:<NAME>END_PI
# (http://www.propulsionjs.com/), as well as the Wikipedia pages for
# the Separating Axis Theorem. It took me a week to wrap my head
# around these ideas.
#
#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.
Math.vector =
add: (v1, v2) -> {x: (v1.x + v2.x), y: (v1.y + v2.y)}
# Scale a given vector.
scalar: (v, s) -> {x: (v.x * s), y: (v.y * s)}
dot: (v1, v2) -> v1.x * v2.x + v1.y * v2.y
magnitude2: (v) ->
x = v.x
y = v.y
x * x + y * y
magnitude: (v) -> Math.sqrt(Math.vector.magnitude2(v))
normalize: (v) ->
mag = Math.vector.magnitude(v)
{x: (v.x / mag), y: (v.y / mag)}
leftNormal: (v) -> {x: -v.y, y: v.x}
this.colliding = (shape1, shape2) ->
# Return the axes of a shape. In a polygon, each potential
# separating axis is the normal to each edge. For our purposes, a
# "shape" is an array of points with the structure [{x: 0, y: 0}, .. ]
# We assume that the final edge is from the last point back to the
# first.
genAxes = (shape) ->
throw "Cannot handle non-polygons" if shape.length < 3
# Calculate the normal of a single pair of points in the
# shape.
axis = (shape, pi) ->
p1 = shape[pi]
p2 = shape[if pi == (shape.length - 1) then 0 else pi + 1]
edge = {x: p1.x - p2.x, y: p1.y - p2.y}
Math.vector.normalize(Math.vector.leftNormal(edge))
(axis(shape, i) for i in [0...shape.length])
# Calculate the extremis of the shape "above" a given axis
genProjection = (shape, axis) ->
min = Math.vector.dot(axis, shape[0])
max = min
for i in [1...shape.length]
p = Math.vector.dot(axis, shape[i])
min = p if p < min
max = p if p > max
{min: min, max: max}
axes1 = genAxes(shape1)
axes2 = genAxes(shape2)
axes = axes1.concat axes2
for axis in axes
proj1 = genProjection(shape1, axis)
proj2 = genProjection(shape2, axis)
if not ( \
(proj1.min >= proj2.min and proj1.min <= proj2.max) or \
(proj1.max >= proj2.min and proj1.max <= proj2.max) or \
(proj2.min >= proj1.min and proj2.min <= proj1.max) or \
(proj2.max >= proj1.min and proj2.max <= proj1.max))
return false
return true
|
[
{
"context": "s!\n# Entry for the GitHub Game Off 2013\n# Author : Paul Joannon for H-Bomb\n# <paul.joannon@gmail.com>\n##\n#####\n\n#",
"end": 85,
"score": 0.9998569488525391,
"start": 73,
"tag": "NAME",
"value": "Paul Joannon"
},
{
"context": "e GitHub Game Off 2013\n# Author : Pau... | assets/js/coffee/character.coffee | MySweetWhomp/demcreepers | 1 | #####
##
# Dem Creepers!
# Entry for the GitHub Game Off 2013
# Author : Paul Joannon for H-Bomb
# <paul.joannon@gmail.com>
##
#####
###
# Characters base class
###
class Character
constructor : (@x, @y, @speed, @feetShift, width, height) ->
@_box = new jaws.Sprite
x : @x
y : @y
width : width
height : height
anchor : 'center'
scale : 2
@_sprite = new jaws.Sprite
x : @x
y : @y
anchor : 'center'
scale : 2
@_feets = new jaws.Sprite
x : @x
y : @y + @feetShift
anchor : 'center'
scale : 2
@_vx = 0
@_vy = 0
@_orientation = 'E'
@_bump = no
@_state = 'idle'
getToDraw : => @
update : (map) =>
@_bump = no
@move map
@_sprite.moveTo @x, @y
@_box.coll = undefined
draw : =>
#do (do @_box.rect).draw
#do (do @_feets.rect).draw
moveOneComp : (comp, map) =>
moved = yes
old = @[comp]
@[comp] += @["_v#{comp}"]
if @_box.coll?
distance = window.DemCreepers.Utils.pointDistance @_box.x, @_box.y, @_box.coll.x, @_box.coll.y
@_box.moveTo @x, @y
distance2 = window.DemCreepers.Utils.pointDistance @_box.x, @_box.y, @_box.coll.x, @_box.coll.y
if distance2 < distance
@[comp] -= @["_v#{comp}"]
@_box.moveTo @x, @y
moved = no
else
@_box.moveTo @x, @y
@_feets.moveTo @x, @y + @feetShift
box = do @_feets.rect
if moved
atRect = map.atRect box
if atRect.length > 0
atRect = _.sortBy atRect, (a) => - a.type.length
for cell in atRect
cellRect = do cell.rect
if cellRect.collideRect box
if cell.type is 'Gob'
@[comp] -= @["_v#{comp}"] / 2
@_feets.moveTo @x, @y + @feetShift
else
moved = no
@_bump = yes
step = @["_v#{comp}"] / Math.abs @["_v#{comp}"]
@[comp] -= step
@_feets.moveTo @x, @y + @feetShift
box = do @_feets.rect
i = 0
while (cellRect.collideRect box)
@[comp] -= step
@_feets.moveTo @x, @y + @feetShift
box = do @_feets.rect
break
@_box.moveTo @x, @y
return moved
move : (map) =>
if @_vx is 0 and @_vy is 0
return
movedX = (@moveOneComp 'x', map) if @_vx isnt 0
movedY = (@moveOneComp 'y', map) if @_vy isnt 0
movedX or movedY
class Player extends Character
constructor : (@x, @y) ->
super @x, @y, 6, 35, 12, 20
@Mult = 1
@Chain = 0
@PerfectChain = 0
@_hit = no
@_feets.resizeTo 30, 25
@_orientation = 'SW'
@Dead = no
@WOOSH = new jaws.Audio audio : 'audio/WOOSH.ogg', volume : window.DemCreepers.Volumes.FX
@DEAD = [
new jaws.Audio audio : 'audio/MORT01.ogg', volume : window.DemCreepers.Volumes.FX
new jaws.Audio audio : 'audio/MORT02.ogg', volume : window.DemCreepers.Volumes.FX
]
@GAMEOVER = new jaws.Audio audio : 'audio/GAMEOVER.ogg', volume : window.DemCreepers.Volumes.FX
@_hp = 100
@_attack = @attack
@_changeStateOr = @changeStateOr
@_getHit = @getHit
@_onlasframe = =>
@_sheet = new jaws.Animation
sprite_sheet : 'img/Barbarian.gif'
frame_size : [50, 50]
orientation : 'right'
@_sheet2 = new jaws.Animation
sprite_sheet : 'img/Barbarian.gif'
frame_size : [50, 50]
orientation : 'right'
frame_duration : 60
@_state = 'idle'
@_anims =
'idle' :
'N' : @_sheet.slice 24, 28
'NE' : @_sheet.slice 30, 34
'E' : @_sheet.slice 36, 40
'SE' : @_sheet.slice 42, 46
'S' : @_sheet.slice 0, 4
'SW' : @_sheet.slice 6, 10
'W' : @_sheet.slice 12, 16
'NW' : @_sheet.slice 18, 22
'run' :
'N' : @_sheet.slice 72, 78
'NE' : @_sheet.slice 78, 84
'E' : @_sheet.slice 84, 90
'SE' : @_sheet.slice 90, 96
'S' : @_sheet.slice 48, 54
'SW' : @_sheet.slice 54, 60
'W' : @_sheet.slice 60, 66
'NW' : @_sheet.slice 66, 72
'attack' :
'N' : @_sheet2.slice 108, 111
'NE' : @_sheet2.slice 111, 114
'E' : @_sheet2.slice 114, 117
'SE' : @_sheet2.slice 117, 120
'S' : @_sheet2.slice 96, 99
'SW' : @_sheet2.slice 99, 102
'W' : @_sheet2.slice 102, 105
'NW' : @_sheet2.slice 105, 108
'dead' :
'N' : @_sheet.slice 120, 127
@_anims['dead']['E'] = @_anims['dead']['NE'] = @_anims['dead']['SE'] = @_anims['dead']['S'] =
@_anims['dead']['SW'] = @_anims['dead']['W'] = @_anims['dead']['NW'] = @_anims['dead']['N']
@_axes = []
getToDraw : =>
_.union @_axes, [@]
simpleUpdate : =>
@_sprite.setImage do @_anims[@_state][@_orientation].next
update : (viewport, map) =>
if @Dead
return no
if do @_anims[@_state][@_orientation].atLastFrame
do @_onlasframe
if @_state isnt 'dead'
@_vx = @_vy = 0
viewport.forceInsideVisibleArea @_sprite, 20
@x = @_sprite.x
@y = @_sprite.y
@handleInputs viewport
try
super map
@_sprite.setImage do @_anims[@_state][@_orientation].next
###
# Manage axes
###
toDel = []
_.map @_axes, (axe, index) =>
axe.update map
if axe._toGo <= 0
toDel.push index
toDel = toDel.sort (a, b) => b - a
_.map toDel, (index) =>
@_axes.splice index, 1
return yes
draw : =>
do @_sprite.draw
try
do super
getHit : (n) =>
@_getHit = =>
setTimeout (=>
@_getHit = @getHit
), 1000
@_hit = yes
@Chain = 0
@PerfectChain = 0
@Mult = 1
if (@_hp -= n) <= 0
if @_state isnt 'dead'
do @DEAD[_.random 0, 1].play
setTimeout (=>
do @GAMEOVER.play
), 800
@_hp = 0
@_state = 'dead'
@_onlasframe = =>
@Dead = yes
@_onlasframe = =>
changeStateOr : (state, orientation) =>
@_state = state
if orientation?
@_orientation = orientation
attack : (dir) =>
do @WOOSH.play
old = @_orientation
@_orientation = dir
@_axes.push new Axe dir, @x, @y
@_state = 'attack'
@_attack = =>
@_changeStateOr = =>
@_onlasframe = =>
@_orientation = old
@_changeStateOr = @changeStateOr
@_onlasframe = =>
setTimeout (=>
@_attack = @attack
), 50
handleInputs : (viewport) =>
###
# Movements
###
mov = x : 0, y : 0
vComp = ''
hComp = ''
controls = window.DemCreepers.Controls[window.DemCreepers.Config.ActiveControls]
if jaws.pressed "#{controls.up}"
--mov.y
vComp = 'N'
if jaws.pressed "#{controls.right}"
++mov.x
hComp = 'E'
if jaws.pressed "#{controls.down}"
++mov.y
vComp = 'S'
if jaws.pressed "#{controls.left}"
--mov.x
hComp = 'W'
if not (newOr = vComp + hComp)
@_changeStateOr 'idle'
else
@_changeStateOr 'run', (vComp + hComp)
@_vx = @speed * mov.x
@_vy = @speed * mov.y
###
# Attacks
###
if jaws.pressedWithoutRepeat "left_mouse_button"
relX = @x - viewport.x
relY = @y - viewport.y
dir = window.DemCreepers.Utils.pointOrientation jaws.mouse_x, jaws.mouse_y, relX, relY
@_attack dir
###
# DEBUG
###
if jaws.pressedWithoutRepeat "shift"
@_attack @_orientation
class Axe extends Character
constructor : (dir, @x, @y) ->
super @x, @y, 7, 0, 10, 10
@_toGo = 500
@_dirx = @_diry = 0
if (dir.indexOf 'N') >= 0
@_diry = -1
else if (dir.indexOf 'S') >= 0
@_diry = 1
if (dir.indexOf 'W') >= 0
@_dirx = -1
else if (dir.indexOf 'E') >= 0
@_dirx = 1
@_sheet = new jaws.Animation
sprite_sheet : 'img/Axe.gif'
frame_size : [20, 20]
orientation : 'right'
frame_duration : 75
move : (map) =>
if @_vx is 0 and @_vy is 0
return
@x += @_vx
@_box.moveTo @x, @y
@y += @_vy
@_box.moveTo @x, @y
update : (map) =>
@_vx = @speed * @_dirx
@_vy = @speed * @_diry
@_toGo -= @speed
try
super map
if @_bump
@_toGo = 0
@_sprite.setImage do @_sheet.next
draw : =>
do @_sprite.draw
try
do super
###
# Monsters base class
###
class Monster extends Character
constructor : (@x, @y, @speed, @feetShift, @pv, @reward, @distAttack, width, height, sheetName, frameSize) ->
super @x, @y, @speed, @feetShift, width, height
@_state = 'run'
@_sheet = new jaws.Animation
sprite_sheet : "img/#{sheetName}"
frame_size : frameSize
orientation : 'right'
frame_duration : 70
@_changeOrientation = (o) => @_orientation = o
@_changestate = (s) => @_state = s
@_attack = @attack
###
# Define orientation based move methods
# Allows not to check direction each game loop iteration
###
@_move =
'N' : () => @_vy = -@speed ; @_vx = 0
'NE' : () => @_vy = -@speed ; @_vx = @speed
'E' : () => @_vy = 0 ; @_vx = @speed
'SE' : () => @_vy = @speed ; @_vx = @speed
'S' : () => @_vy = @speed ; @_vx = 0
'SW' : () => @_vy = @speed ; @_vx = -@speed
'W' : () => @_vy = 0 ; @_vx = -@speed
'NW' : () => @_vy = -@speed ; @_vx = -@speed
update : (player, map) =>
@_bump = no
@_distToPlayer = window.DemCreepers.Utils.pointDistance player.x, player.y, @x, @y
@_changeOrientation window.DemCreepers.Utils.pointOrientation player.x, player.y, @x, @y
@_sprite.setImage do @_anims[@_state][@_orientation].next
if @_state isnt 'attack' and @_distToPlayer > @distAttack
do @_move[@_orientation]
moved = @move map
if not moved
oldOr = @_orientation
ors = window.DemCreepers.Utils.getNextOr @_orientation
i = 0
while not moved
@_orientation = ors[i++]
break if @_orientation is oldOr
do @_move[@_orientation]
moved = @move map
if moved
@_changeOrientation = =>
setTimeout (=>
@_changeOrientation = (o) => @_orientation = o
), (if @_bump then (@speed * 200) else (@speed * 100))
@_changestate 'run'
else
@_vx = @_vy = 0
@_attack player
@_box.coll = undefined
@_sprite.moveTo @x, @y
attack : (player) =>
@_changestate 'attack'
player._getHit 5
@_attack = =>
setTimeout (=>
@_attack = @attack
(@_changestate 'run') if @_distToPlayer > @distAttack
), 420
class Gob extends Monster
constructor : (@x, @y) ->
super @x, @y, 4, 10, 1, 10, 35, 15, 15, 'Gob.gif', [50, 50]
@_feets.resizeTo 30, 20
@_anims =
'run' :
'N' : @_sheet.slice 20, 30
'NE' : @_sheet.slice 30, 40
'E' : @_sheet.slice 30, 40
'SE' : @_sheet.slice 30, 40
'S' : @_sheet.slice 0, 10
'SW' : @_sheet.slice 10, 20
'W' : @_sheet.slice 10, 20
'NW' : @_sheet.slice 10, 20
'attack' :
'N' : @_sheet.slice 70, 76
'NE' : @_sheet.slice 60, 66
'E' : @_sheet.slice 60, 66
'SE' : @_sheet.slice 60, 66
'S' : @_sheet.slice 40, 46
'SW' : @_sheet.slice 50, 56
'W' : @_sheet.slice 50, 56
'NW' : @_sheet.slice 50, 56
update : (player, map) =>
try
super player, map
draw : =>
do @_sprite.draw
try
do super
class Golem extends Monster
constructor : (@x, @y) ->
super @x, @y, 2, 75, 7, 50, 200, 75, 75, 'GOLEM.gif', [200, 200]
@_feets.resizeTo 150, 40
@_sheet.frame_duration = 150
@_sheet2 = new jaws.Animation
sprite_sheet : "img/GOLEM.gif"
frame_size : [200, 200]
orientation : 'right'
frame_duration : 80
@_anims =
'run' :
'N' : @_sheet.slice 10, 20
'NE' : @_sheet.slice 10, 20
'E' : @_sheet.slice 20, 30
'SE' : @_sheet.slice 20, 30
'S' : @_sheet.slice 0, 10
'SW' : @_sheet.slice 0, 10
'W' : @_sheet.slice 0, 10
'NW' : @_sheet.slice 30, 40
'attack' :
'N' : @_sheet2.slice 70, 79
'NE' : @_sheet2.slice 110, 119
'E' : @_sheet2.slice 50, 59
'SE' : @_sheet2.slice 90, 99
'S' : @_sheet2.slice 60, 69
'SW' : @_sheet2.slice 80, 89
'W' : @_sheet2.slice 40, 49
'NW' : @_sheet2.slice 100, 109
@_fist = new jaws.Sprite
anchor : 'center'
x : @x
y : @y
width: 70
height : 70
update : (player, map) =>
try
super player, map
@frame = @_anims[@_state][@_orientation].index
@_fist.moveTo @x, @y
if 'E' in @_orientation
@_fist.move 140, 0
else if 'W' in @_orientation
@_fist.move -140, 0
if 'S' in @_orientation
@_fist.move 0, 140
else if 'N' in @_orientation
@_fist.move 0, -140
if @_state is 'attack' and 3 < @frame < 8 and (do @_fist.rect).collideRect (do player._box.rect)
player._getHit 15
draw : =>
do @_sprite.draw
# if @_state is 'attack'
# if 3 < @frame < 8
# do @_fist.draw
try
do super
attack : (player) =>
@_state = 'attack'
@_attack = =>
@_changestate = =>
@_changeOrientation = =>
setTimeout (=>
@_attack = @attack
@_changestate = (s) => @_state = s
@_changeOrientation = (o) => @_orientation = o
(@_changestate 'run') if @_distToPlayer > @distAttack
), 720
if window.DemCreepers?
window.DemCreepers.Character = Character
window.DemCreepers.Player = Player
window.DemCreepers.Gob = Gob
window.DemCreepers.Golem = Golem
| 71299 | #####
##
# Dem Creepers!
# Entry for the GitHub Game Off 2013
# Author : <NAME> for <NAME>
# <<EMAIL>>
##
#####
###
# Characters base class
###
class Character
constructor : (@x, @y, @speed, @feetShift, width, height) ->
@_box = new jaws.Sprite
x : @x
y : @y
width : width
height : height
anchor : 'center'
scale : 2
@_sprite = new jaws.Sprite
x : @x
y : @y
anchor : 'center'
scale : 2
@_feets = new jaws.Sprite
x : @x
y : @y + @feetShift
anchor : 'center'
scale : 2
@_vx = 0
@_vy = 0
@_orientation = 'E'
@_bump = no
@_state = 'idle'
getToDraw : => @
update : (map) =>
@_bump = no
@move map
@_sprite.moveTo @x, @y
@_box.coll = undefined
draw : =>
#do (do @_box.rect).draw
#do (do @_feets.rect).draw
moveOneComp : (comp, map) =>
moved = yes
old = @[comp]
@[comp] += @["_v#{comp}"]
if @_box.coll?
distance = window.DemCreepers.Utils.pointDistance @_box.x, @_box.y, @_box.coll.x, @_box.coll.y
@_box.moveTo @x, @y
distance2 = window.DemCreepers.Utils.pointDistance @_box.x, @_box.y, @_box.coll.x, @_box.coll.y
if distance2 < distance
@[comp] -= @["_v#{comp}"]
@_box.moveTo @x, @y
moved = no
else
@_box.moveTo @x, @y
@_feets.moveTo @x, @y + @feetShift
box = do @_feets.rect
if moved
atRect = map.atRect box
if atRect.length > 0
atRect = _.sortBy atRect, (a) => - a.type.length
for cell in atRect
cellRect = do cell.rect
if cellRect.collideRect box
if cell.type is 'Gob'
@[comp] -= @["_v#{comp}"] / 2
@_feets.moveTo @x, @y + @feetShift
else
moved = no
@_bump = yes
step = @["_v#{comp}"] / Math.abs @["_v#{comp}"]
@[comp] -= step
@_feets.moveTo @x, @y + @feetShift
box = do @_feets.rect
i = 0
while (cellRect.collideRect box)
@[comp] -= step
@_feets.moveTo @x, @y + @feetShift
box = do @_feets.rect
break
@_box.moveTo @x, @y
return moved
move : (map) =>
if @_vx is 0 and @_vy is 0
return
movedX = (@moveOneComp 'x', map) if @_vx isnt 0
movedY = (@moveOneComp 'y', map) if @_vy isnt 0
movedX or movedY
class Player extends Character
constructor : (@x, @y) ->
super @x, @y, 6, 35, 12, 20
@Mult = 1
@Chain = 0
@PerfectChain = 0
@_hit = no
@_feets.resizeTo 30, 25
@_orientation = 'SW'
@Dead = no
@WOOSH = new jaws.Audio audio : 'audio/WOOSH.ogg', volume : window.DemCreepers.Volumes.FX
@DEAD = [
new jaws.Audio audio : 'audio/MORT01.ogg', volume : window.DemCreepers.Volumes.FX
new jaws.Audio audio : 'audio/MORT02.ogg', volume : window.DemCreepers.Volumes.FX
]
@GAMEOVER = new jaws.Audio audio : 'audio/GAMEOVER.ogg', volume : window.DemCreepers.Volumes.FX
@_hp = 100
@_attack = @attack
@_changeStateOr = @changeStateOr
@_getHit = @getHit
@_onlasframe = =>
@_sheet = new jaws.Animation
sprite_sheet : 'img/Barbarian.gif'
frame_size : [50, 50]
orientation : 'right'
@_sheet2 = new jaws.Animation
sprite_sheet : 'img/Barbarian.gif'
frame_size : [50, 50]
orientation : 'right'
frame_duration : 60
@_state = 'idle'
@_anims =
'idle' :
'N' : @_sheet.slice 24, 28
'NE' : @_sheet.slice 30, 34
'E' : @_sheet.slice 36, 40
'SE' : @_sheet.slice 42, 46
'S' : @_sheet.slice 0, 4
'SW' : @_sheet.slice 6, 10
'W' : @_sheet.slice 12, 16
'NW' : @_sheet.slice 18, 22
'run' :
'N' : @_sheet.slice 72, 78
'NE' : @_sheet.slice 78, 84
'E' : @_sheet.slice 84, 90
'SE' : @_sheet.slice 90, 96
'S' : @_sheet.slice 48, 54
'SW' : @_sheet.slice 54, 60
'W' : @_sheet.slice 60, 66
'NW' : @_sheet.slice 66, 72
'attack' :
'N' : @_sheet2.slice 108, 111
'NE' : @_sheet2.slice 111, 114
'E' : @_sheet2.slice 114, 117
'SE' : @_sheet2.slice 117, 120
'S' : @_sheet2.slice 96, 99
'SW' : @_sheet2.slice 99, 102
'W' : @_sheet2.slice 102, 105
'NW' : @_sheet2.slice 105, 108
'dead' :
'N' : @_sheet.slice 120, 127
@_anims['dead']['E'] = @_anims['dead']['NE'] = @_anims['dead']['SE'] = @_anims['dead']['S'] =
@_anims['dead']['SW'] = @_anims['dead']['W'] = @_anims['dead']['NW'] = @_anims['dead']['N']
@_axes = []
getToDraw : =>
_.union @_axes, [@]
simpleUpdate : =>
@_sprite.setImage do @_anims[@_state][@_orientation].next
update : (viewport, map) =>
if @Dead
return no
if do @_anims[@_state][@_orientation].atLastFrame
do @_onlasframe
if @_state isnt 'dead'
@_vx = @_vy = 0
viewport.forceInsideVisibleArea @_sprite, 20
@x = @_sprite.x
@y = @_sprite.y
@handleInputs viewport
try
super map
@_sprite.setImage do @_anims[@_state][@_orientation].next
###
# Manage axes
###
toDel = []
_.map @_axes, (axe, index) =>
axe.update map
if axe._toGo <= 0
toDel.push index
toDel = toDel.sort (a, b) => b - a
_.map toDel, (index) =>
@_axes.splice index, 1
return yes
draw : =>
do @_sprite.draw
try
do super
getHit : (n) =>
@_getHit = =>
setTimeout (=>
@_getHit = @getHit
), 1000
@_hit = yes
@Chain = 0
@PerfectChain = 0
@Mult = 1
if (@_hp -= n) <= 0
if @_state isnt 'dead'
do @DEAD[_.random 0, 1].play
setTimeout (=>
do @GAMEOVER.play
), 800
@_hp = 0
@_state = 'dead'
@_onlasframe = =>
@Dead = yes
@_onlasframe = =>
changeStateOr : (state, orientation) =>
@_state = state
if orientation?
@_orientation = orientation
attack : (dir) =>
do @WOOSH.play
old = @_orientation
@_orientation = dir
@_axes.push new Axe dir, @x, @y
@_state = 'attack'
@_attack = =>
@_changeStateOr = =>
@_onlasframe = =>
@_orientation = old
@_changeStateOr = @changeStateOr
@_onlasframe = =>
setTimeout (=>
@_attack = @attack
), 50
handleInputs : (viewport) =>
###
# Movements
###
mov = x : 0, y : 0
vComp = ''
hComp = ''
controls = window.DemCreepers.Controls[window.DemCreepers.Config.ActiveControls]
if jaws.pressed "#{controls.up}"
--mov.y
vComp = 'N'
if jaws.pressed "#{controls.right}"
++mov.x
hComp = 'E'
if jaws.pressed "#{controls.down}"
++mov.y
vComp = 'S'
if jaws.pressed "#{controls.left}"
--mov.x
hComp = 'W'
if not (newOr = vComp + hComp)
@_changeStateOr 'idle'
else
@_changeStateOr 'run', (vComp + hComp)
@_vx = @speed * mov.x
@_vy = @speed * mov.y
###
# Attacks
###
if jaws.pressedWithoutRepeat "left_mouse_button"
relX = @x - viewport.x
relY = @y - viewport.y
dir = window.DemCreepers.Utils.pointOrientation jaws.mouse_x, jaws.mouse_y, relX, relY
@_attack dir
###
# DEBUG
###
if jaws.pressedWithoutRepeat "shift"
@_attack @_orientation
class Axe extends Character
constructor : (dir, @x, @y) ->
super @x, @y, 7, 0, 10, 10
@_toGo = 500
@_dirx = @_diry = 0
if (dir.indexOf 'N') >= 0
@_diry = -1
else if (dir.indexOf 'S') >= 0
@_diry = 1
if (dir.indexOf 'W') >= 0
@_dirx = -1
else if (dir.indexOf 'E') >= 0
@_dirx = 1
@_sheet = new jaws.Animation
sprite_sheet : 'img/Axe.gif'
frame_size : [20, 20]
orientation : 'right'
frame_duration : 75
move : (map) =>
if @_vx is 0 and @_vy is 0
return
@x += @_vx
@_box.moveTo @x, @y
@y += @_vy
@_box.moveTo @x, @y
update : (map) =>
@_vx = @speed * @_dirx
@_vy = @speed * @_diry
@_toGo -= @speed
try
super map
if @_bump
@_toGo = 0
@_sprite.setImage do @_sheet.next
draw : =>
do @_sprite.draw
try
do super
###
# Monsters base class
###
class Monster extends Character
constructor : (@x, @y, @speed, @feetShift, @pv, @reward, @distAttack, width, height, sheetName, frameSize) ->
super @x, @y, @speed, @feetShift, width, height
@_state = 'run'
@_sheet = new jaws.Animation
sprite_sheet : "img/#{sheetName}"
frame_size : frameSize
orientation : 'right'
frame_duration : 70
@_changeOrientation = (o) => @_orientation = o
@_changestate = (s) => @_state = s
@_attack = @attack
###
# Define orientation based move methods
# Allows not to check direction each game loop iteration
###
@_move =
'N' : () => @_vy = -@speed ; @_vx = 0
'NE' : () => @_vy = -@speed ; @_vx = @speed
'E' : () => @_vy = 0 ; @_vx = @speed
'SE' : () => @_vy = @speed ; @_vx = @speed
'S' : () => @_vy = @speed ; @_vx = 0
'SW' : () => @_vy = @speed ; @_vx = -@speed
'W' : () => @_vy = 0 ; @_vx = -@speed
'NW' : () => @_vy = -@speed ; @_vx = -@speed
update : (player, map) =>
@_bump = no
@_distToPlayer = window.DemCreepers.Utils.pointDistance player.x, player.y, @x, @y
@_changeOrientation window.DemCreepers.Utils.pointOrientation player.x, player.y, @x, @y
@_sprite.setImage do @_anims[@_state][@_orientation].next
if @_state isnt 'attack' and @_distToPlayer > @distAttack
do @_move[@_orientation]
moved = @move map
if not moved
oldOr = @_orientation
ors = window.DemCreepers.Utils.getNextOr @_orientation
i = 0
while not moved
@_orientation = ors[i++]
break if @_orientation is oldOr
do @_move[@_orientation]
moved = @move map
if moved
@_changeOrientation = =>
setTimeout (=>
@_changeOrientation = (o) => @_orientation = o
), (if @_bump then (@speed * 200) else (@speed * 100))
@_changestate 'run'
else
@_vx = @_vy = 0
@_attack player
@_box.coll = undefined
@_sprite.moveTo @x, @y
attack : (player) =>
@_changestate 'attack'
player._getHit 5
@_attack = =>
setTimeout (=>
@_attack = @attack
(@_changestate 'run') if @_distToPlayer > @distAttack
), 420
class Gob extends Monster
constructor : (@x, @y) ->
super @x, @y, 4, 10, 1, 10, 35, 15, 15, 'Gob.gif', [50, 50]
@_feets.resizeTo 30, 20
@_anims =
'run' :
'N' : @_sheet.slice 20, 30
'NE' : @_sheet.slice 30, 40
'E' : @_sheet.slice 30, 40
'SE' : @_sheet.slice 30, 40
'S' : @_sheet.slice 0, 10
'SW' : @_sheet.slice 10, 20
'W' : @_sheet.slice 10, 20
'NW' : @_sheet.slice 10, 20
'attack' :
'N' : @_sheet.slice 70, 76
'NE' : @_sheet.slice 60, 66
'E' : @_sheet.slice 60, 66
'SE' : @_sheet.slice 60, 66
'S' : @_sheet.slice 40, 46
'SW' : @_sheet.slice 50, 56
'W' : @_sheet.slice 50, 56
'NW' : @_sheet.slice 50, 56
update : (player, map) =>
try
super player, map
draw : =>
do @_sprite.draw
try
do super
class Golem extends Monster
constructor : (@x, @y) ->
super @x, @y, 2, 75, 7, 50, 200, 75, 75, 'GOLEM.gif', [200, 200]
@_feets.resizeTo 150, 40
@_sheet.frame_duration = 150
@_sheet2 = new jaws.Animation
sprite_sheet : "img/GOLEM.gif"
frame_size : [200, 200]
orientation : 'right'
frame_duration : 80
@_anims =
'run' :
'N' : @_sheet.slice 10, 20
'NE' : @_sheet.slice 10, 20
'E' : @_sheet.slice 20, 30
'SE' : @_sheet.slice 20, 30
'S' : @_sheet.slice 0, 10
'SW' : @_sheet.slice 0, 10
'W' : @_sheet.slice 0, 10
'NW' : @_sheet.slice 30, 40
'attack' :
'N' : @_sheet2.slice 70, 79
'NE' : @_sheet2.slice 110, 119
'E' : @_sheet2.slice 50, 59
'SE' : @_sheet2.slice 90, 99
'S' : @_sheet2.slice 60, 69
'SW' : @_sheet2.slice 80, 89
'W' : @_sheet2.slice 40, 49
'NW' : @_sheet2.slice 100, 109
@_fist = new jaws.Sprite
anchor : 'center'
x : @x
y : @y
width: 70
height : 70
update : (player, map) =>
try
super player, map
@frame = @_anims[@_state][@_orientation].index
@_fist.moveTo @x, @y
if 'E' in @_orientation
@_fist.move 140, 0
else if 'W' in @_orientation
@_fist.move -140, 0
if 'S' in @_orientation
@_fist.move 0, 140
else if 'N' in @_orientation
@_fist.move 0, -140
if @_state is 'attack' and 3 < @frame < 8 and (do @_fist.rect).collideRect (do player._box.rect)
player._getHit 15
draw : =>
do @_sprite.draw
# if @_state is 'attack'
# if 3 < @frame < 8
# do @_fist.draw
try
do super
attack : (player) =>
@_state = 'attack'
@_attack = =>
@_changestate = =>
@_changeOrientation = =>
setTimeout (=>
@_attack = @attack
@_changestate = (s) => @_state = s
@_changeOrientation = (o) => @_orientation = o
(@_changestate 'run') if @_distToPlayer > @distAttack
), 720
if window.DemCreepers?
window.DemCreepers.Character = Character
window.DemCreepers.Player = Player
window.DemCreepers.Gob = Gob
window.DemCreepers.Golem = Golem
| true | #####
##
# Dem Creepers!
# Entry for the GitHub Game Off 2013
# Author : PI:NAME:<NAME>END_PI for PI:NAME:<NAME>END_PI
# <PI:EMAIL:<EMAIL>END_PI>
##
#####
###
# Characters base class
###
class Character
constructor : (@x, @y, @speed, @feetShift, width, height) ->
@_box = new jaws.Sprite
x : @x
y : @y
width : width
height : height
anchor : 'center'
scale : 2
@_sprite = new jaws.Sprite
x : @x
y : @y
anchor : 'center'
scale : 2
@_feets = new jaws.Sprite
x : @x
y : @y + @feetShift
anchor : 'center'
scale : 2
@_vx = 0
@_vy = 0
@_orientation = 'E'
@_bump = no
@_state = 'idle'
getToDraw : => @
update : (map) =>
@_bump = no
@move map
@_sprite.moveTo @x, @y
@_box.coll = undefined
draw : =>
#do (do @_box.rect).draw
#do (do @_feets.rect).draw
moveOneComp : (comp, map) =>
moved = yes
old = @[comp]
@[comp] += @["_v#{comp}"]
if @_box.coll?
distance = window.DemCreepers.Utils.pointDistance @_box.x, @_box.y, @_box.coll.x, @_box.coll.y
@_box.moveTo @x, @y
distance2 = window.DemCreepers.Utils.pointDistance @_box.x, @_box.y, @_box.coll.x, @_box.coll.y
if distance2 < distance
@[comp] -= @["_v#{comp}"]
@_box.moveTo @x, @y
moved = no
else
@_box.moveTo @x, @y
@_feets.moveTo @x, @y + @feetShift
box = do @_feets.rect
if moved
atRect = map.atRect box
if atRect.length > 0
atRect = _.sortBy atRect, (a) => - a.type.length
for cell in atRect
cellRect = do cell.rect
if cellRect.collideRect box
if cell.type is 'Gob'
@[comp] -= @["_v#{comp}"] / 2
@_feets.moveTo @x, @y + @feetShift
else
moved = no
@_bump = yes
step = @["_v#{comp}"] / Math.abs @["_v#{comp}"]
@[comp] -= step
@_feets.moveTo @x, @y + @feetShift
box = do @_feets.rect
i = 0
while (cellRect.collideRect box)
@[comp] -= step
@_feets.moveTo @x, @y + @feetShift
box = do @_feets.rect
break
@_box.moveTo @x, @y
return moved
move : (map) =>
if @_vx is 0 and @_vy is 0
return
movedX = (@moveOneComp 'x', map) if @_vx isnt 0
movedY = (@moveOneComp 'y', map) if @_vy isnt 0
movedX or movedY
class Player extends Character
constructor : (@x, @y) ->
super @x, @y, 6, 35, 12, 20
@Mult = 1
@Chain = 0
@PerfectChain = 0
@_hit = no
@_feets.resizeTo 30, 25
@_orientation = 'SW'
@Dead = no
@WOOSH = new jaws.Audio audio : 'audio/WOOSH.ogg', volume : window.DemCreepers.Volumes.FX
@DEAD = [
new jaws.Audio audio : 'audio/MORT01.ogg', volume : window.DemCreepers.Volumes.FX
new jaws.Audio audio : 'audio/MORT02.ogg', volume : window.DemCreepers.Volumes.FX
]
@GAMEOVER = new jaws.Audio audio : 'audio/GAMEOVER.ogg', volume : window.DemCreepers.Volumes.FX
@_hp = 100
@_attack = @attack
@_changeStateOr = @changeStateOr
@_getHit = @getHit
@_onlasframe = =>
@_sheet = new jaws.Animation
sprite_sheet : 'img/Barbarian.gif'
frame_size : [50, 50]
orientation : 'right'
@_sheet2 = new jaws.Animation
sprite_sheet : 'img/Barbarian.gif'
frame_size : [50, 50]
orientation : 'right'
frame_duration : 60
@_state = 'idle'
@_anims =
'idle' :
'N' : @_sheet.slice 24, 28
'NE' : @_sheet.slice 30, 34
'E' : @_sheet.slice 36, 40
'SE' : @_sheet.slice 42, 46
'S' : @_sheet.slice 0, 4
'SW' : @_sheet.slice 6, 10
'W' : @_sheet.slice 12, 16
'NW' : @_sheet.slice 18, 22
'run' :
'N' : @_sheet.slice 72, 78
'NE' : @_sheet.slice 78, 84
'E' : @_sheet.slice 84, 90
'SE' : @_sheet.slice 90, 96
'S' : @_sheet.slice 48, 54
'SW' : @_sheet.slice 54, 60
'W' : @_sheet.slice 60, 66
'NW' : @_sheet.slice 66, 72
'attack' :
'N' : @_sheet2.slice 108, 111
'NE' : @_sheet2.slice 111, 114
'E' : @_sheet2.slice 114, 117
'SE' : @_sheet2.slice 117, 120
'S' : @_sheet2.slice 96, 99
'SW' : @_sheet2.slice 99, 102
'W' : @_sheet2.slice 102, 105
'NW' : @_sheet2.slice 105, 108
'dead' :
'N' : @_sheet.slice 120, 127
@_anims['dead']['E'] = @_anims['dead']['NE'] = @_anims['dead']['SE'] = @_anims['dead']['S'] =
@_anims['dead']['SW'] = @_anims['dead']['W'] = @_anims['dead']['NW'] = @_anims['dead']['N']
@_axes = []
getToDraw : =>
_.union @_axes, [@]
simpleUpdate : =>
@_sprite.setImage do @_anims[@_state][@_orientation].next
update : (viewport, map) =>
if @Dead
return no
if do @_anims[@_state][@_orientation].atLastFrame
do @_onlasframe
if @_state isnt 'dead'
@_vx = @_vy = 0
viewport.forceInsideVisibleArea @_sprite, 20
@x = @_sprite.x
@y = @_sprite.y
@handleInputs viewport
try
super map
@_sprite.setImage do @_anims[@_state][@_orientation].next
###
# Manage axes
###
toDel = []
_.map @_axes, (axe, index) =>
axe.update map
if axe._toGo <= 0
toDel.push index
toDel = toDel.sort (a, b) => b - a
_.map toDel, (index) =>
@_axes.splice index, 1
return yes
draw : =>
do @_sprite.draw
try
do super
getHit : (n) =>
@_getHit = =>
setTimeout (=>
@_getHit = @getHit
), 1000
@_hit = yes
@Chain = 0
@PerfectChain = 0
@Mult = 1
if (@_hp -= n) <= 0
if @_state isnt 'dead'
do @DEAD[_.random 0, 1].play
setTimeout (=>
do @GAMEOVER.play
), 800
@_hp = 0
@_state = 'dead'
@_onlasframe = =>
@Dead = yes
@_onlasframe = =>
changeStateOr : (state, orientation) =>
@_state = state
if orientation?
@_orientation = orientation
attack : (dir) =>
do @WOOSH.play
old = @_orientation
@_orientation = dir
@_axes.push new Axe dir, @x, @y
@_state = 'attack'
@_attack = =>
@_changeStateOr = =>
@_onlasframe = =>
@_orientation = old
@_changeStateOr = @changeStateOr
@_onlasframe = =>
setTimeout (=>
@_attack = @attack
), 50
handleInputs : (viewport) =>
###
# Movements
###
mov = x : 0, y : 0
vComp = ''
hComp = ''
controls = window.DemCreepers.Controls[window.DemCreepers.Config.ActiveControls]
if jaws.pressed "#{controls.up}"
--mov.y
vComp = 'N'
if jaws.pressed "#{controls.right}"
++mov.x
hComp = 'E'
if jaws.pressed "#{controls.down}"
++mov.y
vComp = 'S'
if jaws.pressed "#{controls.left}"
--mov.x
hComp = 'W'
if not (newOr = vComp + hComp)
@_changeStateOr 'idle'
else
@_changeStateOr 'run', (vComp + hComp)
@_vx = @speed * mov.x
@_vy = @speed * mov.y
###
# Attacks
###
if jaws.pressedWithoutRepeat "left_mouse_button"
relX = @x - viewport.x
relY = @y - viewport.y
dir = window.DemCreepers.Utils.pointOrientation jaws.mouse_x, jaws.mouse_y, relX, relY
@_attack dir
###
# DEBUG
###
if jaws.pressedWithoutRepeat "shift"
@_attack @_orientation
class Axe extends Character
constructor : (dir, @x, @y) ->
super @x, @y, 7, 0, 10, 10
@_toGo = 500
@_dirx = @_diry = 0
if (dir.indexOf 'N') >= 0
@_diry = -1
else if (dir.indexOf 'S') >= 0
@_diry = 1
if (dir.indexOf 'W') >= 0
@_dirx = -1
else if (dir.indexOf 'E') >= 0
@_dirx = 1
@_sheet = new jaws.Animation
sprite_sheet : 'img/Axe.gif'
frame_size : [20, 20]
orientation : 'right'
frame_duration : 75
move : (map) =>
if @_vx is 0 and @_vy is 0
return
@x += @_vx
@_box.moveTo @x, @y
@y += @_vy
@_box.moveTo @x, @y
update : (map) =>
@_vx = @speed * @_dirx
@_vy = @speed * @_diry
@_toGo -= @speed
try
super map
if @_bump
@_toGo = 0
@_sprite.setImage do @_sheet.next
draw : =>
do @_sprite.draw
try
do super
###
# Monsters base class
###
class Monster extends Character
constructor : (@x, @y, @speed, @feetShift, @pv, @reward, @distAttack, width, height, sheetName, frameSize) ->
super @x, @y, @speed, @feetShift, width, height
@_state = 'run'
@_sheet = new jaws.Animation
sprite_sheet : "img/#{sheetName}"
frame_size : frameSize
orientation : 'right'
frame_duration : 70
@_changeOrientation = (o) => @_orientation = o
@_changestate = (s) => @_state = s
@_attack = @attack
###
# Define orientation based move methods
# Allows not to check direction each game loop iteration
###
@_move =
'N' : () => @_vy = -@speed ; @_vx = 0
'NE' : () => @_vy = -@speed ; @_vx = @speed
'E' : () => @_vy = 0 ; @_vx = @speed
'SE' : () => @_vy = @speed ; @_vx = @speed
'S' : () => @_vy = @speed ; @_vx = 0
'SW' : () => @_vy = @speed ; @_vx = -@speed
'W' : () => @_vy = 0 ; @_vx = -@speed
'NW' : () => @_vy = -@speed ; @_vx = -@speed
update : (player, map) =>
@_bump = no
@_distToPlayer = window.DemCreepers.Utils.pointDistance player.x, player.y, @x, @y
@_changeOrientation window.DemCreepers.Utils.pointOrientation player.x, player.y, @x, @y
@_sprite.setImage do @_anims[@_state][@_orientation].next
if @_state isnt 'attack' and @_distToPlayer > @distAttack
do @_move[@_orientation]
moved = @move map
if not moved
oldOr = @_orientation
ors = window.DemCreepers.Utils.getNextOr @_orientation
i = 0
while not moved
@_orientation = ors[i++]
break if @_orientation is oldOr
do @_move[@_orientation]
moved = @move map
if moved
@_changeOrientation = =>
setTimeout (=>
@_changeOrientation = (o) => @_orientation = o
), (if @_bump then (@speed * 200) else (@speed * 100))
@_changestate 'run'
else
@_vx = @_vy = 0
@_attack player
@_box.coll = undefined
@_sprite.moveTo @x, @y
attack : (player) =>
@_changestate 'attack'
player._getHit 5
@_attack = =>
setTimeout (=>
@_attack = @attack
(@_changestate 'run') if @_distToPlayer > @distAttack
), 420
class Gob extends Monster
constructor : (@x, @y) ->
super @x, @y, 4, 10, 1, 10, 35, 15, 15, 'Gob.gif', [50, 50]
@_feets.resizeTo 30, 20
@_anims =
'run' :
'N' : @_sheet.slice 20, 30
'NE' : @_sheet.slice 30, 40
'E' : @_sheet.slice 30, 40
'SE' : @_sheet.slice 30, 40
'S' : @_sheet.slice 0, 10
'SW' : @_sheet.slice 10, 20
'W' : @_sheet.slice 10, 20
'NW' : @_sheet.slice 10, 20
'attack' :
'N' : @_sheet.slice 70, 76
'NE' : @_sheet.slice 60, 66
'E' : @_sheet.slice 60, 66
'SE' : @_sheet.slice 60, 66
'S' : @_sheet.slice 40, 46
'SW' : @_sheet.slice 50, 56
'W' : @_sheet.slice 50, 56
'NW' : @_sheet.slice 50, 56
update : (player, map) =>
try
super player, map
draw : =>
do @_sprite.draw
try
do super
class Golem extends Monster
constructor : (@x, @y) ->
super @x, @y, 2, 75, 7, 50, 200, 75, 75, 'GOLEM.gif', [200, 200]
@_feets.resizeTo 150, 40
@_sheet.frame_duration = 150
@_sheet2 = new jaws.Animation
sprite_sheet : "img/GOLEM.gif"
frame_size : [200, 200]
orientation : 'right'
frame_duration : 80
@_anims =
'run' :
'N' : @_sheet.slice 10, 20
'NE' : @_sheet.slice 10, 20
'E' : @_sheet.slice 20, 30
'SE' : @_sheet.slice 20, 30
'S' : @_sheet.slice 0, 10
'SW' : @_sheet.slice 0, 10
'W' : @_sheet.slice 0, 10
'NW' : @_sheet.slice 30, 40
'attack' :
'N' : @_sheet2.slice 70, 79
'NE' : @_sheet2.slice 110, 119
'E' : @_sheet2.slice 50, 59
'SE' : @_sheet2.slice 90, 99
'S' : @_sheet2.slice 60, 69
'SW' : @_sheet2.slice 80, 89
'W' : @_sheet2.slice 40, 49
'NW' : @_sheet2.slice 100, 109
@_fist = new jaws.Sprite
anchor : 'center'
x : @x
y : @y
width: 70
height : 70
update : (player, map) =>
try
super player, map
@frame = @_anims[@_state][@_orientation].index
@_fist.moveTo @x, @y
if 'E' in @_orientation
@_fist.move 140, 0
else if 'W' in @_orientation
@_fist.move -140, 0
if 'S' in @_orientation
@_fist.move 0, 140
else if 'N' in @_orientation
@_fist.move 0, -140
if @_state is 'attack' and 3 < @frame < 8 and (do @_fist.rect).collideRect (do player._box.rect)
player._getHit 15
draw : =>
do @_sprite.draw
# if @_state is 'attack'
# if 3 < @frame < 8
# do @_fist.draw
try
do super
attack : (player) =>
@_state = 'attack'
@_attack = =>
@_changestate = =>
@_changeOrientation = =>
setTimeout (=>
@_attack = @attack
@_changestate = (s) => @_state = s
@_changeOrientation = (o) => @_orientation = o
(@_changestate 'run') if @_distToPlayer > @distAttack
), 720
if window.DemCreepers?
window.DemCreepers.Character = Character
window.DemCreepers.Player = Player
window.DemCreepers.Gob = Gob
window.DemCreepers.Golem = Golem
|
[
{
"context": "ck-knock-user.coffee'\n @nima = pretend.user 'nima'\n @pema = pretend.user 'pema'\n\n context '",
"end": 509,
"score": 0.9992904663085938,
"start": 505,
"tag": "USERNAME",
"value": "nima"
},
{
"context": "= pretend.user 'nima'\n @pema = pretend.user 'p... | integration/test/Usage_test.coffee | PropertyUX/nubot-playbook | 0 | _ = require 'lodash'
co = require 'co'
chai = require 'chai'
should = chai.should()
pretend = require 'hubot-pretend'
# director methods are async, need to allow enter middleware time to process
wait = (delay) -> new Promise (resolve, reject) -> setTimeout resolve, delay
describe 'Playbook demo', ->
afterEach ->
pretend.shutdown().clear()
context 'knock knock test - user scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-user.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
context 'Nima begins in A, continues in B, Pema tries in both', ->
it 'responds to Nima in both, ignores Pema in both', -> co =>
yield @nima.in('#A').send "knock knock" # ... Who's there?
yield @pema.in('#A').send "Pema A" # ... -ignored-
yield @nima.in('#B').send "Nima B" # ... Nima B who?
yield @pema.in('#B').send "Pema B" # ... -ignored-
pretend.messages.should.eql [
[ '#A', 'nima', "knock knock" ]
[ '#A', 'hubot', "Who's there?" ]
[ '#A', 'pema', "Pema A" ]
[ '#B', 'nima', "Nima B" ]
[ '#B', 'hubot', "Nima B who?" ]
[ '#B', 'pema', "Pema B" ]
]
context 'knock knock test - room scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-room.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
@A = pretend.room '#A'
@B = pretend.room '#B'
context 'Nima begins in A, continues in B, Pema responds in A', ->
it 'responds to Nima or Pema in A', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... Pema who?
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "No it's Nima!" # ... No it's Nima who?
@A.messages().should.eql [
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Who's there?" ]
[ 'pema', "Pema" ]
[ 'hubot', "@pema Pema who?" ]
[ 'nima', "No it's Nima!" ]
[ 'hubot', "@nima lol" ]
]
it 'ignores both in B', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... Pema who?
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "No it's Nima!" # ... No it's Nima who?
@B.messages().should.eql [
[ 'nima', "Nima" ]
[ 'pema', "Pema B" ]
]
context 'knock knock test - direct scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-direct-noreply.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
@A = pretend.room '#A'
@B = pretend.room '#B'
context 'Nima begins in A, continues in both, Pema responds in A', ->
it 'responds only to Nima in A', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... -ignored-
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "Nima" # ... Nima who?
yield @A.receive @nima, "Nima A" # ... lol
@A.messages().should.eql [
[ 'nima', "knock knock" ]
[ 'hubot', "Who's there?" ]
[ 'pema', "Pema" ]
[ 'nima', "Nima" ]
[ 'hubot', "Nima who?" ]
[ 'nima', "Nima A" ]
[ 'hubot', "lol" ]
]
it 'ignores both in B', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... -ignored-
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "Nima" # ... Nima who?
yield @A.receive @nima, "Nima A" # ... lol
@B.messages().should.eql [
[ 'nima', "Nima" ]
[ 'pema', "Pema B" ]
]
context 'knock knock test - parallel direct scenes + reply', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-direct-reply.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
context 'Nima begins, Pema begins, both continue in same room', ->
it 'responds to both without conflict', -> co =>
yield @nima.send "knock knock" # ... Who's there?
yield @pema.send "knock knock" # ... Who's there?
yield @nima.send "Nima" # ... Nima who?
yield @pema.send "Pema" # ... Pema who?
yield @pema.send "Just Pema" # ... lol
yield @nima.send "Just Nima" # ... lol
pretend.messages.should.eql [
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Who's there?" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Who's there?" ]
[ 'nima', "Nima" ]
[ 'hubot', "@nima Nima who?" ]
[ 'pema', "Pema" ]
[ 'hubot', "@pema Pema who?" ]
[ 'pema', "Just Pema" ]
[ 'hubot', "@pema lol" ]
[ 'nima', "Just Nima" ]
[ 'hubot', "@nima lol" ]
]
context 'knock and enter test - directed user scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-and-enter-user.coffee'
pretend.log.level = 'silent'
@director = pretend.user 'director'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
context 'Nima gets whitelisted, both try to enter', ->
it 'allows Nima', -> co =>
yield @director.send "allow nima"
yield @nima.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "allow nima" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima You may enter!" ]
]
it 'gives others default response', -> co =>
yield @director.send "allow nima"
yield @pema.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "allow nima" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Sorry, nima's only." ]
]
context 'Nima is blacklisted user, both try to enter', ->
it 'allows any but Nima', -> co =>
yield @director.send "deny nima"
yield @pema.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "deny nima" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema You may enter!" ]
]
it 'gives others default response', -> co =>
yield @director.send "deny nima"
yield @nima.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "deny nima" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Sorry, no nima's." ]
]
context 'knock and enter test - directed room scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-and-enter-room.coffee'
pretend.log.level = 'silent'
@director = pretend.user 'director'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
@A = pretend.room '#A'
@B = pretend.room '#B'
context 'Room #A is whitelisted, nima and pema try to enter in both', ->
it 'allows any in room #A', -> co =>
yield @A.receive @director, "allow #A"
yield @A.receive @pema, "knock knock"
yield wait 10
yield @A.receive @nima, "knock knock"
yield wait 10
@A.messages().should.eql [
[ 'director', "allow #A" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema You may enter!" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima You may enter!" ]
]
it 'sends default response to other rooms', -> co =>
yield @A.receive @director, "allow #A"
yield @B.receive @pema, "knock knock"
yield wait 10
yield @B.receive @nima, "knock knock"
yield wait 10
@B.messages().should.eql [
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Sorry, #A users only." ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Sorry, #A users only." ]
]
context 'Room #A is blacklisted, nima and pema try to enter in both', ->
it 'allows any in room #A', -> co =>
yield @A.receive @director, "deny #A"
yield @A.receive @pema, "knock knock"
yield wait 10
yield @A.receive @nima, "knock knock"
yield wait 10
@A.messages().should.eql [
[ 'director', "deny #A" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Sorry, no #A users." ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Sorry, no #A users." ]
]
it 'sends default response to other rooms', -> co =>
yield @A.receive @director, "deny #A"
yield @B.receive @pema, "knock knock"
yield wait 10
yield @B.receive @nima, "knock knock"
yield wait 10
@B.messages().should.eql [
[ 'pema', "knock knock" ]
[ 'hubot', "@pema You may enter!" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima You may enter!" ]
]
###
e.g. transcript diagnostics for scene timeouts, to determine common causes
- using key, returns series of users and their last message before timeout occur
- demonstrates with non-default types
###
| 195208 | _ = require 'lodash'
co = require 'co'
chai = require 'chai'
should = chai.should()
pretend = require 'hubot-pretend'
# director methods are async, need to allow enter middleware time to process
wait = (delay) -> new Promise (resolve, reject) -> setTimeout resolve, delay
describe 'Playbook demo', ->
afterEach ->
pretend.shutdown().clear()
context 'knock knock test - user scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-user.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
context 'Nima begins in A, continues in B, Pema tries in both', ->
it 'responds to Nima in both, ignores Pema in both', -> co =>
yield @nima.in('#A').send "knock knock" # ... Who's there?
yield @pema.in('#A').send "Pema A" # ... -ignored-
yield @nima.in('#B').send "Nima B" # ... Nima B who?
yield @pema.in('#B').send "Pema B" # ... -ignored-
pretend.messages.should.eql [
[ '#A', 'nima', "knock knock" ]
[ '#A', 'hubot', "Who's there?" ]
[ '#A', 'pema', "Pema A" ]
[ '#B', 'nima', "Nima B" ]
[ '#B', 'hubot', "Nima B who?" ]
[ '#B', 'pema', "Pema B" ]
]
context 'knock knock test - room scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-room.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
@A = pretend.room '#A'
@B = pretend.room '#B'
context 'Nima begins in A, continues in B, Pema responds in A', ->
it 'responds to Nima or Pema in A', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... Pema who?
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "No it's Nima!" # ... No it's Nima who?
@A.messages().should.eql [
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Who's there?" ]
[ 'pema', "Pema" ]
[ 'hubot', "@pema Pema who?" ]
[ 'nima', "No it's Nima!" ]
[ 'hubot', "@nima lol" ]
]
it 'ignores both in B', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... Pema who?
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "No it's Nima!" # ... No it's Nima who?
@B.messages().should.eql [
[ 'nima', "Nima" ]
[ 'pema', "Pema B" ]
]
context 'knock knock test - direct scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-direct-noreply.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
@A = pretend.room '#A'
@B = pretend.room '#B'
context 'Nima begins in A, continues in both, Pema responds in A', ->
it 'responds only to Nima in A', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... -ignored-
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "Nima" # ... Nima who?
yield @A.receive @nima, "Nima A" # ... lol
@A.messages().should.eql [
[ 'nima', "knock knock" ]
[ 'hubot', "Who's there?" ]
[ 'pema', "Pema" ]
[ 'nima', "Nima" ]
[ 'hubot', "Nima who?" ]
[ 'nima', "Nima A" ]
[ 'hubot', "lol" ]
]
it 'ignores both in B', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... -ignored-
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "Nima" # ... Nima who?
yield @A.receive @nima, "Nima A" # ... lol
@B.messages().should.eql [
[ 'nima', "Nima" ]
[ 'pema', "Pema B" ]
]
context 'knock knock test - parallel direct scenes + reply', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-direct-reply.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
context 'Nima begins, Pema begins, both continue in same room', ->
it 'responds to both without conflict', -> co =>
yield @nima.send "knock knock" # ... Who's there?
yield @pema.send "knock knock" # ... Who's there?
yield @nima.send "<NAME>" # ... Nima who?
yield @pema.send "<NAME>" # ... Pema who?
yield @pema.send "<NAME>" # ... lol
yield @nima.send "<NAME>" # ... lol
pretend.messages.should.eql [
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Who's there?" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Who's there?" ]
[ 'nima', "<NAME>" ]
[ 'hubot', "@nima Nima who?" ]
[ 'pema', "<NAME>" ]
[ 'hubot', "@pema Pema who?" ]
[ 'pema', "<NAME>" ]
[ 'hubot', "@pema lol" ]
[ 'nima', "<NAME>" ]
[ 'hubot', "@nima lol" ]
]
context 'knock and enter test - directed user scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-and-enter-user.coffee'
pretend.log.level = 'silent'
@director = pretend.user 'director'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
context 'Nima gets whitelisted, both try to enter', ->
it 'allows Nima', -> co =>
yield @director.send "allow nima"
yield @nima.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "allow nima" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima You may enter!" ]
]
it 'gives others default response', -> co =>
yield @director.send "allow nima"
yield @pema.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "allow nima" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Sorry, nima's only." ]
]
context 'Nima is blacklisted user, both try to enter', ->
it 'allows any but Nima', -> co =>
yield @director.send "deny nima"
yield @pema.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "deny nima" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema You may enter!" ]
]
it 'gives others default response', -> co =>
yield @director.send "deny nima"
yield @nima.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "deny nima" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Sorry, no nima's." ]
]
context 'knock and enter test - directed room scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-and-enter-room.coffee'
pretend.log.level = 'silent'
@director = pretend.user 'director'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
@A = pretend.room '#A'
@B = pretend.room '#B'
context 'Room #A is whitelisted, nima and pema try to enter in both', ->
it 'allows any in room #A', -> co =>
yield @A.receive @director, "allow #A"
yield @A.receive @pema, "knock knock"
yield wait 10
yield @A.receive @nima, "knock knock"
yield wait 10
@A.messages().should.eql [
[ 'director', "allow #A" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema You may enter!" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima You may enter!" ]
]
it 'sends default response to other rooms', -> co =>
yield @A.receive @director, "allow #A"
yield @B.receive @pema, "knock knock"
yield wait 10
yield @B.receive @nima, "knock knock"
yield wait 10
@B.messages().should.eql [
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Sorry, #A users only." ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Sorry, #A users only." ]
]
context 'Room #A is blacklisted, nima and pema try to enter in both', ->
it 'allows any in room #A', -> co =>
yield @A.receive @director, "deny #A"
yield @A.receive @pema, "knock knock"
yield wait 10
yield @A.receive @nima, "knock knock"
yield wait 10
@A.messages().should.eql [
[ 'director', "deny #A" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Sorry, no #A users." ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Sorry, no #A users." ]
]
it 'sends default response to other rooms', -> co =>
yield @A.receive @director, "deny #A"
yield @B.receive @pema, "knock knock"
yield wait 10
yield @B.receive @nima, "knock knock"
yield wait 10
@B.messages().should.eql [
[ 'pema', "knock knock" ]
[ 'hubot', "@pema You may enter!" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima You may enter!" ]
]
###
e.g. transcript diagnostics for scene timeouts, to determine common causes
- using key, returns series of users and their last message before timeout occur
- demonstrates with non-default types
###
| true | _ = require 'lodash'
co = require 'co'
chai = require 'chai'
should = chai.should()
pretend = require 'hubot-pretend'
# director methods are async, need to allow enter middleware time to process
wait = (delay) -> new Promise (resolve, reject) -> setTimeout resolve, delay
describe 'Playbook demo', ->
afterEach ->
pretend.shutdown().clear()
context 'knock knock test - user scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-user.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
context 'Nima begins in A, continues in B, Pema tries in both', ->
it 'responds to Nima in both, ignores Pema in both', -> co =>
yield @nima.in('#A').send "knock knock" # ... Who's there?
yield @pema.in('#A').send "Pema A" # ... -ignored-
yield @nima.in('#B').send "Nima B" # ... Nima B who?
yield @pema.in('#B').send "Pema B" # ... -ignored-
pretend.messages.should.eql [
[ '#A', 'nima', "knock knock" ]
[ '#A', 'hubot', "Who's there?" ]
[ '#A', 'pema', "Pema A" ]
[ '#B', 'nima', "Nima B" ]
[ '#B', 'hubot', "Nima B who?" ]
[ '#B', 'pema', "Pema B" ]
]
context 'knock knock test - room scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-room.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
@A = pretend.room '#A'
@B = pretend.room '#B'
context 'Nima begins in A, continues in B, Pema responds in A', ->
it 'responds to Nima or Pema in A', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... Pema who?
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "No it's Nima!" # ... No it's Nima who?
@A.messages().should.eql [
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Who's there?" ]
[ 'pema', "Pema" ]
[ 'hubot', "@pema Pema who?" ]
[ 'nima', "No it's Nima!" ]
[ 'hubot', "@nima lol" ]
]
it 'ignores both in B', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... Pema who?
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "No it's Nima!" # ... No it's Nima who?
@B.messages().should.eql [
[ 'nima', "Nima" ]
[ 'pema', "Pema B" ]
]
context 'knock knock test - direct scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-direct-noreply.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
@A = pretend.room '#A'
@B = pretend.room '#B'
context 'Nima begins in A, continues in both, Pema responds in A', ->
it 'responds only to Nima in A', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... -ignored-
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "Nima" # ... Nima who?
yield @A.receive @nima, "Nima A" # ... lol
@A.messages().should.eql [
[ 'nima', "knock knock" ]
[ 'hubot', "Who's there?" ]
[ 'pema', "Pema" ]
[ 'nima', "Nima" ]
[ 'hubot', "Nima who?" ]
[ 'nima', "Nima A" ]
[ 'hubot', "lol" ]
]
it 'ignores both in B', -> co =>
yield @A.receive @nima, "knock knock" # ... Who's there?
yield @B.receive @nima, "Nima" # ... -ignored-
yield @A.receive @pema, "Pema" # ... -ignored-
yield @B.receive @pema, "Pema B" # ... -ignored-
yield @A.receive @nima, "Nima" # ... Nima who?
yield @A.receive @nima, "Nima A" # ... lol
@B.messages().should.eql [
[ 'nima', "Nima" ]
[ 'pema', "Pema B" ]
]
context 'knock knock test - parallel direct scenes + reply', ->
beforeEach ->
pretend.start().read 'scripts/knock-knock-direct-reply.coffee'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
context 'Nima begins, Pema begins, both continue in same room', ->
it 'responds to both without conflict', -> co =>
yield @nima.send "knock knock" # ... Who's there?
yield @pema.send "knock knock" # ... Who's there?
yield @nima.send "PI:NAME:<NAME>END_PI" # ... Nima who?
yield @pema.send "PI:NAME:<NAME>END_PI" # ... Pema who?
yield @pema.send "PI:NAME:<NAME>END_PI" # ... lol
yield @nima.send "PI:NAME:<NAME>END_PI" # ... lol
pretend.messages.should.eql [
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Who's there?" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Who's there?" ]
[ 'nima', "PI:NAME:<NAME>END_PI" ]
[ 'hubot', "@nima Nima who?" ]
[ 'pema', "PI:NAME:<NAME>END_PI" ]
[ 'hubot', "@pema Pema who?" ]
[ 'pema', "PI:NAME:<NAME>END_PI" ]
[ 'hubot', "@pema lol" ]
[ 'nima', "PI:NAME:<NAME>END_PI" ]
[ 'hubot', "@nima lol" ]
]
context 'knock and enter test - directed user scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-and-enter-user.coffee'
pretend.log.level = 'silent'
@director = pretend.user 'director'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
context 'Nima gets whitelisted, both try to enter', ->
it 'allows Nima', -> co =>
yield @director.send "allow nima"
yield @nima.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "allow nima" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima You may enter!" ]
]
it 'gives others default response', -> co =>
yield @director.send "allow nima"
yield @pema.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "allow nima" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Sorry, nima's only." ]
]
context 'Nima is blacklisted user, both try to enter', ->
it 'allows any but Nima', -> co =>
yield @director.send "deny nima"
yield @pema.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "deny nima" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema You may enter!" ]
]
it 'gives others default response', -> co =>
yield @director.send "deny nima"
yield @nima.send "knock knock"
yield wait 20
pretend.messages.should.eql [
[ 'director', "deny nima" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Sorry, no nima's." ]
]
context 'knock and enter test - directed room scene', ->
beforeEach ->
pretend.start().read 'scripts/knock-and-enter-room.coffee'
pretend.log.level = 'silent'
@director = pretend.user 'director'
@nima = pretend.user 'nima'
@pema = pretend.user 'pema'
@A = pretend.room '#A'
@B = pretend.room '#B'
context 'Room #A is whitelisted, nima and pema try to enter in both', ->
it 'allows any in room #A', -> co =>
yield @A.receive @director, "allow #A"
yield @A.receive @pema, "knock knock"
yield wait 10
yield @A.receive @nima, "knock knock"
yield wait 10
@A.messages().should.eql [
[ 'director', "allow #A" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema You may enter!" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima You may enter!" ]
]
it 'sends default response to other rooms', -> co =>
yield @A.receive @director, "allow #A"
yield @B.receive @pema, "knock knock"
yield wait 10
yield @B.receive @nima, "knock knock"
yield wait 10
@B.messages().should.eql [
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Sorry, #A users only." ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Sorry, #A users only." ]
]
context 'Room #A is blacklisted, nima and pema try to enter in both', ->
it 'allows any in room #A', -> co =>
yield @A.receive @director, "deny #A"
yield @A.receive @pema, "knock knock"
yield wait 10
yield @A.receive @nima, "knock knock"
yield wait 10
@A.messages().should.eql [
[ 'director', "deny #A" ]
[ 'pema', "knock knock" ]
[ 'hubot', "@pema Sorry, no #A users." ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima Sorry, no #A users." ]
]
it 'sends default response to other rooms', -> co =>
yield @A.receive @director, "deny #A"
yield @B.receive @pema, "knock knock"
yield wait 10
yield @B.receive @nima, "knock knock"
yield wait 10
@B.messages().should.eql [
[ 'pema', "knock knock" ]
[ 'hubot', "@pema You may enter!" ]
[ 'nima', "knock knock" ]
[ 'hubot', "@nima You may enter!" ]
]
###
e.g. transcript diagnostics for scene timeouts, to determine common causes
- using key, returns series of users and their last message before timeout occur
- demonstrates with non-default types
###
|
[
{
"context": ": 'thank-you-for-considering'\n token: 'the-environment'\n toUuid: '2-you-you-eye-dee'\n ra",
"end": 961,
"score": 0.9982740879058838,
"start": 946,
"tag": "PASSWORD",
"value": "the-environment"
}
] | test/create-session-token-spec.coffee | ramonhpr/meshblu-core-task-create-session-token | 0 | _ = require 'lodash'
mongojs = require 'mongojs'
Datastore = require 'meshblu-core-datastore'
TokenManager = require 'meshblu-core-manager-token'
CreateSessionToken = require '../'
describe 'CreateSessionToken', ->
beforeEach (done) ->
@uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid)
database = mongojs 'meshblu-core-task-update-device', ['tokens']
@datastore = new Datastore {
database,
collection: 'tokens'
}
database.tokens.remove done
beforeEach ->
pepper = 'im-a-pepper'
@tokenManager = new TokenManager { @datastore, @uuidAliasResolver, pepper }
@sut = new CreateSessionToken { @datastore, @uuidAliasResolver, pepper }
describe '->do', ->
beforeEach (done) ->
request =
metadata:
responseId: 'used-as-biofuel'
auth:
uuid: 'thank-you-for-considering'
token: 'the-environment'
toUuid: '2-you-you-eye-dee'
rawData: '{"tag":"foo"}'
@sut.do request, (error, @response) => done error
it 'should respond with a 201', ->
expect(@response.metadata.code).to.equal 201
expect(@response.data.token).to.exist
expect(@response.data.tag).to.equal 'foo'
it 'should create a session token', ->
@datastore.findOne { uuid: 'thank-you-for-considering' }, (error, record) =>
return done error if error?
expect(record.uuid).to.equal 'thank-you-for-considering'
expect(record.hashedToken).to.exist
expect(record.metadata.tag).to.equal 'foo'
expect(record.metadata.createdAt).to.exist
done()
it 'should be a valid session token', ->
@tokenManager.verifyToken {uuid: 'thank-you-for-considering', token: @response.data.token}, (error, valid) =>
return done error if error?
expect(valid).to.be.true
done()
| 150158 | _ = require 'lodash'
mongojs = require 'mongojs'
Datastore = require 'meshblu-core-datastore'
TokenManager = require 'meshblu-core-manager-token'
CreateSessionToken = require '../'
describe 'CreateSessionToken', ->
beforeEach (done) ->
@uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid)
database = mongojs 'meshblu-core-task-update-device', ['tokens']
@datastore = new Datastore {
database,
collection: 'tokens'
}
database.tokens.remove done
beforeEach ->
pepper = 'im-a-pepper'
@tokenManager = new TokenManager { @datastore, @uuidAliasResolver, pepper }
@sut = new CreateSessionToken { @datastore, @uuidAliasResolver, pepper }
describe '->do', ->
beforeEach (done) ->
request =
metadata:
responseId: 'used-as-biofuel'
auth:
uuid: 'thank-you-for-considering'
token: '<PASSWORD>'
toUuid: '2-you-you-eye-dee'
rawData: '{"tag":"foo"}'
@sut.do request, (error, @response) => done error
it 'should respond with a 201', ->
expect(@response.metadata.code).to.equal 201
expect(@response.data.token).to.exist
expect(@response.data.tag).to.equal 'foo'
it 'should create a session token', ->
@datastore.findOne { uuid: 'thank-you-for-considering' }, (error, record) =>
return done error if error?
expect(record.uuid).to.equal 'thank-you-for-considering'
expect(record.hashedToken).to.exist
expect(record.metadata.tag).to.equal 'foo'
expect(record.metadata.createdAt).to.exist
done()
it 'should be a valid session token', ->
@tokenManager.verifyToken {uuid: 'thank-you-for-considering', token: @response.data.token}, (error, valid) =>
return done error if error?
expect(valid).to.be.true
done()
| true | _ = require 'lodash'
mongojs = require 'mongojs'
Datastore = require 'meshblu-core-datastore'
TokenManager = require 'meshblu-core-manager-token'
CreateSessionToken = require '../'
describe 'CreateSessionToken', ->
beforeEach (done) ->
@uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid)
database = mongojs 'meshblu-core-task-update-device', ['tokens']
@datastore = new Datastore {
database,
collection: 'tokens'
}
database.tokens.remove done
beforeEach ->
pepper = 'im-a-pepper'
@tokenManager = new TokenManager { @datastore, @uuidAliasResolver, pepper }
@sut = new CreateSessionToken { @datastore, @uuidAliasResolver, pepper }
describe '->do', ->
beforeEach (done) ->
request =
metadata:
responseId: 'used-as-biofuel'
auth:
uuid: 'thank-you-for-considering'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
toUuid: '2-you-you-eye-dee'
rawData: '{"tag":"foo"}'
@sut.do request, (error, @response) => done error
it 'should respond with a 201', ->
expect(@response.metadata.code).to.equal 201
expect(@response.data.token).to.exist
expect(@response.data.tag).to.equal 'foo'
it 'should create a session token', ->
@datastore.findOne { uuid: 'thank-you-for-considering' }, (error, record) =>
return done error if error?
expect(record.uuid).to.equal 'thank-you-for-considering'
expect(record.hashedToken).to.exist
expect(record.metadata.tag).to.equal 'foo'
expect(record.metadata.createdAt).to.exist
done()
it 'should be a valid session token', ->
@tokenManager.verifyToken {uuid: 'thank-you-for-considering', token: @response.data.token}, (error, valid) =>
return done error if error?
expect(valid).to.be.true
done()
|
[
{
"context": "ength - 1\n\t\t\t\t\tel = data.pop()\n\t\t\t\telse\n\t\t\t\t\tkey = @keys(data)[0]\n\t\t\t\t\tel = data[key]\n\t\t\t\t\tdelete data[key",
"end": 3425,
"score": 0.9536553621292114,
"start": 3420,
"tag": "KEY",
"value": "@keys"
},
{
"context": "\t\t\t\tel = data.pop()\n\t... | lib/hash.coffee | jbielick/hash-js | 1 | ((factory, root) ->
if typeof define is 'function' and define.amd
define [], factory
else if module? and module.exports
module.exports = factory()
else
root.Hash = factory()
)(() ->
class Hash
remove: (data, path) ->
tokens = @tokenize path
if path.indexOf('{') is -1
return @simpleOp 'remove', data, path
token = tokens.shift()
nextPath = tokens.join '.'
for own key, value of data
if @matchToken key, token
if value and (@isObject(value) or @isArray(value)) && nextPath
if nextPath.split('.').shift() is '{n}' and @isArray(value)
delete data[key]
else
value = @remove value, nextPath
else if @isArray(data)
data.splice key, 1
else
delete data[key]
data
insert: (data, path, insertValue) ->
tokens = @tokenize path
expand = {}
if path.indexOf('{') is -1 and path.indexOf('[]') is -1
return @simpleOp 'insert', data, path, insertValue
if @keys(data).length or data.length > 0
token = tokens.shift()
nextPath = tokens.join '.'
for own key, value of data
if @matchToken key, token
if nextPath is ''
data[key] = insertValue
else
data[key] = @insert data[key], nextPath, insertValue
else
expand[path] = insertValue
return @expand expand
data
simpleOp: (operation, data, path, value) ->
tokens = @tokenize(path)
hold = data
for token in tokens
if operation is 'insert'
if _i is tokens.length - 1
hold[token] = value
return data
if not @isObject(hold[token]) && not @isArray(hold[token])
if not isNaN parseInt tokens[_i + 1]
hold[token] = []
else
hold[token] = {}
hold = hold[token];
else if operation is 'remove'
if _i is tokens.length - 1
(removed = {}).item = hold[token]
if @isArray(hold)
Array.prototype.splice.call hold, token, 1
else
delete hold[token]
data = removed.item
return data
if not hold[token]?
return data
hold = hold[token]
get: (data, path) ->
out = data
tokens = @tokenize path
for token in tokens
if @isObject(out) or (out and @isArray(out)) and out[token]?
out = out[token]
else
return null
out
extract: (data, path) ->
if not new RegExp('[{\[]').test path
@get(data, path) || []
tokens = @tokenize path
out = []
context = set: [data]
for token in tokens
got = []
for item in context.set
for own key, value of item
if @matchToken key, token
got.push value
context.set = got
got
expand: (flat) ->
out = {}
if (flat.constructor isnt Array)
flat = [flat]
for set in flat
for own path, value of set
tokens = @tokenize(path).reverse()
value = set[path]
if tokens[0] is '{n}' or not isNaN Number tokens[0]
(child = [])[tokens[0]] = value;
else
(child = {})[tokens[0]] = value;
tokens.shift()
for token in tokens
if not isNaN Number token
(parent = [])[parseInt(token, 10)] = child
else
(parent = {})[token] = child
child = parent
@merge(out, child)
out
flatten: (data, separator = '.', depthLimit = false) ->
data = @merge {}, data
path = ''
stack = []
out = {}
while (@keys(data).length)
if @isArray(data) and data.length > 0
key = data.length - 1
el = data.pop()
else
key = @keys(data)[0]
el = data[key]
delete data[key]
if not el? or path.split(separator).length is depthLimit or typeof el isnt 'object' or el.nodeType or (typeof el is 'object' and (el.constructor is Date or el.constructor is RegExp or el.constructor is Function)) or el.constructor isnt Object
out[path + key] = el
else
if @keys(data).length > 0
stack.push [data, path]
data = el
path += key + separator
if (@keys(data).length is 0 and stack.length > 0)
curr = stack.pop()
[data, path] = curr
out
merge: if Object.assign then Object.assign else (objects...) ->
out = objects.shift()
for object in objects
for own key, value of object
if out[key] and value and (@isObject(out[key]) and @isObject(value) or @isArray(out[key]))
out[key] = @merge out[key], value
else
out[key] = value
out
matchToken: (key, token) ->
if token is '{n}'
return parseInt(key, 10) % 1 is 0
if token is '{s}'
return typeof key is 'string'
if parseInt(token, 10) % 1 is 0
return parseInt(key, 10) is parseInt(token, 10)
return key is token
dotToBracketNotation: (path, reverse = false) ->
if not path
throw new TypeError 'Not Enough Arguments'
if reverse
path.replace(/\]/g, '').split('[').join('.')
else
path.replace(/([\w]+)\.?/g, '[$1]').replace(/^\[(\w+)\]/, '$1')
tokenize: (path) ->
if path.indexOf('[') is -1
path.split '.'
else
@map path.split('['), (v) ->
v = v.replace /\]/, ''
if v is '' then '{n}' else v
isObject: (item) ->
return typeof item is 'object' and Object.prototype.toString.call(item) is '[object Object]'
isArray: if Array.isArray then Array.isArray else (item) ->
return typeof item is 'object' and typeof item.length is 'number' and Object.prototype.toString.call(item) is '[object Array]'
keys: if Object.keys then Object.keys else (object) ->
keys = []
if @isObject object
for own key of object
keys.push key
else if @isArray(object)
for key in object
keys.push _i
keys
Hash = new Hash()
, this) | 54529 | ((factory, root) ->
if typeof define is 'function' and define.amd
define [], factory
else if module? and module.exports
module.exports = factory()
else
root.Hash = factory()
)(() ->
class Hash
remove: (data, path) ->
tokens = @tokenize path
if path.indexOf('{') is -1
return @simpleOp 'remove', data, path
token = tokens.shift()
nextPath = tokens.join '.'
for own key, value of data
if @matchToken key, token
if value and (@isObject(value) or @isArray(value)) && nextPath
if nextPath.split('.').shift() is '{n}' and @isArray(value)
delete data[key]
else
value = @remove value, nextPath
else if @isArray(data)
data.splice key, 1
else
delete data[key]
data
insert: (data, path, insertValue) ->
tokens = @tokenize path
expand = {}
if path.indexOf('{') is -1 and path.indexOf('[]') is -1
return @simpleOp 'insert', data, path, insertValue
if @keys(data).length or data.length > 0
token = tokens.shift()
nextPath = tokens.join '.'
for own key, value of data
if @matchToken key, token
if nextPath is ''
data[key] = insertValue
else
data[key] = @insert data[key], nextPath, insertValue
else
expand[path] = insertValue
return @expand expand
data
simpleOp: (operation, data, path, value) ->
tokens = @tokenize(path)
hold = data
for token in tokens
if operation is 'insert'
if _i is tokens.length - 1
hold[token] = value
return data
if not @isObject(hold[token]) && not @isArray(hold[token])
if not isNaN parseInt tokens[_i + 1]
hold[token] = []
else
hold[token] = {}
hold = hold[token];
else if operation is 'remove'
if _i is tokens.length - 1
(removed = {}).item = hold[token]
if @isArray(hold)
Array.prototype.splice.call hold, token, 1
else
delete hold[token]
data = removed.item
return data
if not hold[token]?
return data
hold = hold[token]
get: (data, path) ->
out = data
tokens = @tokenize path
for token in tokens
if @isObject(out) or (out and @isArray(out)) and out[token]?
out = out[token]
else
return null
out
extract: (data, path) ->
if not new RegExp('[{\[]').test path
@get(data, path) || []
tokens = @tokenize path
out = []
context = set: [data]
for token in tokens
got = []
for item in context.set
for own key, value of item
if @matchToken key, token
got.push value
context.set = got
got
expand: (flat) ->
out = {}
if (flat.constructor isnt Array)
flat = [flat]
for set in flat
for own path, value of set
tokens = @tokenize(path).reverse()
value = set[path]
if tokens[0] is '{n}' or not isNaN Number tokens[0]
(child = [])[tokens[0]] = value;
else
(child = {})[tokens[0]] = value;
tokens.shift()
for token in tokens
if not isNaN Number token
(parent = [])[parseInt(token, 10)] = child
else
(parent = {})[token] = child
child = parent
@merge(out, child)
out
flatten: (data, separator = '.', depthLimit = false) ->
data = @merge {}, data
path = ''
stack = []
out = {}
while (@keys(data).length)
if @isArray(data) and data.length > 0
key = data.length - 1
el = data.pop()
else
key = <KEY>(data)[<KEY>]
el = data[key]
delete data[key]
if not el? or path.split(separator).length is depthLimit or typeof el isnt 'object' or el.nodeType or (typeof el is 'object' and (el.constructor is Date or el.constructor is RegExp or el.constructor is Function)) or el.constructor isnt Object
out[path + key] = el
else
if @keys(data).length > 0
stack.push [data, path]
data = el
path += key + separator
if (@keys(data).length is 0 and stack.length > 0)
curr = stack.pop()
[data, path] = curr
out
merge: if Object.assign then Object.assign else (objects...) ->
out = objects.shift()
for object in objects
for own key, value of object
if out[key] and value and (@isObject(out[key]) and @isObject(value) or @isArray(out[key]))
out[key] = @merge out[key], value
else
out[key] = value
out
matchToken: (key, token) ->
if token is '{n}'
return parseInt(key, 10) % 1 is 0
if token is '{s}'
return typeof key is 'string'
if parseInt(token, 10) % 1 is 0
return parseInt(key, 10) is parseInt(token, 10)
return key is token
dotToBracketNotation: (path, reverse = false) ->
if not path
throw new TypeError 'Not Enough Arguments'
if reverse
path.replace(/\]/g, '').split('[').join('.')
else
path.replace(/([\w]+)\.?/g, '[$1]').replace(/^\[(\w+)\]/, '$1')
tokenize: (path) ->
if path.indexOf('[') is -1
path.split '.'
else
@map path.split('['), (v) ->
v = v.replace /\]/, ''
if v is '' then '{n}' else v
isObject: (item) ->
return typeof item is 'object' and Object.prototype.toString.call(item) is '[object Object]'
isArray: if Array.isArray then Array.isArray else (item) ->
return typeof item is 'object' and typeof item.length is 'number' and Object.prototype.toString.call(item) is '[object Array]'
keys: if Object.keys then Object.keys else (object) ->
keys = []
if @isObject object
for own key of object
keys.push key
else if @isArray(object)
for key in object
keys.push _i
keys
Hash = new Hash()
, this) | true | ((factory, root) ->
if typeof define is 'function' and define.amd
define [], factory
else if module? and module.exports
module.exports = factory()
else
root.Hash = factory()
)(() ->
class Hash
remove: (data, path) ->
tokens = @tokenize path
if path.indexOf('{') is -1
return @simpleOp 'remove', data, path
token = tokens.shift()
nextPath = tokens.join '.'
for own key, value of data
if @matchToken key, token
if value and (@isObject(value) or @isArray(value)) && nextPath
if nextPath.split('.').shift() is '{n}' and @isArray(value)
delete data[key]
else
value = @remove value, nextPath
else if @isArray(data)
data.splice key, 1
else
delete data[key]
data
insert: (data, path, insertValue) ->
tokens = @tokenize path
expand = {}
if path.indexOf('{') is -1 and path.indexOf('[]') is -1
return @simpleOp 'insert', data, path, insertValue
if @keys(data).length or data.length > 0
token = tokens.shift()
nextPath = tokens.join '.'
for own key, value of data
if @matchToken key, token
if nextPath is ''
data[key] = insertValue
else
data[key] = @insert data[key], nextPath, insertValue
else
expand[path] = insertValue
return @expand expand
data
simpleOp: (operation, data, path, value) ->
tokens = @tokenize(path)
hold = data
for token in tokens
if operation is 'insert'
if _i is tokens.length - 1
hold[token] = value
return data
if not @isObject(hold[token]) && not @isArray(hold[token])
if not isNaN parseInt tokens[_i + 1]
hold[token] = []
else
hold[token] = {}
hold = hold[token];
else if operation is 'remove'
if _i is tokens.length - 1
(removed = {}).item = hold[token]
if @isArray(hold)
Array.prototype.splice.call hold, token, 1
else
delete hold[token]
data = removed.item
return data
if not hold[token]?
return data
hold = hold[token]
get: (data, path) ->
out = data
tokens = @tokenize path
for token in tokens
if @isObject(out) or (out and @isArray(out)) and out[token]?
out = out[token]
else
return null
out
extract: (data, path) ->
if not new RegExp('[{\[]').test path
@get(data, path) || []
tokens = @tokenize path
out = []
context = set: [data]
for token in tokens
got = []
for item in context.set
for own key, value of item
if @matchToken key, token
got.push value
context.set = got
got
expand: (flat) ->
out = {}
if (flat.constructor isnt Array)
flat = [flat]
for set in flat
for own path, value of set
tokens = @tokenize(path).reverse()
value = set[path]
if tokens[0] is '{n}' or not isNaN Number tokens[0]
(child = [])[tokens[0]] = value;
else
(child = {})[tokens[0]] = value;
tokens.shift()
for token in tokens
if not isNaN Number token
(parent = [])[parseInt(token, 10)] = child
else
(parent = {})[token] = child
child = parent
@merge(out, child)
out
flatten: (data, separator = '.', depthLimit = false) ->
data = @merge {}, data
path = ''
stack = []
out = {}
while (@keys(data).length)
if @isArray(data) and data.length > 0
key = data.length - 1
el = data.pop()
else
key = PI:KEY:<KEY>END_PI(data)[PI:KEY:<KEY>END_PI]
el = data[key]
delete data[key]
if not el? or path.split(separator).length is depthLimit or typeof el isnt 'object' or el.nodeType or (typeof el is 'object' and (el.constructor is Date or el.constructor is RegExp or el.constructor is Function)) or el.constructor isnt Object
out[path + key] = el
else
if @keys(data).length > 0
stack.push [data, path]
data = el
path += key + separator
if (@keys(data).length is 0 and stack.length > 0)
curr = stack.pop()
[data, path] = curr
out
merge: if Object.assign then Object.assign else (objects...) ->
out = objects.shift()
for object in objects
for own key, value of object
if out[key] and value and (@isObject(out[key]) and @isObject(value) or @isArray(out[key]))
out[key] = @merge out[key], value
else
out[key] = value
out
matchToken: (key, token) ->
if token is '{n}'
return parseInt(key, 10) % 1 is 0
if token is '{s}'
return typeof key is 'string'
if parseInt(token, 10) % 1 is 0
return parseInt(key, 10) is parseInt(token, 10)
return key is token
dotToBracketNotation: (path, reverse = false) ->
if not path
throw new TypeError 'Not Enough Arguments'
if reverse
path.replace(/\]/g, '').split('[').join('.')
else
path.replace(/([\w]+)\.?/g, '[$1]').replace(/^\[(\w+)\]/, '$1')
tokenize: (path) ->
if path.indexOf('[') is -1
path.split '.'
else
@map path.split('['), (v) ->
v = v.replace /\]/, ''
if v is '' then '{n}' else v
isObject: (item) ->
return typeof item is 'object' and Object.prototype.toString.call(item) is '[object Object]'
isArray: if Array.isArray then Array.isArray else (item) ->
return typeof item is 'object' and typeof item.length is 'number' and Object.prototype.toString.call(item) is '[object Array]'
keys: if Object.keys then Object.keys else (object) ->
keys = []
if @isObject object
for own key of object
keys.push key
else if @isArray(object)
for key in object
keys.push _i
keys
Hash = new Hash()
, this) |
[
{
"context": "---------------------------------\n# Copyright 2013 I.B.M.\n# \n# Licensed under the Apache License, Version 2",
"end": 427,
"score": 0.9997615814208984,
"start": 422,
"tag": "NAME",
"value": "I.B.M"
}
] | test/package-test.coffee | pmuellr/nodprof | 6 | # Licensed under the Apache License. See footer for details.
assert = require "assert"
fs = require "fs"
nodprof = require "../lib"
describe "package", ->
pkg = JSON.parse fs.readFileSync __dirname + "/../package.json", "utf8"
it "should have version", ->
assert.equal pkg.version, nodprof.version
#-------------------------------------------------------------------------------
# Copyright 2013 I.B.M.
#
# 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.
#-------------------------------------------------------------------------------
| 125585 | # Licensed under the Apache License. See footer for details.
assert = require "assert"
fs = require "fs"
nodprof = require "../lib"
describe "package", ->
pkg = JSON.parse fs.readFileSync __dirname + "/../package.json", "utf8"
it "should have version", ->
assert.equal pkg.version, nodprof.version
#-------------------------------------------------------------------------------
# Copyright 2013 <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.
#-------------------------------------------------------------------------------
| true | # Licensed under the Apache License. See footer for details.
assert = require "assert"
fs = require "fs"
nodprof = require "../lib"
describe "package", ->
pkg = JSON.parse fs.readFileSync __dirname + "/../package.json", "utf8"
it "should have version", ->
assert.equal pkg.version, nodprof.version
#-------------------------------------------------------------------------------
# Copyright 2013 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.
#-------------------------------------------------------------------------------
|
[
{
"context": "h bytes greater than 255')\n .addBatch\n '209.256.68.22/255.255.224.0': shouldFailWithError 'Invalid net'",
"end": 716,
"score": 0.9989206790924072,
"start": 703,
"tag": "IP_ADDRESS",
"value": "209.256.68.22"
},
{
"context": "24.0': shouldFailWithError 'Invali... | test/badnets.coffee | olleolleolle/node-netmask | 0 | vows = require 'vows'
assert = require 'assert'
Netmask = require('../lib/netmask').Netmask
shouldFailWithError = (msg) ->
context =
topic: ->
try
return new Netmask(@context.name)
catch e
return e
'should fail': (e) ->
assert.ok isError(e), "is an Error object #{e}"
"with error `#{msg}'": (e) ->
assert.ok e.message?.toLowerCase().indexOf(msg.toLowerCase()) > -1, "'#{e.message}' =~ #{msg}"
return context
isError = (e) ->
return typeof e == 'object' and Object.prototype.toString.call(e) == '[object Error]'
vows.describe('IPs with bytes greater than 255')
.addBatch
'209.256.68.22/255.255.224.0': shouldFailWithError 'Invalid net'
'209.180.68.22/256.255.224.0': shouldFailWithError 'Invalid mask'
'209.500.70.33/19': shouldFailWithError 'Invalid net'
'140.999.82': shouldFailWithError 'Invalid net'
'899.174': shouldFailWithError 'Invalid net'
'209.157.65536/19': shouldFailWithError 'Invalid net'
'209.300.64.0.10': shouldFailWithError 'Invalid net'
'garbage': shouldFailWithError 'Invalid net'
.export(module)
vows.describe('Invalid IP format')
.addBatch
' 1.2.3.4': shouldFailWithError 'Invalid net'
' 1.2.3.4': shouldFailWithError 'Invalid net'
'1. 2.3.4': shouldFailWithError 'Invalid net'
'1.2. 3.4': shouldFailWithError 'Invalid net'
'1.2.3. 4': shouldFailWithError 'Invalid net'
'1.2.3.4 ': shouldFailWithError 'Invalid net'
'1 .2.3.4': shouldFailWithError 'Invalid net'
'018.0.0.0': shouldFailWithError 'Invalid net'
'0xfg.0.0.0': shouldFailWithError 'Invalid net'
.export(module)
vows.describe('Ranges that are a power-of-two big, but are not legal blocks')
.addBatch
'218.0.0.0/221.255.255.255': shouldFailWithError 'Invalid mask'
'218.0.0.4/218.0.0.11': shouldFailWithError 'Invalid mask'
.export(module)
| 7243 | vows = require 'vows'
assert = require 'assert'
Netmask = require('../lib/netmask').Netmask
shouldFailWithError = (msg) ->
context =
topic: ->
try
return new Netmask(@context.name)
catch e
return e
'should fail': (e) ->
assert.ok isError(e), "is an Error object #{e}"
"with error `#{msg}'": (e) ->
assert.ok e.message?.toLowerCase().indexOf(msg.toLowerCase()) > -1, "'#{e.message}' =~ #{msg}"
return context
isError = (e) ->
return typeof e == 'object' and Object.prototype.toString.call(e) == '[object Error]'
vows.describe('IPs with bytes greater than 255')
.addBatch
'209.256.68.22/255.255.224.0': shouldFailWithError 'Invalid net'
'192.168.3.11/256.255.224.0': shouldFailWithError 'Invalid mask'
'209.500.70.33/19': shouldFailWithError 'Invalid net'
'140.999.82': shouldFailWithError 'Invalid net'
'899.174': shouldFailWithError 'Invalid net'
'209.157.65536/19': shouldFailWithError 'Invalid net'
'209.300.64.0.10': shouldFailWithError 'Invalid net'
'garbage': shouldFailWithError 'Invalid net'
.export(module)
vows.describe('Invalid IP format')
.addBatch
' 1.2.3.4': shouldFailWithError 'Invalid net'
' 1.2.3.4': shouldFailWithError 'Invalid net'
'1. 2.3.4': shouldFailWithError 'Invalid net'
'1.2. 3.4': shouldFailWithError 'Invalid net'
'1.2.3. 4': shouldFailWithError 'Invalid net'
'1.2.3.4 ': shouldFailWithError 'Invalid net'
'1 .2.3.4': shouldFailWithError 'Invalid net'
'018.0.0.0': shouldFailWithError 'Invalid net'
'0xfg.0.0.0': shouldFailWithError 'Invalid net'
.export(module)
vows.describe('Ranges that are a power-of-two big, but are not legal blocks')
.addBatch
'172.16.31.10/221.255.255.255': shouldFailWithError 'Invalid mask'
'172.16.17.32/218.0.0.11': shouldFailWithError 'Invalid mask'
.export(module)
| true | vows = require 'vows'
assert = require 'assert'
Netmask = require('../lib/netmask').Netmask
shouldFailWithError = (msg) ->
context =
topic: ->
try
return new Netmask(@context.name)
catch e
return e
'should fail': (e) ->
assert.ok isError(e), "is an Error object #{e}"
"with error `#{msg}'": (e) ->
assert.ok e.message?.toLowerCase().indexOf(msg.toLowerCase()) > -1, "'#{e.message}' =~ #{msg}"
return context
isError = (e) ->
return typeof e == 'object' and Object.prototype.toString.call(e) == '[object Error]'
vows.describe('IPs with bytes greater than 255')
.addBatch
'209.256.68.22/255.255.224.0': shouldFailWithError 'Invalid net'
'PI:IP_ADDRESS:192.168.3.11END_PI/256.255.224.0': shouldFailWithError 'Invalid mask'
'209.500.70.33/19': shouldFailWithError 'Invalid net'
'140.999.82': shouldFailWithError 'Invalid net'
'899.174': shouldFailWithError 'Invalid net'
'209.157.65536/19': shouldFailWithError 'Invalid net'
'209.300.64.0.10': shouldFailWithError 'Invalid net'
'garbage': shouldFailWithError 'Invalid net'
.export(module)
vows.describe('Invalid IP format')
.addBatch
' 1.2.3.4': shouldFailWithError 'Invalid net'
' 1.2.3.4': shouldFailWithError 'Invalid net'
'1. 2.3.4': shouldFailWithError 'Invalid net'
'1.2. 3.4': shouldFailWithError 'Invalid net'
'1.2.3. 4': shouldFailWithError 'Invalid net'
'1.2.3.4 ': shouldFailWithError 'Invalid net'
'1 .2.3.4': shouldFailWithError 'Invalid net'
'018.0.0.0': shouldFailWithError 'Invalid net'
'0xfg.0.0.0': shouldFailWithError 'Invalid net'
.export(module)
vows.describe('Ranges that are a power-of-two big, but are not legal blocks')
.addBatch
'PI:IP_ADDRESS:172.16.31.10END_PI/221.255.255.255': shouldFailWithError 'Invalid mask'
'PI:IP_ADDRESS:172.16.17.32END_PI/218.0.0.11': shouldFailWithError 'Invalid mask'
.export(module)
|
[
{
"context": "\n\nclass Request\n constructor: (@fi, @username = 'anonymous00000000000000000000000', @password = 'anonymous00",
"end": 606,
"score": 0.9126690030097961,
"start": 597,
"tag": "USERNAME",
"value": "anonymous"
},
{
"context": "equest\n constructor: (@fi, @username = 'a... | application/chrome/content/wesabe/ofx/Request.coffee | wesabe/ssu | 28 | date = require 'lang/date'
func = require 'lang/func'
type = require 'lang/type'
{uuid} = require 'lang/UUID'
xhr = require 'io/xhr'
privacy = require 'util/privacy'
Response = require 'ofx/Response'
## Request - build an OFX request message
## Construct with the ORG and FID of the financial institution, and then
## call methods for each request type you want to generate. Return values
## are strings suitable for sending to OFX servers. Currently supports
## account info, bank statement, and credit card statement requests.
class Request
constructor: (@fi, @username = 'anonymous00000000000000000000000', @password = 'anonymous00000000000000000000000', @job) ->
request: (data, callback, metadata) ->
# log the request if we *really* need to
logger.radioactive('OFX Request: ', data)
xhr.post @fi.ofxUrl, null, data,
before: (request) =>
request.setRequestHeader("Content-type", "application/x-ofx")
request.setRequestHeader("Accept", "*/*, application/x-ofx")
if not type.isFunction callback
func.executeCallback(callback, 'before', [this].concat(metadata || []))
success: (request) =>
ofxresponse = new Response request.responseText, @job
wesabe.success callback, [this, ofxresponse, request]
failure: (request) =>
ofxresponse = null
try
ofxresponse = new Response request.responseText, @job
catch e
logger.error "Could not parse response as OFX: ", request.responseText
wesabe.failure callback, [this, ofxresponse, request]
after: (request) =>
if not type.isFunction callback
func.executeCallback callback, 'after', [this].concat(metadata or [])
fiProfile: ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_fiprofile() +
"</OFX>\r\n"
requestFiProfile: (callback) ->
data = @fiProfile()
@request data,
success: (self, response, request) ->
func.executeCallback callback, 'success', [self, response, request]
failure: (self, response, request) ->
func.executeCallback callback, 'failure', [self, response, request]
accountInfo: ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_acctinfo() +
"</OFX>\r\n"
requestAccountInfo: (callback) ->
data = @accountInfo()
@request data,
success: (self, response, request) ->
accounts = []
if response.isSuccess()
accounts = accounts.concat(response.bankAccounts)
.concat(response.creditcardAccounts)
.concat(response.investmentAccounts)
wesabe.success callback, [{ accounts, text: request.responseText }]
else
logger.error("ofx.Request#requestAccountInfo: login failure")
wesabe.failure callback, [{ accounts: null, text: request.responseText, ofx: response }]
failure: (self, response, request) ->
logger.error 'ofx.Request#requestAccountInfo: error: ', request.responseText
wesabe.failure callback, [{ accounts: null, text: request.responseText}]
bank_stmt: (ofx_account, dtstart) ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_bankstmt(ofx_account.bankid, ofx_account.acctid, ofx_account.accttype, dtstart) +
"</OFX>\r\n"
creditcard_stmt: (ofx_account, dtstart) ->
@_init();
@_header() +
"<OFX>\r\n" +
@_signon() +
@_ccardstmt(ofx_account.acctid, dtstart) +
"</OFX>\r\n"
investment_stmt: (ofx_account, dtstart) ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_investstmt(ofx_account.acctid, dtstart) +
"</OFX>\r\n"
requestStatement: (account, options, callback) ->
account = privacy.untaint account
data = switch account.accttype
when 'CREDITCARD'
@creditcard_stmt account, options.dtstart
when 'INVESTMENT'
@investment_stmt account, options.dtstart
else
@bank_stmt account, options.dtstart
@request data, {
success: (self, response, request) ->
if response.response && response.isSuccess()
wesabe.success callback, [{ statement: response.getSanitizedResponse(), text: request.responseText }]
else
logger.error 'ofx.Request#requestStatement: response failure'
wesabe.failure callback, [{ statement: null, text: request.responseText, ofx: response }]
failure: (self, response, request) ->
logger.error 'ofx.Request#requestStatement: error: ', request.responseText
wesabe.failure callback, [{ statement: null, text: request.responseText }]
}, [{
request: this
type: 'ofx.statement'
url: @fi.ofxUrl
job: @job
}]
this::__defineGetter__ 'appId', ->
@_appId or 'Money'
this::__defineSetter__ 'appId', (appId) ->
@_appId = appId
this::__defineGetter__ 'appVersion', ->
@_appVersion or '1700'
this::__defineSetter__ 'appVersion', (appVersion) ->
@_appVersion = appVersion
# Private methods
_init: ->
@uuid = uuid()
@datetime = date.format new Date(), 'yyyyMMddHHmmss'
_header: ->
"OFXHEADER:100\r\n" +
"DATA:OFXSGML\r\n" +
"VERSION:102\r\n" +
"SECURITY:NONE\r\n" +
"ENCODING:USASCII\r\n" +
"CHARSET:1252\r\n" +
"COMPRESSION:NONE\r\n" +
"OLDFILEUID:NONE\r\n" +
"NEWFILEUID:#{@uuid}\r\n\r\n"
_signon: ->
"<SIGNONMSGSRQV1>\r\n" +
"<SONRQ>\r\n" +
"<DTCLIENT>#{@datetime}\r\n" +
"<USERID>#{@username}\r\n" +
"<USERPASS>#{@password}\r\n" +
"<LANGUAGE>ENG\r\n" +
(if @fi.ofxOrg or @fi.ofxFid then "<FI>\r\n" else '') +
(if @fi.ofxOrg then "<ORG>#{@fi.ofxOrg}\r\n" else '') +
(if @fi.ofxFid then "<FID>#{@fi.ofxFid}\r\n" else '') +
(if @fi.ofxOrg or @fi.ofxFid then "</FI>\r\n" else '') +
"<APPID>#{@appId}\r\n" +
"<APPVER>#{@appVersion}\r\n" +
"</SONRQ>\r\n" +
"</SIGNONMSGSRQV1>\r\n"
_fiprofile: ->
"<PROFMSGSRQV1>\r\n" +
"<PROFTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<PROFRQ>\r\n" +
"<CLIENTROUTING>NONE\r\n" +
"<DTPROFUP>19980101\r\n" +
"</PROFRQ>\r\n" +
"</PROFTRNRQ>\r\n" +
"</PROFMSGSRQV1>\r\n"
_acctinfo: ->
"<SIGNUPMSGSRQV1>\r\n" +
"<ACCTINFOTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<ACCTINFORQ>\r\n" +
"<DTACCTUP>19980101\r\n" +
"</ACCTINFORQ>\r\n" +
"</ACCTINFOTRNRQ>\r\n" +
"</SIGNUPMSGSRQV1>\r\n"
_bankstmt: (bankid, acctid, accttype, dtstart) ->
"<BANKMSGSRQV1>\r\n" +
"<STMTTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<STMTRQ>\r\n" +
"<BANKACCTFROM>\r\n" +
"<BANKID>#{bankid}\r\n" +
"<ACCTID>#{acctid}\r\n" +
"<ACCTTYPE>#{accttype}\r\n" +
"</BANKACCTFROM>\r\n" +
"<INCTRAN>\r\n" +
"<DTSTART>#{date.format dtstart, 'yyyyMMdd'}\r\n" +
"<INCLUDE>Y\r\n" +
"</INCTRAN>\r\n" +
"</STMTRQ>\r\n" +
"</STMTTRNRQ>\r\n" +
"</BANKMSGSRQV1>\r\n"
_ccardstmt: (acctid, dtstart) ->
"<CREDITCARDMSGSRQV1>\r\n" +
"<CCSTMTTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<CCSTMTRQ>\r\n" +
"<CCACCTFROM>\r\n" +
"<ACCTID>#{acctid}\r\n" +
"</CCACCTFROM>\r\n" +
"<INCTRAN>\r\n" +
"<DTSTART>#{date.format dtstart, 'yyyyMMdd'}\r\n" +
"<INCLUDE>Y\r\n" +
"</INCTRAN>\r\n" +
"</CCSTMTRQ>\r\n" +
"</CCSTMTTRNRQ>\r\n" +
"</CREDITCARDMSGSRQV1>\r\n"
_investstmt: (acctid, dtstart) ->
"<INVSTMTMSGSRQV1>\r\n" +
"<INVSTMTTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<INVSTMTRQ>\r\n" +
"<INVACCTFROM>\r\n" +
"<BROKERID>#{@fi.ofxBroker}\r\n" +
"<ACCTID>#{acctid}\r\n" +
"</INVACCTFROM>\r\n" +
"<INCTRAN>\r\n" +
"<DTSTART>#{date.format dtstart, 'yyyyMMdd'}\r\n" +
"<INCLUDE>Y\r\n" +
"</INCTRAN>\r\n" +
"<INCOO>Y\r\n" +
"<INCPOS>\r\n" +
"<INCLUDE>Y\r\n" +
"</INCPOS>\r\n" +
"<INCBAL>Y\r\n" +
"</INVSTMTRQ>\r\n" +
"</INVSTMTTRNRQ>\r\n" +
"</INVSTMTMSGSRQV1>\r\n"
module.exports = Request
| 54095 | date = require 'lang/date'
func = require 'lang/func'
type = require 'lang/type'
{uuid} = require 'lang/UUID'
xhr = require 'io/xhr'
privacy = require 'util/privacy'
Response = require 'ofx/Response'
## Request - build an OFX request message
## Construct with the ORG and FID of the financial institution, and then
## call methods for each request type you want to generate. Return values
## are strings suitable for sending to OFX servers. Currently supports
## account info, bank statement, and credit card statement requests.
class Request
constructor: (@fi, @username = 'anonymous<PASSWORD>', @password = '<PASSWORD>', @job) ->
request: (data, callback, metadata) ->
# log the request if we *really* need to
logger.radioactive('OFX Request: ', data)
xhr.post @fi.ofxUrl, null, data,
before: (request) =>
request.setRequestHeader("Content-type", "application/x-ofx")
request.setRequestHeader("Accept", "*/*, application/x-ofx")
if not type.isFunction callback
func.executeCallback(callback, 'before', [this].concat(metadata || []))
success: (request) =>
ofxresponse = new Response request.responseText, @job
wesabe.success callback, [this, ofxresponse, request]
failure: (request) =>
ofxresponse = null
try
ofxresponse = new Response request.responseText, @job
catch e
logger.error "Could not parse response as OFX: ", request.responseText
wesabe.failure callback, [this, ofxresponse, request]
after: (request) =>
if not type.isFunction callback
func.executeCallback callback, 'after', [this].concat(metadata or [])
fiProfile: ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_fiprofile() +
"</OFX>\r\n"
requestFiProfile: (callback) ->
data = @fiProfile()
@request data,
success: (self, response, request) ->
func.executeCallback callback, 'success', [self, response, request]
failure: (self, response, request) ->
func.executeCallback callback, 'failure', [self, response, request]
accountInfo: ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_acctinfo() +
"</OFX>\r\n"
requestAccountInfo: (callback) ->
data = @accountInfo()
@request data,
success: (self, response, request) ->
accounts = []
if response.isSuccess()
accounts = accounts.concat(response.bankAccounts)
.concat(response.creditcardAccounts)
.concat(response.investmentAccounts)
wesabe.success callback, [{ accounts, text: request.responseText }]
else
logger.error("ofx.Request#requestAccountInfo: login failure")
wesabe.failure callback, [{ accounts: null, text: request.responseText, ofx: response }]
failure: (self, response, request) ->
logger.error 'ofx.Request#requestAccountInfo: error: ', request.responseText
wesabe.failure callback, [{ accounts: null, text: request.responseText}]
bank_stmt: (ofx_account, dtstart) ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_bankstmt(ofx_account.bankid, ofx_account.acctid, ofx_account.accttype, dtstart) +
"</OFX>\r\n"
creditcard_stmt: (ofx_account, dtstart) ->
@_init();
@_header() +
"<OFX>\r\n" +
@_signon() +
@_ccardstmt(ofx_account.acctid, dtstart) +
"</OFX>\r\n"
investment_stmt: (ofx_account, dtstart) ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_investstmt(ofx_account.acctid, dtstart) +
"</OFX>\r\n"
requestStatement: (account, options, callback) ->
account = privacy.untaint account
data = switch account.accttype
when 'CREDITCARD'
@creditcard_stmt account, options.dtstart
when 'INVESTMENT'
@investment_stmt account, options.dtstart
else
@bank_stmt account, options.dtstart
@request data, {
success: (self, response, request) ->
if response.response && response.isSuccess()
wesabe.success callback, [{ statement: response.getSanitizedResponse(), text: request.responseText }]
else
logger.error 'ofx.Request#requestStatement: response failure'
wesabe.failure callback, [{ statement: null, text: request.responseText, ofx: response }]
failure: (self, response, request) ->
logger.error 'ofx.Request#requestStatement: error: ', request.responseText
wesabe.failure callback, [{ statement: null, text: request.responseText }]
}, [{
request: this
type: 'ofx.statement'
url: @fi.ofxUrl
job: @job
}]
this::__defineGetter__ 'appId', ->
@_appId or 'Money'
this::__defineSetter__ 'appId', (appId) ->
@_appId = appId
this::__defineGetter__ 'appVersion', ->
@_appVersion or '1700'
this::__defineSetter__ 'appVersion', (appVersion) ->
@_appVersion = appVersion
# Private methods
_init: ->
@uuid = uuid()
@datetime = date.format new Date(), 'yyyyMMddHHmmss'
_header: ->
"OFXHEADER:100\r\n" +
"DATA:OFXSGML\r\n" +
"VERSION:102\r\n" +
"SECURITY:NONE\r\n" +
"ENCODING:USASCII\r\n" +
"CHARSET:1252\r\n" +
"COMPRESSION:NONE\r\n" +
"OLDFILEUID:NONE\r\n" +
"NEWFILEUID:#{@uuid}\r\n\r\n"
_signon: ->
"<SIGNONMSGSRQV1>\r\n" +
"<SONRQ>\r\n" +
"<DTCLIENT>#{@datetime}\r\n" +
"<USERID>#{@username}\r\n" +
"<USERPASS>#{@password}\r\n" +
"<LANGUAGE>ENG\r\n" +
(if @fi.ofxOrg or @fi.ofxFid then "<FI>\r\n" else '') +
(if @fi.ofxOrg then "<ORG>#{@fi.ofxOrg}\r\n" else '') +
(if @fi.ofxFid then "<FID>#{@fi.ofxFid}\r\n" else '') +
(if @fi.ofxOrg or @fi.ofxFid then "</FI>\r\n" else '') +
"<APPID>#{@appId}\r\n" +
"<APPVER>#{@appVersion}\r\n" +
"</SONRQ>\r\n" +
"</SIGNONMSGSRQV1>\r\n"
_fiprofile: ->
"<PROFMSGSRQV1>\r\n" +
"<PROFTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<PROFRQ>\r\n" +
"<CLIENTROUTING>NONE\r\n" +
"<DTPROFUP>19980101\r\n" +
"</PROFRQ>\r\n" +
"</PROFTRNRQ>\r\n" +
"</PROFMSGSRQV1>\r\n"
_acctinfo: ->
"<SIGNUPMSGSRQV1>\r\n" +
"<ACCTINFOTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<ACCTINFORQ>\r\n" +
"<DTACCTUP>19980101\r\n" +
"</ACCTINFORQ>\r\n" +
"</ACCTINFOTRNRQ>\r\n" +
"</SIGNUPMSGSRQV1>\r\n"
_bankstmt: (bankid, acctid, accttype, dtstart) ->
"<BANKMSGSRQV1>\r\n" +
"<STMTTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<STMTRQ>\r\n" +
"<BANKACCTFROM>\r\n" +
"<BANKID>#{bankid}\r\n" +
"<ACCTID>#{acctid}\r\n" +
"<ACCTTYPE>#{accttype}\r\n" +
"</BANKACCTFROM>\r\n" +
"<INCTRAN>\r\n" +
"<DTSTART>#{date.format dtstart, 'yyyyMMdd'}\r\n" +
"<INCLUDE>Y\r\n" +
"</INCTRAN>\r\n" +
"</STMTRQ>\r\n" +
"</STMTTRNRQ>\r\n" +
"</BANKMSGSRQV1>\r\n"
_ccardstmt: (acctid, dtstart) ->
"<CREDITCARDMSGSRQV1>\r\n" +
"<CCSTMTTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<CCSTMTRQ>\r\n" +
"<CCACCTFROM>\r\n" +
"<ACCTID>#{acctid}\r\n" +
"</CCACCTFROM>\r\n" +
"<INCTRAN>\r\n" +
"<DTSTART>#{date.format dtstart, 'yyyyMMdd'}\r\n" +
"<INCLUDE>Y\r\n" +
"</INCTRAN>\r\n" +
"</CCSTMTRQ>\r\n" +
"</CCSTMTTRNRQ>\r\n" +
"</CREDITCARDMSGSRQV1>\r\n"
_investstmt: (acctid, dtstart) ->
"<INVSTMTMSGSRQV1>\r\n" +
"<INVSTMTTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<INVSTMTRQ>\r\n" +
"<INVACCTFROM>\r\n" +
"<BROKERID>#{@fi.ofxBroker}\r\n" +
"<ACCTID>#{acctid}\r\n" +
"</INVACCTFROM>\r\n" +
"<INCTRAN>\r\n" +
"<DTSTART>#{date.format dtstart, 'yyyyMMdd'}\r\n" +
"<INCLUDE>Y\r\n" +
"</INCTRAN>\r\n" +
"<INCOO>Y\r\n" +
"<INCPOS>\r\n" +
"<INCLUDE>Y\r\n" +
"</INCPOS>\r\n" +
"<INCBAL>Y\r\n" +
"</INVSTMTRQ>\r\n" +
"</INVSTMTTRNRQ>\r\n" +
"</INVSTMTMSGSRQV1>\r\n"
module.exports = Request
| true | date = require 'lang/date'
func = require 'lang/func'
type = require 'lang/type'
{uuid} = require 'lang/UUID'
xhr = require 'io/xhr'
privacy = require 'util/privacy'
Response = require 'ofx/Response'
## Request - build an OFX request message
## Construct with the ORG and FID of the financial institution, and then
## call methods for each request type you want to generate. Return values
## are strings suitable for sending to OFX servers. Currently supports
## account info, bank statement, and credit card statement requests.
class Request
constructor: (@fi, @username = 'anonymousPI:PASSWORD:<PASSWORD>END_PI', @password = 'PI:PASSWORD:<PASSWORD>END_PI', @job) ->
request: (data, callback, metadata) ->
# log the request if we *really* need to
logger.radioactive('OFX Request: ', data)
xhr.post @fi.ofxUrl, null, data,
before: (request) =>
request.setRequestHeader("Content-type", "application/x-ofx")
request.setRequestHeader("Accept", "*/*, application/x-ofx")
if not type.isFunction callback
func.executeCallback(callback, 'before', [this].concat(metadata || []))
success: (request) =>
ofxresponse = new Response request.responseText, @job
wesabe.success callback, [this, ofxresponse, request]
failure: (request) =>
ofxresponse = null
try
ofxresponse = new Response request.responseText, @job
catch e
logger.error "Could not parse response as OFX: ", request.responseText
wesabe.failure callback, [this, ofxresponse, request]
after: (request) =>
if not type.isFunction callback
func.executeCallback callback, 'after', [this].concat(metadata or [])
fiProfile: ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_fiprofile() +
"</OFX>\r\n"
requestFiProfile: (callback) ->
data = @fiProfile()
@request data,
success: (self, response, request) ->
func.executeCallback callback, 'success', [self, response, request]
failure: (self, response, request) ->
func.executeCallback callback, 'failure', [self, response, request]
accountInfo: ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_acctinfo() +
"</OFX>\r\n"
requestAccountInfo: (callback) ->
data = @accountInfo()
@request data,
success: (self, response, request) ->
accounts = []
if response.isSuccess()
accounts = accounts.concat(response.bankAccounts)
.concat(response.creditcardAccounts)
.concat(response.investmentAccounts)
wesabe.success callback, [{ accounts, text: request.responseText }]
else
logger.error("ofx.Request#requestAccountInfo: login failure")
wesabe.failure callback, [{ accounts: null, text: request.responseText, ofx: response }]
failure: (self, response, request) ->
logger.error 'ofx.Request#requestAccountInfo: error: ', request.responseText
wesabe.failure callback, [{ accounts: null, text: request.responseText}]
bank_stmt: (ofx_account, dtstart) ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_bankstmt(ofx_account.bankid, ofx_account.acctid, ofx_account.accttype, dtstart) +
"</OFX>\r\n"
creditcard_stmt: (ofx_account, dtstart) ->
@_init();
@_header() +
"<OFX>\r\n" +
@_signon() +
@_ccardstmt(ofx_account.acctid, dtstart) +
"</OFX>\r\n"
investment_stmt: (ofx_account, dtstart) ->
@_init()
@_header() +
"<OFX>\r\n" +
@_signon() +
@_investstmt(ofx_account.acctid, dtstart) +
"</OFX>\r\n"
requestStatement: (account, options, callback) ->
account = privacy.untaint account
data = switch account.accttype
when 'CREDITCARD'
@creditcard_stmt account, options.dtstart
when 'INVESTMENT'
@investment_stmt account, options.dtstart
else
@bank_stmt account, options.dtstart
@request data, {
success: (self, response, request) ->
if response.response && response.isSuccess()
wesabe.success callback, [{ statement: response.getSanitizedResponse(), text: request.responseText }]
else
logger.error 'ofx.Request#requestStatement: response failure'
wesabe.failure callback, [{ statement: null, text: request.responseText, ofx: response }]
failure: (self, response, request) ->
logger.error 'ofx.Request#requestStatement: error: ', request.responseText
wesabe.failure callback, [{ statement: null, text: request.responseText }]
}, [{
request: this
type: 'ofx.statement'
url: @fi.ofxUrl
job: @job
}]
this::__defineGetter__ 'appId', ->
@_appId or 'Money'
this::__defineSetter__ 'appId', (appId) ->
@_appId = appId
this::__defineGetter__ 'appVersion', ->
@_appVersion or '1700'
this::__defineSetter__ 'appVersion', (appVersion) ->
@_appVersion = appVersion
# Private methods
_init: ->
@uuid = uuid()
@datetime = date.format new Date(), 'yyyyMMddHHmmss'
_header: ->
"OFXHEADER:100\r\n" +
"DATA:OFXSGML\r\n" +
"VERSION:102\r\n" +
"SECURITY:NONE\r\n" +
"ENCODING:USASCII\r\n" +
"CHARSET:1252\r\n" +
"COMPRESSION:NONE\r\n" +
"OLDFILEUID:NONE\r\n" +
"NEWFILEUID:#{@uuid}\r\n\r\n"
_signon: ->
"<SIGNONMSGSRQV1>\r\n" +
"<SONRQ>\r\n" +
"<DTCLIENT>#{@datetime}\r\n" +
"<USERID>#{@username}\r\n" +
"<USERPASS>#{@password}\r\n" +
"<LANGUAGE>ENG\r\n" +
(if @fi.ofxOrg or @fi.ofxFid then "<FI>\r\n" else '') +
(if @fi.ofxOrg then "<ORG>#{@fi.ofxOrg}\r\n" else '') +
(if @fi.ofxFid then "<FID>#{@fi.ofxFid}\r\n" else '') +
(if @fi.ofxOrg or @fi.ofxFid then "</FI>\r\n" else '') +
"<APPID>#{@appId}\r\n" +
"<APPVER>#{@appVersion}\r\n" +
"</SONRQ>\r\n" +
"</SIGNONMSGSRQV1>\r\n"
_fiprofile: ->
"<PROFMSGSRQV1>\r\n" +
"<PROFTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<PROFRQ>\r\n" +
"<CLIENTROUTING>NONE\r\n" +
"<DTPROFUP>19980101\r\n" +
"</PROFRQ>\r\n" +
"</PROFTRNRQ>\r\n" +
"</PROFMSGSRQV1>\r\n"
_acctinfo: ->
"<SIGNUPMSGSRQV1>\r\n" +
"<ACCTINFOTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<ACCTINFORQ>\r\n" +
"<DTACCTUP>19980101\r\n" +
"</ACCTINFORQ>\r\n" +
"</ACCTINFOTRNRQ>\r\n" +
"</SIGNUPMSGSRQV1>\r\n"
_bankstmt: (bankid, acctid, accttype, dtstart) ->
"<BANKMSGSRQV1>\r\n" +
"<STMTTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<STMTRQ>\r\n" +
"<BANKACCTFROM>\r\n" +
"<BANKID>#{bankid}\r\n" +
"<ACCTID>#{acctid}\r\n" +
"<ACCTTYPE>#{accttype}\r\n" +
"</BANKACCTFROM>\r\n" +
"<INCTRAN>\r\n" +
"<DTSTART>#{date.format dtstart, 'yyyyMMdd'}\r\n" +
"<INCLUDE>Y\r\n" +
"</INCTRAN>\r\n" +
"</STMTRQ>\r\n" +
"</STMTTRNRQ>\r\n" +
"</BANKMSGSRQV1>\r\n"
_ccardstmt: (acctid, dtstart) ->
"<CREDITCARDMSGSRQV1>\r\n" +
"<CCSTMTTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<CCSTMTRQ>\r\n" +
"<CCACCTFROM>\r\n" +
"<ACCTID>#{acctid}\r\n" +
"</CCACCTFROM>\r\n" +
"<INCTRAN>\r\n" +
"<DTSTART>#{date.format dtstart, 'yyyyMMdd'}\r\n" +
"<INCLUDE>Y\r\n" +
"</INCTRAN>\r\n" +
"</CCSTMTRQ>\r\n" +
"</CCSTMTTRNRQ>\r\n" +
"</CREDITCARDMSGSRQV1>\r\n"
_investstmt: (acctid, dtstart) ->
"<INVSTMTMSGSRQV1>\r\n" +
"<INVSTMTTRNRQ>\r\n" +
"<TRNUID>#{@uuid}\r\n" +
"<CLTCOOKIE>4\r\n" +
"<INVSTMTRQ>\r\n" +
"<INVACCTFROM>\r\n" +
"<BROKERID>#{@fi.ofxBroker}\r\n" +
"<ACCTID>#{acctid}\r\n" +
"</INVACCTFROM>\r\n" +
"<INCTRAN>\r\n" +
"<DTSTART>#{date.format dtstart, 'yyyyMMdd'}\r\n" +
"<INCLUDE>Y\r\n" +
"</INCTRAN>\r\n" +
"<INCOO>Y\r\n" +
"<INCPOS>\r\n" +
"<INCLUDE>Y\r\n" +
"</INCPOS>\r\n" +
"<INCBAL>Y\r\n" +
"</INVSTMTRQ>\r\n" +
"</INVSTMTTRNRQ>\r\n" +
"</INVSTMTMSGSRQV1>\r\n"
module.exports = Request
|
[
{
"context": "# @author mrdoob / http://mrdoob.com/\n# @author alteredq / http://",
"end": 16,
"score": 0.9996011853218079,
"start": 10,
"tag": "USERNAME",
"value": "mrdoob"
},
{
"context": "# @author mrdoob / http://mrdoob.com/\n# @author alteredq / http://alteredqualia.com/\n# @aut... | source/javascripts/new_src/core/frustum.coffee | andrew-aladev/three.js | 0 | # @author mrdoob / http://mrdoob.com/
# @author alteredq / http://alteredqualia.com/
# @author aladjev.andrew@gmail.com
#= require new_src/core/vector_3
#= require new_src/core/vector_4
class Frustum
constructor: ->
@planes = [
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
]
setFromMatrix: (m) ->
i = undefined
plane = undefined
planes = @planes
me = m.elements
me0 = me[0]
me1 = me[1]
me2 = me[2]
me3 = me[3]
me4 = me[4]
me5 = me[5]
me6 = me[6]
me7 = me[7]
me8 = me[8]
me9 = me[9]
me10 = me[10]
me11 = me[11]
me12 = me[12]
me13 = me[13]
me14 = me[14]
me15 = me[15]
planes[0].set me3 - me0, me7 - me4, me11 - me8, me15 - me12
planes[1].set me3 + me0, me7 + me4, me11 + me8, me15 + me12
planes[2].set me3 + me1, me7 + me5, me11 + me9, me15 + me13
planes[3].set me3 - me1, me7 - me5, me11 - me9, me15 - me13
planes[4].set me3 - me2, me7 - me6, me11 - me10, me15 - me14
planes[5].set me3 + me2, me7 + me6, me11 + me10, me15 + me14
i = 0
while i < 6
plane = planes[i]
plane.divideScalar Math.sqrt(plane.x * plane.x + plane.y * plane.y + plane.z * plane.z)
i++
contains: (object) ->
distance = undefined
planes = @planes
matrix = object.matrixWorld
me = matrix.elements
radius = -object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis()
i = 0
while i < 6
distance = planes[i].x * me[12] + planes[i].y * me[13] + planes[i].z * me[14] + planes[i].w
return false if distance <= radius
i++
true
namespace "THREE", (exports) ->
exports.Frustum = Frustum
exports.Frustum.__v1 = new THREE.Vector3() | 134122 | # @author mrdoob / http://mrdoob.com/
# @author alteredq / http://alteredqualia.com/
# @author <EMAIL>
#= require new_src/core/vector_3
#= require new_src/core/vector_4
class Frustum
constructor: ->
@planes = [
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
]
setFromMatrix: (m) ->
i = undefined
plane = undefined
planes = @planes
me = m.elements
me0 = me[0]
me1 = me[1]
me2 = me[2]
me3 = me[3]
me4 = me[4]
me5 = me[5]
me6 = me[6]
me7 = me[7]
me8 = me[8]
me9 = me[9]
me10 = me[10]
me11 = me[11]
me12 = me[12]
me13 = me[13]
me14 = me[14]
me15 = me[15]
planes[0].set me3 - me0, me7 - me4, me11 - me8, me15 - me12
planes[1].set me3 + me0, me7 + me4, me11 + me8, me15 + me12
planes[2].set me3 + me1, me7 + me5, me11 + me9, me15 + me13
planes[3].set me3 - me1, me7 - me5, me11 - me9, me15 - me13
planes[4].set me3 - me2, me7 - me6, me11 - me10, me15 - me14
planes[5].set me3 + me2, me7 + me6, me11 + me10, me15 + me14
i = 0
while i < 6
plane = planes[i]
plane.divideScalar Math.sqrt(plane.x * plane.x + plane.y * plane.y + plane.z * plane.z)
i++
contains: (object) ->
distance = undefined
planes = @planes
matrix = object.matrixWorld
me = matrix.elements
radius = -object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis()
i = 0
while i < 6
distance = planes[i].x * me[12] + planes[i].y * me[13] + planes[i].z * me[14] + planes[i].w
return false if distance <= radius
i++
true
namespace "THREE", (exports) ->
exports.Frustum = Frustum
exports.Frustum.__v1 = new THREE.Vector3() | true | # @author mrdoob / http://mrdoob.com/
# @author alteredq / http://alteredqualia.com/
# @author PI:EMAIL:<EMAIL>END_PI
#= require new_src/core/vector_3
#= require new_src/core/vector_4
class Frustum
constructor: ->
@planes = [
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
new THREE.Vector4()
]
setFromMatrix: (m) ->
i = undefined
plane = undefined
planes = @planes
me = m.elements
me0 = me[0]
me1 = me[1]
me2 = me[2]
me3 = me[3]
me4 = me[4]
me5 = me[5]
me6 = me[6]
me7 = me[7]
me8 = me[8]
me9 = me[9]
me10 = me[10]
me11 = me[11]
me12 = me[12]
me13 = me[13]
me14 = me[14]
me15 = me[15]
planes[0].set me3 - me0, me7 - me4, me11 - me8, me15 - me12
planes[1].set me3 + me0, me7 + me4, me11 + me8, me15 + me12
planes[2].set me3 + me1, me7 + me5, me11 + me9, me15 + me13
planes[3].set me3 - me1, me7 - me5, me11 - me9, me15 - me13
planes[4].set me3 - me2, me7 - me6, me11 - me10, me15 - me14
planes[5].set me3 + me2, me7 + me6, me11 + me10, me15 + me14
i = 0
while i < 6
plane = planes[i]
plane.divideScalar Math.sqrt(plane.x * plane.x + plane.y * plane.y + plane.z * plane.z)
i++
contains: (object) ->
distance = undefined
planes = @planes
matrix = object.matrixWorld
me = matrix.elements
radius = -object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis()
i = 0
while i < 6
distance = planes[i].x * me[12] + planes[i].y * me[13] + planes[i].z * me[14] + planes[i].w
return false if distance <= radius
i++
true
namespace "THREE", (exports) ->
exports.Frustum = Frustum
exports.Frustum.__v1 = new THREE.Vector3() |
[
{
"context": "d: '12345'\n authors = [\n { name: 'Molly' }\n { name: 'Kana' }\n ]\n @",
"end": 1362,
"score": 0.9998289346694946,
"start": 1357,
"tag": "NAME",
"value": "Molly"
},
{
"context": " [\n { name: 'Molly' }\n { name: ... | src/api/test/models/article.test.coffee | craigspaeth/positron | 0 | _ = require 'underscore'
Q = require 'bluebird-q'
Backbone = require 'backbone'
rewire = require 'rewire'
Article = rewire '../../models/article.coffee'
sinon = require 'sinon'
moment = require 'moment'
gravity = require('antigravity').server
app = require('express')()
describe "Article", ->
beforeEach ->
Article.__set__ 'FORCE_URL', 'https://artsy.net'
Article.__set__ 'Authors', mongoFetch: @AuthorFetch = sinon.stub()
Article.__set__ 'EDITORIAL_CHANNEL', '12345'
@article = new Article
describe '#isFeature', ->
it 'returns true for featured articles', ->
@article.set 'featured', true
@article.isFeatured().should.be.true()
it 'returns false for non-featured articles', ->
@article.set 'featured', false
@article.isFeatured().should.be.false()
describe '#isEditorial', ->
it 'returns true for featured articles', ->
@article.set 'channel_id', '12345'
@article.isEditorial().should.be.true()
it 'returns false for non-featured articles', ->
@article.set 'partner_channel_id', '13579'
@article.isEditorial().should.be.false()
describe '#getAuthors', ->
describe 'Editorial', ->
it 'returns a list of authors', (cb) ->
@article.set
author_ids: ['123', '456']
channel_id: '12345'
authors = [
{ name: 'Molly' }
{ name: 'Kana' }
]
@AuthorFetch.yields null, results: authors
@article.getAuthors (authors) ->
authors[0].should.equal 'Molly'
authors[1].should.equal 'Kana'
cb()
it 'has a fallback author', (cb) ->
@article.set 'channel_id', '12345'
@AuthorFetch.yields null, results: []
@article.getAuthors (authors) ->
authors[0].should.equal 'Artsy Editors'
authors.length.should.equal 1
cb()
describe 'Non-Editorial', ->
it 'returns contributing authors', (cb) ->
@article.set 'contributing_authors', [
{ name: 'Molly' }
{ name: 'Kana' }
]
@article.getAuthors (authors) ->
authors[0].should.equal 'Molly'
authors[1].should.equal 'Kana'
cb()
it 'returns an author', (cb) ->
@article.set 'author', name: 'Kana'
@article.getAuthors (authors) ->
authors[0].should.equal 'Kana'
cb()
describe '#searchBoost', ->
it 'creates a freshness score for search with a maximum cap', ->
@article.set 'published', true
@article.set 'published_at', new Date()
@article.searchBoost().should.be.below(1001)
@article.searchBoost().should.be.above(998)
it 'creates a lower score for an older article', ->
@article.set 'published', true
@article.set 'published_at', new Date(2016, 4, 10)
@article.searchBoost().should.be.below(1000)
@article.searchBoost().should.be.above(100)
describe '#date', ->
it 'return a moment object with the attribute', ->
@article.set 'published_at', '2017-05-05'
@article.date('published_at').format('YYYYMMDD').should.equal '20170505'
describe '#fullHref', ->
it 'returns the full href', ->
@article.set 'slugs', ['artsy-editorial-test']
@article.fullHref().should.equal 'https://artsy.net/article/artsy-editorial-test'
describe '#href', ->
it 'returns the relative url', ->
@article.set 'slugs', ['artsy-editorial-relative']
@article.href().should.equal '/article/artsy-editorial-relative'
describe '#slug', ->
it 'gets the slug', ->
@article.set 'slugs', [
'artsy-editorial-test1'
'artsy-editorial-test2'
'artsy-editorial-test3'
]
@article.slug().should.equal 'artsy-editorial-test3'
| 202737 | _ = require 'underscore'
Q = require 'bluebird-q'
Backbone = require 'backbone'
rewire = require 'rewire'
Article = rewire '../../models/article.coffee'
sinon = require 'sinon'
moment = require 'moment'
gravity = require('antigravity').server
app = require('express')()
describe "Article", ->
beforeEach ->
Article.__set__ 'FORCE_URL', 'https://artsy.net'
Article.__set__ 'Authors', mongoFetch: @AuthorFetch = sinon.stub()
Article.__set__ 'EDITORIAL_CHANNEL', '12345'
@article = new Article
describe '#isFeature', ->
it 'returns true for featured articles', ->
@article.set 'featured', true
@article.isFeatured().should.be.true()
it 'returns false for non-featured articles', ->
@article.set 'featured', false
@article.isFeatured().should.be.false()
describe '#isEditorial', ->
it 'returns true for featured articles', ->
@article.set 'channel_id', '12345'
@article.isEditorial().should.be.true()
it 'returns false for non-featured articles', ->
@article.set 'partner_channel_id', '13579'
@article.isEditorial().should.be.false()
describe '#getAuthors', ->
describe 'Editorial', ->
it 'returns a list of authors', (cb) ->
@article.set
author_ids: ['123', '456']
channel_id: '12345'
authors = [
{ name: '<NAME>' }
{ name: '<NAME>' }
]
@AuthorFetch.yields null, results: authors
@article.getAuthors (authors) ->
authors[0].should.equal '<NAME>'
authors[1].should.equal '<NAME>'
cb()
it 'has a fallback author', (cb) ->
@article.set 'channel_id', '12345'
@AuthorFetch.yields null, results: []
@article.getAuthors (authors) ->
authors[0].should.equal '<NAME> Editors'
authors.length.should.equal 1
cb()
describe 'Non-Editorial', ->
it 'returns contributing authors', (cb) ->
@article.set 'contributing_authors', [
{ name: '<NAME>' }
{ name: '<NAME>' }
]
@article.getAuthors (authors) ->
authors[0].should.equal '<NAME>'
authors[1].should.equal '<NAME>'
cb()
it 'returns an author', (cb) ->
@article.set 'author', name: '<NAME>'
@article.getAuthors (authors) ->
authors[0].should.equal '<NAME>'
cb()
describe '#searchBoost', ->
it 'creates a freshness score for search with a maximum cap', ->
@article.set 'published', true
@article.set 'published_at', new Date()
@article.searchBoost().should.be.below(1001)
@article.searchBoost().should.be.above(998)
it 'creates a lower score for an older article', ->
@article.set 'published', true
@article.set 'published_at', new Date(2016, 4, 10)
@article.searchBoost().should.be.below(1000)
@article.searchBoost().should.be.above(100)
describe '#date', ->
it 'return a moment object with the attribute', ->
@article.set 'published_at', '2017-05-05'
@article.date('published_at').format('YYYYMMDD').should.equal '20170505'
describe '#fullHref', ->
it 'returns the full href', ->
@article.set 'slugs', ['artsy-editorial-test']
@article.fullHref().should.equal 'https://artsy.net/article/artsy-editorial-test'
describe '#href', ->
it 'returns the relative url', ->
@article.set 'slugs', ['artsy-editorial-relative']
@article.href().should.equal '/article/artsy-editorial-relative'
describe '#slug', ->
it 'gets the slug', ->
@article.set 'slugs', [
'artsy-editorial-test1'
'artsy-editorial-test2'
'artsy-editorial-test3'
]
@article.slug().should.equal 'artsy-editorial-test3'
| true | _ = require 'underscore'
Q = require 'bluebird-q'
Backbone = require 'backbone'
rewire = require 'rewire'
Article = rewire '../../models/article.coffee'
sinon = require 'sinon'
moment = require 'moment'
gravity = require('antigravity').server
app = require('express')()
describe "Article", ->
beforeEach ->
Article.__set__ 'FORCE_URL', 'https://artsy.net'
Article.__set__ 'Authors', mongoFetch: @AuthorFetch = sinon.stub()
Article.__set__ 'EDITORIAL_CHANNEL', '12345'
@article = new Article
describe '#isFeature', ->
it 'returns true for featured articles', ->
@article.set 'featured', true
@article.isFeatured().should.be.true()
it 'returns false for non-featured articles', ->
@article.set 'featured', false
@article.isFeatured().should.be.false()
describe '#isEditorial', ->
it 'returns true for featured articles', ->
@article.set 'channel_id', '12345'
@article.isEditorial().should.be.true()
it 'returns false for non-featured articles', ->
@article.set 'partner_channel_id', '13579'
@article.isEditorial().should.be.false()
describe '#getAuthors', ->
describe 'Editorial', ->
it 'returns a list of authors', (cb) ->
@article.set
author_ids: ['123', '456']
channel_id: '12345'
authors = [
{ name: 'PI:NAME:<NAME>END_PI' }
{ name: 'PI:NAME:<NAME>END_PI' }
]
@AuthorFetch.yields null, results: authors
@article.getAuthors (authors) ->
authors[0].should.equal 'PI:NAME:<NAME>END_PI'
authors[1].should.equal 'PI:NAME:<NAME>END_PI'
cb()
it 'has a fallback author', (cb) ->
@article.set 'channel_id', '12345'
@AuthorFetch.yields null, results: []
@article.getAuthors (authors) ->
authors[0].should.equal 'PI:NAME:<NAME>END_PI Editors'
authors.length.should.equal 1
cb()
describe 'Non-Editorial', ->
it 'returns contributing authors', (cb) ->
@article.set 'contributing_authors', [
{ name: 'PI:NAME:<NAME>END_PI' }
{ name: 'PI:NAME:<NAME>END_PI' }
]
@article.getAuthors (authors) ->
authors[0].should.equal 'PI:NAME:<NAME>END_PI'
authors[1].should.equal 'PI:NAME:<NAME>END_PI'
cb()
it 'returns an author', (cb) ->
@article.set 'author', name: 'PI:NAME:<NAME>END_PI'
@article.getAuthors (authors) ->
authors[0].should.equal 'PI:NAME:<NAME>END_PI'
cb()
describe '#searchBoost', ->
it 'creates a freshness score for search with a maximum cap', ->
@article.set 'published', true
@article.set 'published_at', new Date()
@article.searchBoost().should.be.below(1001)
@article.searchBoost().should.be.above(998)
it 'creates a lower score for an older article', ->
@article.set 'published', true
@article.set 'published_at', new Date(2016, 4, 10)
@article.searchBoost().should.be.below(1000)
@article.searchBoost().should.be.above(100)
describe '#date', ->
it 'return a moment object with the attribute', ->
@article.set 'published_at', '2017-05-05'
@article.date('published_at').format('YYYYMMDD').should.equal '20170505'
describe '#fullHref', ->
it 'returns the full href', ->
@article.set 'slugs', ['artsy-editorial-test']
@article.fullHref().should.equal 'https://artsy.net/article/artsy-editorial-test'
describe '#href', ->
it 'returns the relative url', ->
@article.set 'slugs', ['artsy-editorial-relative']
@article.href().should.equal '/article/artsy-editorial-relative'
describe '#slug', ->
it 'gets the slug', ->
@article.set 'slugs', [
'artsy-editorial-test1'
'artsy-editorial-test2'
'artsy-editorial-test3'
]
@article.slug().should.equal 'artsy-editorial-test3'
|
[
{
"context": "Meteor.startup ->\n\tMandrill.config({\n\t\tusername: \"jonathan@teamstitch.com\",\n\t\tkey: \"bAaMyq6HRKH5drmbjLVDgQ\"\n\t});\n\n",
"end": 116,
"score": 0.9999194145202637,
"start": 93,
"tag": "EMAIL",
"value": "jonathan@teamstitch.com"
},
{
"context": "({\n\t\tusernam... | server/startup/mandrill.coffee | akio46/Stitch | 0 | # Remove runtime settings (non-persistent)
Meteor.startup ->
Mandrill.config({
username: "jonathan@teamstitch.com",
key: "bAaMyq6HRKH5drmbjLVDgQ"
});
| 18172 | # Remove runtime settings (non-persistent)
Meteor.startup ->
Mandrill.config({
username: "<EMAIL>",
key: "<KEY>"
});
| true | # Remove runtime settings (non-persistent)
Meteor.startup ->
Mandrill.config({
username: "PI:EMAIL:<EMAIL>END_PI",
key: "PI:KEY:<KEY>END_PI"
});
|
[
{
"context": "$.cloudinary.config\n api_key: \"162536167369695\"\n cloud_name: \"poor-richard-s-list\"\n",
"end": 47,
"score": 0.9992978572845459,
"start": 32,
"tag": "KEY",
"value": "162536167369695"
},
{
"context": "fig\n api_key: \"162536167369695\"\n cloud_name: \"poor-richar... | client/cloudinary.coffee | pennlabs/poorrichardslist | 0 | $.cloudinary.config
api_key: "162536167369695"
cloud_name: "poor-richard-s-list"
| 175874 | $.cloudinary.config
api_key: "<KEY>"
cloud_name: "poor-richard-s-list"
| true | $.cloudinary.config
api_key: "PI:KEY:<KEY>END_PI"
cloud_name: "poor-richard-s-list"
|
[
{
"context": "ache.org/licenses/LICENSE-2.0\n# Copyright (c) 2014 David Sheldrick\n###\n\ntabangular = angular.module \"tabangular\", []",
"end": 118,
"score": 0.9997367858886719,
"start": 103,
"tag": "NAME",
"value": "David Sheldrick"
}
] | tabangular.coffee | ds300/tabangular | 0 | ###*
# Tabangular.js v1.0.0
# License: http://www.apache.org/licenses/LICENSE-2.0
# Copyright (c) 2014 David Sheldrick
###
tabangular = angular.module "tabangular", []
# get a display: none; style in ther somewhere
tabangular.run ->
head = angular.element document.head
head.ready ->
head.append "<style type='text/css'>.tabangular-hide {display: none;}</style>"
###########
# Helpers #
###########
removeFromArray = (arr, item) ->
if (i = arr.indexOf item) isnt -1
arr.splice i, 1
true
else
false
lastItem = (arr) ->
arr[arr.length-1]
#################
# Events system #
#################
attach = (ctx, handlersObj, event, callback) ->
if not (cbs = handlersObj[event])?
cbs = []
handlersObj[event] = cbs
cbs.push callback
ctx.trigger "_attach", {event: event, callback: callback}
# return detach fn
->
i = cbs.indexOf callback
if i isnt -1
cbs.splice i, 1
ctx.trigger "_detach", {event: event, callback: callback}
true
else
false
class Evented
constructor: ->
@_handlers = {}
@_onceHandlers = {}
# both of these return 'off' fns to detach cb from ev
on: (ev, cb) -> attach @, @_handlers, ev, cb
one: (ev, cb) -> attach @, @_onceHandlers, ev, cb
trigger: (ev, data) ->
cb.call(@, data) for cb in ons if (ons = @_handlers[ev])?
cb.call(@, data) for cb in ones if (ones = @_onceHandlers[ev])?
ones?.length = 0
return
########################
# Tabs service factory #
########################
tabTypeDefaults =
scope: true
class TabsProvider
constructor: ->
@_tabTypes = {}
@_templateLoadCallbacks = {}
@_tabTypeFetcher = null
@$get = [
"$http", "$compile", "$controller", "$templateCache", "$q", "$injector"
($http, $compile, $controller, $templateCache, $q, $injector) =>
new TabsService @, $http, $compile, $controller, $templateCache, $q, $injector
]
###*
# registers a new tab type with the system
# @param id the string id of the tab type
# @param options the tab type options. Some combination of the following:
#
# scope: boolean
# specifies whether or not to define a new scope for
# tabs of this type. defaults to true
# templateUrl: string
# specifies a url from which to load a template (or the id of a
# template already in the dom)
# template: string
# specifies the template to use in the tab. takes
# precedence over templateUrl
# controller: function or string
# specifies the controller to call against the scope.
# Should be a function or a string denoting the
# controller to use. See
# https://docs.angularjs.org/api/ng/service/$controller
# defaults to a noop function
###
registerTabType: (id, options) ->
if @_tabTypes[id]?
throw new Error "duplicate tab type '#{id}'"
else
@_tabTypes[id] = options
# TODO: validate that we have enough information to decide how to compile
# tabs
typeFetcherFactory: (@_typeFetcherFactory) ->
_reifyFetcher: ($injector) ->
if @_typeFetcherFactory?
@_tabTypeFetcher = $injector.invoke @_typeFetcherFactory
delete @_typeFetcherFactory
if typeof @_tabTypeFetcher isnt 'function'
throw new Error "Tab type fetcher must be a function"
class TabsService
constructor: (@provider, @$http, @$compile, @$controller, @$templateCache,
@$q, @$injector) ->
_getTabType: (id) ->
@provider._reifyFetcher @$injector
if @provider._tabTypes[id]?
promise = @$q.when(@provider._tabTypes[id])
else if @provider._tabTypeFetcher?
deferred = @$q.defer()
@provider._tabTypeFetcher deferred, id
@provider._tabTypes[id] = deferred.promise
promise = deferred.promise
else
promise = @$q.when(null)
promise
# takes template and ctrl and does angular magic to create a DOM node, puts it
# in tab._elem and adds the tabangular-hide class
_compileElem: (tab, templateString, ctrl) ->
if ctrl?
@$controller(ctrl, {$scope: tab._scope, Tab: tab})
tab._elem = @$compile(templateString.trim())(tab._scope)
tab._elem.addClass "tabangular-hide"
_compileContent: (tab, parentScope, cb) ->
if typeof (tab.type) is 'string'
@_getTabType(tab.type).then(
(type) =>
if !type?
throw new Error "Unrecognised tab type: " + tab.type
else
@__compileContent tab, parentScope, cb, type
,
(reason) ->
console.warn "Tab type not found: " + tab.type
console.warn "Reason: " + reason
type = {
templateString: "Tab type '#{tab.type}' not found because #{reason}"
scope: false
}
@__compileContent tab, parentScope, cb, type
)
else
@__compileContent tab, parentScope, cb, tab.type
__compileContent: (tab, parentScope, cb, type) ->
type = angular.extend {}, tabTypeDefaults, type
tab._scope = if type.scope then parentScope.$new() else parentScope
# maybe TODO: isolates and weird binding junk like directives
# does the actual compilation once we found the template
doCompile = (templateString) =>
@_compileElem tab, templateString, type.controller
cb()
# find the template
if type.template?
doCompile type.template
else if (url = type.templateUrl)?
# look in template cache first
if (cached = @$templateCache.get url)?
doCompile cached
else
# check if this template is already being loaded, and if so, just get
# in line for a callback
if (waiting = @provider._templateLoadCallbacks[url])?
waiting.push doCompile
else
# create the queue and trigger the load.
@provider._templateLoadCallbacks[url] = [doCompile]
@$http.get(url).then(
(response) =>
template = response.data
@$templateCache.put url, template
done(template) for done in @provider._templateLoadCallbacks[url]
delete @provider._templateLoadCallbacks[url]
,
(error) =>
delete @provider._templateLoadCallbacks[url]
tab.trigger "load_fail", error
throw new Error "Unable to load template from " + url
)
else
throw new Error "no template supplied"
newArea: (options) ->
area = new TabArea @, options
window.addEventListener "beforeunload", ->
area._persist()
area
class Tab extends Evented
constructor: (@area, @type, @options) ->
super()
@loading = true
@loadingDeferred = false
@closed = false
@focused = false
@_elem = null
@_scope = null
@enableAutoClose()
@on "_attach", (data) =>
if data.event is "loaded" and not @loading
data.callback()
deferLoading: ->
@loadingDeferred = true
@
doneLoading: ->
if @loading
@loading = false
@area._scope.$root.$$phase or @area._scope.$apply()
if not @closed
@trigger 'loaded'
@
close: (silent) ->
if @closed
throw new Error "Tab already closed"
else if silent or @autoClose
removeFromArray @area._tabs, @
removeFromArray @area._focusStack, @
@closed = true
@area._persist()
if not @loading
@_elem.remove()
if @_scope isnt @area._scope
@_scope.$destroy()
@_elem = @_scope = null
@trigger "closed"
if @focused
(lastItem(@area._focusStack) or lastItem(@area._tabs))?.focus()
@focused = false
else
@trigger "close"
@
enableAutoClose: ->
@autoClose = true
@
disableAutoClose: ->
@autoClose = false
@
focus: ->
if @loading
@on "loaded", => @focus()
else if @closed
throw new Error "Cannot focus closed tab"
else if not @focused
if (len = @area._focusStack.length) isnt 0
current = @area._focusStack[len-1]
current._elem.addClass "tabangular-hide"
current.focused = false
@focused = true
@_elem.removeClass "tabangular-hide"
removeFromArray @area._focusStack, @
@area._focusStack.push @
@area._persist()
@trigger "focused"
@
move: (toArea, idx) ->
removeFromArray @area._tabs, @
if toArea isnt @area
removeFromArray @area._focusStack, @
@area._persist()
toArea._contentPane.append @_elem
if @focused
(lastItem(@area._focusStack) or lastItem(@area._tabs))?.focus()
@area = toArea
idx = Math.min Math.max(0, idx), @area._tabs.length
@area._tabs.splice idx, 0, @
if @focused or @area._tabs.length is 1
@focused = false
@focus()
@area._persist()
@
DEFAULT_TAB_AREA_OPTIONS =
id: null
persist: (json) ->
if @id?
window.localStorage["tabangular:" + @id] = json
getExisting: (cb) ->
if @id? and (json = window.localStorage["tabangular:" + @id])?
cb(json)
transformOptions: (options) -> options
parseOptions: (options) -> options
class TabArea extends Evented
constructor: (@_service, @options={}) ->
super()
@options = angular.extend {}, DEFAULT_TAB_AREA_OPTIONS, @options
# handle existing tabs
@_existingReady = false
@_existingTabs = []
# calls to @handleExisting get placed here if @_existingReady is false
@_existingReadyQueue = []
# initiate loading of existing tabs
@options.getExisting? (json) =>
json = json?.trim() or "[]" # allow empty string
@_existingReady = true
@_existingTabs = JSON.parse(json).map (tab) =>
tab.options = @options.parseOptions tab.options
tab
cb() for cb in @_existingReadyQueue
@_existingReadyQueue = []
# actual state
@_tabs = []
@_focusStack = []
# postpone loading of tabs until dom is ready
@_readyQueue = []
@_contentPane = null
@_scope = null
@on "_attach", (data) =>
if data.event is "loaded" and @_contentPane?
data.callback()
# saves the junk to the place
_persist: ->
@options.persist? JSON.stringify @_tabs.map (tab) =>
type: tab.type
options: @options.transformOptions tab.options
focused: !!tab.focused
# calls cb on existing tabs like {type, options, active}. if cb returns
# true, automatically reloads tab by calling @load(type, options)
handleExisting: (cb) ->
cb = cb or -> true
if not @_existingReady
@_existingReadyQueue.push => @handleExisting cb
else
for tab in @_existingTabs
if cb tab
loaded = @load tab.type, tab.options
loaded.focus() if tab.focused
@_persist()
@
_registerContentPane: (scope, elem) ->
@_contentPane = elem
@_scope = scope
cb() for cb in @_readyQueue
@_readyQueue = []
@trigger "loaded"
_createTab: (tabType, options) ->
tab = new Tab @, tabType, options
@_tabs.push tab
tab
load: (tabType, options={}) ->
tab = @_createTab tabType, options
if @_contentPane?
@_load tab
else
@_readyQueue.push => @_load tab
@_persist()
tab
_load: (tab) ->
@_service._compileContent tab, @_scope, =>
@_contentPane.append tab._elem
tab.trigger "dom_ready"
if not tab.loadingDeferred
tab.doneLoading()
open: (tabType, options) ->
@load(tabType, options).focus()
list: ->
@_tabs
tabangular.provider 'Tabs', TabsProvider
tabangular.directive 'tabContent', ->
scope: false
restrict: 'A'
link: ($scope, $elem, $attrs) ->
area = $scope.$eval $attrs.tabContent
if not (area instanceof TabArea)
throw new Error "'#{$attrs.tabContent}' is not a tab area"
else
area._registerContentPane $scope, $elem
return
| 67852 | ###*
# Tabangular.js v1.0.0
# License: http://www.apache.org/licenses/LICENSE-2.0
# Copyright (c) 2014 <NAME>
###
tabangular = angular.module "tabangular", []
# get a display: none; style in ther somewhere
tabangular.run ->
head = angular.element document.head
head.ready ->
head.append "<style type='text/css'>.tabangular-hide {display: none;}</style>"
###########
# Helpers #
###########
removeFromArray = (arr, item) ->
if (i = arr.indexOf item) isnt -1
arr.splice i, 1
true
else
false
lastItem = (arr) ->
arr[arr.length-1]
#################
# Events system #
#################
attach = (ctx, handlersObj, event, callback) ->
if not (cbs = handlersObj[event])?
cbs = []
handlersObj[event] = cbs
cbs.push callback
ctx.trigger "_attach", {event: event, callback: callback}
# return detach fn
->
i = cbs.indexOf callback
if i isnt -1
cbs.splice i, 1
ctx.trigger "_detach", {event: event, callback: callback}
true
else
false
class Evented
constructor: ->
@_handlers = {}
@_onceHandlers = {}
# both of these return 'off' fns to detach cb from ev
on: (ev, cb) -> attach @, @_handlers, ev, cb
one: (ev, cb) -> attach @, @_onceHandlers, ev, cb
trigger: (ev, data) ->
cb.call(@, data) for cb in ons if (ons = @_handlers[ev])?
cb.call(@, data) for cb in ones if (ones = @_onceHandlers[ev])?
ones?.length = 0
return
########################
# Tabs service factory #
########################
tabTypeDefaults =
scope: true
class TabsProvider
constructor: ->
@_tabTypes = {}
@_templateLoadCallbacks = {}
@_tabTypeFetcher = null
@$get = [
"$http", "$compile", "$controller", "$templateCache", "$q", "$injector"
($http, $compile, $controller, $templateCache, $q, $injector) =>
new TabsService @, $http, $compile, $controller, $templateCache, $q, $injector
]
###*
# registers a new tab type with the system
# @param id the string id of the tab type
# @param options the tab type options. Some combination of the following:
#
# scope: boolean
# specifies whether or not to define a new scope for
# tabs of this type. defaults to true
# templateUrl: string
# specifies a url from which to load a template (or the id of a
# template already in the dom)
# template: string
# specifies the template to use in the tab. takes
# precedence over templateUrl
# controller: function or string
# specifies the controller to call against the scope.
# Should be a function or a string denoting the
# controller to use. See
# https://docs.angularjs.org/api/ng/service/$controller
# defaults to a noop function
###
registerTabType: (id, options) ->
if @_tabTypes[id]?
throw new Error "duplicate tab type '#{id}'"
else
@_tabTypes[id] = options
# TODO: validate that we have enough information to decide how to compile
# tabs
typeFetcherFactory: (@_typeFetcherFactory) ->
_reifyFetcher: ($injector) ->
if @_typeFetcherFactory?
@_tabTypeFetcher = $injector.invoke @_typeFetcherFactory
delete @_typeFetcherFactory
if typeof @_tabTypeFetcher isnt 'function'
throw new Error "Tab type fetcher must be a function"
class TabsService
constructor: (@provider, @$http, @$compile, @$controller, @$templateCache,
@$q, @$injector) ->
_getTabType: (id) ->
@provider._reifyFetcher @$injector
if @provider._tabTypes[id]?
promise = @$q.when(@provider._tabTypes[id])
else if @provider._tabTypeFetcher?
deferred = @$q.defer()
@provider._tabTypeFetcher deferred, id
@provider._tabTypes[id] = deferred.promise
promise = deferred.promise
else
promise = @$q.when(null)
promise
# takes template and ctrl and does angular magic to create a DOM node, puts it
# in tab._elem and adds the tabangular-hide class
_compileElem: (tab, templateString, ctrl) ->
if ctrl?
@$controller(ctrl, {$scope: tab._scope, Tab: tab})
tab._elem = @$compile(templateString.trim())(tab._scope)
tab._elem.addClass "tabangular-hide"
_compileContent: (tab, parentScope, cb) ->
if typeof (tab.type) is 'string'
@_getTabType(tab.type).then(
(type) =>
if !type?
throw new Error "Unrecognised tab type: " + tab.type
else
@__compileContent tab, parentScope, cb, type
,
(reason) ->
console.warn "Tab type not found: " + tab.type
console.warn "Reason: " + reason
type = {
templateString: "Tab type '#{tab.type}' not found because #{reason}"
scope: false
}
@__compileContent tab, parentScope, cb, type
)
else
@__compileContent tab, parentScope, cb, tab.type
__compileContent: (tab, parentScope, cb, type) ->
type = angular.extend {}, tabTypeDefaults, type
tab._scope = if type.scope then parentScope.$new() else parentScope
# maybe TODO: isolates and weird binding junk like directives
# does the actual compilation once we found the template
doCompile = (templateString) =>
@_compileElem tab, templateString, type.controller
cb()
# find the template
if type.template?
doCompile type.template
else if (url = type.templateUrl)?
# look in template cache first
if (cached = @$templateCache.get url)?
doCompile cached
else
# check if this template is already being loaded, and if so, just get
# in line for a callback
if (waiting = @provider._templateLoadCallbacks[url])?
waiting.push doCompile
else
# create the queue and trigger the load.
@provider._templateLoadCallbacks[url] = [doCompile]
@$http.get(url).then(
(response) =>
template = response.data
@$templateCache.put url, template
done(template) for done in @provider._templateLoadCallbacks[url]
delete @provider._templateLoadCallbacks[url]
,
(error) =>
delete @provider._templateLoadCallbacks[url]
tab.trigger "load_fail", error
throw new Error "Unable to load template from " + url
)
else
throw new Error "no template supplied"
newArea: (options) ->
area = new TabArea @, options
window.addEventListener "beforeunload", ->
area._persist()
area
class Tab extends Evented
constructor: (@area, @type, @options) ->
super()
@loading = true
@loadingDeferred = false
@closed = false
@focused = false
@_elem = null
@_scope = null
@enableAutoClose()
@on "_attach", (data) =>
if data.event is "loaded" and not @loading
data.callback()
deferLoading: ->
@loadingDeferred = true
@
doneLoading: ->
if @loading
@loading = false
@area._scope.$root.$$phase or @area._scope.$apply()
if not @closed
@trigger 'loaded'
@
close: (silent) ->
if @closed
throw new Error "Tab already closed"
else if silent or @autoClose
removeFromArray @area._tabs, @
removeFromArray @area._focusStack, @
@closed = true
@area._persist()
if not @loading
@_elem.remove()
if @_scope isnt @area._scope
@_scope.$destroy()
@_elem = @_scope = null
@trigger "closed"
if @focused
(lastItem(@area._focusStack) or lastItem(@area._tabs))?.focus()
@focused = false
else
@trigger "close"
@
enableAutoClose: ->
@autoClose = true
@
disableAutoClose: ->
@autoClose = false
@
focus: ->
if @loading
@on "loaded", => @focus()
else if @closed
throw new Error "Cannot focus closed tab"
else if not @focused
if (len = @area._focusStack.length) isnt 0
current = @area._focusStack[len-1]
current._elem.addClass "tabangular-hide"
current.focused = false
@focused = true
@_elem.removeClass "tabangular-hide"
removeFromArray @area._focusStack, @
@area._focusStack.push @
@area._persist()
@trigger "focused"
@
move: (toArea, idx) ->
removeFromArray @area._tabs, @
if toArea isnt @area
removeFromArray @area._focusStack, @
@area._persist()
toArea._contentPane.append @_elem
if @focused
(lastItem(@area._focusStack) or lastItem(@area._tabs))?.focus()
@area = toArea
idx = Math.min Math.max(0, idx), @area._tabs.length
@area._tabs.splice idx, 0, @
if @focused or @area._tabs.length is 1
@focused = false
@focus()
@area._persist()
@
DEFAULT_TAB_AREA_OPTIONS =
id: null
persist: (json) ->
if @id?
window.localStorage["tabangular:" + @id] = json
getExisting: (cb) ->
if @id? and (json = window.localStorage["tabangular:" + @id])?
cb(json)
transformOptions: (options) -> options
parseOptions: (options) -> options
class TabArea extends Evented
constructor: (@_service, @options={}) ->
super()
@options = angular.extend {}, DEFAULT_TAB_AREA_OPTIONS, @options
# handle existing tabs
@_existingReady = false
@_existingTabs = []
# calls to @handleExisting get placed here if @_existingReady is false
@_existingReadyQueue = []
# initiate loading of existing tabs
@options.getExisting? (json) =>
json = json?.trim() or "[]" # allow empty string
@_existingReady = true
@_existingTabs = JSON.parse(json).map (tab) =>
tab.options = @options.parseOptions tab.options
tab
cb() for cb in @_existingReadyQueue
@_existingReadyQueue = []
# actual state
@_tabs = []
@_focusStack = []
# postpone loading of tabs until dom is ready
@_readyQueue = []
@_contentPane = null
@_scope = null
@on "_attach", (data) =>
if data.event is "loaded" and @_contentPane?
data.callback()
# saves the junk to the place
_persist: ->
@options.persist? JSON.stringify @_tabs.map (tab) =>
type: tab.type
options: @options.transformOptions tab.options
focused: !!tab.focused
# calls cb on existing tabs like {type, options, active}. if cb returns
# true, automatically reloads tab by calling @load(type, options)
handleExisting: (cb) ->
cb = cb or -> true
if not @_existingReady
@_existingReadyQueue.push => @handleExisting cb
else
for tab in @_existingTabs
if cb tab
loaded = @load tab.type, tab.options
loaded.focus() if tab.focused
@_persist()
@
_registerContentPane: (scope, elem) ->
@_contentPane = elem
@_scope = scope
cb() for cb in @_readyQueue
@_readyQueue = []
@trigger "loaded"
_createTab: (tabType, options) ->
tab = new Tab @, tabType, options
@_tabs.push tab
tab
load: (tabType, options={}) ->
tab = @_createTab tabType, options
if @_contentPane?
@_load tab
else
@_readyQueue.push => @_load tab
@_persist()
tab
_load: (tab) ->
@_service._compileContent tab, @_scope, =>
@_contentPane.append tab._elem
tab.trigger "dom_ready"
if not tab.loadingDeferred
tab.doneLoading()
open: (tabType, options) ->
@load(tabType, options).focus()
list: ->
@_tabs
tabangular.provider 'Tabs', TabsProvider
tabangular.directive 'tabContent', ->
scope: false
restrict: 'A'
link: ($scope, $elem, $attrs) ->
area = $scope.$eval $attrs.tabContent
if not (area instanceof TabArea)
throw new Error "'#{$attrs.tabContent}' is not a tab area"
else
area._registerContentPane $scope, $elem
return
| true | ###*
# Tabangular.js v1.0.0
# License: http://www.apache.org/licenses/LICENSE-2.0
# Copyright (c) 2014 PI:NAME:<NAME>END_PI
###
tabangular = angular.module "tabangular", []
# get a display: none; style in ther somewhere
tabangular.run ->
head = angular.element document.head
head.ready ->
head.append "<style type='text/css'>.tabangular-hide {display: none;}</style>"
###########
# Helpers #
###########
removeFromArray = (arr, item) ->
if (i = arr.indexOf item) isnt -1
arr.splice i, 1
true
else
false
lastItem = (arr) ->
arr[arr.length-1]
#################
# Events system #
#################
attach = (ctx, handlersObj, event, callback) ->
if not (cbs = handlersObj[event])?
cbs = []
handlersObj[event] = cbs
cbs.push callback
ctx.trigger "_attach", {event: event, callback: callback}
# return detach fn
->
i = cbs.indexOf callback
if i isnt -1
cbs.splice i, 1
ctx.trigger "_detach", {event: event, callback: callback}
true
else
false
class Evented
constructor: ->
@_handlers = {}
@_onceHandlers = {}
# both of these return 'off' fns to detach cb from ev
on: (ev, cb) -> attach @, @_handlers, ev, cb
one: (ev, cb) -> attach @, @_onceHandlers, ev, cb
trigger: (ev, data) ->
cb.call(@, data) for cb in ons if (ons = @_handlers[ev])?
cb.call(@, data) for cb in ones if (ones = @_onceHandlers[ev])?
ones?.length = 0
return
########################
# Tabs service factory #
########################
tabTypeDefaults =
scope: true
class TabsProvider
constructor: ->
@_tabTypes = {}
@_templateLoadCallbacks = {}
@_tabTypeFetcher = null
@$get = [
"$http", "$compile", "$controller", "$templateCache", "$q", "$injector"
($http, $compile, $controller, $templateCache, $q, $injector) =>
new TabsService @, $http, $compile, $controller, $templateCache, $q, $injector
]
###*
# registers a new tab type with the system
# @param id the string id of the tab type
# @param options the tab type options. Some combination of the following:
#
# scope: boolean
# specifies whether or not to define a new scope for
# tabs of this type. defaults to true
# templateUrl: string
# specifies a url from which to load a template (or the id of a
# template already in the dom)
# template: string
# specifies the template to use in the tab. takes
# precedence over templateUrl
# controller: function or string
# specifies the controller to call against the scope.
# Should be a function or a string denoting the
# controller to use. See
# https://docs.angularjs.org/api/ng/service/$controller
# defaults to a noop function
###
registerTabType: (id, options) ->
if @_tabTypes[id]?
throw new Error "duplicate tab type '#{id}'"
else
@_tabTypes[id] = options
# TODO: validate that we have enough information to decide how to compile
# tabs
typeFetcherFactory: (@_typeFetcherFactory) ->
_reifyFetcher: ($injector) ->
if @_typeFetcherFactory?
@_tabTypeFetcher = $injector.invoke @_typeFetcherFactory
delete @_typeFetcherFactory
if typeof @_tabTypeFetcher isnt 'function'
throw new Error "Tab type fetcher must be a function"
class TabsService
constructor: (@provider, @$http, @$compile, @$controller, @$templateCache,
@$q, @$injector) ->
_getTabType: (id) ->
@provider._reifyFetcher @$injector
if @provider._tabTypes[id]?
promise = @$q.when(@provider._tabTypes[id])
else if @provider._tabTypeFetcher?
deferred = @$q.defer()
@provider._tabTypeFetcher deferred, id
@provider._tabTypes[id] = deferred.promise
promise = deferred.promise
else
promise = @$q.when(null)
promise
# takes template and ctrl and does angular magic to create a DOM node, puts it
# in tab._elem and adds the tabangular-hide class
_compileElem: (tab, templateString, ctrl) ->
if ctrl?
@$controller(ctrl, {$scope: tab._scope, Tab: tab})
tab._elem = @$compile(templateString.trim())(tab._scope)
tab._elem.addClass "tabangular-hide"
_compileContent: (tab, parentScope, cb) ->
if typeof (tab.type) is 'string'
@_getTabType(tab.type).then(
(type) =>
if !type?
throw new Error "Unrecognised tab type: " + tab.type
else
@__compileContent tab, parentScope, cb, type
,
(reason) ->
console.warn "Tab type not found: " + tab.type
console.warn "Reason: " + reason
type = {
templateString: "Tab type '#{tab.type}' not found because #{reason}"
scope: false
}
@__compileContent tab, parentScope, cb, type
)
else
@__compileContent tab, parentScope, cb, tab.type
__compileContent: (tab, parentScope, cb, type) ->
type = angular.extend {}, tabTypeDefaults, type
tab._scope = if type.scope then parentScope.$new() else parentScope
# maybe TODO: isolates and weird binding junk like directives
# does the actual compilation once we found the template
doCompile = (templateString) =>
@_compileElem tab, templateString, type.controller
cb()
# find the template
if type.template?
doCompile type.template
else if (url = type.templateUrl)?
# look in template cache first
if (cached = @$templateCache.get url)?
doCompile cached
else
# check if this template is already being loaded, and if so, just get
# in line for a callback
if (waiting = @provider._templateLoadCallbacks[url])?
waiting.push doCompile
else
# create the queue and trigger the load.
@provider._templateLoadCallbacks[url] = [doCompile]
@$http.get(url).then(
(response) =>
template = response.data
@$templateCache.put url, template
done(template) for done in @provider._templateLoadCallbacks[url]
delete @provider._templateLoadCallbacks[url]
,
(error) =>
delete @provider._templateLoadCallbacks[url]
tab.trigger "load_fail", error
throw new Error "Unable to load template from " + url
)
else
throw new Error "no template supplied"
newArea: (options) ->
area = new TabArea @, options
window.addEventListener "beforeunload", ->
area._persist()
area
class Tab extends Evented
constructor: (@area, @type, @options) ->
super()
@loading = true
@loadingDeferred = false
@closed = false
@focused = false
@_elem = null
@_scope = null
@enableAutoClose()
@on "_attach", (data) =>
if data.event is "loaded" and not @loading
data.callback()
deferLoading: ->
@loadingDeferred = true
@
doneLoading: ->
if @loading
@loading = false
@area._scope.$root.$$phase or @area._scope.$apply()
if not @closed
@trigger 'loaded'
@
close: (silent) ->
if @closed
throw new Error "Tab already closed"
else if silent or @autoClose
removeFromArray @area._tabs, @
removeFromArray @area._focusStack, @
@closed = true
@area._persist()
if not @loading
@_elem.remove()
if @_scope isnt @area._scope
@_scope.$destroy()
@_elem = @_scope = null
@trigger "closed"
if @focused
(lastItem(@area._focusStack) or lastItem(@area._tabs))?.focus()
@focused = false
else
@trigger "close"
@
enableAutoClose: ->
@autoClose = true
@
disableAutoClose: ->
@autoClose = false
@
focus: ->
if @loading
@on "loaded", => @focus()
else if @closed
throw new Error "Cannot focus closed tab"
else if not @focused
if (len = @area._focusStack.length) isnt 0
current = @area._focusStack[len-1]
current._elem.addClass "tabangular-hide"
current.focused = false
@focused = true
@_elem.removeClass "tabangular-hide"
removeFromArray @area._focusStack, @
@area._focusStack.push @
@area._persist()
@trigger "focused"
@
move: (toArea, idx) ->
removeFromArray @area._tabs, @
if toArea isnt @area
removeFromArray @area._focusStack, @
@area._persist()
toArea._contentPane.append @_elem
if @focused
(lastItem(@area._focusStack) or lastItem(@area._tabs))?.focus()
@area = toArea
idx = Math.min Math.max(0, idx), @area._tabs.length
@area._tabs.splice idx, 0, @
if @focused or @area._tabs.length is 1
@focused = false
@focus()
@area._persist()
@
DEFAULT_TAB_AREA_OPTIONS =
id: null
persist: (json) ->
if @id?
window.localStorage["tabangular:" + @id] = json
getExisting: (cb) ->
if @id? and (json = window.localStorage["tabangular:" + @id])?
cb(json)
transformOptions: (options) -> options
parseOptions: (options) -> options
class TabArea extends Evented
constructor: (@_service, @options={}) ->
super()
@options = angular.extend {}, DEFAULT_TAB_AREA_OPTIONS, @options
# handle existing tabs
@_existingReady = false
@_existingTabs = []
# calls to @handleExisting get placed here if @_existingReady is false
@_existingReadyQueue = []
# initiate loading of existing tabs
@options.getExisting? (json) =>
json = json?.trim() or "[]" # allow empty string
@_existingReady = true
@_existingTabs = JSON.parse(json).map (tab) =>
tab.options = @options.parseOptions tab.options
tab
cb() for cb in @_existingReadyQueue
@_existingReadyQueue = []
# actual state
@_tabs = []
@_focusStack = []
# postpone loading of tabs until dom is ready
@_readyQueue = []
@_contentPane = null
@_scope = null
@on "_attach", (data) =>
if data.event is "loaded" and @_contentPane?
data.callback()
# saves the junk to the place
_persist: ->
@options.persist? JSON.stringify @_tabs.map (tab) =>
type: tab.type
options: @options.transformOptions tab.options
focused: !!tab.focused
# calls cb on existing tabs like {type, options, active}. if cb returns
# true, automatically reloads tab by calling @load(type, options)
handleExisting: (cb) ->
cb = cb or -> true
if not @_existingReady
@_existingReadyQueue.push => @handleExisting cb
else
for tab in @_existingTabs
if cb tab
loaded = @load tab.type, tab.options
loaded.focus() if tab.focused
@_persist()
@
_registerContentPane: (scope, elem) ->
@_contentPane = elem
@_scope = scope
cb() for cb in @_readyQueue
@_readyQueue = []
@trigger "loaded"
_createTab: (tabType, options) ->
tab = new Tab @, tabType, options
@_tabs.push tab
tab
load: (tabType, options={}) ->
tab = @_createTab tabType, options
if @_contentPane?
@_load tab
else
@_readyQueue.push => @_load tab
@_persist()
tab
_load: (tab) ->
@_service._compileContent tab, @_scope, =>
@_contentPane.append tab._elem
tab.trigger "dom_ready"
if not tab.loadingDeferred
tab.doneLoading()
open: (tabType, options) ->
@load(tabType, options).focus()
list: ->
@_tabs
tabangular.provider 'Tabs', TabsProvider
tabangular.directive 'tabContent', ->
scope: false
restrict: 'A'
link: ($scope, $elem, $attrs) ->
area = $scope.$eval $attrs.tabContent
if not (area instanceof TabArea)
throw new Error "'#{$attrs.tabContent}' is not a tab area"
else
area._registerContentPane $scope, $elem
return
|
[
{
"context": "AccountsTemplates.configure\n confirmPassword: false\n showForgotPasswordLink: true\n overrideLoginErr",
"end": 52,
"score": 0.9606711268424988,
"start": 47,
"tag": "PASSWORD",
"value": "false"
}
] | lib/auth/at_config.coffee | orlade/cortex | 4 | AccountsTemplates.configure
confirmPassword: false
showForgotPasswordLink: true
overrideLoginErrors: true
enablePasswordChange: true
sendVerificationEmail: false
| 214629 | AccountsTemplates.configure
confirmPassword: <PASSWORD>
showForgotPasswordLink: true
overrideLoginErrors: true
enablePasswordChange: true
sendVerificationEmail: false
| true | AccountsTemplates.configure
confirmPassword: PI:PASSWORD:<PASSWORD>END_PI
showForgotPasswordLink: true
overrideLoginErrors: true
enablePasswordChange: true
sendVerificationEmail: false
|
[
{
"context": "feature/878'\n FormattedID: 'F1'\n Name: 'Name of first PI'\n Owner:\n _ref: '/user/1'\n ",
"end": 2015,
"score": 0.9990295767784119,
"start": 2008,
"tag": "NAME",
"value": "Name of"
},
{
"context": "/878'\n FormattedID: 'F1'\n Name: 'Na... | test/spec/portfoliokanban/PortfolioKanbanAppSpec.coffee | RallyHackathon/app-catalog | 1 | Ext = window.Ext4 || window.Ext
describe 'Rally.apps.portfoliokanban.PortfolioKanbanApp', ->
helpers
_createApp: (settings) ->
globalContext = Rally.environment.getContext()
context = Ext.create 'Rally.app.Context',
initialValues:
project:globalContext.getProject()
workspace:globalContext.getWorkspace()
user:globalContext.getUser()
subscription:globalContext.getSubscription()
options =
context: context,
renderTo: 'testDiv'
options.settings = settings if settings?
@app = Ext.create('Rally.apps.portfoliokanban.PortfolioKanbanApp', options)
@waitForComponentReady @app
_getTextsForElements: (cssQuery) ->
Ext.Array.map(@app.getEl().query(cssQuery), (el) -> el.innerHTML).join('__')
_createAppAndWaitForVisible: (callback) ->
@_createApp(project: '/project/431439')
@waitForVisible(css: '.progress-bar-container.field-PercentDoneByStoryCount').then =>
callback()
_clickAndWaitForVisible: (fieldName) ->
@click(css: '.progress-bar-container.field-' + fieldName).then =>
@waitForVisible(css: '.percentDonePopover')
beforeEach ->
Rally.environment.getContext().context.subscription.Modules = ['Rally Portfolio Manager']
@ajax.whenQuerying('typedefinition').respondWith([
{
'_ref':'/typedefinition/1'
ObjectID:'1'
Ordinal:1
Name:'Feature'
TypePath:'PortfolioItem/Feature'
}
])
afterEach ->
if @app?
if @app.down('rallyfilterinfo')?.tooltip?
@app.down('rallyfilterinfo').tooltip.destroy()
@app.destroy()
it 'should create popover when the progress bar is clicked', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
}
])
feature =
ObjectID: 878
_ref: '/portfolioitem/feature/878'
FormattedID: 'F1'
Name: 'Name of first PI'
Owner:
_ref: '/user/1'
_refObjectName: 'Name of Owner'
State: '/state/1'
Summary:
Discussion:
Count: 1
@ajax.whenQuerying('PortfolioItem/Feature').respondWith [feature]
@_createAppAndWaitForVisible =>
@_clickAndWaitForVisible('PercentDoneByStoryCount').then =>
expect(Ext.select('.percentDonePopover').elements.length).toEqual(1)
it 'loads type with ordinal of 1 if no type setting is provided', ->
@_createApp().then (app) =>
expect(app.currentType.get('_ref')).toEqual '/typedefinition/1'
expect(app.currentType.get('Name')).toEqual 'Feature'
it 'shows help component', ->
@_createApp().then (app) =>
expect(@app.down('#header').getEl().down('.rally-help-icon').dom.innerHTML).toContain 'Help & Training'
it 'shows ShowPolicies checkbox', ->
@_createApp().then (app) =>
expect(@app.down('#header').el.down('input[type="button"]')).toHaveCls 'showPoliciesCheckbox'
it 'creates columns from states', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
},
{
'_type': "State"
'Name': "Column2"
'_ref': '/state/2'
'WIPLimit': 3
}
])
@_createApp(type:'/typedefinition/1').then =>
expect(@app.down('rallycardboard').getColumns().length).toEqual 3
it 'shows message if no states are found', ->
@ajax.whenQuerying('state').respondWith()
@_createApp().then (app) =>
expect(@app.el.dom.textContent).toContain "This Type has no states defined."
it 'displays filter icon', ->
@_createApp().then (app) =>
expect(app.getEl().down('.filterInfo') instanceof Ext.Element).toBeTruthy()
it 'shows project setting label if following a specific project scope', ->
@_createApp(
project: '/project/431439'
).then (app) =>
app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get Ext.query('.filterInfoTooltip')[0]
expect(tooltipContent.dom.textContent).toContain 'Project'
expect(tooltipContent.dom.textContent).toContain 'Project 1'
it 'shows "Following Global Project Setting" in project setting label if following global project scope', ->
@ajax.whenQuerying('project').respondWith([
{
Name: 'Test Project'
'_ref': '/project/2'
}
])
@_createApp().then (app) =>
app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get Ext.query('.filterInfoTooltip')[0]
expect(tooltipContent.dom.textContent).toContain 'Following Global Project Setting'
it 'shows Discussion on Card', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
}
])
feature =
ObjectID: 878
_ref: '/portfolioitem/feature/878'
FormattedID: 'F1'
Name: 'Name of first PI'
Owner:
_ref: '/user/1'
_refObjectName: 'Name of Owner'
State: '/state/1'
Summary:
Discussion:
Count: 1
@ajax.whenQuerying('PortfolioItem/Feature').respondWith [feature]
@_createApp().then (app) =>
expect(app.down('rallycardboard').getColumns()[1].getCards()[0].getEl().down('.status-field.Discussion')).not.toBeNull()
it 'displays mandatory fields on the cards', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
}
])
feature =
ObjectID: 878
_ref: '/portfolioitem/feature/878'
FormattedID: 'F1'
Name: 'Name of first PI'
Owner:
_ref: '/user/1'
_refObjectName: 'Name of Owner'
State: '/state/1'
@ajax.whenQuerying('PortfolioItem/Feature').respondWith [feature]
@_createApp().then (app) =>
expect(@_getTextsForElements('.field-content')).toContain feature.Name
expect(@_getTextsForElements('.id')).toContain feature.FormattedID
expect(app.getEl().query('.Owner .rui-field-value')[0].title).toContain feature.Owner._refObjectName
it 'creates loading mask with unique id', ->
@_createApp().then (app) =>
expect(app.getMaskId()).toBe('btid-portfolio-kanban-board-load-mask-' + app.id)
it 'should display an error message if you do not have RPM turned on ', ->
Rally.environment.getContext().context.subscription.Modules = []
loadSpy = @spy Rally.data.util.PortfolioItemHelper, 'loadTypeOrDefault'
@_createApp().then =>
expect(loadSpy.callCount).toBe 0
expect(@app.down('#bodyContainer').getEl().dom.innerHTML).toContain 'You do not have RPM enabled for your subscription'
| 53591 | Ext = window.Ext4 || window.Ext
describe 'Rally.apps.portfoliokanban.PortfolioKanbanApp', ->
helpers
_createApp: (settings) ->
globalContext = Rally.environment.getContext()
context = Ext.create 'Rally.app.Context',
initialValues:
project:globalContext.getProject()
workspace:globalContext.getWorkspace()
user:globalContext.getUser()
subscription:globalContext.getSubscription()
options =
context: context,
renderTo: 'testDiv'
options.settings = settings if settings?
@app = Ext.create('Rally.apps.portfoliokanban.PortfolioKanbanApp', options)
@waitForComponentReady @app
_getTextsForElements: (cssQuery) ->
Ext.Array.map(@app.getEl().query(cssQuery), (el) -> el.innerHTML).join('__')
_createAppAndWaitForVisible: (callback) ->
@_createApp(project: '/project/431439')
@waitForVisible(css: '.progress-bar-container.field-PercentDoneByStoryCount').then =>
callback()
_clickAndWaitForVisible: (fieldName) ->
@click(css: '.progress-bar-container.field-' + fieldName).then =>
@waitForVisible(css: '.percentDonePopover')
beforeEach ->
Rally.environment.getContext().context.subscription.Modules = ['Rally Portfolio Manager']
@ajax.whenQuerying('typedefinition').respondWith([
{
'_ref':'/typedefinition/1'
ObjectID:'1'
Ordinal:1
Name:'Feature'
TypePath:'PortfolioItem/Feature'
}
])
afterEach ->
if @app?
if @app.down('rallyfilterinfo')?.tooltip?
@app.down('rallyfilterinfo').tooltip.destroy()
@app.destroy()
it 'should create popover when the progress bar is clicked', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
}
])
feature =
ObjectID: 878
_ref: '/portfolioitem/feature/878'
FormattedID: 'F1'
Name: '<NAME> <NAME>'
Owner:
_ref: '/user/1'
_refObjectName: 'Name of Owner'
State: '/state/1'
Summary:
Discussion:
Count: 1
@ajax.whenQuerying('PortfolioItem/Feature').respondWith [feature]
@_createAppAndWaitForVisible =>
@_clickAndWaitForVisible('PercentDoneByStoryCount').then =>
expect(Ext.select('.percentDonePopover').elements.length).toEqual(1)
it 'loads type with ordinal of 1 if no type setting is provided', ->
@_createApp().then (app) =>
expect(app.currentType.get('_ref')).toEqual '/typedefinition/1'
expect(app.currentType.get('Name')).toEqual 'Feature'
it 'shows help component', ->
@_createApp().then (app) =>
expect(@app.down('#header').getEl().down('.rally-help-icon').dom.innerHTML).toContain 'Help & Training'
it 'shows ShowPolicies checkbox', ->
@_createApp().then (app) =>
expect(@app.down('#header').el.down('input[type="button"]')).toHaveCls 'showPoliciesCheckbox'
it 'creates columns from states', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
},
{
'_type': "State"
'Name': "Column2"
'_ref': '/state/2'
'WIPLimit': 3
}
])
@_createApp(type:'/typedefinition/1').then =>
expect(@app.down('rallycardboard').getColumns().length).toEqual 3
it 'shows message if no states are found', ->
@ajax.whenQuerying('state').respondWith()
@_createApp().then (app) =>
expect(@app.el.dom.textContent).toContain "This Type has no states defined."
it 'displays filter icon', ->
@_createApp().then (app) =>
expect(app.getEl().down('.filterInfo') instanceof Ext.Element).toBeTruthy()
it 'shows project setting label if following a specific project scope', ->
@_createApp(
project: '/project/431439'
).then (app) =>
app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get Ext.query('.filterInfoTooltip')[0]
expect(tooltipContent.dom.textContent).toContain 'Project'
expect(tooltipContent.dom.textContent).toContain 'Project 1'
it 'shows "Following Global Project Setting" in project setting label if following global project scope', ->
@ajax.whenQuerying('project').respondWith([
{
Name: '<NAME> Project'
'_ref': '/project/2'
}
])
@_createApp().then (app) =>
app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get Ext.query('.filterInfoTooltip')[0]
expect(tooltipContent.dom.textContent).toContain 'Following Global Project Setting'
it 'shows Discussion on Card', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
}
])
feature =
ObjectID: 878
_ref: '/portfolioitem/feature/878'
FormattedID: 'F1'
Name: '<NAME> <NAME>'
Owner:
_ref: '/user/1'
_refObjectName: 'Name of Owner'
State: '/state/1'
Summary:
Discussion:
Count: 1
@ajax.whenQuerying('PortfolioItem/Feature').respondWith [feature]
@_createApp().then (app) =>
expect(app.down('rallycardboard').getColumns()[1].getCards()[0].getEl().down('.status-field.Discussion')).not.toBeNull()
it 'displays mandatory fields on the cards', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
}
])
feature =
ObjectID: 878
_ref: '/portfolioitem/feature/878'
FormattedID: 'F1'
Name: '<NAME> <NAME>'
Owner:
_ref: '/user/1'
_refObjectName: 'Name of Owner'
State: '/state/1'
@ajax.whenQuerying('PortfolioItem/Feature').respondWith [feature]
@_createApp().then (app) =>
expect(@_getTextsForElements('.field-content')).toContain feature.Name
expect(@_getTextsForElements('.id')).toContain feature.FormattedID
expect(app.getEl().query('.Owner .rui-field-value')[0].title).toContain feature.Owner._refObjectName
it 'creates loading mask with unique id', ->
@_createApp().then (app) =>
expect(app.getMaskId()).toBe('btid-portfolio-kanban-board-load-mask-' + app.id)
it 'should display an error message if you do not have RPM turned on ', ->
Rally.environment.getContext().context.subscription.Modules = []
loadSpy = @spy Rally.data.util.PortfolioItemHelper, 'loadTypeOrDefault'
@_createApp().then =>
expect(loadSpy.callCount).toBe 0
expect(@app.down('#bodyContainer').getEl().dom.innerHTML).toContain 'You do not have RPM enabled for your subscription'
| true | Ext = window.Ext4 || window.Ext
describe 'Rally.apps.portfoliokanban.PortfolioKanbanApp', ->
helpers
_createApp: (settings) ->
globalContext = Rally.environment.getContext()
context = Ext.create 'Rally.app.Context',
initialValues:
project:globalContext.getProject()
workspace:globalContext.getWorkspace()
user:globalContext.getUser()
subscription:globalContext.getSubscription()
options =
context: context,
renderTo: 'testDiv'
options.settings = settings if settings?
@app = Ext.create('Rally.apps.portfoliokanban.PortfolioKanbanApp', options)
@waitForComponentReady @app
_getTextsForElements: (cssQuery) ->
Ext.Array.map(@app.getEl().query(cssQuery), (el) -> el.innerHTML).join('__')
_createAppAndWaitForVisible: (callback) ->
@_createApp(project: '/project/431439')
@waitForVisible(css: '.progress-bar-container.field-PercentDoneByStoryCount').then =>
callback()
_clickAndWaitForVisible: (fieldName) ->
@click(css: '.progress-bar-container.field-' + fieldName).then =>
@waitForVisible(css: '.percentDonePopover')
beforeEach ->
Rally.environment.getContext().context.subscription.Modules = ['Rally Portfolio Manager']
@ajax.whenQuerying('typedefinition').respondWith([
{
'_ref':'/typedefinition/1'
ObjectID:'1'
Ordinal:1
Name:'Feature'
TypePath:'PortfolioItem/Feature'
}
])
afterEach ->
if @app?
if @app.down('rallyfilterinfo')?.tooltip?
@app.down('rallyfilterinfo').tooltip.destroy()
@app.destroy()
it 'should create popover when the progress bar is clicked', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
}
])
feature =
ObjectID: 878
_ref: '/portfolioitem/feature/878'
FormattedID: 'F1'
Name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
Owner:
_ref: '/user/1'
_refObjectName: 'Name of Owner'
State: '/state/1'
Summary:
Discussion:
Count: 1
@ajax.whenQuerying('PortfolioItem/Feature').respondWith [feature]
@_createAppAndWaitForVisible =>
@_clickAndWaitForVisible('PercentDoneByStoryCount').then =>
expect(Ext.select('.percentDonePopover').elements.length).toEqual(1)
it 'loads type with ordinal of 1 if no type setting is provided', ->
@_createApp().then (app) =>
expect(app.currentType.get('_ref')).toEqual '/typedefinition/1'
expect(app.currentType.get('Name')).toEqual 'Feature'
it 'shows help component', ->
@_createApp().then (app) =>
expect(@app.down('#header').getEl().down('.rally-help-icon').dom.innerHTML).toContain 'Help & Training'
it 'shows ShowPolicies checkbox', ->
@_createApp().then (app) =>
expect(@app.down('#header').el.down('input[type="button"]')).toHaveCls 'showPoliciesCheckbox'
it 'creates columns from states', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
},
{
'_type': "State"
'Name': "Column2"
'_ref': '/state/2'
'WIPLimit': 3
}
])
@_createApp(type:'/typedefinition/1').then =>
expect(@app.down('rallycardboard').getColumns().length).toEqual 3
it 'shows message if no states are found', ->
@ajax.whenQuerying('state').respondWith()
@_createApp().then (app) =>
expect(@app.el.dom.textContent).toContain "This Type has no states defined."
it 'displays filter icon', ->
@_createApp().then (app) =>
expect(app.getEl().down('.filterInfo') instanceof Ext.Element).toBeTruthy()
it 'shows project setting label if following a specific project scope', ->
@_createApp(
project: '/project/431439'
).then (app) =>
app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get Ext.query('.filterInfoTooltip')[0]
expect(tooltipContent.dom.textContent).toContain 'Project'
expect(tooltipContent.dom.textContent).toContain 'Project 1'
it 'shows "Following Global Project Setting" in project setting label if following global project scope', ->
@ajax.whenQuerying('project').respondWith([
{
Name: 'PI:NAME:<NAME>END_PI Project'
'_ref': '/project/2'
}
])
@_createApp().then (app) =>
app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get Ext.query('.filterInfoTooltip')[0]
expect(tooltipContent.dom.textContent).toContain 'Following Global Project Setting'
it 'shows Discussion on Card', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
}
])
feature =
ObjectID: 878
_ref: '/portfolioitem/feature/878'
FormattedID: 'F1'
Name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
Owner:
_ref: '/user/1'
_refObjectName: 'Name of Owner'
State: '/state/1'
Summary:
Discussion:
Count: 1
@ajax.whenQuerying('PortfolioItem/Feature').respondWith [feature]
@_createApp().then (app) =>
expect(app.down('rallycardboard').getColumns()[1].getCards()[0].getEl().down('.status-field.Discussion')).not.toBeNull()
it 'displays mandatory fields on the cards', ->
@ajax.whenQuerying('state').respondWith([
{
'_type': "State"
'Name': "Column1"
'_ref': '/state/1'
'WIPLimit': 4
}
])
feature =
ObjectID: 878
_ref: '/portfolioitem/feature/878'
FormattedID: 'F1'
Name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
Owner:
_ref: '/user/1'
_refObjectName: 'Name of Owner'
State: '/state/1'
@ajax.whenQuerying('PortfolioItem/Feature').respondWith [feature]
@_createApp().then (app) =>
expect(@_getTextsForElements('.field-content')).toContain feature.Name
expect(@_getTextsForElements('.id')).toContain feature.FormattedID
expect(app.getEl().query('.Owner .rui-field-value')[0].title).toContain feature.Owner._refObjectName
it 'creates loading mask with unique id', ->
@_createApp().then (app) =>
expect(app.getMaskId()).toBe('btid-portfolio-kanban-board-load-mask-' + app.id)
it 'should display an error message if you do not have RPM turned on ', ->
Rally.environment.getContext().context.subscription.Modules = []
loadSpy = @spy Rally.data.util.PortfolioItemHelper, 'loadTypeOrDefault'
@_createApp().then =>
expect(loadSpy.callCount).toBe 0
expect(@app.down('#bodyContainer').getEl().dom.innerHTML).toContain 'You do not have RPM enabled for your subscription'
|
[
{
"context": "# Contributors\ncontributors: [\n name: 'Season千'\n avatar: 'http://7xkd7e.com1.z0.glb.clouddn.c",
"end": 49,
"score": 0.9922714233398438,
"start": 42,
"tag": "USERNAME",
"value": "Season千"
},
{
"context": "w.pixiv.net/member.php?id=3991162'\n ,\n name: 'Magic... | assets/data/constant.cson | AlanJager/poi | 1 | # Contributors
contributors: [
name: 'Season千'
avatar: 'http://7xkd7e.com1.z0.glb.clouddn.com/season.jpg'
link: 'http://www.pixiv.net/member.php?id=3991162'
,
name: 'Magica'
avatar: 'https://avatars0.githubusercontent.com/u/6753092?v=3&s=460'
link: 'http://weibo.com/maginya'
,
name: 'Yunze'
avatar: 'https://avatars3.githubusercontent.com/u/3362438?v=3&s=460'
link: 'http://weibo.com/myzwillmake'
,
name: 'Chiba'
avatar: 'https://avatars1.githubusercontent.com/u/6986642?v=3&s=460'
link: 'http://weibo.com/chibaheit'
,
name: 'KochiyaOcean'
avatar: 'https://avatars3.githubusercontent.com/u/8194131?v=3&s=460'
link: 'http://www.kochiyaocean.org'
,
name: '马里酱'
avatar: 'https://avatars3.githubusercontent.com/u/10855724?v=3&s=460'
link: 'http://www.weibo.com/1791427467'
,
name: '吴钩霜雪明'
avatar: 'https://avatars2.githubusercontent.com/u/6861365?v=3&s=460'
link: 'http://www.weibo.com/jenningswu'
,
name: 'Rui'
avatar: 'https://avatars3.githubusercontent.com/u/11897118?v=3&s=460'
link: 'https://github.com/ruiii'
,
name: 'Artoria'
avatar: 'https://avatars1.githubusercontent.com/u/1183568?v=3&s=460'
link: 'http://www.weibo.com/pheliox'
,
name: 'Alvin'
avatar: 'https://avatars3.githubusercontent.com/u/13615512?v=3&s=460'
link: 'https://github.com/alvin-777'
,
name: 'Ayaphis'
avatar: 'https://avatars2.githubusercontent.com/u/11754367?v=3&s=400'
link: 'https://github.com/ayaphis'
,
name: 'ZYC'
avatar: 'https://avatars3.githubusercontent.com/u/13725370?v=3&s=460'
link: 'http://weibo.com/zyc43'
,
name: 'Dazzy Ding'
avatar: 'https://avatars1.githubusercontent.com/u/3337921'
link: 'http://dazzyd.org/'
,
name: 'taroxd'
avatar: 'https://avatars3.githubusercontent.com/u/6070540?v=3&s=460'
link: 'http://github.com/taroxd'
,
name: 'edwardaaaa'
avatar: 'https://avatars1.githubusercontent.com/u/11089376?v=3&s=460'
link: 'https://github.com/edwardaaaa'
,
name: 'DKWings'
avatar: 'https://avatars3.githubusercontent.com/u/1596656?v=3&s=460'
link: 'https://github.com/dkwingsmt'
,
name: 'grzhan'
avatar: 'https://avatars2.githubusercontent.com/u/2235314?v=3&s=460'
link: 'https://github.com/grzhan'
,
name: 'Gizeta'
avatar: 'https://avatars2.githubusercontent.com/u/1572561?v=3&s=400'
link: 'https://github.com/Gizeta'
,
name: 'KagamiChan'
avatar: 'https://avatars2.githubusercontent.com/u/3816900?v=3&s=400'
link: 'https://github.com/KagamiChan'
,
name: 'CirnoV'
avatar: 'https://avatars3.githubusercontent.com/u/17797795?v=3&s=400'
link: 'https://github.com/CirnoV'
,
name: 'Javran'
avatar: 'https://gist.githubusercontent.com/Javran/02ac7ebefc307829d02e5dc942f8ef28/raw/250x250.png'
link: 'https://github.com/Javran'
]
thanksTo: [
name: 'KCwiki'
link: 'https://zh.kcwiki.moe/wiki/%E8%88%B0%E5%A8%98%E7%99%BE%E7%A7%91'
avatar: 'https://upload.kcwiki.moe/commons/thumb/d/d1/Kcwiki-banner.png/600px-Kcwiki-banner.png'
description: 'For providing data of item imporvment, task info, shipgirl qoutes, etc.'
extraCSS:
WebkitClipPath: "inset(0px 78% 0px 0px)"
maxHeight: "100%"
marginLeft: "5%"
,
name: 'TaoNPM'
link: 'https://npm.taobao.org/'
avatar: 'https://zos.alipayobjects.com/rmsportal/UQvFKvLLWPPmxTM.png'
description: 'For providing China mirror for the project.'
extraCSS:
maxWidth: "100%"
marginTop: "40%"
,
name: 'Kancolle English Wikia'
link: 'http://kancolle.wikia.com/wiki/Kancolle_Wiki'
avatar: 'http://vignette4.wikia.nocookie.net/kancolle/images/8/89/Wiki-wordmark.png/revision/latest?cb=20141226051229'
description: 'For providing English translation.'
extraCSS:
WebkitClipPath: "inset(0px 74% 0px 0px)"
maxHeight: "100%"
marginLeft: "5%"
marginTop: "7%"
,
name: 'Type 74 Electronic Observer'
link: 'https://github.com/andanteyk/ElectronicObserver'
avatar: 'https://github.com/andanteyk/ElectronicObserver/blob/develop/ElectronicObserver/Assets/AppIcon_64.png?raw=true'
description: 'For providing KanColle API references.'
extraCSS:
margin: "auto"
display: "block"
,
name: 'Kensuke Tanaka'
link: 'https://www.facebook.com/kensuke.tanaka.790'
avatar: 'http://www.famitsu.com/images/000/039/658/l_522b1c633860a.jpg'
description: 'For providing development difficulties (which we enjoyed a lot, sincerely).'
extraCSS:
maxHeight: "200%"
marginLeft: "-65%"
marginTop: "-20%"
]
| 152322 | # Contributors
contributors: [
name: 'Season千'
avatar: 'http://7xkd7e.com1.z0.glb.clouddn.com/season.jpg'
link: 'http://www.pixiv.net/member.php?id=3991162'
,
name: '<NAME>'
avatar: 'https://avatars0.githubusercontent.com/u/6753092?v=3&s=460'
link: 'http://weibo.com/maginya'
,
name: '<NAME>'
avatar: 'https://avatars3.githubusercontent.com/u/3362438?v=3&s=460'
link: 'http://weibo.com/myzwillmake'
,
name: '<NAME>'
avatar: 'https://avatars1.githubusercontent.com/u/6986642?v=3&s=460'
link: 'http://weibo.com/chibaheit'
,
name: '<NAME>Ocean'
avatar: 'https://avatars3.githubusercontent.com/u/8194131?v=3&s=460'
link: 'http://www.kochiyaocean.org'
,
name: '<NAME>'
avatar: 'https://avatars3.githubusercontent.com/u/10855724?v=3&s=460'
link: 'http://www.weibo.com/1791427467'
,
name: '<NAME>'
avatar: 'https://avatars2.githubusercontent.com/u/6861365?v=3&s=460'
link: 'http://www.weibo.com/jenningswu'
,
name: '<NAME>'
avatar: 'https://avatars3.githubusercontent.com/u/11897118?v=3&s=460'
link: 'https://github.com/ruiii'
,
name: '<NAME>'
avatar: 'https://avatars1.githubusercontent.com/u/1183568?v=3&s=460'
link: 'http://www.weibo.com/pheliox'
,
name: '<NAME>'
avatar: 'https://avatars3.githubusercontent.com/u/13615512?v=3&s=460'
link: 'https://github.com/alvin-777'
,
name: '<NAME>'
avatar: 'https://avatars2.githubusercontent.com/u/11754367?v=3&s=400'
link: 'https://github.com/ayaphis'
,
name: '<NAME>'
avatar: 'https://avatars3.githubusercontent.com/u/13725370?v=3&s=460'
link: 'http://weibo.com/zyc43'
,
name: '<NAME>'
avatar: 'https://avatars1.githubusercontent.com/u/3337921'
link: 'http://dazzyd.org/'
,
name: '<NAME>'
avatar: 'https://avatars3.githubusercontent.com/u/6070540?v=3&s=460'
link: 'http://github.com/taroxd'
,
name: 'edwardaaaa'
avatar: 'https://avatars1.githubusercontent.com/u/11089376?v=3&s=460'
link: 'https://github.com/edwardaaaa'
,
name: 'DKWings'
avatar: 'https://avatars3.githubusercontent.com/u/1596656?v=3&s=460'
link: 'https://github.com/dkwingsmt'
,
name: 'grzhan'
avatar: 'https://avatars2.githubusercontent.com/u/2235314?v=3&s=460'
link: 'https://github.com/grzhan'
,
name: '<NAME>'
avatar: 'https://avatars2.githubusercontent.com/u/1572561?v=3&s=400'
link: 'https://github.com/Gizeta'
,
name: '<NAME>'
avatar: 'https://avatars2.githubusercontent.com/u/3816900?v=3&s=400'
link: 'https://github.com/KagamiChan'
,
name: '<NAME>'
avatar: 'https://avatars3.githubusercontent.com/u/17797795?v=3&s=400'
link: 'https://github.com/CirnoV'
,
name: '<NAME>'
avatar: 'https://gist.githubusercontent.com/Javran/02ac7ebefc307829d02e5dc942f8ef28/raw/250x250.png'
link: 'https://github.com/Javran'
]
thanksTo: [
name: 'KCwiki'
link: 'https://zh.kcwiki.moe/wiki/%E8%88%B0%E5%A8%98%E7%99%BE%E7%A7%91'
avatar: 'https://upload.kcwiki.moe/commons/thumb/d/d1/Kcwiki-banner.png/600px-Kcwiki-banner.png'
description: 'For providing data of item imporvment, task info, shipgirl qoutes, etc.'
extraCSS:
WebkitClipPath: "inset(0px 78% 0px 0px)"
maxHeight: "100%"
marginLeft: "5%"
,
name: 'TaoNPM'
link: 'https://npm.taobao.org/'
avatar: 'https://zos.alipayobjects.com/rmsportal/UQvFKvLLWPPmxTM.png'
description: 'For providing China mirror for the project.'
extraCSS:
maxWidth: "100%"
marginTop: "40%"
,
name: 'Kancolle English Wikia'
link: 'http://kancolle.wikia.com/wiki/Kancolle_Wiki'
avatar: 'http://vignette4.wikia.nocookie.net/kancolle/images/8/89/Wiki-wordmark.png/revision/latest?cb=20141226051229'
description: 'For providing English translation.'
extraCSS:
WebkitClipPath: "inset(0px 74% 0px 0px)"
maxHeight: "100%"
marginLeft: "5%"
marginTop: "7%"
,
name: 'Type 74 Electronic Observer'
link: 'https://github.com/andanteyk/ElectronicObserver'
avatar: 'https://github.com/andanteyk/ElectronicObserver/blob/develop/ElectronicObserver/Assets/AppIcon_64.png?raw=true'
description: 'For providing KanColle API references.'
extraCSS:
margin: "auto"
display: "block"
,
name: '<NAME>'
link: 'https://www.facebook.com/kensuke.tanaka.790'
avatar: 'http://www.famitsu.com/images/000/039/658/l_522b1c633860a.jpg'
description: 'For providing development difficulties (which we enjoyed a lot, sincerely).'
extraCSS:
maxHeight: "200%"
marginLeft: "-65%"
marginTop: "-20%"
]
| true | # Contributors
contributors: [
name: 'Season千'
avatar: 'http://7xkd7e.com1.z0.glb.clouddn.com/season.jpg'
link: 'http://www.pixiv.net/member.php?id=3991162'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars0.githubusercontent.com/u/6753092?v=3&s=460'
link: 'http://weibo.com/maginya'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars3.githubusercontent.com/u/3362438?v=3&s=460'
link: 'http://weibo.com/myzwillmake'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars1.githubusercontent.com/u/6986642?v=3&s=460'
link: 'http://weibo.com/chibaheit'
,
name: 'PI:NAME:<NAME>END_PIOcean'
avatar: 'https://avatars3.githubusercontent.com/u/8194131?v=3&s=460'
link: 'http://www.kochiyaocean.org'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars3.githubusercontent.com/u/10855724?v=3&s=460'
link: 'http://www.weibo.com/1791427467'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars2.githubusercontent.com/u/6861365?v=3&s=460'
link: 'http://www.weibo.com/jenningswu'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars3.githubusercontent.com/u/11897118?v=3&s=460'
link: 'https://github.com/ruiii'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars1.githubusercontent.com/u/1183568?v=3&s=460'
link: 'http://www.weibo.com/pheliox'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars3.githubusercontent.com/u/13615512?v=3&s=460'
link: 'https://github.com/alvin-777'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars2.githubusercontent.com/u/11754367?v=3&s=400'
link: 'https://github.com/ayaphis'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars3.githubusercontent.com/u/13725370?v=3&s=460'
link: 'http://weibo.com/zyc43'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars1.githubusercontent.com/u/3337921'
link: 'http://dazzyd.org/'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars3.githubusercontent.com/u/6070540?v=3&s=460'
link: 'http://github.com/taroxd'
,
name: 'edwardaaaa'
avatar: 'https://avatars1.githubusercontent.com/u/11089376?v=3&s=460'
link: 'https://github.com/edwardaaaa'
,
name: 'DKWings'
avatar: 'https://avatars3.githubusercontent.com/u/1596656?v=3&s=460'
link: 'https://github.com/dkwingsmt'
,
name: 'grzhan'
avatar: 'https://avatars2.githubusercontent.com/u/2235314?v=3&s=460'
link: 'https://github.com/grzhan'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars2.githubusercontent.com/u/1572561?v=3&s=400'
link: 'https://github.com/Gizeta'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars2.githubusercontent.com/u/3816900?v=3&s=400'
link: 'https://github.com/KagamiChan'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars3.githubusercontent.com/u/17797795?v=3&s=400'
link: 'https://github.com/CirnoV'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://gist.githubusercontent.com/Javran/02ac7ebefc307829d02e5dc942f8ef28/raw/250x250.png'
link: 'https://github.com/Javran'
]
thanksTo: [
name: 'KCwiki'
link: 'https://zh.kcwiki.moe/wiki/%E8%88%B0%E5%A8%98%E7%99%BE%E7%A7%91'
avatar: 'https://upload.kcwiki.moe/commons/thumb/d/d1/Kcwiki-banner.png/600px-Kcwiki-banner.png'
description: 'For providing data of item imporvment, task info, shipgirl qoutes, etc.'
extraCSS:
WebkitClipPath: "inset(0px 78% 0px 0px)"
maxHeight: "100%"
marginLeft: "5%"
,
name: 'TaoNPM'
link: 'https://npm.taobao.org/'
avatar: 'https://zos.alipayobjects.com/rmsportal/UQvFKvLLWPPmxTM.png'
description: 'For providing China mirror for the project.'
extraCSS:
maxWidth: "100%"
marginTop: "40%"
,
name: 'Kancolle English Wikia'
link: 'http://kancolle.wikia.com/wiki/Kancolle_Wiki'
avatar: 'http://vignette4.wikia.nocookie.net/kancolle/images/8/89/Wiki-wordmark.png/revision/latest?cb=20141226051229'
description: 'For providing English translation.'
extraCSS:
WebkitClipPath: "inset(0px 74% 0px 0px)"
maxHeight: "100%"
marginLeft: "5%"
marginTop: "7%"
,
name: 'Type 74 Electronic Observer'
link: 'https://github.com/andanteyk/ElectronicObserver'
avatar: 'https://github.com/andanteyk/ElectronicObserver/blob/develop/ElectronicObserver/Assets/AppIcon_64.png?raw=true'
description: 'For providing KanColle API references.'
extraCSS:
margin: "auto"
display: "block"
,
name: 'PI:NAME:<NAME>END_PI'
link: 'https://www.facebook.com/kensuke.tanaka.790'
avatar: 'http://www.famitsu.com/images/000/039/658/l_522b1c633860a.jpg'
description: 'For providing development difficulties (which we enjoyed a lot, sincerely).'
extraCSS:
maxHeight: "200%"
marginLeft: "-65%"
marginTop: "-20%"
]
|
[
{
"context": "# TuringType\n# 0.0.2\n# Dan Motzenbecker\n# http://oxism.com\n# Copyright 2014, MIT License\n",
"end": 39,
"score": 0.9998701810836792,
"start": 23,
"tag": "NAME",
"value": "Dan Motzenbecker"
},
{
"context": "ype\n\n int: 100\n accuracy: .95\n keys: 'qwerty... | turingtype.coffee | dmotz/TuringType | 74 | # TuringType
# 0.0.2
# Dan Motzenbecker
# http://oxism.com
# Copyright 2014, MIT License
rand = Math.random
{floor} = Math
class TuringType
int: 100
accuracy: .95
keys: 'qwertyuiopasdfghjklzxcvbnm,./;-=[]'.split ''
constructor: (@el, @text, @options = {}) ->
return new TuringType @el, @text, @options unless @ instanceof TuringType
@el = document.querySelector @el if typeof @el is 'string'
@len = @text.length
@i = 0
{accuracy, interval, @callback} = @options
@accuracy = accuracy ? @accuracy
@int = interval ? @int
if tag = @el.tagName.toLowerCase() is 'textarea' or tag is 'input'
@attr = 'value'
@el.focus()
else
@attr = 'innerText'
@type()
type: =>
return @callback?() if @i is @len + 1
if rand() > @accuracy
@el[@attr] = @text.slice(0, @i) + @keys[floor rand() * @keys.length]
@timer = setTimeout =>
@el[@attr] = @text.slice 0, @i
@timer = setTimeout @type, rand() * @int + @int * .8
, @int * 1.5
else
@el[@attr] = @text.slice 0, @i++
@timer = setTimeout @type, do =>
t = rand() * @int + @int * .1
t += rand() * @int if @text[@i] is ' '
t += rand() * @int * 3 if @text[@i] is '.' or @text[@i] is ','
t += @int * 2 if rand() > .97
t += @int if rand() > .95
t
pause: ->
clearTimeout @timer
@el[@attr]
clear: (n = @len) =>
return if n is -2
@el[@attr] = @text.slice 0, @i--
setTimeout @clear.bind(@, --n), rand() * @int
if module?.exports
module.exports = TuringType
else if define?.amd
define -> TuringType
else
window.TuringType = TuringType
| 171531 | # TuringType
# 0.0.2
# <NAME>
# http://oxism.com
# Copyright 2014, MIT License
rand = Math.random
{floor} = Math
class TuringType
int: 100
accuracy: .95
keys: '<KEY>'.split ''
constructor: (@el, @text, @options = {}) ->
return new TuringType @el, @text, @options unless @ instanceof TuringType
@el = document.querySelector @el if typeof @el is 'string'
@len = @text.length
@i = 0
{accuracy, interval, @callback} = @options
@accuracy = accuracy ? @accuracy
@int = interval ? @int
if tag = @el.tagName.toLowerCase() is 'textarea' or tag is 'input'
@attr = 'value'
@el.focus()
else
@attr = 'innerText'
@type()
type: =>
return @callback?() if @i is @len + 1
if rand() > @accuracy
@el[@attr] = @text.slice(0, @i) + @keys[floor rand() * @keys.length]
@timer = setTimeout =>
@el[@attr] = @text.slice 0, @i
@timer = setTimeout @type, rand() * @int + @int * .8
, @int * 1.5
else
@el[@attr] = @text.slice 0, @i++
@timer = setTimeout @type, do =>
t = rand() * @int + @int * .1
t += rand() * @int if @text[@i] is ' '
t += rand() * @int * 3 if @text[@i] is '.' or @text[@i] is ','
t += @int * 2 if rand() > .97
t += @int if rand() > .95
t
pause: ->
clearTimeout @timer
@el[@attr]
clear: (n = @len) =>
return if n is -2
@el[@attr] = @text.slice 0, @i--
setTimeout @clear.bind(@, --n), rand() * @int
if module?.exports
module.exports = TuringType
else if define?.amd
define -> TuringType
else
window.TuringType = TuringType
| true | # TuringType
# 0.0.2
# PI:NAME:<NAME>END_PI
# http://oxism.com
# Copyright 2014, MIT License
rand = Math.random
{floor} = Math
class TuringType
int: 100
accuracy: .95
keys: 'PI:KEY:<KEY>END_PI'.split ''
constructor: (@el, @text, @options = {}) ->
return new TuringType @el, @text, @options unless @ instanceof TuringType
@el = document.querySelector @el if typeof @el is 'string'
@len = @text.length
@i = 0
{accuracy, interval, @callback} = @options
@accuracy = accuracy ? @accuracy
@int = interval ? @int
if tag = @el.tagName.toLowerCase() is 'textarea' or tag is 'input'
@attr = 'value'
@el.focus()
else
@attr = 'innerText'
@type()
type: =>
return @callback?() if @i is @len + 1
if rand() > @accuracy
@el[@attr] = @text.slice(0, @i) + @keys[floor rand() * @keys.length]
@timer = setTimeout =>
@el[@attr] = @text.slice 0, @i
@timer = setTimeout @type, rand() * @int + @int * .8
, @int * 1.5
else
@el[@attr] = @text.slice 0, @i++
@timer = setTimeout @type, do =>
t = rand() * @int + @int * .1
t += rand() * @int if @text[@i] is ' '
t += rand() * @int * 3 if @text[@i] is '.' or @text[@i] is ','
t += @int * 2 if rand() > .97
t += @int if rand() > .95
t
pause: ->
clearTimeout @timer
@el[@attr]
clear: (n = @len) =>
return if n is -2
@el[@attr] = @text.slice 0, @i--
setTimeout @clear.bind(@, --n), rand() * @int
if module?.exports
module.exports = TuringType
else if define?.amd
define -> TuringType
else
window.TuringType = TuringType
|
[
{
"context": " visualStatus\n\t\t\t_id: Meteor.userId()\n\t\t\tusername: username\n\t\t\tdisplayName: displayName\n\t\t}\n\n\tshowAdminOption",
"end": 962,
"score": 0.999125063419342,
"start": 954,
"tag": "USERNAME",
"value": "username"
},
{
"context": "eor.userId()\n\t\t\tusername: ... | client/views/app/sideNav/sideNav.coffee | akio46/Stitch | 0 | Template.sideNav.helpers
flexTemplate: ->
return SideNav.getFlex().template
flexData: ->
return SideNav.getFlex().data
# footer: ->
# return ''; #RocketChat.settings.get 'Layout_Sidenav_Footer'
showStarredRooms: ->
favoritesEnabled = !RocketChat.settings.get 'Disable_Favorite_Rooms'
hasFavoriteRoomOpened = ChatSubscription.findOne({ 'u._id': Meteor.userId(), f: true, open: true })
return true if favoritesEnabled and hasFavoriteRoomOpened
myUserInfo: ->
visualStatus = "online"
username = Meteor.user()?.username
displayName = Meteor.user()?.name
switch Session.get('user_' + username + '_status')
when "away"
visualStatus = t("away")
when "busy"
visualStatus = t("busy")
when "offline"
visualStatus = t("invisible")
return {
name: Session.get('user_' + username + '_name')
status: Session.get('user_' + username + '_status')
visualStatus: visualStatus
_id: Meteor.userId()
username: username
displayName: displayName
}
showAdminOption: ->
return RocketChat.authz.hasAtLeastOnePermission( ['view-statistics', 'view-room-administration', 'view-user-administration', 'view-privileged-setting'])
registeredMenus: ->
return AccountBox.getOptions()
Template.sideNav.events
'click .close-flex': ->
SideNav.closeFlex()
'click .arrow': ->
SideNav.toggleCurrent()
'mouseenter .header': ->
SideNav.overArrow()
'mouseleave .header': ->
SideNav.leaveArrow()
'scroll .rooms-list': ->
menu.updateUnreadBars()
'click .options .status': (event) ->
event.preventDefault()
AccountBox.setStatus(event.currentTarget.dataset.status)
'click .account-box': (event) ->
AccountBox.toggle()
'click #logout': (event) ->
event.preventDefault()
user = Meteor.user()
Meteor.logout ->
FlowRouter.go 'home'
Meteor.call('logoutCleanUp', user)
'click #avatar': (event) ->
FlowRouter.go 'changeAvatar'
'click #account': (event) ->
SideNav.setFlex "accountFlex"
SideNav.openFlex()
FlowRouter.go 'account'
'click #admin': ->
SideNav.setFlex "adminFlex"
SideNav.openFlex()
'click .account-link': ->
menu.close()
'click #inviteUsers': ->
menu.close()
AccountBox.toggle()
Template.sideNav.onRendered ->
SideNav.init()
menu.init()
Meteor.defer ->
menu.updateUnreadBars()
AccountBox.init()
wrapper = $('.rooms-list .wrapper').get(0)
lastLink = $('.rooms-list h3.history-div').get(0)
RocketChat.roomTypes.getTypes().forEach (roomType) ->
if RocketChat.authz.hasRole(Meteor.userId(), roomType.roles) && Template[roomType.template]?
Blaze.render Template[roomType.template], wrapper, lastLink
| 185482 | Template.sideNav.helpers
flexTemplate: ->
return SideNav.getFlex().template
flexData: ->
return SideNav.getFlex().data
# footer: ->
# return ''; #RocketChat.settings.get 'Layout_Sidenav_Footer'
showStarredRooms: ->
favoritesEnabled = !RocketChat.settings.get 'Disable_Favorite_Rooms'
hasFavoriteRoomOpened = ChatSubscription.findOne({ 'u._id': Meteor.userId(), f: true, open: true })
return true if favoritesEnabled and hasFavoriteRoomOpened
myUserInfo: ->
visualStatus = "online"
username = Meteor.user()?.username
displayName = Meteor.user()?.name
switch Session.get('user_' + username + '_status')
when "away"
visualStatus = t("away")
when "busy"
visualStatus = t("busy")
when "offline"
visualStatus = t("invisible")
return {
name: Session.get('user_' + username + '_name')
status: Session.get('user_' + username + '_status')
visualStatus: visualStatus
_id: Meteor.userId()
username: username
displayName: <NAME>
}
showAdminOption: ->
return RocketChat.authz.hasAtLeastOnePermission( ['view-statistics', 'view-room-administration', 'view-user-administration', 'view-privileged-setting'])
registeredMenus: ->
return AccountBox.getOptions()
Template.sideNav.events
'click .close-flex': ->
SideNav.closeFlex()
'click .arrow': ->
SideNav.toggleCurrent()
'mouseenter .header': ->
SideNav.overArrow()
'mouseleave .header': ->
SideNav.leaveArrow()
'scroll .rooms-list': ->
menu.updateUnreadBars()
'click .options .status': (event) ->
event.preventDefault()
AccountBox.setStatus(event.currentTarget.dataset.status)
'click .account-box': (event) ->
AccountBox.toggle()
'click #logout': (event) ->
event.preventDefault()
user = Meteor.user()
Meteor.logout ->
FlowRouter.go 'home'
Meteor.call('logoutCleanUp', user)
'click #avatar': (event) ->
FlowRouter.go 'changeAvatar'
'click #account': (event) ->
SideNav.setFlex "accountFlex"
SideNav.openFlex()
FlowRouter.go 'account'
'click #admin': ->
SideNav.setFlex "adminFlex"
SideNav.openFlex()
'click .account-link': ->
menu.close()
'click #inviteUsers': ->
menu.close()
AccountBox.toggle()
Template.sideNav.onRendered ->
SideNav.init()
menu.init()
Meteor.defer ->
menu.updateUnreadBars()
AccountBox.init()
wrapper = $('.rooms-list .wrapper').get(0)
lastLink = $('.rooms-list h3.history-div').get(0)
RocketChat.roomTypes.getTypes().forEach (roomType) ->
if RocketChat.authz.hasRole(Meteor.userId(), roomType.roles) && Template[roomType.template]?
Blaze.render Template[roomType.template], wrapper, lastLink
| true | Template.sideNav.helpers
flexTemplate: ->
return SideNav.getFlex().template
flexData: ->
return SideNav.getFlex().data
# footer: ->
# return ''; #RocketChat.settings.get 'Layout_Sidenav_Footer'
showStarredRooms: ->
favoritesEnabled = !RocketChat.settings.get 'Disable_Favorite_Rooms'
hasFavoriteRoomOpened = ChatSubscription.findOne({ 'u._id': Meteor.userId(), f: true, open: true })
return true if favoritesEnabled and hasFavoriteRoomOpened
myUserInfo: ->
visualStatus = "online"
username = Meteor.user()?.username
displayName = Meteor.user()?.name
switch Session.get('user_' + username + '_status')
when "away"
visualStatus = t("away")
when "busy"
visualStatus = t("busy")
when "offline"
visualStatus = t("invisible")
return {
name: Session.get('user_' + username + '_name')
status: Session.get('user_' + username + '_status')
visualStatus: visualStatus
_id: Meteor.userId()
username: username
displayName: PI:NAME:<NAME>END_PI
}
showAdminOption: ->
return RocketChat.authz.hasAtLeastOnePermission( ['view-statistics', 'view-room-administration', 'view-user-administration', 'view-privileged-setting'])
registeredMenus: ->
return AccountBox.getOptions()
Template.sideNav.events
'click .close-flex': ->
SideNav.closeFlex()
'click .arrow': ->
SideNav.toggleCurrent()
'mouseenter .header': ->
SideNav.overArrow()
'mouseleave .header': ->
SideNav.leaveArrow()
'scroll .rooms-list': ->
menu.updateUnreadBars()
'click .options .status': (event) ->
event.preventDefault()
AccountBox.setStatus(event.currentTarget.dataset.status)
'click .account-box': (event) ->
AccountBox.toggle()
'click #logout': (event) ->
event.preventDefault()
user = Meteor.user()
Meteor.logout ->
FlowRouter.go 'home'
Meteor.call('logoutCleanUp', user)
'click #avatar': (event) ->
FlowRouter.go 'changeAvatar'
'click #account': (event) ->
SideNav.setFlex "accountFlex"
SideNav.openFlex()
FlowRouter.go 'account'
'click #admin': ->
SideNav.setFlex "adminFlex"
SideNav.openFlex()
'click .account-link': ->
menu.close()
'click #inviteUsers': ->
menu.close()
AccountBox.toggle()
Template.sideNav.onRendered ->
SideNav.init()
menu.init()
Meteor.defer ->
menu.updateUnreadBars()
AccountBox.init()
wrapper = $('.rooms-list .wrapper').get(0)
lastLink = $('.rooms-list h3.history-div').get(0)
RocketChat.roomTypes.getTypes().forEach (roomType) ->
if RocketChat.authz.hasRole(Meteor.userId(), roomType.roles) && Template[roomType.template]?
Blaze.render Template[roomType.template], wrapper, lastLink
|
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.9998548626899719,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | src/widgets/dropdownform.coffee | git-j/hallo | 0 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.hallodropdownform',
button: null
debug: false
options:
uuid: ''
label: null
icon: null
editable: null
target: '' # dropdown
setup: null
cssClass: null
_create: ->
@options.icon ?= "icon-#{@options.label.toLowerCase()}"
_init: ->
target = jQuery @options.target
target.css 'position', 'absolute'
target.addClass 'dropdown-menu'
target.addClass 'dropdown-form'
target.addClass 'dropdown-form-' + @options.command
target.hide()
@button = @_prepareButton() unless @button
@button.bind 'click', =>
if target.hasClass 'open'
@_hideTarget()
return
@_showTarget()
target.bind 'bindShowTrigger', (event) =>
# trigger handler to get correct this from live() events
# console.log('dropdownform show handler',event,this)# if @debug
# this should be correct
toolbar = jQuery('.hallotoolbar').eq(0)
return if ( !toolbar.length )
@options.target = toolbar.find('.dropdown-form-' + @options.command)
return if ( !@options.target.length )
@button = toolbar.find('.' + @options.command + '_button')
@_showTarget(@options.target)
@element.append @button
bindShowHandler: (event) ->
@_showTarget(event.target)
bindShow: (selector) ->
event_name = 'click'
console.log('bindShow:',selector,event_name) if @debug
jQuery(document).undelegate selector, event_name
jQuery(document).delegate selector, event_name, (event) =>
#jQuery(selector).live event_name, =>
console.log(event.target) if @debug
# # find the toolbar and reset the button/@options.target members
# # they were destroyed when the user changes the editable
# # this is NOT as expected!
if ( jQuery(event.target).closest('.dropdown-form-' + @options.command).length )
return
toolbar = jQuery('.hallotoolbar').eq(0)
return if ( !toolbar.length )
target = toolbar.find('.dropdown-form-' + @options.command)
window.live_target = event.target # HACK will be consumed by first user
target.trigger('bindShowTrigger')
_showTarget: (select_target) ->
console.log('dropdownform target show',select_target) if @debug
jQuery(".dropdown-form:visible, .dropdown-menu:visible").each (index,item) ->
jQuery(item).trigger('hide')
target_id = jQuery(@options.target).attr('id')
target = jQuery('#' + target_id)
@options.editable.storeContentPosition()
setup_success = @options.setup(select_target,target_id) if @options.setup
console.log('setup success:',setup_success) if @debug
if ( ! setup_success )
@_hideTarget()
return
target.addClass 'open'
target.show()
# must be visible for correct positions
@_updateTargetPosition()
if ( target.find('textarea').length )
target.find('textarea:first').focus()
else
target.find('input:first').focus()
target.bind 'hide', =>
@_hideTarget()
_hideTarget: ->
console.log('target remove') if @debug
target = jQuery @options.target
if ( target.hasClass 'open' )
target.removeClass 'open'
jQuery("select",target).selectBox('destroy')
target.trigger('hide')
target.hide()
@options.editable.restoreContentPosition()
hideForm: ->
jQuery(".dropdown-form:visible, .dropdown-menu:visible").each (index,item) ->
console.log('index',index) if @debug
jQuery(item).trigger('hide')
@options.editable.restoreContentPosition()
_updateTargetPosition: ->
target_id = jQuery(@options.target).attr('id')
target = jQuery('#' + target_id)
button_id = jQuery(@button).attr('id')
button = jQuery('#' + button_id)
button_position = button.position()
top = button_position.top
left = button_position.left
top += button.outerHeight()
target.css 'top', top
last_button = target.closest('.hallotoolbar').find('button:last')
if last_button.length
last_button_pos =last_button.position().left
last_button_pos+=last_button.width()
if ( last_button.length && left + target.width() > last_button_pos )
left = left - target.width() + last_button.width()
if ( left < 0 )
left = 0
target.css('left', left);
console.log('target position:',target.position(),top,left,last_button) if @debug
console.log(target.width(),last_button.width()) if @debug
_prepareButton: ->
id = "#{@options.uuid}-#{@options.command}"
button_str = "<button id=\"#{id}\" data-toggle=\"dropdown\""
button_str+= " class=\"#{@options.command}_button ui-button ui-widget ui-state-default ui-corner-all\""
button_str+= " data-target=\"##{@options.target.attr('id')}\""
button_str+= " title=\"#{@options.label}\" rel=\"#{@options.command}\""
button_str+= "></button>"
buttonEl = jQuery button_str;
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.addClass 'btn-large' if @options.editable.options.touchScreen
button = buttonEl.button { "icons": { "primary": "ui-icon-#{@options.command}-p" }, "text": false }
button.addClass @options.cssClass if @options.cssClass
button
)(jQuery)
| 16664 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.hallodropdownform',
button: null
debug: false
options:
uuid: ''
label: null
icon: null
editable: null
target: '' # dropdown
setup: null
cssClass: null
_create: ->
@options.icon ?= "icon-#{@options.label.toLowerCase()}"
_init: ->
target = jQuery @options.target
target.css 'position', 'absolute'
target.addClass 'dropdown-menu'
target.addClass 'dropdown-form'
target.addClass 'dropdown-form-' + @options.command
target.hide()
@button = @_prepareButton() unless @button
@button.bind 'click', =>
if target.hasClass 'open'
@_hideTarget()
return
@_showTarget()
target.bind 'bindShowTrigger', (event) =>
# trigger handler to get correct this from live() events
# console.log('dropdownform show handler',event,this)# if @debug
# this should be correct
toolbar = jQuery('.hallotoolbar').eq(0)
return if ( !toolbar.length )
@options.target = toolbar.find('.dropdown-form-' + @options.command)
return if ( !@options.target.length )
@button = toolbar.find('.' + @options.command + '_button')
@_showTarget(@options.target)
@element.append @button
bindShowHandler: (event) ->
@_showTarget(event.target)
bindShow: (selector) ->
event_name = 'click'
console.log('bindShow:',selector,event_name) if @debug
jQuery(document).undelegate selector, event_name
jQuery(document).delegate selector, event_name, (event) =>
#jQuery(selector).live event_name, =>
console.log(event.target) if @debug
# # find the toolbar and reset the button/@options.target members
# # they were destroyed when the user changes the editable
# # this is NOT as expected!
if ( jQuery(event.target).closest('.dropdown-form-' + @options.command).length )
return
toolbar = jQuery('.hallotoolbar').eq(0)
return if ( !toolbar.length )
target = toolbar.find('.dropdown-form-' + @options.command)
window.live_target = event.target # HACK will be consumed by first user
target.trigger('bindShowTrigger')
_showTarget: (select_target) ->
console.log('dropdownform target show',select_target) if @debug
jQuery(".dropdown-form:visible, .dropdown-menu:visible").each (index,item) ->
jQuery(item).trigger('hide')
target_id = jQuery(@options.target).attr('id')
target = jQuery('#' + target_id)
@options.editable.storeContentPosition()
setup_success = @options.setup(select_target,target_id) if @options.setup
console.log('setup success:',setup_success) if @debug
if ( ! setup_success )
@_hideTarget()
return
target.addClass 'open'
target.show()
# must be visible for correct positions
@_updateTargetPosition()
if ( target.find('textarea').length )
target.find('textarea:first').focus()
else
target.find('input:first').focus()
target.bind 'hide', =>
@_hideTarget()
_hideTarget: ->
console.log('target remove') if @debug
target = jQuery @options.target
if ( target.hasClass 'open' )
target.removeClass 'open'
jQuery("select",target).selectBox('destroy')
target.trigger('hide')
target.hide()
@options.editable.restoreContentPosition()
hideForm: ->
jQuery(".dropdown-form:visible, .dropdown-menu:visible").each (index,item) ->
console.log('index',index) if @debug
jQuery(item).trigger('hide')
@options.editable.restoreContentPosition()
_updateTargetPosition: ->
target_id = jQuery(@options.target).attr('id')
target = jQuery('#' + target_id)
button_id = jQuery(@button).attr('id')
button = jQuery('#' + button_id)
button_position = button.position()
top = button_position.top
left = button_position.left
top += button.outerHeight()
target.css 'top', top
last_button = target.closest('.hallotoolbar').find('button:last')
if last_button.length
last_button_pos =last_button.position().left
last_button_pos+=last_button.width()
if ( last_button.length && left + target.width() > last_button_pos )
left = left - target.width() + last_button.width()
if ( left < 0 )
left = 0
target.css('left', left);
console.log('target position:',target.position(),top,left,last_button) if @debug
console.log(target.width(),last_button.width()) if @debug
_prepareButton: ->
id = "#{@options.uuid}-#{@options.command}"
button_str = "<button id=\"#{id}\" data-toggle=\"dropdown\""
button_str+= " class=\"#{@options.command}_button ui-button ui-widget ui-state-default ui-corner-all\""
button_str+= " data-target=\"##{@options.target.attr('id')}\""
button_str+= " title=\"#{@options.label}\" rel=\"#{@options.command}\""
button_str+= "></button>"
buttonEl = jQuery button_str;
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.addClass 'btn-large' if @options.editable.options.touchScreen
button = buttonEl.button { "icons": { "primary": "ui-icon-#{@options.command}-p" }, "text": false }
button.addClass @options.cssClass if @options.cssClass
button
)(jQuery)
| true | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.hallodropdownform',
button: null
debug: false
options:
uuid: ''
label: null
icon: null
editable: null
target: '' # dropdown
setup: null
cssClass: null
_create: ->
@options.icon ?= "icon-#{@options.label.toLowerCase()}"
_init: ->
target = jQuery @options.target
target.css 'position', 'absolute'
target.addClass 'dropdown-menu'
target.addClass 'dropdown-form'
target.addClass 'dropdown-form-' + @options.command
target.hide()
@button = @_prepareButton() unless @button
@button.bind 'click', =>
if target.hasClass 'open'
@_hideTarget()
return
@_showTarget()
target.bind 'bindShowTrigger', (event) =>
# trigger handler to get correct this from live() events
# console.log('dropdownform show handler',event,this)# if @debug
# this should be correct
toolbar = jQuery('.hallotoolbar').eq(0)
return if ( !toolbar.length )
@options.target = toolbar.find('.dropdown-form-' + @options.command)
return if ( !@options.target.length )
@button = toolbar.find('.' + @options.command + '_button')
@_showTarget(@options.target)
@element.append @button
bindShowHandler: (event) ->
@_showTarget(event.target)
bindShow: (selector) ->
event_name = 'click'
console.log('bindShow:',selector,event_name) if @debug
jQuery(document).undelegate selector, event_name
jQuery(document).delegate selector, event_name, (event) =>
#jQuery(selector).live event_name, =>
console.log(event.target) if @debug
# # find the toolbar and reset the button/@options.target members
# # they were destroyed when the user changes the editable
# # this is NOT as expected!
if ( jQuery(event.target).closest('.dropdown-form-' + @options.command).length )
return
toolbar = jQuery('.hallotoolbar').eq(0)
return if ( !toolbar.length )
target = toolbar.find('.dropdown-form-' + @options.command)
window.live_target = event.target # HACK will be consumed by first user
target.trigger('bindShowTrigger')
_showTarget: (select_target) ->
console.log('dropdownform target show',select_target) if @debug
jQuery(".dropdown-form:visible, .dropdown-menu:visible").each (index,item) ->
jQuery(item).trigger('hide')
target_id = jQuery(@options.target).attr('id')
target = jQuery('#' + target_id)
@options.editable.storeContentPosition()
setup_success = @options.setup(select_target,target_id) if @options.setup
console.log('setup success:',setup_success) if @debug
if ( ! setup_success )
@_hideTarget()
return
target.addClass 'open'
target.show()
# must be visible for correct positions
@_updateTargetPosition()
if ( target.find('textarea').length )
target.find('textarea:first').focus()
else
target.find('input:first').focus()
target.bind 'hide', =>
@_hideTarget()
_hideTarget: ->
console.log('target remove') if @debug
target = jQuery @options.target
if ( target.hasClass 'open' )
target.removeClass 'open'
jQuery("select",target).selectBox('destroy')
target.trigger('hide')
target.hide()
@options.editable.restoreContentPosition()
hideForm: ->
jQuery(".dropdown-form:visible, .dropdown-menu:visible").each (index,item) ->
console.log('index',index) if @debug
jQuery(item).trigger('hide')
@options.editable.restoreContentPosition()
_updateTargetPosition: ->
target_id = jQuery(@options.target).attr('id')
target = jQuery('#' + target_id)
button_id = jQuery(@button).attr('id')
button = jQuery('#' + button_id)
button_position = button.position()
top = button_position.top
left = button_position.left
top += button.outerHeight()
target.css 'top', top
last_button = target.closest('.hallotoolbar').find('button:last')
if last_button.length
last_button_pos =last_button.position().left
last_button_pos+=last_button.width()
if ( last_button.length && left + target.width() > last_button_pos )
left = left - target.width() + last_button.width()
if ( left < 0 )
left = 0
target.css('left', left);
console.log('target position:',target.position(),top,left,last_button) if @debug
console.log(target.width(),last_button.width()) if @debug
_prepareButton: ->
id = "#{@options.uuid}-#{@options.command}"
button_str = "<button id=\"#{id}\" data-toggle=\"dropdown\""
button_str+= " class=\"#{@options.command}_button ui-button ui-widget ui-state-default ui-corner-all\""
button_str+= " data-target=\"##{@options.target.attr('id')}\""
button_str+= " title=\"#{@options.label}\" rel=\"#{@options.command}\""
button_str+= "></button>"
buttonEl = jQuery button_str;
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.addClass 'btn-large' if @options.editable.options.touchScreen
button = buttonEl.button { "icons": { "primary": "ui-icon-#{@options.command}-p" }, "text": false }
button.addClass @options.cssClass if @options.cssClass
button
)(jQuery)
|
[
{
"context": "'00000@000'\n process.env.HUBOT_FLICKR_API_KEY='foo123bar'\n nock.disableNetConnect()\n @room = helper.",
"end": 399,
"score": 0.9991769790649414,
"start": 390,
"tag": "KEY",
"value": "foo123bar"
},
{
"context": "on')\n\n selfRoom = @room\n selfRoom.user.... | test/flickr-group-search-slack-test.coffee | stephenyeargin/hubot-flickr-group-search | 1 | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper [
'adapters/slack.coffee',
'../src/flickr-group-search.coffee'
]
describe 'hubot-flickr-group-search for slack', ->
beforeEach ->
process.env.HUBOT_LOG_LEVEL='error'
process.env.HUBOT_FLICKR_GROUP_ID='00000@000'
process.env.HUBOT_FLICKR_API_KEY='foo123bar'
nock.disableNetConnect()
@room = helper.createRoom()
afterEach ->
delete process.env.HUBOT_LOG_LEVEL
delete process.env.HUBOT_FLICKR_GROUP_ID
delete process.env.HUBOT_FLICKR_API_KEY
nock.cleanAll()
@room.destroy()
it 'retrieves photos matching a query', (done) ->
nock('https://api.flickr.com')
.get('/services/rest')
.query(true)
.replyWithFile(200, __dirname + '/fixtures/photos.search.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot photos dogs')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot photos dogs']
['hubot', '@alice Retrieving photos matching: "dogs"']
[
'hubot',
{
"attachments": [
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "Flickr"
"image_url": "https://c1.staticflickr.com/5/4380/36155994663_668de89232_b.jpg"
"title": "R0015531 - dog with hat"
"title_link": "https://flickr.com/photos/135188764@N04/36155994663"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "Flickr"
"image_url": "https://c1.staticflickr.com/8/7668/26967112975_ba2f2a75f0_b.jpg"
"title": "Hot Diggity Dog Hot Dog place"
"title_link": "https://flickr.com/photos/91210007@N06/26967112975"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "Flickr"
"image_url": "https://c1.staticflickr.com/8/7143/26284057513_5eb0b15867_b.jpg"
"title": "Dog In The Middle"
"title_link": "https://flickr.com/photos/123677698@N03/26284057513"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "Flickr"
"image_url": "https://c1.staticflickr.com/4/3742/11227992813_c079f40aeb_b.jpg"
"title": "Hot Dogs"
"title_link": "https://flickr.com/photos/82879511@N00/11227992813"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "Flickr"
"image_url": "https://c1.staticflickr.com/9/8465/8367619593_9f06974095_b.jpg"
"title": "girl in tub"
"title_link": "https://flickr.com/photos/23128100@N00/8367619593"
}
]
"fallback": "There are 142 photos in the group that match your search. Here are the 5 most recent:\n- https://flickr.com/photos/135188764@N04/36155994663 - R0015531 - dog with hat\n- https://flickr.com/photos/91210007@N06/26967112975 - Hot Diggity Dog Hot Dog place\n- https://flickr.com/photos/123677698@N03/26284057513 - Dog In The Middle\n- https://flickr.com/photos/82879511@N00/11227992813 - Hot Dogs\n- https://flickr.com/photos/23128100@N00/8367619593 - girl in tub"
"text": "There are 142 photos in the group that match your search. Here are the 5 most recent:"
"unfurl_links": false
}
]
]
done()
catch err
done err
return
, 1000)
| 189304 | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper [
'adapters/slack.coffee',
'../src/flickr-group-search.coffee'
]
describe 'hubot-flickr-group-search for slack', ->
beforeEach ->
process.env.HUBOT_LOG_LEVEL='error'
process.env.HUBOT_FLICKR_GROUP_ID='00000@000'
process.env.HUBOT_FLICKR_API_KEY='<KEY>'
nock.disableNetConnect()
@room = helper.createRoom()
afterEach ->
delete process.env.HUBOT_LOG_LEVEL
delete process.env.HUBOT_FLICKR_GROUP_ID
delete process.env.HUBOT_FLICKR_API_KEY
nock.cleanAll()
@room.destroy()
it 'retrieves photos matching a query', (done) ->
nock('https://api.flickr.com')
.get('/services/rest')
.query(true)
.replyWithFile(200, __dirname + '/fixtures/photos.search.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot photos dogs')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot photos dogs']
['hubot', '@alice Retrieving photos matching: "dogs"']
[
'hubot',
{
"attachments": [
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "<NAME>"
"image_url": "https://c1.staticflickr.com/5/4380/36155994663_668de89232_b.jpg"
"title": "R0015531 - dog with hat"
"title_link": "https://flickr.com/photos/135188764@N04/36155994663"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "<NAME>"
"image_url": "https://c1.staticflickr.com/8/7668/26967112975_ba2f2a75f0_b.jpg"
"title": "Hot Diggity Dog Hot Dog place"
"title_link": "https://flickr.com/photos/91210007@N06/26967112975"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "<NAME>"
"image_url": "https://c1.staticflickr.com/8/7143/26284057513_5eb0b15867_b.jpg"
"title": "Dog In The Middle"
"title_link": "https://flickr.com/photos/123677698@N03/26284057513"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "<NAME>"
"image_url": "https://c1.staticflickr.com/4/3742/11227992813_c079f40aeb_b.jpg"
"title": "Hot Dogs"
"title_link": "https://flickr.com/photos/82879511@N00/11227992813"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "<NAME>"
"image_url": "https://c1.staticflickr.com/9/8465/8367619593_9f06974095_b.jpg"
"title": "girl in tub"
"title_link": "https://flickr.com/photos/23128100@N00/8367619593"
}
]
"fallback": "There are 142 photos in the group that match your search. Here are the 5 most recent:\n- https://flickr.com/photos/135188764@N04/36155994663 - R0015531 - dog with hat\n- https://flickr.com/photos/91210007@N06/26967112975 - Hot Diggity Dog Hot Dog place\n- https://flickr.com/photos/123677698@N03/26284057513 - Dog In The Middle\n- https://flickr.com/photos/82879511@N00/11227992813 - Hot Dogs\n- https://flickr.com/photos/23128100@N00/8367619593 - girl in tub"
"text": "There are 142 photos in the group that match your search. Here are the 5 most recent:"
"unfurl_links": false
}
]
]
done()
catch err
done err
return
, 1000)
| true | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper [
'adapters/slack.coffee',
'../src/flickr-group-search.coffee'
]
describe 'hubot-flickr-group-search for slack', ->
beforeEach ->
process.env.HUBOT_LOG_LEVEL='error'
process.env.HUBOT_FLICKR_GROUP_ID='00000@000'
process.env.HUBOT_FLICKR_API_KEY='PI:KEY:<KEY>END_PI'
nock.disableNetConnect()
@room = helper.createRoom()
afterEach ->
delete process.env.HUBOT_LOG_LEVEL
delete process.env.HUBOT_FLICKR_GROUP_ID
delete process.env.HUBOT_FLICKR_API_KEY
nock.cleanAll()
@room.destroy()
it 'retrieves photos matching a query', (done) ->
nock('https://api.flickr.com')
.get('/services/rest')
.query(true)
.replyWithFile(200, __dirname + '/fixtures/photos.search.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot photos dogs')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot photos dogs']
['hubot', '@alice Retrieving photos matching: "dogs"']
[
'hubot',
{
"attachments": [
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "PI:NAME:<NAME>END_PI"
"image_url": "https://c1.staticflickr.com/5/4380/36155994663_668de89232_b.jpg"
"title": "R0015531 - dog with hat"
"title_link": "https://flickr.com/photos/135188764@N04/36155994663"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "PI:NAME:<NAME>END_PI"
"image_url": "https://c1.staticflickr.com/8/7668/26967112975_ba2f2a75f0_b.jpg"
"title": "Hot Diggity Dog Hot Dog place"
"title_link": "https://flickr.com/photos/91210007@N06/26967112975"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "PI:NAME:<NAME>END_PI"
"image_url": "https://c1.staticflickr.com/8/7143/26284057513_5eb0b15867_b.jpg"
"title": "Dog In The Middle"
"title_link": "https://flickr.com/photos/123677698@N03/26284057513"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "PI:NAME:<NAME>END_PI"
"image_url": "https://c1.staticflickr.com/4/3742/11227992813_c079f40aeb_b.jpg"
"title": "Hot Dogs"
"title_link": "https://flickr.com/photos/82879511@N00/11227992813"
}
{
"author_icon": "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png"
"author_link": "https://flickr.com/groups/00000@000"
"author_name": "PI:NAME:<NAME>END_PI"
"image_url": "https://c1.staticflickr.com/9/8465/8367619593_9f06974095_b.jpg"
"title": "girl in tub"
"title_link": "https://flickr.com/photos/23128100@N00/8367619593"
}
]
"fallback": "There are 142 photos in the group that match your search. Here are the 5 most recent:\n- https://flickr.com/photos/135188764@N04/36155994663 - R0015531 - dog with hat\n- https://flickr.com/photos/91210007@N06/26967112975 - Hot Diggity Dog Hot Dog place\n- https://flickr.com/photos/123677698@N03/26284057513 - Dog In The Middle\n- https://flickr.com/photos/82879511@N00/11227992813 - Hot Dogs\n- https://flickr.com/photos/23128100@N00/8367619593 - girl in tub"
"text": "There are 142 photos in the group that match your search. Here are the 5 most recent:"
"unfurl_links": false
}
]
]
done()
catch err
done err
return
, 1000)
|
[
{
"context": "###\nCopyright 2017 Balena\n\nLicensed under the Apache License, Version 2.0 (",
"end": 25,
"score": 0.9986509680747986,
"start": 19,
"tag": "NAME",
"value": "Balena"
}
] | lib/actions/local/index.coffee | bjornmagnusson/balena-cli | 0 | ###
Copyright 2017 Balena
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.
###
exports.configure = require('./configure')
exports.flash = require('./flash').flash
exports.logs = require('./logs')
exports.scan = require('./scan')
exports.ssh = require('./ssh')
exports.push = require('./push')
exports.stop = require('./stop')
| 73543 | ###
Copyright 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.
###
exports.configure = require('./configure')
exports.flash = require('./flash').flash
exports.logs = require('./logs')
exports.scan = require('./scan')
exports.ssh = require('./ssh')
exports.push = require('./push')
exports.stop = require('./stop')
| true | ###
Copyright 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.
###
exports.configure = require('./configure')
exports.flash = require('./flash').flash
exports.logs = require('./logs')
exports.scan = require('./scan')
exports.ssh = require('./ssh')
exports.push = require('./push')
exports.stop = require('./stop')
|
[
{
"context": " allow_multiple_files: true\n valid_s3_keys: ['key', 'acl', 'AWSAccessKeyId', 'policy', 'signature',",
"end": 488,
"score": 0.7608227729797363,
"start": 485,
"tag": "KEY",
"value": "key"
},
{
"context": "_multiple_files: true\n valid_s3_keys: ['key', 'acl', 'AWSA... | app/assets/javascripts/effective_assets/s3_uploader.js.coffee | code-and-effect/effective_assets | 11 | $ = jQuery
$.fn.S3Uploader = (options) ->
# support multiple elements
if @length > 1
@each -> $(this).S3Uploader options
return this
$uploadForm = this # the .asset-box-uploader div .asset-box-input > [.attachments, .uploads, .asset-box-uploader]
settings =
url: ''
remove_completed_progress_bar: true
remove_failed_progress_bar: true
progress_bar_target: null
progress_bar_template: null
allow_multiple_files: true
valid_s3_keys: ['key', 'acl', 'AWSAccessKeyId', 'policy', 'signature', 'success_action_status', 'X-Requested-With', 'content-type']
create_asset_url: null
update_asset_url: null
file_types: 'any'
click_submit: false
$.extend settings, options
current_files = []
setUploadForm = ->
$uploadForm.fileupload
url: settings.url
add: (e, data) ->
# Ensure correct $uploadForm is being used
$uploadForms = $('.asset-box-uploader')
return false if $uploadForms.index($uploadForm) == -1
$uploadForms.find("input[type='file']").removeAttr('required')
# Make sure the user isn't over the upload limit
$asset_box = $uploadForm.closest('.asset-box-input')
limit = $asset_box.data('limit')
if typeof limit == 'number' && limit > 1
count = parseInt($asset_box.attr('data-attachment-count'), 10)
if count >= limit
alert("Unable to add file(s). You have exceeded the limit of #{limit} uploads.") unless $asset_box.data('over-limit-alerted')
$asset_box.data('over-limit-alerted', true)
return false
else
$asset_box.attr('data-attachment-count', count + 1)
# Add the file to the upload
file = data.files[0]
# Check File Type
if settings.file_types != 'any'
types = new RegExp("(\.|\/)(#{settings.file_types})$")
unless types.test(file.type) || types.test(file.name.toLowerCase()) || file.name.toLowerCase().indexOf('._test') > 0
alert("Unable to add #{file.name}.\n\nOnly #{settings.file_types.replace(/\|/g, ', ')} files allowed.")
return false
if file.name.length > 180
alert("Unable to add #{file.name}.\n\nFile name too long. File name must be 180 or fewer characters long.")
return false
# We're all good. Let's go ahead and add this
current_files.push data
$uploadForm.trigger("s3_file_added", [e, file])
template = settings.progress_bar_template
data.context = $($.trim(tmpl(template.html(), file)))
$(data.context).appendTo(settings.progress_bar_target)
data.submit()
start: (e) ->
$uploadForm.trigger("s3_uploads_start", [e])
disable_submit()
progress: (e, data) ->
if data.context
progress = parseInt(data.loaded / data.total * 100, 10)
data.context.find('.bar').css('width', progress + '%').html(format_bitrate(data.bitrate))
data.context.find('.progress > span').remove()
done: (e, data) ->
content = build_content_object($uploadForm, data.files[0], data.result)
if settings.update_asset_url
update_asset_and_load_attachment(content)
data.context.fadeOut('slow', -> $(this).remove()) if data.context && settings.remove_completed_progress_bar # remove progress bar
$uploadForm.trigger("s3_upload_complete", [$uploadForm, content])
current_files.splice($.inArray(data, current_files), 1) # remove that element from the array
unless current_files.length
$uploadForm.trigger("s3_uploads_complete", [$uploadForm, content])
enable_submit()
fail: (e, data) ->
content = build_content_object($uploadForm, data.files[0], data.result)
content.error_thrown = data.errorThrown
data.context.fadeOut('slow', -> $(this).remove()) if data.context && settings.remove_failed_progress_bar # remove progress bar
$uploadForm.trigger("s3_upload_failed", [$uploadForm, content])
enable_submit()
formData: (form) ->
inputs = form.find($uploadForm).children('input')
inputs.each -> $(this).prop('disabled', false)
data = inputs.serializeArray()
inputs = form.find($uploadForm).children("input:not([name='file'])")
inputs.each -> $(this).prop('disabled', true)
fileType = ""
if "type" of @files[0]
fileType = @files[0].type
data.push
name: "content-type"
value: fileType
# Remove anything we can't submit to S3
for item in data
data.splice(data.indexOf(data), 1) unless item.name in settings.valid_s3_keys
# Ask our server for a unique ID for this Asset
asset = create_asset(@files[0])
@files[0].asset_id = asset.id
key = asset.s3_key
# substitute upload timestamp and unique_id into key
key_field = $.grep data, (n) ->
n if n.name == "key"
if key_field.length > 0
key_field[0].value = key
# IE <= 9 doesn't have XHR2 hence it can't use formData
# replace 'key' field to submit form
unless 'FormData' of window
$uploadForm.find("input[name='key']").val(key)
data
build_content_object = ($uploadForm, file, result) ->
content = {}
if result # Use the S3 response to set the URL to avoid character encodings bugs
content.url = $(result).find("Location").text()
content.filepath = $('<a />').attr('href', content.url)[0].pathname
else # IE <= 9 return a null result object so we use the file object instead
domain = settings.url
content.filepath = $uploadForm.find('input[name=key]').val().replace('/${filename}', '')
content.url = domain + content.filepath + '/' + encodeURIComponent(file.name)
content.url = s3urlDecode(content.url)
content.filepath = s3urlDecode(content.filepath)
content.filename = file.name
content.filesize = file.size if 'size' of file
content.lastModified = file.lastModified if 'lastModified' of file
content.filetype = file.type if 'type' of file
content.asset_id = file.asset_id if 'asset_id' of file
content.relativePath = build_relativePath(file) if has_relativePath(file)
content
has_relativePath = (file) ->
file.relativePath || file.webkitRelativePath
build_relativePath = (file) ->
file.relativePath || (file.webkitRelativePath.split("/")[0..-2].join("/") + "/" if file.webkitRelativePath)
s3urlDecode = (url) -> url.replace(/%2F/g, "/").replace(/\+/g, '%20')
extra_fields_for_asset = ->
# Any field in our form that shares our name like effective_asset[#{box}][something2] should be gotten
# And we return something2 => something2.value
box = $uploadForm.closest('.asset-box-input').data('box')
fields = $uploadForm.closest('form').find(":input[name*='[#{box}]']").serializeArray()
extra = {}
$.each fields, (i, field) ->
pieces = field.name.split('[').map (piece) -> piece.replace(']', '')
if (index_of_box = pieces.indexOf(box)) == -1
name = pieces.join()
else
name = pieces.slice(index_of_box+1, pieces.length).join()
extra[name] = field.value if name.length > 0
extra
create_asset = (file) ->
asset = 'false'
$.ajax
url: settings.create_asset_url
type: 'POST'
dataType: 'json'
data:
title: file.name
content_type: file.type
data_size: file.size
extra: extra_fields_for_asset()
async: false
success: (data) -> asset = data
asset
update_asset_and_load_attachment = (file) ->
asset_box = $uploadForm.closest('.asset-box-input')
$.ajax
url: settings.update_asset_url.replace(':id', file.asset_id)
type: 'PUT'
data:
upload_file: file.url
data_size: file.filesize
content_type: file.filetype
title: file.filename
attachable_type: asset_box.data('attachable-type')
attachable_id: asset_box.data('attachable-id')
attachable_object_name: asset_box.data('attachable-object-name')
attachment_style: asset_box.data('attachment-style')
attachment_actions: asset_box.data('attachment-actions')
attachment_links: asset_box.data('attachment-links')
aws_acl: asset_box.data('aws-acl')
box: asset_box.data('box')
async: true
success: (data) ->
limit = asset_box.data('limit')
direction = asset_box.data('attachment-add-to') # bottom or top. bottom is default append behaviour
if limit == 10000 && direction != 'top' # Guard value for no limit. There is no limit
asset_box.find('.attachments').append($(data))
else
asset_box.find('.attachments').prepend($(data))
asset_box.find("input.asset-box-remove").each (index) ->
if "#{$(this).val()}" == '1' # If we're going to delete it...
$(this).closest('.attachment').hide()
limit = limit + 1
return
if index >= limit
$(this).closest('.attachment').hide()
else
$(this).closest('.attachment').show()
click_submit() if settings.click_submit
disable_submit = ->
$uploadForm.data('effective-assets-uploading', true)
$uploadForm.closest('form').find('input[type=submit]').each ->
submit = $(this)
submit.data('effective-assets-original-label', submit.val()) if submit.data('effective-assets-original-label') == undefined
submit.prop('disabled', true)
submit.val('Uploading...')
enable_submit = ->
$uploadForm.data('effective-assets-uploading', false)
anyUploading = false
$uploadForm.closest('form').find('.asset-box-uploader').each ->
anyUploading = true if $(this).data('effective-assets-uploading') == true
unless anyUploading
$uploadForm.closest('form').find('input[type=submit]').each ->
submit = $(this)
submit.val(submit.data('effective-assets-original-label') || 'Submit')
submit.prop('disabled', false)
submit.removeData('effective-assets-original-label')
return !anyUploading # Returns true if we submitted it
click_submit = -> $uploadForm.closest('form').submit()
format_bitrate = (bits) ->
if typeof bits != 'number'
''
else if (bits >= 1000000000)
(bits / 1000000000).toFixed(2) + ' Gbit/s'
else if (bits >= 1000000)
(bits / 1000000).toFixed(2) + ' Mbit/s'
else if (bits >= 1000)
(bits / 1000).toFixed(2) + ' kbit/s'
else
bits.toFixed(2) + ' bit/s'
resetOverLimitAlert = (event) ->
$assetBox = $(event.target).closest('.asset-box-input')
$assetBox.data('over-limit-alerted', false)
#public methods
@initialize = ->
# Save key for IE9 Fix
$uploadForm.data('key', $uploadForm.find("input[name='key']").val())
$uploadForm.data('fileCount', 0)
$(document).on 'drop', '#' + $uploadForm.attr('id'), (event) ->
resetOverLimitAlert(event)
true
$(document).on 'click', "##{$uploadForm.attr('id')} .asset-box-uploader-fileinput", (event) ->
resetOverLimitAlert(event)
event.stopPropagation()
setUploadForm()
this
@initialize()
| 99115 | $ = jQuery
$.fn.S3Uploader = (options) ->
# support multiple elements
if @length > 1
@each -> $(this).S3Uploader options
return this
$uploadForm = this # the .asset-box-uploader div .asset-box-input > [.attachments, .uploads, .asset-box-uploader]
settings =
url: ''
remove_completed_progress_bar: true
remove_failed_progress_bar: true
progress_bar_target: null
progress_bar_template: null
allow_multiple_files: true
valid_s3_keys: ['<KEY>', '<KEY>', '<KEY>', 'policy', 'signature', 'success_action_status', 'X-Requested-With', 'content-type']
create_asset_url: null
update_asset_url: null
file_types: 'any'
click_submit: false
$.extend settings, options
current_files = []
setUploadForm = ->
$uploadForm.fileupload
url: settings.url
add: (e, data) ->
# Ensure correct $uploadForm is being used
$uploadForms = $('.asset-box-uploader')
return false if $uploadForms.index($uploadForm) == -1
$uploadForms.find("input[type='file']").removeAttr('required')
# Make sure the user isn't over the upload limit
$asset_box = $uploadForm.closest('.asset-box-input')
limit = $asset_box.data('limit')
if typeof limit == 'number' && limit > 1
count = parseInt($asset_box.attr('data-attachment-count'), 10)
if count >= limit
alert("Unable to add file(s). You have exceeded the limit of #{limit} uploads.") unless $asset_box.data('over-limit-alerted')
$asset_box.data('over-limit-alerted', true)
return false
else
$asset_box.attr('data-attachment-count', count + 1)
# Add the file to the upload
file = data.files[0]
# Check File Type
if settings.file_types != 'any'
types = new RegExp("(\.|\/)(#{settings.file_types})$")
unless types.test(file.type) || types.test(file.name.toLowerCase()) || file.name.toLowerCase().indexOf('._test') > 0
alert("Unable to add #{file.name}.\n\nOnly #{settings.file_types.replace(/\|/g, ', ')} files allowed.")
return false
if file.name.length > 180
alert("Unable to add #{file.name}.\n\nFile name too long. File name must be 180 or fewer characters long.")
return false
# We're all good. Let's go ahead and add this
current_files.push data
$uploadForm.trigger("s3_file_added", [e, file])
template = settings.progress_bar_template
data.context = $($.trim(tmpl(template.html(), file)))
$(data.context).appendTo(settings.progress_bar_target)
data.submit()
start: (e) ->
$uploadForm.trigger("s3_uploads_start", [e])
disable_submit()
progress: (e, data) ->
if data.context
progress = parseInt(data.loaded / data.total * 100, 10)
data.context.find('.bar').css('width', progress + '%').html(format_bitrate(data.bitrate))
data.context.find('.progress > span').remove()
done: (e, data) ->
content = build_content_object($uploadForm, data.files[0], data.result)
if settings.update_asset_url
update_asset_and_load_attachment(content)
data.context.fadeOut('slow', -> $(this).remove()) if data.context && settings.remove_completed_progress_bar # remove progress bar
$uploadForm.trigger("s3_upload_complete", [$uploadForm, content])
current_files.splice($.inArray(data, current_files), 1) # remove that element from the array
unless current_files.length
$uploadForm.trigger("s3_uploads_complete", [$uploadForm, content])
enable_submit()
fail: (e, data) ->
content = build_content_object($uploadForm, data.files[0], data.result)
content.error_thrown = data.errorThrown
data.context.fadeOut('slow', -> $(this).remove()) if data.context && settings.remove_failed_progress_bar # remove progress bar
$uploadForm.trigger("s3_upload_failed", [$uploadForm, content])
enable_submit()
formData: (form) ->
inputs = form.find($uploadForm).children('input')
inputs.each -> $(this).prop('disabled', false)
data = inputs.serializeArray()
inputs = form.find($uploadForm).children("input:not([name='file'])")
inputs.each -> $(this).prop('disabled', true)
fileType = ""
if "type" of @files[0]
fileType = @files[0].type
data.push
name: "content-type"
value: fileType
# Remove anything we can't submit to S3
for item in data
data.splice(data.indexOf(data), 1) unless item.name in settings.valid_s3_keys
# Ask our server for a unique ID for this Asset
asset = create_asset(@files[0])
@files[0].asset_id = asset.id
key = asset.s3_key
# substitute upload timestamp and unique_id into key
key_field = $.grep data, (n) ->
n if n.name == "key"
if key_field.length > 0
key_field[0].value = key
# IE <= 9 doesn't have XHR2 hence it can't use formData
# replace 'key' field to submit form
unless 'FormData' of window
$uploadForm.find("input[name='key']").val(key)
data
build_content_object = ($uploadForm, file, result) ->
content = {}
if result # Use the S3 response to set the URL to avoid character encodings bugs
content.url = $(result).find("Location").text()
content.filepath = $('<a />').attr('href', content.url)[0].pathname
else # IE <= 9 return a null result object so we use the file object instead
domain = settings.url
content.filepath = $uploadForm.find('input[name=key]').val().replace('/${filename}', '')
content.url = domain + content.filepath + '/' + encodeURIComponent(file.name)
content.url = s3urlDecode(content.url)
content.filepath = s3urlDecode(content.filepath)
content.filename = file.name
content.filesize = file.size if 'size' of file
content.lastModified = file.lastModified if 'lastModified' of file
content.filetype = file.type if 'type' of file
content.asset_id = file.asset_id if 'asset_id' of file
content.relativePath = build_relativePath(file) if has_relativePath(file)
content
has_relativePath = (file) ->
file.relativePath || file.webkitRelativePath
build_relativePath = (file) ->
file.relativePath || (file.webkitRelativePath.split("/")[0..-2].join("/") + "/" if file.webkitRelativePath)
s3urlDecode = (url) -> url.replace(/%2F/g, "/").replace(/\+/g, '%20')
extra_fields_for_asset = ->
# Any field in our form that shares our name like effective_asset[#{box}][something2] should be gotten
# And we return something2 => something2.value
box = $uploadForm.closest('.asset-box-input').data('box')
fields = $uploadForm.closest('form').find(":input[name*='[#{box}]']").serializeArray()
extra = {}
$.each fields, (i, field) ->
pieces = field.name.split('[').map (piece) -> piece.replace(']', '')
if (index_of_box = pieces.indexOf(box)) == -1
name = pieces.join()
else
name = pieces.slice(index_of_box+1, pieces.length).join()
extra[name] = field.value if name.length > 0
extra
create_asset = (file) ->
asset = 'false'
$.ajax
url: settings.create_asset_url
type: 'POST'
dataType: 'json'
data:
title: file.name
content_type: file.type
data_size: file.size
extra: extra_fields_for_asset()
async: false
success: (data) -> asset = data
asset
update_asset_and_load_attachment = (file) ->
asset_box = $uploadForm.closest('.asset-box-input')
$.ajax
url: settings.update_asset_url.replace(':id', file.asset_id)
type: 'PUT'
data:
upload_file: file.url
data_size: file.filesize
content_type: file.filetype
title: file.filename
attachable_type: asset_box.data('attachable-type')
attachable_id: asset_box.data('attachable-id')
attachable_object_name: asset_box.data('attachable-object-name')
attachment_style: asset_box.data('attachment-style')
attachment_actions: asset_box.data('attachment-actions')
attachment_links: asset_box.data('attachment-links')
aws_acl: asset_box.data('aws-acl')
box: asset_box.data('box')
async: true
success: (data) ->
limit = asset_box.data('limit')
direction = asset_box.data('attachment-add-to') # bottom or top. bottom is default append behaviour
if limit == 10000 && direction != 'top' # Guard value for no limit. There is no limit
asset_box.find('.attachments').append($(data))
else
asset_box.find('.attachments').prepend($(data))
asset_box.find("input.asset-box-remove").each (index) ->
if "#{$(this).val()}" == '1' # If we're going to delete it...
$(this).closest('.attachment').hide()
limit = limit + 1
return
if index >= limit
$(this).closest('.attachment').hide()
else
$(this).closest('.attachment').show()
click_submit() if settings.click_submit
disable_submit = ->
$uploadForm.data('effective-assets-uploading', true)
$uploadForm.closest('form').find('input[type=submit]').each ->
submit = $(this)
submit.data('effective-assets-original-label', submit.val()) if submit.data('effective-assets-original-label') == undefined
submit.prop('disabled', true)
submit.val('Uploading...')
enable_submit = ->
$uploadForm.data('effective-assets-uploading', false)
anyUploading = false
$uploadForm.closest('form').find('.asset-box-uploader').each ->
anyUploading = true if $(this).data('effective-assets-uploading') == true
unless anyUploading
$uploadForm.closest('form').find('input[type=submit]').each ->
submit = $(this)
submit.val(submit.data('effective-assets-original-label') || 'Submit')
submit.prop('disabled', false)
submit.removeData('effective-assets-original-label')
return !anyUploading # Returns true if we submitted it
click_submit = -> $uploadForm.closest('form').submit()
format_bitrate = (bits) ->
if typeof bits != 'number'
''
else if (bits >= 1000000000)
(bits / 1000000000).toFixed(2) + ' Gbit/s'
else if (bits >= 1000000)
(bits / 1000000).toFixed(2) + ' Mbit/s'
else if (bits >= 1000)
(bits / 1000).toFixed(2) + ' kbit/s'
else
bits.toFixed(2) + ' bit/s'
resetOverLimitAlert = (event) ->
$assetBox = $(event.target).closest('.asset-box-input')
$assetBox.data('over-limit-alerted', false)
#public methods
@initialize = ->
# Save key for IE9 Fix
$uploadForm.data('key', $uploadForm.find("input[name='key']").val())
$uploadForm.data('fileCount', 0)
$(document).on 'drop', '#' + $uploadForm.attr('id'), (event) ->
resetOverLimitAlert(event)
true
$(document).on 'click', "##{$uploadForm.attr('id')} .asset-box-uploader-fileinput", (event) ->
resetOverLimitAlert(event)
event.stopPropagation()
setUploadForm()
this
@initialize()
| true | $ = jQuery
$.fn.S3Uploader = (options) ->
# support multiple elements
if @length > 1
@each -> $(this).S3Uploader options
return this
$uploadForm = this # the .asset-box-uploader div .asset-box-input > [.attachments, .uploads, .asset-box-uploader]
settings =
url: ''
remove_completed_progress_bar: true
remove_failed_progress_bar: true
progress_bar_target: null
progress_bar_template: null
allow_multiple_files: true
valid_s3_keys: ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'policy', 'signature', 'success_action_status', 'X-Requested-With', 'content-type']
create_asset_url: null
update_asset_url: null
file_types: 'any'
click_submit: false
$.extend settings, options
current_files = []
setUploadForm = ->
$uploadForm.fileupload
url: settings.url
add: (e, data) ->
# Ensure correct $uploadForm is being used
$uploadForms = $('.asset-box-uploader')
return false if $uploadForms.index($uploadForm) == -1
$uploadForms.find("input[type='file']").removeAttr('required')
# Make sure the user isn't over the upload limit
$asset_box = $uploadForm.closest('.asset-box-input')
limit = $asset_box.data('limit')
if typeof limit == 'number' && limit > 1
count = parseInt($asset_box.attr('data-attachment-count'), 10)
if count >= limit
alert("Unable to add file(s). You have exceeded the limit of #{limit} uploads.") unless $asset_box.data('over-limit-alerted')
$asset_box.data('over-limit-alerted', true)
return false
else
$asset_box.attr('data-attachment-count', count + 1)
# Add the file to the upload
file = data.files[0]
# Check File Type
if settings.file_types != 'any'
types = new RegExp("(\.|\/)(#{settings.file_types})$")
unless types.test(file.type) || types.test(file.name.toLowerCase()) || file.name.toLowerCase().indexOf('._test') > 0
alert("Unable to add #{file.name}.\n\nOnly #{settings.file_types.replace(/\|/g, ', ')} files allowed.")
return false
if file.name.length > 180
alert("Unable to add #{file.name}.\n\nFile name too long. File name must be 180 or fewer characters long.")
return false
# We're all good. Let's go ahead and add this
current_files.push data
$uploadForm.trigger("s3_file_added", [e, file])
template = settings.progress_bar_template
data.context = $($.trim(tmpl(template.html(), file)))
$(data.context).appendTo(settings.progress_bar_target)
data.submit()
start: (e) ->
$uploadForm.trigger("s3_uploads_start", [e])
disable_submit()
progress: (e, data) ->
if data.context
progress = parseInt(data.loaded / data.total * 100, 10)
data.context.find('.bar').css('width', progress + '%').html(format_bitrate(data.bitrate))
data.context.find('.progress > span').remove()
done: (e, data) ->
content = build_content_object($uploadForm, data.files[0], data.result)
if settings.update_asset_url
update_asset_and_load_attachment(content)
data.context.fadeOut('slow', -> $(this).remove()) if data.context && settings.remove_completed_progress_bar # remove progress bar
$uploadForm.trigger("s3_upload_complete", [$uploadForm, content])
current_files.splice($.inArray(data, current_files), 1) # remove that element from the array
unless current_files.length
$uploadForm.trigger("s3_uploads_complete", [$uploadForm, content])
enable_submit()
fail: (e, data) ->
content = build_content_object($uploadForm, data.files[0], data.result)
content.error_thrown = data.errorThrown
data.context.fadeOut('slow', -> $(this).remove()) if data.context && settings.remove_failed_progress_bar # remove progress bar
$uploadForm.trigger("s3_upload_failed", [$uploadForm, content])
enable_submit()
formData: (form) ->
inputs = form.find($uploadForm).children('input')
inputs.each -> $(this).prop('disabled', false)
data = inputs.serializeArray()
inputs = form.find($uploadForm).children("input:not([name='file'])")
inputs.each -> $(this).prop('disabled', true)
fileType = ""
if "type" of @files[0]
fileType = @files[0].type
data.push
name: "content-type"
value: fileType
# Remove anything we can't submit to S3
for item in data
data.splice(data.indexOf(data), 1) unless item.name in settings.valid_s3_keys
# Ask our server for a unique ID for this Asset
asset = create_asset(@files[0])
@files[0].asset_id = asset.id
key = asset.s3_key
# substitute upload timestamp and unique_id into key
key_field = $.grep data, (n) ->
n if n.name == "key"
if key_field.length > 0
key_field[0].value = key
# IE <= 9 doesn't have XHR2 hence it can't use formData
# replace 'key' field to submit form
unless 'FormData' of window
$uploadForm.find("input[name='key']").val(key)
data
build_content_object = ($uploadForm, file, result) ->
content = {}
if result # Use the S3 response to set the URL to avoid character encodings bugs
content.url = $(result).find("Location").text()
content.filepath = $('<a />').attr('href', content.url)[0].pathname
else # IE <= 9 return a null result object so we use the file object instead
domain = settings.url
content.filepath = $uploadForm.find('input[name=key]').val().replace('/${filename}', '')
content.url = domain + content.filepath + '/' + encodeURIComponent(file.name)
content.url = s3urlDecode(content.url)
content.filepath = s3urlDecode(content.filepath)
content.filename = file.name
content.filesize = file.size if 'size' of file
content.lastModified = file.lastModified if 'lastModified' of file
content.filetype = file.type if 'type' of file
content.asset_id = file.asset_id if 'asset_id' of file
content.relativePath = build_relativePath(file) if has_relativePath(file)
content
has_relativePath = (file) ->
file.relativePath || file.webkitRelativePath
build_relativePath = (file) ->
file.relativePath || (file.webkitRelativePath.split("/")[0..-2].join("/") + "/" if file.webkitRelativePath)
s3urlDecode = (url) -> url.replace(/%2F/g, "/").replace(/\+/g, '%20')
extra_fields_for_asset = ->
# Any field in our form that shares our name like effective_asset[#{box}][something2] should be gotten
# And we return something2 => something2.value
box = $uploadForm.closest('.asset-box-input').data('box')
fields = $uploadForm.closest('form').find(":input[name*='[#{box}]']").serializeArray()
extra = {}
$.each fields, (i, field) ->
pieces = field.name.split('[').map (piece) -> piece.replace(']', '')
if (index_of_box = pieces.indexOf(box)) == -1
name = pieces.join()
else
name = pieces.slice(index_of_box+1, pieces.length).join()
extra[name] = field.value if name.length > 0
extra
create_asset = (file) ->
asset = 'false'
$.ajax
url: settings.create_asset_url
type: 'POST'
dataType: 'json'
data:
title: file.name
content_type: file.type
data_size: file.size
extra: extra_fields_for_asset()
async: false
success: (data) -> asset = data
asset
update_asset_and_load_attachment = (file) ->
asset_box = $uploadForm.closest('.asset-box-input')
$.ajax
url: settings.update_asset_url.replace(':id', file.asset_id)
type: 'PUT'
data:
upload_file: file.url
data_size: file.filesize
content_type: file.filetype
title: file.filename
attachable_type: asset_box.data('attachable-type')
attachable_id: asset_box.data('attachable-id')
attachable_object_name: asset_box.data('attachable-object-name')
attachment_style: asset_box.data('attachment-style')
attachment_actions: asset_box.data('attachment-actions')
attachment_links: asset_box.data('attachment-links')
aws_acl: asset_box.data('aws-acl')
box: asset_box.data('box')
async: true
success: (data) ->
limit = asset_box.data('limit')
direction = asset_box.data('attachment-add-to') # bottom or top. bottom is default append behaviour
if limit == 10000 && direction != 'top' # Guard value for no limit. There is no limit
asset_box.find('.attachments').append($(data))
else
asset_box.find('.attachments').prepend($(data))
asset_box.find("input.asset-box-remove").each (index) ->
if "#{$(this).val()}" == '1' # If we're going to delete it...
$(this).closest('.attachment').hide()
limit = limit + 1
return
if index >= limit
$(this).closest('.attachment').hide()
else
$(this).closest('.attachment').show()
click_submit() if settings.click_submit
disable_submit = ->
$uploadForm.data('effective-assets-uploading', true)
$uploadForm.closest('form').find('input[type=submit]').each ->
submit = $(this)
submit.data('effective-assets-original-label', submit.val()) if submit.data('effective-assets-original-label') == undefined
submit.prop('disabled', true)
submit.val('Uploading...')
enable_submit = ->
$uploadForm.data('effective-assets-uploading', false)
anyUploading = false
$uploadForm.closest('form').find('.asset-box-uploader').each ->
anyUploading = true if $(this).data('effective-assets-uploading') == true
unless anyUploading
$uploadForm.closest('form').find('input[type=submit]').each ->
submit = $(this)
submit.val(submit.data('effective-assets-original-label') || 'Submit')
submit.prop('disabled', false)
submit.removeData('effective-assets-original-label')
return !anyUploading # Returns true if we submitted it
click_submit = -> $uploadForm.closest('form').submit()
format_bitrate = (bits) ->
if typeof bits != 'number'
''
else if (bits >= 1000000000)
(bits / 1000000000).toFixed(2) + ' Gbit/s'
else if (bits >= 1000000)
(bits / 1000000).toFixed(2) + ' Mbit/s'
else if (bits >= 1000)
(bits / 1000).toFixed(2) + ' kbit/s'
else
bits.toFixed(2) + ' bit/s'
resetOverLimitAlert = (event) ->
$assetBox = $(event.target).closest('.asset-box-input')
$assetBox.data('over-limit-alerted', false)
#public methods
@initialize = ->
# Save key for IE9 Fix
$uploadForm.data('key', $uploadForm.find("input[name='key']").val())
$uploadForm.data('fileCount', 0)
$(document).on 'drop', '#' + $uploadForm.attr('id'), (event) ->
resetOverLimitAlert(event)
true
$(document).on 'click', "##{$uploadForm.attr('id')} .asset-box-uploader-fileinput", (event) ->
resetOverLimitAlert(event)
event.stopPropagation()
setUploadForm()
this
@initialize()
|
[
{
"context": "verview Test file for require-jsdoc rule\n# @author Gyandeep Singh\n###\n'use strict'\n\nrule = require '../../rules/req",
"end": 78,
"score": 0.9998089671134949,
"start": 64,
"tag": "NAME",
"value": "Gyandeep Singh"
}
] | src/tests/rules/require-jsdoc.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Test file for require-jsdoc rule
# @author Gyandeep Singh
###
'use strict'
rule = require '../../rules/require-jsdoc'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'require-jsdoc', rule,
valid: [
'''
array = [1,2,3]
array.forEach ->
'''
'''
###*
@class MyClass
###
MyClass = ->
'''
'''
###*
Function doing something
###
myFunction = ->
'''
'''
###*
Function doing something
###
myFunction = ->
'''
'''
###*
Function doing something
###
Object.myFunction = ->
'''
'''
obj =
###*
# Function doing something
###
myFunction: ->
'''
'''
###*
# @func myFunction
###
myFunction = ->
'''
'''
###*
# @method myFunction
###
myFunction = ->
'''
'''
###*
# @function myFunction
###
myFunction = ->
'''
'''
###*
@func myFunction
###
myFunction = ->
'''
'''
###*
# @method myFunction
###
myFunction = ->
'''
'''
###*
# @function myFunction
###
myFunction = ->
'''
'''
###*
# @func myFunction
###
Object.myFunction = ->
'''
'''
###*
# @method myFunction
###
Object.myFunction = ->
'''
'''
###*
# @function myFunction
###
Object.myFunction = ->
'''
'do ->'
'''
object =
###*
@func myFunction - Some function
###
myFunction: ->
'''
'''
object = {
###*
@method myFunction - Some function
###
myFunction: ->
}
'''
'''
object =
###*
@function myFunction - Some function
###
myFunction: ->
'''
'''
array = [1,2,3]
array.filter ->
'''
'''
Object.keys(@options.rules ? {}).forEach ((name) ->).bind @
'''
'''
object = { name: 'key'}
Object.keys(object).forEach ->
'''
,
code: '''
myFunction = ->
'''
options: [
require:
FunctionExpression: no
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
@a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
class App extends Component
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
export default class App extends Component
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
export class App extends Component
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
class A
constructor: (xs) ->
this.a = xs
'''
options: [
require:
MethodDefinition: no
ClassDeclaration: no
]
,
code: '''
###*
# Function doing something
###
myFunction = () => {}
'''
options: [
require:
FunctionExpression: yes
]
,
code: '''
###*
Function doing something
###
myFunction = () => () => {}
'''
options: [
require:
FunctionExpression: yes
]
,
code: 'setTimeout((() => {}), 10)'
options: [
require:
FunctionExpression: yes
]
,
code: '''
###*
JSDoc Block
###
foo = ->
'''
options: [
require:
FunctionExpression: yes
]
,
code: '''
foo =
###*
JSDoc Block
###
bar: ->
'''
options: [
require:
FunctionExpression: yes
]
,
code: '''
foo = {
###*
JSDoc Block
###
bar: ->
}
'''
options: [
require:
FunctionExpression: yes
]
,
code: ' foo = { [(->)]: 1 }'
options: [
require:
FunctionExpression: yes
]
]
invalid: [
code: '''
###*
* Description for A.
###
class A
constructor: (@a) ->
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'FunctionExpression'
]
,
code: '''
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
@a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: '''
class A extends B
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: '''
export class A extends B
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: '''
export default class A extends B
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: 'myFunction = () => {}'
options: [
require:
ArrowFunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ArrowFunctionExpression'
]
,
code: 'myFunction = () => () => {}'
options: [
require:
ArrowFunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ArrowFunctionExpression'
]
,
code: 'foo = ->'
options: [
require:
FunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'FunctionExpression'
]
,
code: 'foo = bar: ->'
options: [
require:
FunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'FunctionExpression'
]
]
| 226102 | ###*
# @fileoverview Test file for require-jsdoc rule
# @author <NAME>
###
'use strict'
rule = require '../../rules/require-jsdoc'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'require-jsdoc', rule,
valid: [
'''
array = [1,2,3]
array.forEach ->
'''
'''
###*
@class MyClass
###
MyClass = ->
'''
'''
###*
Function doing something
###
myFunction = ->
'''
'''
###*
Function doing something
###
myFunction = ->
'''
'''
###*
Function doing something
###
Object.myFunction = ->
'''
'''
obj =
###*
# Function doing something
###
myFunction: ->
'''
'''
###*
# @func myFunction
###
myFunction = ->
'''
'''
###*
# @method myFunction
###
myFunction = ->
'''
'''
###*
# @function myFunction
###
myFunction = ->
'''
'''
###*
@func myFunction
###
myFunction = ->
'''
'''
###*
# @method myFunction
###
myFunction = ->
'''
'''
###*
# @function myFunction
###
myFunction = ->
'''
'''
###*
# @func myFunction
###
Object.myFunction = ->
'''
'''
###*
# @method myFunction
###
Object.myFunction = ->
'''
'''
###*
# @function myFunction
###
Object.myFunction = ->
'''
'do ->'
'''
object =
###*
@func myFunction - Some function
###
myFunction: ->
'''
'''
object = {
###*
@method myFunction - Some function
###
myFunction: ->
}
'''
'''
object =
###*
@function myFunction - Some function
###
myFunction: ->
'''
'''
array = [1,2,3]
array.filter ->
'''
'''
Object.keys(@options.rules ? {}).forEach ((name) ->).bind @
'''
'''
object = { name: 'key'}
Object.keys(object).forEach ->
'''
,
code: '''
myFunction = ->
'''
options: [
require:
FunctionExpression: no
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
@a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
class App extends Component
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
export default class App extends Component
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
export class App extends Component
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
class A
constructor: (xs) ->
this.a = xs
'''
options: [
require:
MethodDefinition: no
ClassDeclaration: no
]
,
code: '''
###*
# Function doing something
###
myFunction = () => {}
'''
options: [
require:
FunctionExpression: yes
]
,
code: '''
###*
Function doing something
###
myFunction = () => () => {}
'''
options: [
require:
FunctionExpression: yes
]
,
code: 'setTimeout((() => {}), 10)'
options: [
require:
FunctionExpression: yes
]
,
code: '''
###*
JSDoc Block
###
foo = ->
'''
options: [
require:
FunctionExpression: yes
]
,
code: '''
foo =
###*
JSDoc Block
###
bar: ->
'''
options: [
require:
FunctionExpression: yes
]
,
code: '''
foo = {
###*
JSDoc Block
###
bar: ->
}
'''
options: [
require:
FunctionExpression: yes
]
,
code: ' foo = { [(->)]: 1 }'
options: [
require:
FunctionExpression: yes
]
]
invalid: [
code: '''
###*
* Description for A.
###
class A
constructor: (@a) ->
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'FunctionExpression'
]
,
code: '''
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
@a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: '''
class A extends B
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: '''
export class A extends B
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: '''
export default class A extends B
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: 'myFunction = () => {}'
options: [
require:
ArrowFunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ArrowFunctionExpression'
]
,
code: 'myFunction = () => () => {}'
options: [
require:
ArrowFunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ArrowFunctionExpression'
]
,
code: 'foo = ->'
options: [
require:
FunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'FunctionExpression'
]
,
code: 'foo = bar: ->'
options: [
require:
FunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'FunctionExpression'
]
]
| true | ###*
# @fileoverview Test file for require-jsdoc rule
# @author PI:NAME:<NAME>END_PI
###
'use strict'
rule = require '../../rules/require-jsdoc'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'require-jsdoc', rule,
valid: [
'''
array = [1,2,3]
array.forEach ->
'''
'''
###*
@class MyClass
###
MyClass = ->
'''
'''
###*
Function doing something
###
myFunction = ->
'''
'''
###*
Function doing something
###
myFunction = ->
'''
'''
###*
Function doing something
###
Object.myFunction = ->
'''
'''
obj =
###*
# Function doing something
###
myFunction: ->
'''
'''
###*
# @func myFunction
###
myFunction = ->
'''
'''
###*
# @method myFunction
###
myFunction = ->
'''
'''
###*
# @function myFunction
###
myFunction = ->
'''
'''
###*
@func myFunction
###
myFunction = ->
'''
'''
###*
# @method myFunction
###
myFunction = ->
'''
'''
###*
# @function myFunction
###
myFunction = ->
'''
'''
###*
# @func myFunction
###
Object.myFunction = ->
'''
'''
###*
# @method myFunction
###
Object.myFunction = ->
'''
'''
###*
# @function myFunction
###
Object.myFunction = ->
'''
'do ->'
'''
object =
###*
@func myFunction - Some function
###
myFunction: ->
'''
'''
object = {
###*
@method myFunction - Some function
###
myFunction: ->
}
'''
'''
object =
###*
@function myFunction - Some function
###
myFunction: ->
'''
'''
array = [1,2,3]
array.filter ->
'''
'''
Object.keys(@options.rules ? {}).forEach ((name) ->).bind @
'''
'''
object = { name: 'key'}
Object.keys(object).forEach ->
'''
,
code: '''
myFunction = ->
'''
options: [
require:
FunctionExpression: no
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
@a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
class App extends Component
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
export default class App extends Component
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
###*
* Description for A.
###
export class App extends Component
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
,
code: '''
class A
constructor: (xs) ->
this.a = xs
'''
options: [
require:
MethodDefinition: no
ClassDeclaration: no
]
,
code: '''
###*
# Function doing something
###
myFunction = () => {}
'''
options: [
require:
FunctionExpression: yes
]
,
code: '''
###*
Function doing something
###
myFunction = () => () => {}
'''
options: [
require:
FunctionExpression: yes
]
,
code: 'setTimeout((() => {}), 10)'
options: [
require:
FunctionExpression: yes
]
,
code: '''
###*
JSDoc Block
###
foo = ->
'''
options: [
require:
FunctionExpression: yes
]
,
code: '''
foo =
###*
JSDoc Block
###
bar: ->
'''
options: [
require:
FunctionExpression: yes
]
,
code: '''
foo = {
###*
JSDoc Block
###
bar: ->
}
'''
options: [
require:
FunctionExpression: yes
]
,
code: ' foo = { [(->)]: 1 }'
options: [
require:
FunctionExpression: yes
]
]
invalid: [
code: '''
###*
* Description for A.
###
class A
constructor: (@a) ->
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'FunctionExpression'
]
,
code: '''
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
@a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: '''
class A extends B
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: '''
export class A extends B
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: '''
export default class A extends B
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
super()
this.a = xs
'''
options: [
require:
MethodDefinition: yes
ClassDeclaration: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ClassDeclaration'
]
,
code: 'myFunction = () => {}'
options: [
require:
ArrowFunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ArrowFunctionExpression'
]
,
code: 'myFunction = () => () => {}'
options: [
require:
ArrowFunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'ArrowFunctionExpression'
]
,
code: 'foo = ->'
options: [
require:
FunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'FunctionExpression'
]
,
code: 'foo = bar: ->'
options: [
require:
FunctionExpression: yes
]
errors: [
message: 'Missing JSDoc comment.'
type: 'FunctionExpression'
]
]
|
[
{
"context": "types[type] = +QR.cooldown.types[type]\n key = \"cooldown.#{g.BOARD}\"\n $.get key, {}, (item) ->\n QR.cooldown.co",
"end": 425,
"score": 0.9931957721710205,
"start": 405,
"tag": "KEY",
"value": "cooldown.#{g.BOARD}\""
}
] | src/Posting/QR.cooldown.coffee | ccd0/4chan-x-mayhem | 2 | QR.cooldown =
init: ->
return unless Conf['Cooldown']
setTimers = (e) => QR.cooldown.types = e.detail
$.on window, 'cooldown:timers', setTimers
$.globalEval 'window.dispatchEvent(new CustomEvent("cooldown:timers", {detail: cooldowns}))'
$.off window, 'cooldown:timers', setTimers
for type of QR.cooldown.types
QR.cooldown.types[type] = +QR.cooldown.types[type]
key = "cooldown.#{g.BOARD}"
$.get key, {}, (item) ->
QR.cooldown.cooldowns = item[key]
QR.cooldown.start()
$.sync key, QR.cooldown.sync
start: ->
return if QR.cooldown.isCounting or !Object.keys(QR.cooldown.cooldowns).length
QR.cooldown.isCounting = true
QR.cooldown.count()
sync: (cooldowns) ->
# Add each cooldowns, don't overwrite everything in case we
# still need to prune one in the current tab to auto-post.
for id of cooldowns
QR.cooldown.cooldowns[id] = cooldowns[id]
QR.cooldown.start()
set: (data) ->
return unless Conf['Cooldown']
{req, post, isReply, threadID, delay} = data
start = if req then req.uploadEndTime else Date.now()
if delay
cooldown = {delay}
else
cooldown = {isReply, threadID}
QR.cooldown.cooldowns[start] = cooldown
$.set "cooldown.#{g.BOARD}", QR.cooldown.cooldowns
QR.cooldown.start()
unset: (id) ->
delete QR.cooldown.cooldowns[id]
if Object.keys(QR.cooldown.cooldowns).length
$.set "cooldown.#{g.BOARD}", QR.cooldown.cooldowns
else
$.delete "cooldown.#{g.BOARD}"
count: ->
unless Object.keys(QR.cooldown.cooldowns).length
$.delete "cooldown.#{g.BOARD}"
delete QR.cooldown.isCounting
delete QR.cooldown.seconds
QR.status()
return
clearTimeout QR.cooldown.timeout
QR.cooldown.timeout = setTimeout QR.cooldown.count, $.SECOND
now = Date.now()
post = QR.posts[0]
isReply = post.thread isnt 'new'
hasFile = !!post.file
seconds = null
{types, cooldowns} = QR.cooldown
for start, cooldown of cooldowns
start = +start
if 'delay' of cooldown
if cooldown.delay
seconds = Math.max seconds, cooldown.delay--
else
seconds = Math.max seconds, 0
QR.cooldown.unset start
continue
if isReply is cooldown.isReply
# Only cooldowns relevant to this post can set the seconds variable:
# reply cooldown with a reply, thread cooldown with a thread
elapsed = (now - start) // $.SECOND
if elapsed < 0 # clock changed since then?
QR.cooldown.unset start
continue
type = unless isReply
'thread'
else if hasFile
'image'
else
'reply'
maxTimer = Math.max types[type] or 0, types[type + '_intra'] or 0
unless start <= now <= start + maxTimer * $.SECOND
QR.cooldown.unset start
type += '_intra' if isReply and +post.thread is cooldown.threadID
seconds = Math.max seconds, types[type] - elapsed
# Update the status when we change posting type.
# Don't get stuck at some random number.
# Don't interfere with progress status updates.
update = seconds isnt null or !!QR.cooldown.seconds
QR.cooldown.seconds = seconds
QR.status() if update
QR.submit() if seconds is 0 and QR.cooldown.auto and !QR.req
| 69054 | QR.cooldown =
init: ->
return unless Conf['Cooldown']
setTimers = (e) => QR.cooldown.types = e.detail
$.on window, 'cooldown:timers', setTimers
$.globalEval 'window.dispatchEvent(new CustomEvent("cooldown:timers", {detail: cooldowns}))'
$.off window, 'cooldown:timers', setTimers
for type of QR.cooldown.types
QR.cooldown.types[type] = +QR.cooldown.types[type]
key = "<KEY>
$.get key, {}, (item) ->
QR.cooldown.cooldowns = item[key]
QR.cooldown.start()
$.sync key, QR.cooldown.sync
start: ->
return if QR.cooldown.isCounting or !Object.keys(QR.cooldown.cooldowns).length
QR.cooldown.isCounting = true
QR.cooldown.count()
sync: (cooldowns) ->
# Add each cooldowns, don't overwrite everything in case we
# still need to prune one in the current tab to auto-post.
for id of cooldowns
QR.cooldown.cooldowns[id] = cooldowns[id]
QR.cooldown.start()
set: (data) ->
return unless Conf['Cooldown']
{req, post, isReply, threadID, delay} = data
start = if req then req.uploadEndTime else Date.now()
if delay
cooldown = {delay}
else
cooldown = {isReply, threadID}
QR.cooldown.cooldowns[start] = cooldown
$.set "cooldown.#{g.BOARD}", QR.cooldown.cooldowns
QR.cooldown.start()
unset: (id) ->
delete QR.cooldown.cooldowns[id]
if Object.keys(QR.cooldown.cooldowns).length
$.set "cooldown.#{g.BOARD}", QR.cooldown.cooldowns
else
$.delete "cooldown.#{g.BOARD}"
count: ->
unless Object.keys(QR.cooldown.cooldowns).length
$.delete "cooldown.#{g.BOARD}"
delete QR.cooldown.isCounting
delete QR.cooldown.seconds
QR.status()
return
clearTimeout QR.cooldown.timeout
QR.cooldown.timeout = setTimeout QR.cooldown.count, $.SECOND
now = Date.now()
post = QR.posts[0]
isReply = post.thread isnt 'new'
hasFile = !!post.file
seconds = null
{types, cooldowns} = QR.cooldown
for start, cooldown of cooldowns
start = +start
if 'delay' of cooldown
if cooldown.delay
seconds = Math.max seconds, cooldown.delay--
else
seconds = Math.max seconds, 0
QR.cooldown.unset start
continue
if isReply is cooldown.isReply
# Only cooldowns relevant to this post can set the seconds variable:
# reply cooldown with a reply, thread cooldown with a thread
elapsed = (now - start) // $.SECOND
if elapsed < 0 # clock changed since then?
QR.cooldown.unset start
continue
type = unless isReply
'thread'
else if hasFile
'image'
else
'reply'
maxTimer = Math.max types[type] or 0, types[type + '_intra'] or 0
unless start <= now <= start + maxTimer * $.SECOND
QR.cooldown.unset start
type += '_intra' if isReply and +post.thread is cooldown.threadID
seconds = Math.max seconds, types[type] - elapsed
# Update the status when we change posting type.
# Don't get stuck at some random number.
# Don't interfere with progress status updates.
update = seconds isnt null or !!QR.cooldown.seconds
QR.cooldown.seconds = seconds
QR.status() if update
QR.submit() if seconds is 0 and QR.cooldown.auto and !QR.req
| true | QR.cooldown =
init: ->
return unless Conf['Cooldown']
setTimers = (e) => QR.cooldown.types = e.detail
$.on window, 'cooldown:timers', setTimers
$.globalEval 'window.dispatchEvent(new CustomEvent("cooldown:timers", {detail: cooldowns}))'
$.off window, 'cooldown:timers', setTimers
for type of QR.cooldown.types
QR.cooldown.types[type] = +QR.cooldown.types[type]
key = "PI:KEY:<KEY>END_PI
$.get key, {}, (item) ->
QR.cooldown.cooldowns = item[key]
QR.cooldown.start()
$.sync key, QR.cooldown.sync
start: ->
return if QR.cooldown.isCounting or !Object.keys(QR.cooldown.cooldowns).length
QR.cooldown.isCounting = true
QR.cooldown.count()
sync: (cooldowns) ->
# Add each cooldowns, don't overwrite everything in case we
# still need to prune one in the current tab to auto-post.
for id of cooldowns
QR.cooldown.cooldowns[id] = cooldowns[id]
QR.cooldown.start()
set: (data) ->
return unless Conf['Cooldown']
{req, post, isReply, threadID, delay} = data
start = if req then req.uploadEndTime else Date.now()
if delay
cooldown = {delay}
else
cooldown = {isReply, threadID}
QR.cooldown.cooldowns[start] = cooldown
$.set "cooldown.#{g.BOARD}", QR.cooldown.cooldowns
QR.cooldown.start()
unset: (id) ->
delete QR.cooldown.cooldowns[id]
if Object.keys(QR.cooldown.cooldowns).length
$.set "cooldown.#{g.BOARD}", QR.cooldown.cooldowns
else
$.delete "cooldown.#{g.BOARD}"
count: ->
unless Object.keys(QR.cooldown.cooldowns).length
$.delete "cooldown.#{g.BOARD}"
delete QR.cooldown.isCounting
delete QR.cooldown.seconds
QR.status()
return
clearTimeout QR.cooldown.timeout
QR.cooldown.timeout = setTimeout QR.cooldown.count, $.SECOND
now = Date.now()
post = QR.posts[0]
isReply = post.thread isnt 'new'
hasFile = !!post.file
seconds = null
{types, cooldowns} = QR.cooldown
for start, cooldown of cooldowns
start = +start
if 'delay' of cooldown
if cooldown.delay
seconds = Math.max seconds, cooldown.delay--
else
seconds = Math.max seconds, 0
QR.cooldown.unset start
continue
if isReply is cooldown.isReply
# Only cooldowns relevant to this post can set the seconds variable:
# reply cooldown with a reply, thread cooldown with a thread
elapsed = (now - start) // $.SECOND
if elapsed < 0 # clock changed since then?
QR.cooldown.unset start
continue
type = unless isReply
'thread'
else if hasFile
'image'
else
'reply'
maxTimer = Math.max types[type] or 0, types[type + '_intra'] or 0
unless start <= now <= start + maxTimer * $.SECOND
QR.cooldown.unset start
type += '_intra' if isReply and +post.thread is cooldown.threadID
seconds = Math.max seconds, types[type] - elapsed
# Update the status when we change posting type.
# Don't get stuck at some random number.
# Don't interfere with progress status updates.
update = seconds isnt null or !!QR.cooldown.seconds
QR.cooldown.seconds = seconds
QR.status() if update
QR.submit() if seconds is 0 and QR.cooldown.auto and !QR.req
|
[
{
"context": ", t) ->\n e.preventDefault()\n username = $('#j-username').val()\n password = $('#j-password').val()\n ",
"end": 611,
"score": 0.8995707035064697,
"start": 601,
"tag": "USERNAME",
"value": "j-username"
},
{
"context": " username = $('#j-username').val()\n ... | client/layouts/hackathonlayout/hackathonHome.coffee | ijayoa/hackifi | 0 | Template.hackathonHome.rendered = () ->
# $('.navbar').css('margin-bottom',0)
thisHackathon = Session.get 'thisHackathon'
if Sponsors.find({owner:thisHackathon.owner}).count() == 0
$('.sponsors').addClass 'hide'
if Judges.find({owner:thisHackathon.owner}).count() == 0
$('.judges').addClass 'hide'
if Mentors.find({owner:thisHackathon.owner}).count() == 0
$('.mentors').addClass 'hide'
Template.hackathonHome.events
'click #judge-login': (e, t) ->
$('.judge-login-div').toggle()
return
'submit #judge-login-form': (e, t) ->
e.preventDefault()
username = $('#j-username').val()
password = $('#j-password').val()
hackathonUrl = Router.current().params._id
hackathonId = Hackathons.findOne({personalizedUrl: hackathonUrl})._id
if isNotEmpty(username) and isNotEmpty(password) and isValidLogin(username, password, hackathonUrl)
judge = Judges.findOne(
hackathon: hackathonId
username: username
password: password)
judgeId = judge._id
Session.setAuth("AuthJudge", judgeId)
'click .auth-sign-out': (e, t) ->
Session.clearAuth()
if Session.get('AuthJudge')
location.reload()
isNotEmpty = (value) ->
if value and value != ''
return true
console.log 'Please fill in all required fields.'
false
isValidLogin = (username, password, hackathonUrl) ->
hackathonId = Hackathons.findOne({personalizedUrl: hackathonUrl})._id
if Judges.findOne(
hackathon: hackathonId
username: username
password: password)
return true
return
Template.hackathonHome.helpers
url: ->
hd = Session.get 'thisHackathon'
photoId = hd.coverPhoto
img = Attachments.findOne(_id: photoId)
url = img.url()
| 65398 | Template.hackathonHome.rendered = () ->
# $('.navbar').css('margin-bottom',0)
thisHackathon = Session.get 'thisHackathon'
if Sponsors.find({owner:thisHackathon.owner}).count() == 0
$('.sponsors').addClass 'hide'
if Judges.find({owner:thisHackathon.owner}).count() == 0
$('.judges').addClass 'hide'
if Mentors.find({owner:thisHackathon.owner}).count() == 0
$('.mentors').addClass 'hide'
Template.hackathonHome.events
'click #judge-login': (e, t) ->
$('.judge-login-div').toggle()
return
'submit #judge-login-form': (e, t) ->
e.preventDefault()
username = $('#j-username').val()
password = <PASSWORD>').<PASSWORD>()
hackathonUrl = Router.current().params._id
hackathonId = Hackathons.findOne({personalizedUrl: hackathonUrl})._id
if isNotEmpty(username) and isNotEmpty(password) and isValidLogin(username, password, hackathonUrl)
judge = Judges.findOne(
hackathon: hackathonId
username: username
password: <PASSWORD>)
judgeId = judge._id
Session.setAuth("AuthJudge", judgeId)
'click .auth-sign-out': (e, t) ->
Session.clearAuth()
if Session.get('AuthJudge')
location.reload()
isNotEmpty = (value) ->
if value and value != ''
return true
console.log 'Please fill in all required fields.'
false
isValidLogin = (username, password, hackathonUrl) ->
hackathonId = Hackathons.findOne({personalizedUrl: hackathonUrl})._id
if Judges.findOne(
hackathon: hackathonId
username: username
password: <PASSWORD>)
return true
return
Template.hackathonHome.helpers
url: ->
hd = Session.get 'thisHackathon'
photoId = hd.coverPhoto
img = Attachments.findOne(_id: photoId)
url = img.url()
| true | Template.hackathonHome.rendered = () ->
# $('.navbar').css('margin-bottom',0)
thisHackathon = Session.get 'thisHackathon'
if Sponsors.find({owner:thisHackathon.owner}).count() == 0
$('.sponsors').addClass 'hide'
if Judges.find({owner:thisHackathon.owner}).count() == 0
$('.judges').addClass 'hide'
if Mentors.find({owner:thisHackathon.owner}).count() == 0
$('.mentors').addClass 'hide'
Template.hackathonHome.events
'click #judge-login': (e, t) ->
$('.judge-login-div').toggle()
return
'submit #judge-login-form': (e, t) ->
e.preventDefault()
username = $('#j-username').val()
password = PI:PASSWORD:<PASSWORD>END_PI').PI:PASSWORD:<PASSWORD>END_PI()
hackathonUrl = Router.current().params._id
hackathonId = Hackathons.findOne({personalizedUrl: hackathonUrl})._id
if isNotEmpty(username) and isNotEmpty(password) and isValidLogin(username, password, hackathonUrl)
judge = Judges.findOne(
hackathon: hackathonId
username: username
password: PI:PASSWORD:<PASSWORD>END_PI)
judgeId = judge._id
Session.setAuth("AuthJudge", judgeId)
'click .auth-sign-out': (e, t) ->
Session.clearAuth()
if Session.get('AuthJudge')
location.reload()
isNotEmpty = (value) ->
if value and value != ''
return true
console.log 'Please fill in all required fields.'
false
isValidLogin = (username, password, hackathonUrl) ->
hackathonId = Hackathons.findOne({personalizedUrl: hackathonUrl})._id
if Judges.findOne(
hackathon: hackathonId
username: username
password: PI:PASSWORD:<PASSWORD>END_PI)
return true
return
Template.hackathonHome.helpers
url: ->
hd = Session.get 'thisHackathon'
photoId = hd.coverPhoto
img = Attachments.findOne(_id: photoId)
url = img.url()
|
[
{
"context": "###\n @author Takahiro INOUE <takahiro.inoue@aist.go.jp>\n @license Songle Wid",
"end": 28,
"score": 0.9998704791069031,
"start": 14,
"tag": "NAME",
"value": "Takahiro INOUE"
},
{
"context": "###\n @author Takahiro INOUE <takahiro.inoue@aist.go.jp>\n @license Songle... | extras/src/sw-extra-stats.coffee | ongacrest/songle-widget-api-examples | 16 | ###
@author Takahiro INOUE <takahiro.inoue@aist.go.jp>
@license Songle Widget API Examples
Visit http://songle.jp/info/Credit.html OR http://widget.songle.jp/docs/v1 for documentation.
Copyright (c) 2015 National Institute of Advanced Industrial Science and Technology (AIST)
Distributed under the terms of the MIT license only for non-commercial purposes.
http://www.opensource.org/licenses/mit-license.html
This notice shall be included in all copies or substantial portions of this Songle Widget API Examples.
If you are interested in commercial use of Songle Widget API, please contact "songle-ml@aist.go.jp".
###
__swExtra__.initializeAllModule
onCreate:
(songleWidget) ->
setTimeout ->
rootElement = document.createElement("div")
rootElement.className = "sw-extra-stats"
rootElement.style.position = "fixed"
rootElement.style.color = "rgb(64, 64, 64)"
rootElement.style.fontFamily = "'consolas', 'Courier New', 'Courier', 'Monaco', 'monospace'"
rootElement.style.fontSize = 11.5 + "px"
rootElement.style.left = 10 + "px"
rootElement.style.bottom = 10 + "px"
rootElement.appendChild(
createStatElement "playing-time", "Playing time",
(rootElement) ->
childElement = document.createElement("span")
childElement.className = "position"
childElement.textContent = "00:00"
rootElement.appendChild(childElement)
childElement = document.createElement("span")
childElement.textContent = "/"
rootElement.appendChild(childElement)
childElement = document.createElement("span")
childElement.className = "duration"
childElement.textContent = "00:00"
rootElement.appendChild(childElement)
)
rootElement.appendChild(
createStatElement "beat", "Beat",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "chord", "Chord",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "note", "Note",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "chorus", "Chorus segment",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "repeat", "Repeat segment",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
document.body.appendChild(rootElement)
, 0 # [ms]
###
@function
@private
###
createStatElement =
(className, statTitle, onCreate) ->
rootElement = document.createElement("div")
childElement = document.createElement("div")
childElement.appendChild(document.createTextNode(statTitle))
childElement.style.padding = "0px 4px"
childElement.style.borderLeft = "2px solid #e17"
rootElement.appendChild(childElement)
childElement = document.createElement("div")
childElement.className = className
childElement.style.padding = "0px 4px"
childElement.style.borderLeft = "0px solid #e17"
rootElement.appendChild(childElement)
onCreate &&
onCreate(childElement)
return rootElement
onReady:
(songleWidget) ->
songleWidget.on "beatPlay",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .beat")
switch(e.beat.position)
when 1
rootElement.textContent = "x - - - (bpm:" + Math.floor(e.beat.bpm) + ")"
when 2
rootElement.textContent = "- x - - (bpm:" + Math.floor(e.beat.bpm) + ")"
when 3
rootElement.textContent = "- - x - (bpm:" + Math.floor(e.beat.bpm) + ")"
when 4
rootElement.textContent = "- - - x (bpm:" + Math.floor(e.beat.bpm) + ")"
songleWidget.on "chordEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .chord")
rootElement.textContent = e.chord.name
songleWidget.on "noteEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .note")
rootElement.textContent = "#{ e.note.pitch } Hz"
songleWidget.on "chorusSegmentEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .chorus")
rootElement.textContent = "o"
songleWidget.on "chorusSegmentLeave",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .chorus")
rootElement.textContent = "-"
songleWidget.on "repeatSegmentEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .repeat")
rootElement.textContent = "o"
songleWidget.on "repeatSegmentLeave",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .repeat")
rootElement.textContent = "-"
songleWidget.on "playingProgress",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .playing-time")
childElementElement = rootElement.querySelector(".duration")
childElementElement.textContent = createPlayingTimeText(songleWidget.duration)
songleWidget.on "playingProgress",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .playing-time")
childElementElement = rootElement.querySelector(".position")
childElementElement.textContent = createPlayingTimeText(songleWidget.position)
###
@function
@private
###
createPlayingTimeText =
(songleWidgetPlayingTime) ->
minutes = "00" + Math.floor(songleWidgetPlayingTime.minutes) % 60
seconds = "00" + Math.floor(songleWidgetPlayingTime.seconds) % 60
return minutes.substr(minutes.length - 2) + ":" + seconds.substr(seconds.length - 2)
| 197571 | ###
@author <NAME> <<EMAIL>>
@license Songle Widget API Examples
Visit http://songle.jp/info/Credit.html OR http://widget.songle.jp/docs/v1 for documentation.
Copyright (c) 2015 National Institute of Advanced Industrial Science and Technology (AIST)
Distributed under the terms of the MIT license only for non-commercial purposes.
http://www.opensource.org/licenses/mit-license.html
This notice shall be included in all copies or substantial portions of this Songle Widget API Examples.
If you are interested in commercial use of Songle Widget API, please contact "<EMAIL>".
###
__swExtra__.initializeAllModule
onCreate:
(songleWidget) ->
setTimeout ->
rootElement = document.createElement("div")
rootElement.className = "sw-extra-stats"
rootElement.style.position = "fixed"
rootElement.style.color = "rgb(64, 64, 64)"
rootElement.style.fontFamily = "'consolas', 'Courier New', 'Courier', 'Monaco', 'monospace'"
rootElement.style.fontSize = 11.5 + "px"
rootElement.style.left = 10 + "px"
rootElement.style.bottom = 10 + "px"
rootElement.appendChild(
createStatElement "playing-time", "Playing time",
(rootElement) ->
childElement = document.createElement("span")
childElement.className = "position"
childElement.textContent = "00:00"
rootElement.appendChild(childElement)
childElement = document.createElement("span")
childElement.textContent = "/"
rootElement.appendChild(childElement)
childElement = document.createElement("span")
childElement.className = "duration"
childElement.textContent = "00:00"
rootElement.appendChild(childElement)
)
rootElement.appendChild(
createStatElement "beat", "Beat",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "chord", "Chord",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "note", "Note",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "chorus", "Chorus segment",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "repeat", "Repeat segment",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
document.body.appendChild(rootElement)
, 0 # [ms]
###
@function
@private
###
createStatElement =
(className, statTitle, onCreate) ->
rootElement = document.createElement("div")
childElement = document.createElement("div")
childElement.appendChild(document.createTextNode(statTitle))
childElement.style.padding = "0px 4px"
childElement.style.borderLeft = "2px solid #e17"
rootElement.appendChild(childElement)
childElement = document.createElement("div")
childElement.className = className
childElement.style.padding = "0px 4px"
childElement.style.borderLeft = "0px solid #e17"
rootElement.appendChild(childElement)
onCreate &&
onCreate(childElement)
return rootElement
onReady:
(songleWidget) ->
songleWidget.on "beatPlay",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .beat")
switch(e.beat.position)
when 1
rootElement.textContent = "x - - - (bpm:" + Math.floor(e.beat.bpm) + ")"
when 2
rootElement.textContent = "- x - - (bpm:" + Math.floor(e.beat.bpm) + ")"
when 3
rootElement.textContent = "- - x - (bpm:" + Math.floor(e.beat.bpm) + ")"
when 4
rootElement.textContent = "- - - x (bpm:" + Math.floor(e.beat.bpm) + ")"
songleWidget.on "chordEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .chord")
rootElement.textContent = e.chord.name
songleWidget.on "noteEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .note")
rootElement.textContent = "#{ e.note.pitch } Hz"
songleWidget.on "chorusSegmentEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .chorus")
rootElement.textContent = "o"
songleWidget.on "chorusSegmentLeave",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .chorus")
rootElement.textContent = "-"
songleWidget.on "repeatSegmentEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .repeat")
rootElement.textContent = "o"
songleWidget.on "repeatSegmentLeave",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .repeat")
rootElement.textContent = "-"
songleWidget.on "playingProgress",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .playing-time")
childElementElement = rootElement.querySelector(".duration")
childElementElement.textContent = createPlayingTimeText(songleWidget.duration)
songleWidget.on "playingProgress",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .playing-time")
childElementElement = rootElement.querySelector(".position")
childElementElement.textContent = createPlayingTimeText(songleWidget.position)
###
@function
@private
###
createPlayingTimeText =
(songleWidgetPlayingTime) ->
minutes = "00" + Math.floor(songleWidgetPlayingTime.minutes) % 60
seconds = "00" + Math.floor(songleWidgetPlayingTime.seconds) % 60
return minutes.substr(minutes.length - 2) + ":" + seconds.substr(seconds.length - 2)
| true | ###
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
@license Songle Widget API Examples
Visit http://songle.jp/info/Credit.html OR http://widget.songle.jp/docs/v1 for documentation.
Copyright (c) 2015 National Institute of Advanced Industrial Science and Technology (AIST)
Distributed under the terms of the MIT license only for non-commercial purposes.
http://www.opensource.org/licenses/mit-license.html
This notice shall be included in all copies or substantial portions of this Songle Widget API Examples.
If you are interested in commercial use of Songle Widget API, please contact "PI:EMAIL:<EMAIL>END_PI".
###
__swExtra__.initializeAllModule
onCreate:
(songleWidget) ->
setTimeout ->
rootElement = document.createElement("div")
rootElement.className = "sw-extra-stats"
rootElement.style.position = "fixed"
rootElement.style.color = "rgb(64, 64, 64)"
rootElement.style.fontFamily = "'consolas', 'Courier New', 'Courier', 'Monaco', 'monospace'"
rootElement.style.fontSize = 11.5 + "px"
rootElement.style.left = 10 + "px"
rootElement.style.bottom = 10 + "px"
rootElement.appendChild(
createStatElement "playing-time", "Playing time",
(rootElement) ->
childElement = document.createElement("span")
childElement.className = "position"
childElement.textContent = "00:00"
rootElement.appendChild(childElement)
childElement = document.createElement("span")
childElement.textContent = "/"
rootElement.appendChild(childElement)
childElement = document.createElement("span")
childElement.className = "duration"
childElement.textContent = "00:00"
rootElement.appendChild(childElement)
)
rootElement.appendChild(
createStatElement "beat", "Beat",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "chord", "Chord",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "note", "Note",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "chorus", "Chorus segment",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
rootElement.appendChild(
createStatElement "repeat", "Repeat segment",
(rootElement) ->
rootElement.appendChild(document.createTextNode("-"))
)
document.body.appendChild(rootElement)
, 0 # [ms]
###
@function
@private
###
createStatElement =
(className, statTitle, onCreate) ->
rootElement = document.createElement("div")
childElement = document.createElement("div")
childElement.appendChild(document.createTextNode(statTitle))
childElement.style.padding = "0px 4px"
childElement.style.borderLeft = "2px solid #e17"
rootElement.appendChild(childElement)
childElement = document.createElement("div")
childElement.className = className
childElement.style.padding = "0px 4px"
childElement.style.borderLeft = "0px solid #e17"
rootElement.appendChild(childElement)
onCreate &&
onCreate(childElement)
return rootElement
onReady:
(songleWidget) ->
songleWidget.on "beatPlay",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .beat")
switch(e.beat.position)
when 1
rootElement.textContent = "x - - - (bpm:" + Math.floor(e.beat.bpm) + ")"
when 2
rootElement.textContent = "- x - - (bpm:" + Math.floor(e.beat.bpm) + ")"
when 3
rootElement.textContent = "- - x - (bpm:" + Math.floor(e.beat.bpm) + ")"
when 4
rootElement.textContent = "- - - x (bpm:" + Math.floor(e.beat.bpm) + ")"
songleWidget.on "chordEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .chord")
rootElement.textContent = e.chord.name
songleWidget.on "noteEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .note")
rootElement.textContent = "#{ e.note.pitch } Hz"
songleWidget.on "chorusSegmentEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .chorus")
rootElement.textContent = "o"
songleWidget.on "chorusSegmentLeave",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .chorus")
rootElement.textContent = "-"
songleWidget.on "repeatSegmentEnter",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .repeat")
rootElement.textContent = "o"
songleWidget.on "repeatSegmentLeave",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .repeat")
rootElement.textContent = "-"
songleWidget.on "playingProgress",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .playing-time")
childElementElement = rootElement.querySelector(".duration")
childElementElement.textContent = createPlayingTimeText(songleWidget.duration)
songleWidget.on "playingProgress",
(e) ->
rootElement = document.querySelector(".sw-extra-stats .playing-time")
childElementElement = rootElement.querySelector(".position")
childElementElement.textContent = createPlayingTimeText(songleWidget.position)
###
@function
@private
###
createPlayingTimeText =
(songleWidgetPlayingTime) ->
minutes = "00" + Math.floor(songleWidgetPlayingTime.minutes) % 60
seconds = "00" + Math.floor(songleWidgetPlayingTime.seconds) % 60
return minutes.substr(minutes.length - 2) + ":" + seconds.substr(seconds.length - 2)
|
[
{
"context": " user', (done) ->\n body = []\n body.login = 'hokayem@gmail.com'\n body.password = '12345678'\n console.log(b",
"end": 166,
"score": 0.9998981356620789,
"start": 149,
"tag": "EMAIL",
"value": "hokayem@gmail.com"
},
{
"context": ".login = 'hokayem@gmail.com'\... | tests/users.coffee | jerem824/project-node-2017 | 0 | should = require 'should'
user = require '../src/users.coffee'
describe 'users', () ->
it 'saves user', (done) ->
body = []
body.login = 'hokayem@gmail.com'
body.password = '12345678'
console.log(body)
user.save body, (err) ->
should.not.exist err
done()
| 201837 | should = require 'should'
user = require '../src/users.coffee'
describe 'users', () ->
it 'saves user', (done) ->
body = []
body.login = '<EMAIL>'
body.password = '<PASSWORD>'
console.log(body)
user.save body, (err) ->
should.not.exist err
done()
| true | should = require 'should'
user = require '../src/users.coffee'
describe 'users', () ->
it 'saves user', (done) ->
body = []
body.login = 'PI:EMAIL:<EMAIL>END_PI'
body.password = 'PI:PASSWORD:<PASSWORD>END_PI'
console.log(body)
user.save body, (err) ->
should.not.exist err
done()
|
[
{
"context": "utils.js\nuid = (len = 6, prefix = \"\", keyspace = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\") ->\n prefix += keyspace.charAt(Math.floor(Math.",
"end": 257,
"score": 0.9995321035385132,
"start": 195,
"tag": "KEY",
"value": "ABCDEFGHIJKLMNOPQRSTUVWXYZab... | lib/plunker/stores/memory.coffee | ggoodman/stsh | 5 | fs = require("fs")
util = require("util")
Cromag = require("cromag")
Backbone = require("backbone")
_ = require("underscore")._
# From connect/utils.js
uid = (len = 6, prefix = "", keyspace = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
delay = (timeout, callback) -> setTimeout(callback, timeout)
class Collection extends Backbone.Collection
comparator: (model) -> -new Cromag(model.get("updated_at") or model.get("created_at")).valueOf()
class Store
constructor: (options = {}) ->
self = @
@options = _.defaults options,
filename: "/tmp/plunker.json"
size: 1000
interval: 1000 * 20
backup: true
@filename = @options.filename
@frequency = @options.interval
@plunks = new Collection
@timeouts = {}
@plunks.on "reset", (coll) -> coll.each(self.setExpiry)
@plunks.on "add", self.setExpiry
@plunks.on "remove", self.clearExpiry
@plunks.on "reset add", ->
# Defer to next tick or something around then
delay 1, ->
while self.plunks.length > self.options.size
self.plunks.remove self.plunks.at(self.plunks.length - 1)
@plunks.on "change:updated_at", ->
self.plunks.sort(silent: true)
if @options.backup
@plunks.on "add remove", _.throttle(@backup, @options.interval)
@restore()
backup: =>
self = @
fs.writeFile @filename, JSON.stringify(@plunks.toJSON()), (err) ->
if err then console.log "Backup failed to: #{self.filename}"
else console.log "Backup completed to: #{self.filename}"
restore: =>
self = @
console.log "Attempting to archive previous state"
util.pump fs.createReadStream(@filename), fs.createWriteStream(@filename + (new Date).valueOf())
console.log "Attempting to restore data from: #{@filename}"
fs.readFile @filename, "utf8", (err, data) ->
if err then console.log "Failed to restore data: #{self.filename} *Note: On your first run of `node server.js` this is expected (you have not stored any data yet)."
else
try
plunks = JSON.parse(data)
plunks = _.map plunks, (json) ->
if matches = json.html_url.match(/^(http:\/\/[^\/]+)(.+)$/)
json.raw_url = "#{matches[1]}/raw#{matches[2]}"
json.edit_url = "#{matches[1]}/edit#{matches[2]}"
for filename, file of json.files
file.raw_url = json.raw_url + filename
json
self.plunks.reset(plunks) and console.log "Restore succeeded from: #{self.filename}"
self.plunks.sort(silent: true)
catch error
console.log "Error parsing #{self.filename}: #{error}"
shrink: =>
if @plunks.length > @options.size
@plunks.remove @plunks.at(@plunks.length - 1)
setExpiry: (model) =>
self = @
if model.get("expires")
@timeouts[model.id] = delay Cromag.parse(model.get("expires")) - Cromag.now(), ->
self.plunks.remove(model)
@
clearExpiry: (model) =>
clearTimeout(@timeouts[model.id]) if model.id and model.get("expires")
@
list: (start, end, cb) ->
filtered = _.filter(@plunks.toJSON(), (plunk) -> !plunk.expires)
cb null, filtered.slice(start, end),
count: filtered.length
reserveId: (cb) -> cb null, uid(6) # OH GOD THE CHILDREN
create: (json, cb) -> cb null, @plunks.add(json).get(json.id).toJSON()
fetch: (id, cb) ->
if plunk = @plunks.get(id) then cb null, plunk.toJSON()
else cb()
update: (plunk, json, cb) ->
if plunk = @plunks.get(plunk.id) then cb null, plunk.set(json).toJSON()
else cb(message: "No such plunk")
remove: (id, cb) -> cb null, @plunks.remove(id)
store = null
exports.createStore = (config) ->
store ||= new Store(config)
| 8481 | fs = require("fs")
util = require("util")
Cromag = require("cromag")
Backbone = require("backbone")
_ = require("underscore")._
# From connect/utils.js
uid = (len = 6, prefix = "", keyspace = "<KEY>") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
delay = (timeout, callback) -> setTimeout(callback, timeout)
class Collection extends Backbone.Collection
comparator: (model) -> -new Cromag(model.get("updated_at") or model.get("created_at")).valueOf()
class Store
constructor: (options = {}) ->
self = @
@options = _.defaults options,
filename: "/tmp/plunker.json"
size: 1000
interval: 1000 * 20
backup: true
@filename = @options.filename
@frequency = @options.interval
@plunks = new Collection
@timeouts = {}
@plunks.on "reset", (coll) -> coll.each(self.setExpiry)
@plunks.on "add", self.setExpiry
@plunks.on "remove", self.clearExpiry
@plunks.on "reset add", ->
# Defer to next tick or something around then
delay 1, ->
while self.plunks.length > self.options.size
self.plunks.remove self.plunks.at(self.plunks.length - 1)
@plunks.on "change:updated_at", ->
self.plunks.sort(silent: true)
if @options.backup
@plunks.on "add remove", _.throttle(@backup, @options.interval)
@restore()
backup: =>
self = @
fs.writeFile @filename, JSON.stringify(@plunks.toJSON()), (err) ->
if err then console.log "Backup failed to: #{self.filename}"
else console.log "Backup completed to: #{self.filename}"
restore: =>
self = @
console.log "Attempting to archive previous state"
util.pump fs.createReadStream(@filename), fs.createWriteStream(@filename + (new Date).valueOf())
console.log "Attempting to restore data from: #{@filename}"
fs.readFile @filename, "utf8", (err, data) ->
if err then console.log "Failed to restore data: #{self.filename} *Note: On your first run of `node server.js` this is expected (you have not stored any data yet)."
else
try
plunks = JSON.parse(data)
plunks = _.map plunks, (json) ->
if matches = json.html_url.match(/^(http:\/\/[^\/]+)(.+)$/)
json.raw_url = "#{matches[1]}/raw#{matches[2]}"
json.edit_url = "#{matches[1]}/edit#{matches[2]}"
for filename, file of json.files
file.raw_url = json.raw_url + filename
json
self.plunks.reset(plunks) and console.log "Restore succeeded from: #{self.filename}"
self.plunks.sort(silent: true)
catch error
console.log "Error parsing #{self.filename}: #{error}"
shrink: =>
if @plunks.length > @options.size
@plunks.remove @plunks.at(@plunks.length - 1)
setExpiry: (model) =>
self = @
if model.get("expires")
@timeouts[model.id] = delay Cromag.parse(model.get("expires")) - Cromag.now(), ->
self.plunks.remove(model)
@
clearExpiry: (model) =>
clearTimeout(@timeouts[model.id]) if model.id and model.get("expires")
@
list: (start, end, cb) ->
filtered = _.filter(@plunks.toJSON(), (plunk) -> !plunk.expires)
cb null, filtered.slice(start, end),
count: filtered.length
reserveId: (cb) -> cb null, uid(6) # OH GOD THE CHILDREN
create: (json, cb) -> cb null, @plunks.add(json).get(json.id).toJSON()
fetch: (id, cb) ->
if plunk = @plunks.get(id) then cb null, plunk.toJSON()
else cb()
update: (plunk, json, cb) ->
if plunk = @plunks.get(plunk.id) then cb null, plunk.set(json).toJSON()
else cb(message: "No such plunk")
remove: (id, cb) -> cb null, @plunks.remove(id)
store = null
exports.createStore = (config) ->
store ||= new Store(config)
| true | fs = require("fs")
util = require("util")
Cromag = require("cromag")
Backbone = require("backbone")
_ = require("underscore")._
# From connect/utils.js
uid = (len = 6, prefix = "", keyspace = "PI:KEY:<KEY>END_PI") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
delay = (timeout, callback) -> setTimeout(callback, timeout)
class Collection extends Backbone.Collection
comparator: (model) -> -new Cromag(model.get("updated_at") or model.get("created_at")).valueOf()
class Store
constructor: (options = {}) ->
self = @
@options = _.defaults options,
filename: "/tmp/plunker.json"
size: 1000
interval: 1000 * 20
backup: true
@filename = @options.filename
@frequency = @options.interval
@plunks = new Collection
@timeouts = {}
@plunks.on "reset", (coll) -> coll.each(self.setExpiry)
@plunks.on "add", self.setExpiry
@plunks.on "remove", self.clearExpiry
@plunks.on "reset add", ->
# Defer to next tick or something around then
delay 1, ->
while self.plunks.length > self.options.size
self.plunks.remove self.plunks.at(self.plunks.length - 1)
@plunks.on "change:updated_at", ->
self.plunks.sort(silent: true)
if @options.backup
@plunks.on "add remove", _.throttle(@backup, @options.interval)
@restore()
backup: =>
self = @
fs.writeFile @filename, JSON.stringify(@plunks.toJSON()), (err) ->
if err then console.log "Backup failed to: #{self.filename}"
else console.log "Backup completed to: #{self.filename}"
restore: =>
self = @
console.log "Attempting to archive previous state"
util.pump fs.createReadStream(@filename), fs.createWriteStream(@filename + (new Date).valueOf())
console.log "Attempting to restore data from: #{@filename}"
fs.readFile @filename, "utf8", (err, data) ->
if err then console.log "Failed to restore data: #{self.filename} *Note: On your first run of `node server.js` this is expected (you have not stored any data yet)."
else
try
plunks = JSON.parse(data)
plunks = _.map plunks, (json) ->
if matches = json.html_url.match(/^(http:\/\/[^\/]+)(.+)$/)
json.raw_url = "#{matches[1]}/raw#{matches[2]}"
json.edit_url = "#{matches[1]}/edit#{matches[2]}"
for filename, file of json.files
file.raw_url = json.raw_url + filename
json
self.plunks.reset(plunks) and console.log "Restore succeeded from: #{self.filename}"
self.plunks.sort(silent: true)
catch error
console.log "Error parsing #{self.filename}: #{error}"
shrink: =>
if @plunks.length > @options.size
@plunks.remove @plunks.at(@plunks.length - 1)
setExpiry: (model) =>
self = @
if model.get("expires")
@timeouts[model.id] = delay Cromag.parse(model.get("expires")) - Cromag.now(), ->
self.plunks.remove(model)
@
clearExpiry: (model) =>
clearTimeout(@timeouts[model.id]) if model.id and model.get("expires")
@
list: (start, end, cb) ->
filtered = _.filter(@plunks.toJSON(), (plunk) -> !plunk.expires)
cb null, filtered.slice(start, end),
count: filtered.length
reserveId: (cb) -> cb null, uid(6) # OH GOD THE CHILDREN
create: (json, cb) -> cb null, @plunks.add(json).get(json.id).toJSON()
fetch: (id, cb) ->
if plunk = @plunks.get(id) then cb null, plunk.toJSON()
else cb()
update: (plunk, json, cb) ->
if plunk = @plunks.get(plunk.id) then cb null, plunk.set(json).toJSON()
else cb(message: "No such plunk")
remove: (id, cb) -> cb null, @plunks.remove(id)
store = null
exports.createStore = (config) ->
store ||= new Store(config)
|
[
{
"context": " - list gists or get a single gist\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\nmodule.exports = (robot) ->\n r",
"end": 263,
"score": 0.9997286200523376,
"start": 256,
"tag": "USERNAME",
"value": "bouzuya"
},
{
"context": "sts or get a single gist\n#\n# Author:\n# ... | src/scripts/gist.coffee | bouzuya/hubot-gist | 1 | # Description
# A Hubot script that list gists or get a single gist
#
# Dependencies:
# "hubot-arm": "^0.2.1",
# "hubot-request-arm": "^0.2.1"
#
# Configuration:
# None
#
# Commands:
# hubot gist - list gists or get a single gist
#
# Author:
# bouzuya <m@bouzuya.net>
#
module.exports = (robot) ->
require('hubot-arm') robot
rpad = (s, l) ->
while s.length < l
s += ' '
s
format = (body) ->
if Array.isArray(body)
gists = body
filtered = gists.filter (item, i) -> i < 10
width = filtered.reduce ((w, i) -> Math.max(i.html_url.length, w)), 0
message = filtered.map (g) ->
rpad(g.html_url, width) + ' ' + g.description
.join '\n'
else
gist = body
key = Object.keys(gist.files)[0]
gist.files[key].content
robot.respond /gist\s+(\S+)(?:\s+(\S+))?\s*$/i, (res) ->
user = res.match[1]
id = res.match[2]
url = if id?
match = id.match /^https:\/\/gist.github.com\/(.+)$/
id = if match? then match[1] else id
"https://api.github.com/gists/#{id}"
else
"https://api.github.com/users/#{user}/gists"
res.robot.arm('request')
method: 'GET'
url: url
json: true
headers:
'User-Agent': 'hubot-gist'
.then (r) ->
res.send format(r.body)
| 201665 | # Description
# A Hubot script that list gists or get a single gist
#
# Dependencies:
# "hubot-arm": "^0.2.1",
# "hubot-request-arm": "^0.2.1"
#
# Configuration:
# None
#
# Commands:
# hubot gist - list gists or get a single gist
#
# Author:
# bouzuya <<EMAIL>>
#
module.exports = (robot) ->
require('hubot-arm') robot
rpad = (s, l) ->
while s.length < l
s += ' '
s
format = (body) ->
if Array.isArray(body)
gists = body
filtered = gists.filter (item, i) -> i < 10
width = filtered.reduce ((w, i) -> Math.max(i.html_url.length, w)), 0
message = filtered.map (g) ->
rpad(g.html_url, width) + ' ' + g.description
.join '\n'
else
gist = body
key = Object.keys(gist.files)[0]
gist.files[key].content
robot.respond /gist\s+(\S+)(?:\s+(\S+))?\s*$/i, (res) ->
user = res.match[1]
id = res.match[2]
url = if id?
match = id.match /^https:\/\/gist.github.com\/(.+)$/
id = if match? then match[1] else id
"https://api.github.com/gists/#{id}"
else
"https://api.github.com/users/#{user}/gists"
res.robot.arm('request')
method: 'GET'
url: url
json: true
headers:
'User-Agent': 'hubot-gist'
.then (r) ->
res.send format(r.body)
| true | # Description
# A Hubot script that list gists or get a single gist
#
# Dependencies:
# "hubot-arm": "^0.2.1",
# "hubot-request-arm": "^0.2.1"
#
# Configuration:
# None
#
# Commands:
# hubot gist - list gists or get a single gist
#
# Author:
# bouzuya <PI:EMAIL:<EMAIL>END_PI>
#
module.exports = (robot) ->
require('hubot-arm') robot
rpad = (s, l) ->
while s.length < l
s += ' '
s
format = (body) ->
if Array.isArray(body)
gists = body
filtered = gists.filter (item, i) -> i < 10
width = filtered.reduce ((w, i) -> Math.max(i.html_url.length, w)), 0
message = filtered.map (g) ->
rpad(g.html_url, width) + ' ' + g.description
.join '\n'
else
gist = body
key = Object.keys(gist.files)[0]
gist.files[key].content
robot.respond /gist\s+(\S+)(?:\s+(\S+))?\s*$/i, (res) ->
user = res.match[1]
id = res.match[2]
url = if id?
match = id.match /^https:\/\/gist.github.com\/(.+)$/
id = if match? then match[1] else id
"https://api.github.com/gists/#{id}"
else
"https://api.github.com/users/#{user}/gists"
res.robot.arm('request')
method: 'GET'
url: url
json: true
headers:
'User-Agent': 'hubot-gist'
.then (r) ->
res.send format(r.body)
|
[
{
"context": "========================================\n# Author: Esteve Lladó (Fundació Bit), 2017\n# Modified by: Elena Aguado ",
"end": 66,
"score": 0.9998787045478821,
"start": 54,
"tag": "NAME",
"value": "Esteve Lladó"
},
{
"context": ": Esteve Lladó (Fundació Bit), 2017\n# Modi... | source/coffee/reports.coffee | Fundacio-Bit/twitter-intranet | 0 | # =========================================
# Author: Esteve Lladó (Fundació Bit), 2017
# Modified by: Elena Aguado and Óscar Moya
# =========================================
refreshIntervalId = 0
g_dictionary_categories = ['esdeveniments', 'esports', 'toponims', 'platges', 'patrimoni', 'naturalesa']
g_brands = []
# Function to extract the brands from the REST API and render the results
# ------------------------------------------------------------------------
getBrands = () ->
brand_list = []
request = "/rest_utils/brands"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Check if the REST API returned an error
# ----------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
data.results.forEach (brand) ->
brand_list.push(brand)
return brand_list
g_brands = getBrands()
g_tweet_counts = {} # it will save tweet count series globally for each yearmonth
g_language_counts = {} # it will save language count globally for each yearmonth
g_zip_status = {} # it will save the zip status for each yearmonth
(($) ->
# ---------------------------------------------------------
# Function to fix EVENTS over the reports items in the list
# ---------------------------------------------------------
setEventsOnReportsList = (source) ->
# ----------------------------------------------------
# EVENT: Button to open the modal 'Tweets escrutats'
# ----------------------------------------------------
$('a.openTweetsEscrutats').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
# Download CSV
# -------------------------------------------
$('#tweetsEscrutatsCSVPanel').html MyApp.templates.tweetsEscrutatsCSVLoad {yearmonth: yearmonth}
# Generate array fo day numbers to write the series X Axis
# ---------------------------------------------------------
year = yearmonth.split("-")[0]
month = yearmonth.split("-")[1]
last_day_in_month = new Date(year, month, 0).getDate()
month_day_numbers = Array.from(Array(last_day_in_month + 1).keys()).slice(1)
# Extract the series data per brand
# ----------------------------------
brand_colors =
mallorca:
borderColor: "rgba(255,255,0, 0.8)"
backgroundColor: "rgba(255,255,0,0)"
menorca:
borderColor: "rgba(0,128,0, 0.8)"
backgroundColor: "rgba(0,128,0,0)"
ibiza:
borderColor: "rgba(255,0,0,0.8)"
backgroundColor: "rgba(255,0,0,0)"
formentera:
borderColor: "rgba(0,0,255,0.8)"
backgroundColor: "rgba(0,0,255,0)"
series = []
g_brands.forEach (brand) ->
series.push {
label: brand,
borderColor: brand_colors[brand].borderColor,
backgroundColor: brand_colors[brand].backgroundColor,
borderWidth: 2,
tension: 0,
radius: 0,
data: g_tweet_counts[yearmonth].series[brand]}
ctx = document.getElementById('reportTweetCountsChart').getContext('2d')
seriesChart = new Chart(ctx,{
type: 'line'
data:
labels: month_day_numbers
datasets : series
options:
responsive: true
title:
display: true
text: "Sèries temporals de tweet counts"
tooltips:
mode: 'x'
intersect: true
hover:
mode: 'nearest'
intersect: true
scales:
xAxes: [{
display: true
gridLines:
display: false
scaleLabel:
display: true
labelString: 'Data'
}]
yAxes: [{
display: true
gridLines:
display: false
scaleLabel:
display: true
labelString: 'Freqüència'
}]
})
$('#reportTweetCountsChart').show()
# Render the tweet counts table
# -------------------------------
tweet_counts_table = '<table width="100%" class="table table-striped table-condensed"><tr><td><b>marca</b></td><td><b>total</b></td><td><b>variació</b></td></tr>'
g_brands.forEach (brand) ->
tweet_counts_table += "<tr><td>#{brand}</td><td>#{g_tweet_counts[yearmonth].total[brand]}</td><td>#{g_tweet_counts[yearmonth].variation[brand]}</td></tr>"
tweet_counts_table += '</table>'
$("#reportTweetCountsTable").html tweet_counts_table
# Fix title, current month and show modal
# ----------------------------------------
$('#reportTweetsEscrutatsTitle').html "Edició de tweets escrutats de <strong>#{source.toUpperCase()}</strong> de <strong>#{yearmonth}</strong>"
$('#reportTweetsEscrutatsStatusPanel').html ''
$('#reportTweetsEscrutatsModal').modal 'show' # show the modal
# Include link to jump to the end of the page
# ---------------------------------------------
$('.bottomLink').unbind().click ->
$('#reportTweetsEscrutatsModal').animate
scrollTop: 10000
return false
# -----------------------------------------
# EVENT: Button to open the modal 'Idiomes'
# -----------------------------------------
$('a.openIdiomes').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
# Download CSV
# -------------------------------------------
$('#idiomesCSVPanel').html MyApp.templates.idiomesCSVLoad {yearmonth: yearmonth}
# Draw the language counts table
# -------------------------------
languages = ['es', 'ca', 'en', 'de', 'other', 'total']
language_counts_table = '<table width="100%" class="table table-striped table-condensed">'
language_counts_table += '<tr><td><b>idioma</b></td>'
g_brands.forEach (brand) -> language_counts_table += "<td><b>#{brand}</b></td>"
language_counts_table += '<td><b>Total</b></td><td><b>%Total</b></td>'
language_counts_table += '</tr>'
languages.forEach (lang) ->
language_counts_table += "<tr><td>#{lang}</td>"
g_brands.forEach (brand) ->
language_counts_table += "<td>#{g_language_counts[yearmonth][brand][lang]}</td>"
language_counts_table += "<td>#{g_language_counts[yearmonth].per_lang[lang].count}</td>"
language_counts_table += "<td>#{g_language_counts[yearmonth].per_lang[lang].percent}</td>"
language_counts_table += "</tr>"
language_counts_table += '</table>'
$("#reportNotesLanguageCountsTable").html language_counts_table
# Fix title, current month and show modal
# ---------------------------------------
$('#reportIdiomesTitle').html "Edició de idiomes de <strong>#{source.toUpperCase()}</strong> de <strong>#{yearmonth}</strong>"
$('#reportIdiomesStatusPanel').html ''
$('#reportIdiomesModal').modal 'show' # mostramos el modal
# Include link to jump to the end of the page
# ---------------------------------------------
$('.bottomLink').unbind().click ->
$('#reportIdiomesModal').animate
scrollTop: 10000
return false
# -----------------------------------------------------
# EVENT: Alert buttons in case of ZIP generation error
# -----------------------------------------------------
$('a.error_message').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
alert g_zip_status[yearmonth].error_message
return false
# -------------------------------------
# EVENT: Buttons to generate ZIP files
# -------------------------------------
$('button[month]').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
# Call REST API to generate the ZIP file
# -------------------------------------------------------------
request = "/rest_reporting/reports/#{source}/generate/zip/yearmonth/#{yearmonth}"
$.ajax({url: request, type: "GET"})
.done (data) ->
if data.error?
console.log("ERROR: #{JSON.stringify data.error}")
alert "ERROR: #{JSON.stringify data.error}"
return false
else
return false
$("#zip_status_#{yearmonth}").html '<span style="color: #00CC00; font-weight: bold;">Generant ZIP...</span> <img src="/img/loading_icon.gif">'
return false
# ------------------------------------------
# Function that refreshes the reports list
# -------------------------------------------
refreshReportsList = (year, source) ->
request = "/rest_reporting/reports/#{source}/year/#{year}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Check if the RSET API returned an error
# ---------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
# =================
# REST call OK
# =================
reports = data.results
reports.forEach (report) ->
report.source = source # fix the source
# Save the zip state globally
# ---------------------------
g_zip_status[report.month] = report.zip_status
# Save the twet count time series globally
# ----------------------------------------
g_tweet_counts[report.month] = report.tweet_counts
# Save the language globally
# -----------------------------------------
g_language_counts[report.month] = report.language_counts
# Status of the ZIP file (errors, presence/absence and generation button)
# NOTE: this HTML content will appear only when the status is 'READY_TO_GENERATE'
# ------------------------------------------------------------------------------
zip_html = ''
zip_html += "<div id=\"zip_status_#{report.month}\">"
# Error messge alert
# ------------------
if report.zip_status.error_message isnt ''
zip_html += "<a href=\"#\" class=\"error_message\" month=\"#{report.month}\"><img src=\"/img/warning_icon.png\" width=\"50\" height=\"50\"></a> "
# ZIP download (if it exists)
# ---------------------------
if report.zip_exists
rest_url_to_zip = "/rest_reporting/reports/#{source}/zip/yearmonth/#{report.month}" # llamada REST que devuelve el ZIP
zip_html += "<a href=\"#{rest_url_to_zip}\"><img src=\"/img/file-zip-icon.png\" width=\"60\" height=\"60\"></a> "
# ZIP generation button
# ---------------------
zip_html += "<button type=\"button\" class=\"btn btn-default\" month=\"#{report.month}\">Genera ZIP</button></div>"
zip_html += "</div>"
report.zip_html = zip_html
# Render the reports list
# -----------------------
html_content = MyApp.templates.reportsTable
total_reports: reports.length
reports: reports
source: source.toUpperCase()
$('#reportsTable').html html_content
$('#statusPanel').html ''
# Activate all eventos once the reports list has been rendered
# -------------------------------------------------------------
setEventsOnReportsList source
# =================================
# Fix event over the search button
# ==================================
$('#searchButton').unbind().click (event) ->
event.preventDefault() # avoid the submit default behaviour
year = $('#searchForm select[name="year"]').val()
source = 'twitter'
# ================
# Form validation
# ================
if year is null
setTimeout ( -> $('#statusPanel').html '' ), 1000
$('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'any'}
else if source is null
setTimeout ( -> $('#statusPanel').html '' ), 1000
$('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'font'}
else
# ==============
# Validation OK
# ==============
# fix values in global variables
# ------------------------------
g_current_year = year
g_current_source = source
# control elements visibility
# ---------------------------
$('#reportsTable').html ''
$('#statusPanel').html '<br><br><br><p align="center"><img src="/img/rendering.gif"> Carregant reports...</p>'
# Render the reports list by the first time
# -----------------------------------------
setTimeout ( -> refreshReportsList g_current_year, g_current_source ), 1000
# ----------------------------------------------
# Refresh the reports limits at every time interval
# -----------------------------------------------
if refreshIntervalId
clearInterval(refreshIntervalId);
refreshIntervalId = setInterval ( ->
refreshReportsList g_current_year, g_current_source
), 7000
# -----------------------------------------------------------
return false
# Initial elements hidding
# ------------------------
$('#statusPanel').html ''
$('#reportsTable').html ''
) jQuery
| 127183 | # =========================================
# Author: <NAME> (Fundació Bit), 2017
# Modified by: <NAME> and <NAME>
# =========================================
refreshIntervalId = 0
g_dictionary_categories = ['esdeveniments', 'esports', 'toponims', 'platges', 'patrimoni', 'naturalesa']
g_brands = []
# Function to extract the brands from the REST API and render the results
# ------------------------------------------------------------------------
getBrands = () ->
brand_list = []
request = "/rest_utils/brands"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Check if the REST API returned an error
# ----------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
data.results.forEach (brand) ->
brand_list.push(brand)
return brand_list
g_brands = getBrands()
g_tweet_counts = {} # it will save tweet count series globally for each yearmonth
g_language_counts = {} # it will save language count globally for each yearmonth
g_zip_status = {} # it will save the zip status for each yearmonth
(($) ->
# ---------------------------------------------------------
# Function to fix EVENTS over the reports items in the list
# ---------------------------------------------------------
setEventsOnReportsList = (source) ->
# ----------------------------------------------------
# EVENT: Button to open the modal 'Tweets escrutats'
# ----------------------------------------------------
$('a.openTweetsEscrutats').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
# Download CSV
# -------------------------------------------
$('#tweetsEscrutatsCSVPanel').html MyApp.templates.tweetsEscrutatsCSVLoad {yearmonth: yearmonth}
# Generate array fo day numbers to write the series X Axis
# ---------------------------------------------------------
year = yearmonth.split("-")[0]
month = yearmonth.split("-")[1]
last_day_in_month = new Date(year, month, 0).getDate()
month_day_numbers = Array.from(Array(last_day_in_month + 1).keys()).slice(1)
# Extract the series data per brand
# ----------------------------------
brand_colors =
mallorca:
borderColor: "rgba(255,255,0, 0.8)"
backgroundColor: "rgba(255,255,0,0)"
menorca:
borderColor: "rgba(0,128,0, 0.8)"
backgroundColor: "rgba(0,128,0,0)"
ibiza:
borderColor: "rgba(255,0,0,0.8)"
backgroundColor: "rgba(255,0,0,0)"
formentera:
borderColor: "rgba(0,0,255,0.8)"
backgroundColor: "rgba(0,0,255,0)"
series = []
g_brands.forEach (brand) ->
series.push {
label: brand,
borderColor: brand_colors[brand].borderColor,
backgroundColor: brand_colors[brand].backgroundColor,
borderWidth: 2,
tension: 0,
radius: 0,
data: g_tweet_counts[yearmonth].series[brand]}
ctx = document.getElementById('reportTweetCountsChart').getContext('2d')
seriesChart = new Chart(ctx,{
type: 'line'
data:
labels: month_day_numbers
datasets : series
options:
responsive: true
title:
display: true
text: "Sèries temporals de tweet counts"
tooltips:
mode: 'x'
intersect: true
hover:
mode: 'nearest'
intersect: true
scales:
xAxes: [{
display: true
gridLines:
display: false
scaleLabel:
display: true
labelString: 'Data'
}]
yAxes: [{
display: true
gridLines:
display: false
scaleLabel:
display: true
labelString: 'Freqüència'
}]
})
$('#reportTweetCountsChart').show()
# Render the tweet counts table
# -------------------------------
tweet_counts_table = '<table width="100%" class="table table-striped table-condensed"><tr><td><b>marca</b></td><td><b>total</b></td><td><b>variació</b></td></tr>'
g_brands.forEach (brand) ->
tweet_counts_table += "<tr><td>#{brand}</td><td>#{g_tweet_counts[yearmonth].total[brand]}</td><td>#{g_tweet_counts[yearmonth].variation[brand]}</td></tr>"
tweet_counts_table += '</table>'
$("#reportTweetCountsTable").html tweet_counts_table
# Fix title, current month and show modal
# ----------------------------------------
$('#reportTweetsEscrutatsTitle').html "Edició de tweets escrutats de <strong>#{source.toUpperCase()}</strong> de <strong>#{yearmonth}</strong>"
$('#reportTweetsEscrutatsStatusPanel').html ''
$('#reportTweetsEscrutatsModal').modal 'show' # show the modal
# Include link to jump to the end of the page
# ---------------------------------------------
$('.bottomLink').unbind().click ->
$('#reportTweetsEscrutatsModal').animate
scrollTop: 10000
return false
# -----------------------------------------
# EVENT: Button to open the modal 'Idiomes'
# -----------------------------------------
$('a.openIdiomes').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
# Download CSV
# -------------------------------------------
$('#idiomesCSVPanel').html MyApp.templates.idiomesCSVLoad {yearmonth: yearmonth}
# Draw the language counts table
# -------------------------------
languages = ['es', 'ca', 'en', 'de', 'other', 'total']
language_counts_table = '<table width="100%" class="table table-striped table-condensed">'
language_counts_table += '<tr><td><b>idioma</b></td>'
g_brands.forEach (brand) -> language_counts_table += "<td><b>#{brand}</b></td>"
language_counts_table += '<td><b>Total</b></td><td><b>%Total</b></td>'
language_counts_table += '</tr>'
languages.forEach (lang) ->
language_counts_table += "<tr><td>#{lang}</td>"
g_brands.forEach (brand) ->
language_counts_table += "<td>#{g_language_counts[yearmonth][brand][lang]}</td>"
language_counts_table += "<td>#{g_language_counts[yearmonth].per_lang[lang].count}</td>"
language_counts_table += "<td>#{g_language_counts[yearmonth].per_lang[lang].percent}</td>"
language_counts_table += "</tr>"
language_counts_table += '</table>'
$("#reportNotesLanguageCountsTable").html language_counts_table
# Fix title, current month and show modal
# ---------------------------------------
$('#reportIdiomesTitle').html "Edició de idiomes de <strong>#{source.toUpperCase()}</strong> de <strong>#{yearmonth}</strong>"
$('#reportIdiomesStatusPanel').html ''
$('#reportIdiomesModal').modal 'show' # mostramos el modal
# Include link to jump to the end of the page
# ---------------------------------------------
$('.bottomLink').unbind().click ->
$('#reportIdiomesModal').animate
scrollTop: 10000
return false
# -----------------------------------------------------
# EVENT: Alert buttons in case of ZIP generation error
# -----------------------------------------------------
$('a.error_message').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
alert g_zip_status[yearmonth].error_message
return false
# -------------------------------------
# EVENT: Buttons to generate ZIP files
# -------------------------------------
$('button[month]').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
# Call REST API to generate the ZIP file
# -------------------------------------------------------------
request = "/rest_reporting/reports/#{source}/generate/zip/yearmonth/#{yearmonth}"
$.ajax({url: request, type: "GET"})
.done (data) ->
if data.error?
console.log("ERROR: #{JSON.stringify data.error}")
alert "ERROR: #{JSON.stringify data.error}"
return false
else
return false
$("#zip_status_#{yearmonth}").html '<span style="color: #00CC00; font-weight: bold;">Generant ZIP...</span> <img src="/img/loading_icon.gif">'
return false
# ------------------------------------------
# Function that refreshes the reports list
# -------------------------------------------
refreshReportsList = (year, source) ->
request = "/rest_reporting/reports/#{source}/year/#{year}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Check if the RSET API returned an error
# ---------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
# =================
# REST call OK
# =================
reports = data.results
reports.forEach (report) ->
report.source = source # fix the source
# Save the zip state globally
# ---------------------------
g_zip_status[report.month] = report.zip_status
# Save the twet count time series globally
# ----------------------------------------
g_tweet_counts[report.month] = report.tweet_counts
# Save the language globally
# -----------------------------------------
g_language_counts[report.month] = report.language_counts
# Status of the ZIP file (errors, presence/absence and generation button)
# NOTE: this HTML content will appear only when the status is 'READY_TO_GENERATE'
# ------------------------------------------------------------------------------
zip_html = ''
zip_html += "<div id=\"zip_status_#{report.month}\">"
# Error messge alert
# ------------------
if report.zip_status.error_message isnt ''
zip_html += "<a href=\"#\" class=\"error_message\" month=\"#{report.month}\"><img src=\"/img/warning_icon.png\" width=\"50\" height=\"50\"></a> "
# ZIP download (if it exists)
# ---------------------------
if report.zip_exists
rest_url_to_zip = "/rest_reporting/reports/#{source}/zip/yearmonth/#{report.month}" # llamada REST que devuelve el ZIP
zip_html += "<a href=\"#{rest_url_to_zip}\"><img src=\"/img/file-zip-icon.png\" width=\"60\" height=\"60\"></a> "
# ZIP generation button
# ---------------------
zip_html += "<button type=\"button\" class=\"btn btn-default\" month=\"#{report.month}\">Genera ZIP</button></div>"
zip_html += "</div>"
report.zip_html = zip_html
# Render the reports list
# -----------------------
html_content = MyApp.templates.reportsTable
total_reports: reports.length
reports: reports
source: source.toUpperCase()
$('#reportsTable').html html_content
$('#statusPanel').html ''
# Activate all eventos once the reports list has been rendered
# -------------------------------------------------------------
setEventsOnReportsList source
# =================================
# Fix event over the search button
# ==================================
$('#searchButton').unbind().click (event) ->
event.preventDefault() # avoid the submit default behaviour
year = $('#searchForm select[name="year"]').val()
source = 'twitter'
# ================
# Form validation
# ================
if year is null
setTimeout ( -> $('#statusPanel').html '' ), 1000
$('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'any'}
else if source is null
setTimeout ( -> $('#statusPanel').html '' ), 1000
$('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'font'}
else
# ==============
# Validation OK
# ==============
# fix values in global variables
# ------------------------------
g_current_year = year
g_current_source = source
# control elements visibility
# ---------------------------
$('#reportsTable').html ''
$('#statusPanel').html '<br><br><br><p align="center"><img src="/img/rendering.gif"> Carregant reports...</p>'
# Render the reports list by the first time
# -----------------------------------------
setTimeout ( -> refreshReportsList g_current_year, g_current_source ), 1000
# ----------------------------------------------
# Refresh the reports limits at every time interval
# -----------------------------------------------
if refreshIntervalId
clearInterval(refreshIntervalId);
refreshIntervalId = setInterval ( ->
refreshReportsList g_current_year, g_current_source
), 7000
# -----------------------------------------------------------
return false
# Initial elements hidding
# ------------------------
$('#statusPanel').html ''
$('#reportsTable').html ''
) jQuery
| true | # =========================================
# Author: PI:NAME:<NAME>END_PI (Fundació Bit), 2017
# Modified by: PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI
# =========================================
refreshIntervalId = 0
g_dictionary_categories = ['esdeveniments', 'esports', 'toponims', 'platges', 'patrimoni', 'naturalesa']
g_brands = []
# Function to extract the brands from the REST API and render the results
# ------------------------------------------------------------------------
getBrands = () ->
brand_list = []
request = "/rest_utils/brands"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Check if the REST API returned an error
# ----------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
data.results.forEach (brand) ->
brand_list.push(brand)
return brand_list
g_brands = getBrands()
g_tweet_counts = {} # it will save tweet count series globally for each yearmonth
g_language_counts = {} # it will save language count globally for each yearmonth
g_zip_status = {} # it will save the zip status for each yearmonth
(($) ->
# ---------------------------------------------------------
# Function to fix EVENTS over the reports items in the list
# ---------------------------------------------------------
setEventsOnReportsList = (source) ->
# ----------------------------------------------------
# EVENT: Button to open the modal 'Tweets escrutats'
# ----------------------------------------------------
$('a.openTweetsEscrutats').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
# Download CSV
# -------------------------------------------
$('#tweetsEscrutatsCSVPanel').html MyApp.templates.tweetsEscrutatsCSVLoad {yearmonth: yearmonth}
# Generate array fo day numbers to write the series X Axis
# ---------------------------------------------------------
year = yearmonth.split("-")[0]
month = yearmonth.split("-")[1]
last_day_in_month = new Date(year, month, 0).getDate()
month_day_numbers = Array.from(Array(last_day_in_month + 1).keys()).slice(1)
# Extract the series data per brand
# ----------------------------------
brand_colors =
mallorca:
borderColor: "rgba(255,255,0, 0.8)"
backgroundColor: "rgba(255,255,0,0)"
menorca:
borderColor: "rgba(0,128,0, 0.8)"
backgroundColor: "rgba(0,128,0,0)"
ibiza:
borderColor: "rgba(255,0,0,0.8)"
backgroundColor: "rgba(255,0,0,0)"
formentera:
borderColor: "rgba(0,0,255,0.8)"
backgroundColor: "rgba(0,0,255,0)"
series = []
g_brands.forEach (brand) ->
series.push {
label: brand,
borderColor: brand_colors[brand].borderColor,
backgroundColor: brand_colors[brand].backgroundColor,
borderWidth: 2,
tension: 0,
radius: 0,
data: g_tweet_counts[yearmonth].series[brand]}
ctx = document.getElementById('reportTweetCountsChart').getContext('2d')
seriesChart = new Chart(ctx,{
type: 'line'
data:
labels: month_day_numbers
datasets : series
options:
responsive: true
title:
display: true
text: "Sèries temporals de tweet counts"
tooltips:
mode: 'x'
intersect: true
hover:
mode: 'nearest'
intersect: true
scales:
xAxes: [{
display: true
gridLines:
display: false
scaleLabel:
display: true
labelString: 'Data'
}]
yAxes: [{
display: true
gridLines:
display: false
scaleLabel:
display: true
labelString: 'Freqüència'
}]
})
$('#reportTweetCountsChart').show()
# Render the tweet counts table
# -------------------------------
tweet_counts_table = '<table width="100%" class="table table-striped table-condensed"><tr><td><b>marca</b></td><td><b>total</b></td><td><b>variació</b></td></tr>'
g_brands.forEach (brand) ->
tweet_counts_table += "<tr><td>#{brand}</td><td>#{g_tweet_counts[yearmonth].total[brand]}</td><td>#{g_tweet_counts[yearmonth].variation[brand]}</td></tr>"
tweet_counts_table += '</table>'
$("#reportTweetCountsTable").html tweet_counts_table
# Fix title, current month and show modal
# ----------------------------------------
$('#reportTweetsEscrutatsTitle').html "Edició de tweets escrutats de <strong>#{source.toUpperCase()}</strong> de <strong>#{yearmonth}</strong>"
$('#reportTweetsEscrutatsStatusPanel').html ''
$('#reportTweetsEscrutatsModal').modal 'show' # show the modal
# Include link to jump to the end of the page
# ---------------------------------------------
$('.bottomLink').unbind().click ->
$('#reportTweetsEscrutatsModal').animate
scrollTop: 10000
return false
# -----------------------------------------
# EVENT: Button to open the modal 'Idiomes'
# -----------------------------------------
$('a.openIdiomes').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
# Download CSV
# -------------------------------------------
$('#idiomesCSVPanel').html MyApp.templates.idiomesCSVLoad {yearmonth: yearmonth}
# Draw the language counts table
# -------------------------------
languages = ['es', 'ca', 'en', 'de', 'other', 'total']
language_counts_table = '<table width="100%" class="table table-striped table-condensed">'
language_counts_table += '<tr><td><b>idioma</b></td>'
g_brands.forEach (brand) -> language_counts_table += "<td><b>#{brand}</b></td>"
language_counts_table += '<td><b>Total</b></td><td><b>%Total</b></td>'
language_counts_table += '</tr>'
languages.forEach (lang) ->
language_counts_table += "<tr><td>#{lang}</td>"
g_brands.forEach (brand) ->
language_counts_table += "<td>#{g_language_counts[yearmonth][brand][lang]}</td>"
language_counts_table += "<td>#{g_language_counts[yearmonth].per_lang[lang].count}</td>"
language_counts_table += "<td>#{g_language_counts[yearmonth].per_lang[lang].percent}</td>"
language_counts_table += "</tr>"
language_counts_table += '</table>'
$("#reportNotesLanguageCountsTable").html language_counts_table
# Fix title, current month and show modal
# ---------------------------------------
$('#reportIdiomesTitle').html "Edició de idiomes de <strong>#{source.toUpperCase()}</strong> de <strong>#{yearmonth}</strong>"
$('#reportIdiomesStatusPanel').html ''
$('#reportIdiomesModal').modal 'show' # mostramos el modal
# Include link to jump to the end of the page
# ---------------------------------------------
$('.bottomLink').unbind().click ->
$('#reportIdiomesModal').animate
scrollTop: 10000
return false
# -----------------------------------------------------
# EVENT: Alert buttons in case of ZIP generation error
# -----------------------------------------------------
$('a.error_message').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
alert g_zip_status[yearmonth].error_message
return false
# -------------------------------------
# EVENT: Buttons to generate ZIP files
# -------------------------------------
$('button[month]').unbind().click (event) ->
event.preventDefault()
yearmonth = $(this).attr('month')
# Call REST API to generate the ZIP file
# -------------------------------------------------------------
request = "/rest_reporting/reports/#{source}/generate/zip/yearmonth/#{yearmonth}"
$.ajax({url: request, type: "GET"})
.done (data) ->
if data.error?
console.log("ERROR: #{JSON.stringify data.error}")
alert "ERROR: #{JSON.stringify data.error}"
return false
else
return false
$("#zip_status_#{yearmonth}").html '<span style="color: #00CC00; font-weight: bold;">Generant ZIP...</span> <img src="/img/loading_icon.gif">'
return false
# ------------------------------------------
# Function that refreshes the reports list
# -------------------------------------------
refreshReportsList = (year, source) ->
request = "/rest_reporting/reports/#{source}/year/#{year}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Check if the RSET API returned an error
# ---------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
# =================
# REST call OK
# =================
reports = data.results
reports.forEach (report) ->
report.source = source # fix the source
# Save the zip state globally
# ---------------------------
g_zip_status[report.month] = report.zip_status
# Save the twet count time series globally
# ----------------------------------------
g_tweet_counts[report.month] = report.tweet_counts
# Save the language globally
# -----------------------------------------
g_language_counts[report.month] = report.language_counts
# Status of the ZIP file (errors, presence/absence and generation button)
# NOTE: this HTML content will appear only when the status is 'READY_TO_GENERATE'
# ------------------------------------------------------------------------------
zip_html = ''
zip_html += "<div id=\"zip_status_#{report.month}\">"
# Error messge alert
# ------------------
if report.zip_status.error_message isnt ''
zip_html += "<a href=\"#\" class=\"error_message\" month=\"#{report.month}\"><img src=\"/img/warning_icon.png\" width=\"50\" height=\"50\"></a> "
# ZIP download (if it exists)
# ---------------------------
if report.zip_exists
rest_url_to_zip = "/rest_reporting/reports/#{source}/zip/yearmonth/#{report.month}" # llamada REST que devuelve el ZIP
zip_html += "<a href=\"#{rest_url_to_zip}\"><img src=\"/img/file-zip-icon.png\" width=\"60\" height=\"60\"></a> "
# ZIP generation button
# ---------------------
zip_html += "<button type=\"button\" class=\"btn btn-default\" month=\"#{report.month}\">Genera ZIP</button></div>"
zip_html += "</div>"
report.zip_html = zip_html
# Render the reports list
# -----------------------
html_content = MyApp.templates.reportsTable
total_reports: reports.length
reports: reports
source: source.toUpperCase()
$('#reportsTable').html html_content
$('#statusPanel').html ''
# Activate all eventos once the reports list has been rendered
# -------------------------------------------------------------
setEventsOnReportsList source
# =================================
# Fix event over the search button
# ==================================
$('#searchButton').unbind().click (event) ->
event.preventDefault() # avoid the submit default behaviour
year = $('#searchForm select[name="year"]').val()
source = 'twitter'
# ================
# Form validation
# ================
if year is null
setTimeout ( -> $('#statusPanel').html '' ), 1000
$('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'any'}
else if source is null
setTimeout ( -> $('#statusPanel').html '' ), 1000
$('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'font'}
else
# ==============
# Validation OK
# ==============
# fix values in global variables
# ------------------------------
g_current_year = year
g_current_source = source
# control elements visibility
# ---------------------------
$('#reportsTable').html ''
$('#statusPanel').html '<br><br><br><p align="center"><img src="/img/rendering.gif"> Carregant reports...</p>'
# Render the reports list by the first time
# -----------------------------------------
setTimeout ( -> refreshReportsList g_current_year, g_current_source ), 1000
# ----------------------------------------------
# Refresh the reports limits at every time interval
# -----------------------------------------------
if refreshIntervalId
clearInterval(refreshIntervalId);
refreshIntervalId = setInterval ( ->
refreshReportsList g_current_year, g_current_source
), 7000
# -----------------------------------------------------------
return false
# Initial elements hidding
# ------------------------
$('#statusPanel').html ''
$('#reportsTable').html ''
) jQuery
|
[
{
"context": " (done) ->\n auth.login(server, {username: \"test@test.com\", password:\"password\"}, 200, \n (res)->",
"end": 584,
"score": 0.9999238848686218,
"start": 571,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": "gin(server, {username: \"test@test.... | test/services_tests/test_permission_operator_services.coffee | ureport-web/ureport-s | 3 | #load application models
server = require('../../app')
_ = require('underscore');
setting = require('../api_objects/setting_api_object')
build = require('../api_objects/build_api_object')
auth = require('../api_objects/auth_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User with Operatpr permission cannot', ->
existInvestigatedTest = undefined;
cookies = undefined;
before (done) ->
auth.login(server, {username: "test@test.com", password:"password"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
)
return
describe 'manipulate setting', ->
it 'should not create a new setting', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API'
}
setting.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'should not update setting', (done) ->
setting.update(server, cookies,
"NONE", {},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'should not delete setting', (done) ->
setting.delete(server, cookies,
"NONE",
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return | 52255 | #load application models
server = require('../../app')
_ = require('underscore');
setting = require('../api_objects/setting_api_object')
build = require('../api_objects/build_api_object')
auth = require('../api_objects/auth_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User with Operatpr permission cannot', ->
existInvestigatedTest = undefined;
cookies = undefined;
before (done) ->
auth.login(server, {username: "<EMAIL>", password:"<PASSWORD>"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
)
return
describe 'manipulate setting', ->
it 'should not create a new setting', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API'
}
setting.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'should not update setting', (done) ->
setting.update(server, cookies,
"NONE", {},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'should not delete setting', (done) ->
setting.delete(server, cookies,
"NONE",
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return | true | #load application models
server = require('../../app')
_ = require('underscore');
setting = require('../api_objects/setting_api_object')
build = require('../api_objects/build_api_object')
auth = require('../api_objects/auth_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User with Operatpr permission cannot', ->
existInvestigatedTest = undefined;
cookies = undefined;
before (done) ->
auth.login(server, {username: "PI:EMAIL:<EMAIL>END_PI", password:"PI:PASSWORD:<PASSWORD>END_PI"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
)
return
describe 'manipulate setting', ->
it 'should not create a new setting', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API'
}
setting.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'should not update setting', (done) ->
setting.update(server, cookies,
"NONE", {},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'should not delete setting', (done) ->
setting.delete(server, cookies,
"NONE",
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return |
[
{
"context": "f[key]\n continue if not set\n if key is 'VERSION'\n menu.label = set.value+' '+atom.appVersi",
"end": 1339,
"score": 0.8833473920822144,
"start": 1332,
"tag": "KEY",
"value": "VERSION"
}
] | lib/main.coffee | CappuccinoRU/atom-simplified-russian-menu | 17 | class RussianSetting
constructor: ->
CSON = require 'cson'
# Menu
@M = CSON.load __dirname + '/../def/menu_'+process.platform+'.cson'
# Right menu
@C = CSON.load __dirname + '/../def/context.cson'
activate: (state) ->
setTimeout(@delay,0)
delay: () =>
config = atom.config.get 'simplified-russian-menu'
if config.useMenu
# Menu
@updateMenu(atom.menu.template, @M.Menu)
atom.menu.update()
if config.useContext
# ContextMenu
@updateContextMenu()
if config.useSetting
# Settings (on init and open)
@updateSettings()
# After switching over overloaded
atom.workspace.onDidChangeActivePaneItem (item) =>
if item and item.uri and item.uri.indexOf('atom://config') isnt -1
settingsTab = document.querySelector('.tab-bar [data-type="SettingsView"]')
russianStatus = settingsTab.getAttribute('inRussian')
if russianStatus isnt 'true'
settingsTab.setAttribute('inRussian','true')
@updateSettings(true)
updateMenu : (menuList, def) ->
return if not def
for menu in menuList
continue if not menu.label
key = menu.label
if key.indexOf '…' isnt -1
key = key.replace('…','...')
set = def[key]
continue if not set
if key is 'VERSION'
menu.label = set.value+' '+atom.appVersion if set?
else
menu.label = set.value if set?
if menu.submenu?
@updateMenu(menu.submenu, set.submenu)
updateContextMenu: () ->
console.log 'carriedout updateContextMenu'
for itemSet in atom.contextMenu.itemSets
set = @C.Context[itemSet.selector]
continue if not set
for item in itemSet.items
continue if item.type is "separator"
label = set[item.command]
item.label = label if label?
updateSettings: (onSettingsOpen = false) ->
setTimeout(@delaySettings, 0, onSettingsOpen)
delaySettings: (onSettingsOpen) ->
settings = require './../tools/settings'
settings.init()
config:
useMenu:
title: 'Русское меню'
description: 'Если Вы не хотите использовать русское меню (по умолчанию английское), то можете его отключить (может потребоваться перезагрузка Atom)'
type: 'boolean'
default: true
useSetting:
title: 'Настройки на русском языке'
description: 'Если Вы не хотите использовать русский язык в настройках программы (по умолчанию английское), то можете его отключить (может потребоваться перезагрузка Atom)'
type: 'boolean'
default: true
useContext:
title: 'Перевод контекстного меню'
description: 'Если Вы не хотите использовать русское контекстное меню (по умолчанию английское), то можете его отключить (может потребоваться перезагрузка Atom)'
type: 'boolean'
default: true
module.exports = new RussianSetting()
| 107520 | class RussianSetting
constructor: ->
CSON = require 'cson'
# Menu
@M = CSON.load __dirname + '/../def/menu_'+process.platform+'.cson'
# Right menu
@C = CSON.load __dirname + '/../def/context.cson'
activate: (state) ->
setTimeout(@delay,0)
delay: () =>
config = atom.config.get 'simplified-russian-menu'
if config.useMenu
# Menu
@updateMenu(atom.menu.template, @M.Menu)
atom.menu.update()
if config.useContext
# ContextMenu
@updateContextMenu()
if config.useSetting
# Settings (on init and open)
@updateSettings()
# After switching over overloaded
atom.workspace.onDidChangeActivePaneItem (item) =>
if item and item.uri and item.uri.indexOf('atom://config') isnt -1
settingsTab = document.querySelector('.tab-bar [data-type="SettingsView"]')
russianStatus = settingsTab.getAttribute('inRussian')
if russianStatus isnt 'true'
settingsTab.setAttribute('inRussian','true')
@updateSettings(true)
updateMenu : (menuList, def) ->
return if not def
for menu in menuList
continue if not menu.label
key = menu.label
if key.indexOf '…' isnt -1
key = key.replace('…','...')
set = def[key]
continue if not set
if key is '<KEY>'
menu.label = set.value+' '+atom.appVersion if set?
else
menu.label = set.value if set?
if menu.submenu?
@updateMenu(menu.submenu, set.submenu)
updateContextMenu: () ->
console.log 'carriedout updateContextMenu'
for itemSet in atom.contextMenu.itemSets
set = @C.Context[itemSet.selector]
continue if not set
for item in itemSet.items
continue if item.type is "separator"
label = set[item.command]
item.label = label if label?
updateSettings: (onSettingsOpen = false) ->
setTimeout(@delaySettings, 0, onSettingsOpen)
delaySettings: (onSettingsOpen) ->
settings = require './../tools/settings'
settings.init()
config:
useMenu:
title: 'Русское меню'
description: 'Если Вы не хотите использовать русское меню (по умолчанию английское), то можете его отключить (может потребоваться перезагрузка Atom)'
type: 'boolean'
default: true
useSetting:
title: 'Настройки на русском языке'
description: 'Если Вы не хотите использовать русский язык в настройках программы (по умолчанию английское), то можете его отключить (может потребоваться перезагрузка Atom)'
type: 'boolean'
default: true
useContext:
title: 'Перевод контекстного меню'
description: 'Если Вы не хотите использовать русское контекстное меню (по умолчанию английское), то можете его отключить (может потребоваться перезагрузка Atom)'
type: 'boolean'
default: true
module.exports = new RussianSetting()
| true | class RussianSetting
constructor: ->
CSON = require 'cson'
# Menu
@M = CSON.load __dirname + '/../def/menu_'+process.platform+'.cson'
# Right menu
@C = CSON.load __dirname + '/../def/context.cson'
activate: (state) ->
setTimeout(@delay,0)
delay: () =>
config = atom.config.get 'simplified-russian-menu'
if config.useMenu
# Menu
@updateMenu(atom.menu.template, @M.Menu)
atom.menu.update()
if config.useContext
# ContextMenu
@updateContextMenu()
if config.useSetting
# Settings (on init and open)
@updateSettings()
# After switching over overloaded
atom.workspace.onDidChangeActivePaneItem (item) =>
if item and item.uri and item.uri.indexOf('atom://config') isnt -1
settingsTab = document.querySelector('.tab-bar [data-type="SettingsView"]')
russianStatus = settingsTab.getAttribute('inRussian')
if russianStatus isnt 'true'
settingsTab.setAttribute('inRussian','true')
@updateSettings(true)
updateMenu : (menuList, def) ->
return if not def
for menu in menuList
continue if not menu.label
key = menu.label
if key.indexOf '…' isnt -1
key = key.replace('…','...')
set = def[key]
continue if not set
if key is 'PI:KEY:<KEY>END_PI'
menu.label = set.value+' '+atom.appVersion if set?
else
menu.label = set.value if set?
if menu.submenu?
@updateMenu(menu.submenu, set.submenu)
updateContextMenu: () ->
console.log 'carriedout updateContextMenu'
for itemSet in atom.contextMenu.itemSets
set = @C.Context[itemSet.selector]
continue if not set
for item in itemSet.items
continue if item.type is "separator"
label = set[item.command]
item.label = label if label?
updateSettings: (onSettingsOpen = false) ->
setTimeout(@delaySettings, 0, onSettingsOpen)
delaySettings: (onSettingsOpen) ->
settings = require './../tools/settings'
settings.init()
config:
useMenu:
title: 'Русское меню'
description: 'Если Вы не хотите использовать русское меню (по умолчанию английское), то можете его отключить (может потребоваться перезагрузка Atom)'
type: 'boolean'
default: true
useSetting:
title: 'Настройки на русском языке'
description: 'Если Вы не хотите использовать русский язык в настройках программы (по умолчанию английское), то можете его отключить (может потребоваться перезагрузка Atom)'
type: 'boolean'
default: true
useContext:
title: 'Перевод контекстного меню'
description: 'Если Вы не хотите использовать русское контекстное меню (по умолчанию английское), то можете его отключить (может потребоваться перезагрузка Atom)'
type: 'boolean'
default: true
module.exports = new RussianSetting()
|
[
{
"context": " --resolve 'smoke#{Settings.cookieDomain}:#{port}:127.0.0.1' http://smoke#{Settings.cookieDomain}:#{port}/#{p",
"end": 547,
"score": 0.9995452165603638,
"start": 538,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "{Settings.smokeTest.user}\", \"password\":\"... | test/smoke/coffee/SmokeTests.coffee | HasanSanli/web-sharelatex | 0 | child = require "child_process"
fs = require "fs"
assert = require("assert")
chai = require("chai")
chai.should() unless Object.prototype.should?
expect = chai.expect
Settings = require "settings-sharelatex"
ownPort = Settings.internal?.web?.port or Settings.port or 3000
port = Settings.web?.web_router_port or ownPort # send requests to web router if this is the api process
cookeFilePath = "/tmp/smoke-test-cookie-#{ownPort}-to-#{port}.txt"
buildUrl = (path) -> " -b #{cookeFilePath} --resolve 'smoke#{Settings.cookieDomain}:#{port}:127.0.0.1' http://smoke#{Settings.cookieDomain}:#{port}/#{path}?setLng=en"
logger = require "logger-sharelatex"
# Change cookie to be non secure so curl will send it
convertCookieFile = (callback) ->
fs = require("fs")
fs.readFile cookeFilePath, "utf8", (err, data) ->
return callback(err) if err
firstTrue = data.indexOf("TRUE")
secondTrue = data.indexOf("TRUE", firstTrue+4)
result = data.slice(0, secondTrue)+"FALSE"+data.slice(secondTrue+4)
fs.writeFile cookeFilePath, result, "utf8", (err) ->
return callback(err) if err
callback()
describe "Opening", ->
before (done) ->
logger.log "smoke test: setup"
require("../../../app/js/Features/Security/LoginRateLimiter.js").recordSuccessfulLogin Settings.smokeTest.user, (err)->
if err?
logger.err err:err, "smoke test: error recoring successful login"
return done(err)
logger.log "smoke test: clearing rate limit "
require("../../../app/js/infrastructure/RateLimiter.js").clearRateLimit "open-project", "#{Settings.smokeTest.projectId}:#{Settings.smokeTest.userId}", ->
logger.log "smoke test: hitting /register"
command = """
curl -H "X-Forwarded-Proto: https" -c #{cookeFilePath} #{buildUrl('register')}
"""
child.exec command, (err, stdout, stderr)->
if err? then done(err)
csrfMatches = stdout.match("<input name=\"_csrf\" type=\"hidden\" value=\"(.*?)\">")
if !csrfMatches?
logger.err stdout:stdout, "smoke test: does not have csrf token"
return done("smoke test: does not have csrf token")
csrf = csrfMatches[1]
logger.log "smoke test: converting cookie file 1"
convertCookieFile (err) ->
return done(err) if err?
logger.log "smoke test: hitting /register with csrf"
command = """
curl -c #{cookeFilePath} -H "Content-Type: application/json" -H "X-Forwarded-Proto: https" -d '{"_csrf":"#{csrf}", "email":"#{Settings.smokeTest.user}", "password":"#{Settings.smokeTest.password}"}' #{buildUrl('register')}
"""
child.exec command, (err) ->
return done(err) if err?
logger.log "smoke test: finishing setup"
convertCookieFile done
after (done)->
logger.log "smoke test: cleaning up"
command = """
curl -H "X-Forwarded-Proto: https" -c #{cookeFilePath} #{buildUrl('logout')}
"""
child.exec command, (err, stdout, stderr)->
if err?
return done(err)
fs.unlink cookeFilePath, done
it "a project", (done) ->
logger.log "smoke test: Checking can load a project"
@timeout(4000)
command = """
curl -H "X-Forwarded-Proto: https" -v #{buildUrl("project/#{Settings.smokeTest.projectId}")}
"""
child.exec command, (error, stdout, stderr)->
expect(error, "smoke test: error in getting project").to.not.exist
statusCodeMatch = !!stderr.match("200 OK")
expect(statusCodeMatch, "smoke test: response code is not 200 getting project").to.equal true
# Check that the project id is present in the javascript that loads up the project
match = !!stdout.match("window.project_id = \"#{Settings.smokeTest.projectId}\"")
expect(match, "smoke test: project page html does not have project_id").to.equal true
done()
it "the project list", (done) ->
logger.log "smoke test: Checking can load project list"
@timeout(4000)
command = """
curl -H "X-Forwarded-Proto: https" -v #{buildUrl("project")}
"""
child.exec command, (error, stdout, stderr)->
expect(error, "smoke test: error returned in getting project list").to.not.exist
expect(!!stderr.match("200 OK"), "smoke test: response code is not 200 getting project list").to.equal true
expect(!!stdout.match("<title>Your Projects - .*, Online LaTeX Editor</title>"), "smoke test: body does not have correct title").to.equal true
expect(!!stdout.match("ProjectPageController"), "smoke test: body does not have correct angular controller").to.equal true
done()
| 20599 | child = require "child_process"
fs = require "fs"
assert = require("assert")
chai = require("chai")
chai.should() unless Object.prototype.should?
expect = chai.expect
Settings = require "settings-sharelatex"
ownPort = Settings.internal?.web?.port or Settings.port or 3000
port = Settings.web?.web_router_port or ownPort # send requests to web router if this is the api process
cookeFilePath = "/tmp/smoke-test-cookie-#{ownPort}-to-#{port}.txt"
buildUrl = (path) -> " -b #{cookeFilePath} --resolve 'smoke#{Settings.cookieDomain}:#{port}:127.0.0.1' http://smoke#{Settings.cookieDomain}:#{port}/#{path}?setLng=en"
logger = require "logger-sharelatex"
# Change cookie to be non secure so curl will send it
convertCookieFile = (callback) ->
fs = require("fs")
fs.readFile cookeFilePath, "utf8", (err, data) ->
return callback(err) if err
firstTrue = data.indexOf("TRUE")
secondTrue = data.indexOf("TRUE", firstTrue+4)
result = data.slice(0, secondTrue)+"FALSE"+data.slice(secondTrue+4)
fs.writeFile cookeFilePath, result, "utf8", (err) ->
return callback(err) if err
callback()
describe "Opening", ->
before (done) ->
logger.log "smoke test: setup"
require("../../../app/js/Features/Security/LoginRateLimiter.js").recordSuccessfulLogin Settings.smokeTest.user, (err)->
if err?
logger.err err:err, "smoke test: error recoring successful login"
return done(err)
logger.log "smoke test: clearing rate limit "
require("../../../app/js/infrastructure/RateLimiter.js").clearRateLimit "open-project", "#{Settings.smokeTest.projectId}:#{Settings.smokeTest.userId}", ->
logger.log "smoke test: hitting /register"
command = """
curl -H "X-Forwarded-Proto: https" -c #{cookeFilePath} #{buildUrl('register')}
"""
child.exec command, (err, stdout, stderr)->
if err? then done(err)
csrfMatches = stdout.match("<input name=\"_csrf\" type=\"hidden\" value=\"(.*?)\">")
if !csrfMatches?
logger.err stdout:stdout, "smoke test: does not have csrf token"
return done("smoke test: does not have csrf token")
csrf = csrfMatches[1]
logger.log "smoke test: converting cookie file 1"
convertCookieFile (err) ->
return done(err) if err?
logger.log "smoke test: hitting /register with csrf"
command = """
curl -c #{cookeFilePath} -H "Content-Type: application/json" -H "X-Forwarded-Proto: https" -d '{"_csrf":"#{csrf}", "email":"#{Settings.smokeTest.user}", "password":"#{Settings.<PASSWORD>Test.<PASSWORD>}"}' #{buildUrl('register')}
"""
child.exec command, (err) ->
return done(err) if err?
logger.log "smoke test: finishing setup"
convertCookieFile done
after (done)->
logger.log "smoke test: cleaning up"
command = """
curl -H "X-Forwarded-Proto: https" -c #{cookeFilePath} #{buildUrl('logout')}
"""
child.exec command, (err, stdout, stderr)->
if err?
return done(err)
fs.unlink cookeFilePath, done
it "a project", (done) ->
logger.log "smoke test: Checking can load a project"
@timeout(4000)
command = """
curl -H "X-Forwarded-Proto: https" -v #{buildUrl("project/#{Settings.smokeTest.projectId}")}
"""
child.exec command, (error, stdout, stderr)->
expect(error, "smoke test: error in getting project").to.not.exist
statusCodeMatch = !!stderr.match("200 OK")
expect(statusCodeMatch, "smoke test: response code is not 200 getting project").to.equal true
# Check that the project id is present in the javascript that loads up the project
match = !!stdout.match("window.project_id = \"#{Settings.smokeTest.projectId}\"")
expect(match, "smoke test: project page html does not have project_id").to.equal true
done()
it "the project list", (done) ->
logger.log "smoke test: Checking can load project list"
@timeout(4000)
command = """
curl -H "X-Forwarded-Proto: https" -v #{buildUrl("project")}
"""
child.exec command, (error, stdout, stderr)->
expect(error, "smoke test: error returned in getting project list").to.not.exist
expect(!!stderr.match("200 OK"), "smoke test: response code is not 200 getting project list").to.equal true
expect(!!stdout.match("<title>Your Projects - .*, Online LaTeX Editor</title>"), "smoke test: body does not have correct title").to.equal true
expect(!!stdout.match("ProjectPageController"), "smoke test: body does not have correct angular controller").to.equal true
done()
| true | child = require "child_process"
fs = require "fs"
assert = require("assert")
chai = require("chai")
chai.should() unless Object.prototype.should?
expect = chai.expect
Settings = require "settings-sharelatex"
ownPort = Settings.internal?.web?.port or Settings.port or 3000
port = Settings.web?.web_router_port or ownPort # send requests to web router if this is the api process
cookeFilePath = "/tmp/smoke-test-cookie-#{ownPort}-to-#{port}.txt"
buildUrl = (path) -> " -b #{cookeFilePath} --resolve 'smoke#{Settings.cookieDomain}:#{port}:127.0.0.1' http://smoke#{Settings.cookieDomain}:#{port}/#{path}?setLng=en"
logger = require "logger-sharelatex"
# Change cookie to be non secure so curl will send it
convertCookieFile = (callback) ->
fs = require("fs")
fs.readFile cookeFilePath, "utf8", (err, data) ->
return callback(err) if err
firstTrue = data.indexOf("TRUE")
secondTrue = data.indexOf("TRUE", firstTrue+4)
result = data.slice(0, secondTrue)+"FALSE"+data.slice(secondTrue+4)
fs.writeFile cookeFilePath, result, "utf8", (err) ->
return callback(err) if err
callback()
describe "Opening", ->
before (done) ->
logger.log "smoke test: setup"
require("../../../app/js/Features/Security/LoginRateLimiter.js").recordSuccessfulLogin Settings.smokeTest.user, (err)->
if err?
logger.err err:err, "smoke test: error recoring successful login"
return done(err)
logger.log "smoke test: clearing rate limit "
require("../../../app/js/infrastructure/RateLimiter.js").clearRateLimit "open-project", "#{Settings.smokeTest.projectId}:#{Settings.smokeTest.userId}", ->
logger.log "smoke test: hitting /register"
command = """
curl -H "X-Forwarded-Proto: https" -c #{cookeFilePath} #{buildUrl('register')}
"""
child.exec command, (err, stdout, stderr)->
if err? then done(err)
csrfMatches = stdout.match("<input name=\"_csrf\" type=\"hidden\" value=\"(.*?)\">")
if !csrfMatches?
logger.err stdout:stdout, "smoke test: does not have csrf token"
return done("smoke test: does not have csrf token")
csrf = csrfMatches[1]
logger.log "smoke test: converting cookie file 1"
convertCookieFile (err) ->
return done(err) if err?
logger.log "smoke test: hitting /register with csrf"
command = """
curl -c #{cookeFilePath} -H "Content-Type: application/json" -H "X-Forwarded-Proto: https" -d '{"_csrf":"#{csrf}", "email":"#{Settings.smokeTest.user}", "password":"#{Settings.PI:PASSWORD:<PASSWORD>END_PITest.PI:PASSWORD:<PASSWORD>END_PI}"}' #{buildUrl('register')}
"""
child.exec command, (err) ->
return done(err) if err?
logger.log "smoke test: finishing setup"
convertCookieFile done
after (done)->
logger.log "smoke test: cleaning up"
command = """
curl -H "X-Forwarded-Proto: https" -c #{cookeFilePath} #{buildUrl('logout')}
"""
child.exec command, (err, stdout, stderr)->
if err?
return done(err)
fs.unlink cookeFilePath, done
it "a project", (done) ->
logger.log "smoke test: Checking can load a project"
@timeout(4000)
command = """
curl -H "X-Forwarded-Proto: https" -v #{buildUrl("project/#{Settings.smokeTest.projectId}")}
"""
child.exec command, (error, stdout, stderr)->
expect(error, "smoke test: error in getting project").to.not.exist
statusCodeMatch = !!stderr.match("200 OK")
expect(statusCodeMatch, "smoke test: response code is not 200 getting project").to.equal true
# Check that the project id is present in the javascript that loads up the project
match = !!stdout.match("window.project_id = \"#{Settings.smokeTest.projectId}\"")
expect(match, "smoke test: project page html does not have project_id").to.equal true
done()
it "the project list", (done) ->
logger.log "smoke test: Checking can load project list"
@timeout(4000)
command = """
curl -H "X-Forwarded-Proto: https" -v #{buildUrl("project")}
"""
child.exec command, (error, stdout, stderr)->
expect(error, "smoke test: error returned in getting project list").to.not.exist
expect(!!stderr.match("200 OK"), "smoke test: response code is not 200 getting project list").to.equal true
expect(!!stdout.match("<title>Your Projects - .*, Online LaTeX Editor</title>"), "smoke test: body does not have correct title").to.equal true
expect(!!stdout.match("ProjectPageController"), "smoke test: body does not have correct angular controller").to.equal true
done()
|
[
{
"context": "ong = [\"do\", \"re\", \"mi\", \"fa\", \"so\"]\n\nsingers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n\nbitlist = [\n 1, 0, 1\n ",
"end": 295,
"score": 0.5069668889045715,
"start": 290,
"tag": "NAME",
"value": "agger"
},
{
"context": "0, 0, 1\n 1, 1, 0\n]\n\nkids =\n bro... | test/snippets.coffee | gkz/CoffeeCoffee | 1 | banner = (header) ->
console.log "******* #{header}"
########
banner "Functions"
fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
console.log fill "cup"
########
banner "Objects and Arrays"
song = ["do", "re", "mi", "fa", "so"]
singers = {Jagger: "Rock", Elvis: "Roll"}
bitlist = [
1, 0, 1
0, 0, 1
1, 1, 0
]
kids =
brother:
name: "Max"
age: 11
sister:
name: "Ida"
age: 9
console.log song.join " "
console.log kids.brother.name
#########
banner "Lexical Scoping"
outer = 1
changeNumbers = ->
inner = -1
outer = 10
inner = changeNumbers()
console.log inner
#########
banner "Splats"
gold = silver = rest = "unknown"
awardMedals = (first, second, others...) ->
gold = first
silver = second
rest = others
contenders = [
"Michael Phelps"
"Liu Xiang"
"Yao Ming"
"Allyson Felix"
"Shawn Johnson"
"Roman Sebrle"
"Guo Jingjing"
"Tyson Gay"
"Asafa Powell"
"Usain Bolt"
]
awardMedals contenders...
console.log "Gold: " + gold
console.log "Silver: " + silver
console.log "The Field: " + rest
#########
banner "Loops and Comprehensions"
countdown = (num for num in [10..1])
console.log countdown
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
console.log ages
# Nursery Rhyme
num = 6
lyrics = while num -= 1
"#{num} little monkeys, jumping on the bed.
One fell out and bumped his head."
console.log lyrics
###########
banner "Slicing and Splicing"
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
copy = numbers[0...numbers.length]
middle = copy[3..6]
console.log middle
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]
console.log numbers
###########
banner "Everything is an Expression"
eldest = if 24 > 21 then "Liz" else "Ike"
console.log eldest
six = (one = 1) + (two = 2) + (three = 3)
console.log six
globals = (name for name of root)[0...10]
console.log globals
console.log(
try
nonexistent / undefined
catch error
"And the error is ... #{error}"
)
###########
banner "The Existential Operator"
footprints = yeti ? "bear"
console.log footprints
###########
banner "Classes, Inheritance, and Super"
class Animal
constructor: (@name) ->
move: (meters) ->
console.log @name + " moved #{meters}m."
class Snake extends Animal
move: ->
console.log "Slithering..."
super 5
class Horse extends Animal
move: ->
console.log "Galloping..."
super 45
sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"
sam.move()
tom.move()
####
String::dasherize = ->
this.replace /_/g, "-"
console.log "one_two".dasherize()
###########
banner "Destructuring Assignment"
theBait = 1000
theSwitch = 0
[theBait, theSwitch] = [theSwitch, theBait]
console.log theBait
weatherReport = (location) ->
# Make an Ajax request to fetch the weather...
[location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"
console.log forecast
futurists =
sculptor: "Umberto Boccioni"
painter: "Vladimir Burliuk"
poet:
name: "F.T. Marinetti"
address: [
"Via Roma 42R"
"Bellagio, Italy 22021"
]
{poet: {name, address: [street, city]}} = futurists
console.log name + '-' + street
# splats
tag = "<impossible>"
[open, contents..., close] = tag.split("")
console.log contents.join ''
#############
banner "Function Binding"
class Button
click: (@f) ->
do_click: -> @f.apply(@)
button = new Button
class Account
constructor: (@customer) ->
button.click =>
console.log @customer
account = new Account("alice")
button.do_click()
##############
banner "Switch/When/Else"
f = (day) ->
long_name = switch day
when "Mon" then "Monday"
when "Tue" then "Tuesday"
else "no match"
console.log long_name
f "Mon"
f "Tue"
f "Wed"
#############
banner "Try/Catch/Finally"
f = (n) ->
try
if n == 1
throw "1 leads to exception"
console.log n
catch error
console.log error
finally
console.log "finally"
f(1)
f(2)
#############
banner "Chained Comparisons"
cholesterol = 127
healthy = 200 > cholesterol > 60
console.log healthy
############
banner "String Interpolation, Heredocs, and Block Comments"
sentence = "#{ 22 / 7 } is a decent approximation of π"
console.log sentence
mobyDick = "Call me Ishmael. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world..."
console.log mobyDick
html = '''
<strong>
cup of coffeescript
</strong>
'''
console.log html
#########
banner "Misc: bare classes and instanceof, etc."
class C
class D
c = new C
console.log c instanceof C
console.log !(c instanceof D)
console.log C not instanceof D
console.log typeof "x"
console.log true, on, yes
console.log !false, !off, not no
console.log 4 is 4, 4 isnt 5
console.log true and true, true or false
console.log "x" of {x: 0}, "y" not of {x: 0}
console.log 1 in [1,2], 3 not in [1,2]
console.log !("x".foo?.bar.whatever)?
console.log 5 == ~~5
console.log 27 % 10 == 7
console.log 3 >=3 and 4 >=3 and 3 <= 3 and 3 <= 4
console.log 5 << 2 == 20 and 15 >> 1 == 7 and 15 >>> 1 == 7
console.log (5 | 2) == 7 and (5 & 4) == 4 and (5 ^ 4) == (4 ^ 5)
x = 5
console.log ++x == 6, --x == 5
########
banner "break and continue"
for i in [0..10]
continue if i % 2 == 0
console.log i
break if i == 5
i = 0
while true
i += 1
continue if i % 2 == 0
console.log i
break if i == 5
| 131571 | banner = (header) ->
console.log "******* #{header}"
########
banner "Functions"
fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
console.log fill "cup"
########
banner "Objects and Arrays"
song = ["do", "re", "mi", "fa", "so"]
singers = {J<NAME>: "Rock", Elvis: "Roll"}
bitlist = [
1, 0, 1
0, 0, 1
1, 1, 0
]
kids =
brother:
name: "<NAME>"
age: 11
sister:
name: "<NAME>"
age: 9
console.log song.join " "
console.log kids.brother.name
#########
banner "Lexical Scoping"
outer = 1
changeNumbers = ->
inner = -1
outer = 10
inner = changeNumbers()
console.log inner
#########
banner "Splats"
gold = silver = rest = "unknown"
awardMedals = (first, second, others...) ->
gold = first
silver = second
rest = others
contenders = [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
awardMedals contenders...
console.log "Gold: " + gold
console.log "Silver: " + silver
console.log "The Field: " + rest
#########
banner "Loops and Comprehensions"
countdown = (num for num in [10..1])
console.log countdown
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
console.log ages
# Nursery Rhyme
num = 6
lyrics = while num -= 1
"#{num} little monkeys, jumping on the bed.
One fell out and bumped his head."
console.log lyrics
###########
banner "Slicing and Splicing"
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
copy = numbers[0...numbers.length]
middle = copy[3..6]
console.log middle
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]
console.log numbers
###########
banner "Everything is an Expression"
eldest = if 24 > 21 then "Liz" else "Ike"
console.log eldest
six = (one = 1) + (two = 2) + (three = 3)
console.log six
globals = (name for name of root)[0...10]
console.log globals
console.log(
try
nonexistent / undefined
catch error
"And the error is ... #{error}"
)
###########
banner "The Existential Operator"
footprints = yeti ? "bear"
console.log footprints
###########
banner "Classes, Inheritance, and Super"
class Animal
constructor: (@name) ->
move: (meters) ->
console.log @name + " moved #{meters}m."
class Snake extends Animal
move: ->
console.log "Slithering..."
super 5
class Horse extends Animal
move: ->
console.log "Galloping..."
super 45
sam = new Snake "<NAME>"
tom = new Horse "<NAME>"
sam.move()
tom.move()
####
String::dasherize = ->
this.replace /_/g, "-"
console.log "one_two".dasherize()
###########
banner "Destructuring Assignment"
theBait = 1000
theSwitch = 0
[theBait, theSwitch] = [theSwitch, theBait]
console.log theBait
weatherReport = (location) ->
# Make an Ajax request to fetch the weather...
[location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"
console.log forecast
futurists =
sculptor: "<NAME>"
painter: "<NAME>"
poet:
name: "<NAME>"
address: [
"Via Roma 42R"
"Bellagio, Italy 22021"
]
{poet: {name, address: [street, city]}} = futurists
console.log name + '-' + street
# splats
tag = "<impossible>"
[open, contents..., close] = tag.split("")
console.log contents.join ''
#############
banner "Function Binding"
class Button
click: (@f) ->
do_click: -> @f.apply(@)
button = new Button
class Account
constructor: (@customer) ->
button.click =>
console.log @customer
account = new Account("<NAME>")
button.do_click()
##############
banner "Switch/When/Else"
f = (day) ->
long_name = switch day
when "Mon" then "Monday"
when "Tue" then "Tuesday"
else "no match"
console.log long_name
f "Mon"
f "Tue"
f "Wed"
#############
banner "Try/Catch/Finally"
f = (n) ->
try
if n == 1
throw "1 leads to exception"
console.log n
catch error
console.log error
finally
console.log "finally"
f(1)
f(2)
#############
banner "Chained Comparisons"
cholesterol = 127
healthy = 200 > cholesterol > 60
console.log healthy
############
banner "String Interpolation, Heredocs, and Block Comments"
sentence = "#{ 22 / 7 } is a decent approximation of π"
console.log sentence
mobyDick = "Call me <NAME>. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world..."
console.log mobyDick
html = '''
<strong>
cup of coffeescript
</strong>
'''
console.log html
#########
banner "Misc: bare classes and instanceof, etc."
class C
class D
c = new C
console.log c instanceof C
console.log !(c instanceof D)
console.log C not instanceof D
console.log typeof "x"
console.log true, on, yes
console.log !false, !off, not no
console.log 4 is 4, 4 isnt 5
console.log true and true, true or false
console.log "x" of {x: 0}, "y" not of {x: 0}
console.log 1 in [1,2], 3 not in [1,2]
console.log !("x".foo?.bar.whatever)?
console.log 5 == ~~5
console.log 27 % 10 == 7
console.log 3 >=3 and 4 >=3 and 3 <= 3 and 3 <= 4
console.log 5 << 2 == 20 and 15 >> 1 == 7 and 15 >>> 1 == 7
console.log (5 | 2) == 7 and (5 & 4) == 4 and (5 ^ 4) == (4 ^ 5)
x = 5
console.log ++x == 6, --x == 5
########
banner "break and continue"
for i in [0..10]
continue if i % 2 == 0
console.log i
break if i == 5
i = 0
while true
i += 1
continue if i % 2 == 0
console.log i
break if i == 5
| true | banner = (header) ->
console.log "******* #{header}"
########
banner "Functions"
fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
console.log fill "cup"
########
banner "Objects and Arrays"
song = ["do", "re", "mi", "fa", "so"]
singers = {JPI:NAME:<NAME>END_PI: "Rock", Elvis: "Roll"}
bitlist = [
1, 0, 1
0, 0, 1
1, 1, 0
]
kids =
brother:
name: "PI:NAME:<NAME>END_PI"
age: 11
sister:
name: "PI:NAME:<NAME>END_PI"
age: 9
console.log song.join " "
console.log kids.brother.name
#########
banner "Lexical Scoping"
outer = 1
changeNumbers = ->
inner = -1
outer = 10
inner = changeNumbers()
console.log inner
#########
banner "Splats"
gold = silver = rest = "unknown"
awardMedals = (first, second, others...) ->
gold = first
silver = second
rest = others
contenders = [
"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"
"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"
]
awardMedals contenders...
console.log "Gold: " + gold
console.log "Silver: " + silver
console.log "The Field: " + rest
#########
banner "Loops and Comprehensions"
countdown = (num for num in [10..1])
console.log countdown
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
console.log ages
# Nursery Rhyme
num = 6
lyrics = while num -= 1
"#{num} little monkeys, jumping on the bed.
One fell out and bumped his head."
console.log lyrics
###########
banner "Slicing and Splicing"
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
copy = numbers[0...numbers.length]
middle = copy[3..6]
console.log middle
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]
console.log numbers
###########
banner "Everything is an Expression"
eldest = if 24 > 21 then "Liz" else "Ike"
console.log eldest
six = (one = 1) + (two = 2) + (three = 3)
console.log six
globals = (name for name of root)[0...10]
console.log globals
console.log(
try
nonexistent / undefined
catch error
"And the error is ... #{error}"
)
###########
banner "The Existential Operator"
footprints = yeti ? "bear"
console.log footprints
###########
banner "Classes, Inheritance, and Super"
class Animal
constructor: (@name) ->
move: (meters) ->
console.log @name + " moved #{meters}m."
class Snake extends Animal
move: ->
console.log "Slithering..."
super 5
class Horse extends Animal
move: ->
console.log "Galloping..."
super 45
sam = new Snake "PI:NAME:<NAME>END_PI"
tom = new Horse "PI:NAME:<NAME>END_PI"
sam.move()
tom.move()
####
String::dasherize = ->
this.replace /_/g, "-"
console.log "one_two".dasherize()
###########
banner "Destructuring Assignment"
theBait = 1000
theSwitch = 0
[theBait, theSwitch] = [theSwitch, theBait]
console.log theBait
weatherReport = (location) ->
# Make an Ajax request to fetch the weather...
[location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"
console.log forecast
futurists =
sculptor: "PI:NAME:<NAME>END_PI"
painter: "PI:NAME:<NAME>END_PI"
poet:
name: "PI:NAME:<NAME>END_PI"
address: [
"Via Roma 42R"
"Bellagio, Italy 22021"
]
{poet: {name, address: [street, city]}} = futurists
console.log name + '-' + street
# splats
tag = "<impossible>"
[open, contents..., close] = tag.split("")
console.log contents.join ''
#############
banner "Function Binding"
class Button
click: (@f) ->
do_click: -> @f.apply(@)
button = new Button
class Account
constructor: (@customer) ->
button.click =>
console.log @customer
account = new Account("PI:NAME:<NAME>END_PI")
button.do_click()
##############
banner "Switch/When/Else"
f = (day) ->
long_name = switch day
when "Mon" then "Monday"
when "Tue" then "Tuesday"
else "no match"
console.log long_name
f "Mon"
f "Tue"
f "Wed"
#############
banner "Try/Catch/Finally"
f = (n) ->
try
if n == 1
throw "1 leads to exception"
console.log n
catch error
console.log error
finally
console.log "finally"
f(1)
f(2)
#############
banner "Chained Comparisons"
cholesterol = 127
healthy = 200 > cholesterol > 60
console.log healthy
############
banner "String Interpolation, Heredocs, and Block Comments"
sentence = "#{ 22 / 7 } is a decent approximation of π"
console.log sentence
mobyDick = "Call me PI:NAME:<NAME>END_PI. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world..."
console.log mobyDick
html = '''
<strong>
cup of coffeescript
</strong>
'''
console.log html
#########
banner "Misc: bare classes and instanceof, etc."
class C
class D
c = new C
console.log c instanceof C
console.log !(c instanceof D)
console.log C not instanceof D
console.log typeof "x"
console.log true, on, yes
console.log !false, !off, not no
console.log 4 is 4, 4 isnt 5
console.log true and true, true or false
console.log "x" of {x: 0}, "y" not of {x: 0}
console.log 1 in [1,2], 3 not in [1,2]
console.log !("x".foo?.bar.whatever)?
console.log 5 == ~~5
console.log 27 % 10 == 7
console.log 3 >=3 and 4 >=3 and 3 <= 3 and 3 <= 4
console.log 5 << 2 == 20 and 15 >> 1 == 7 and 15 >>> 1 == 7
console.log (5 | 2) == 7 and (5 & 4) == 4 and (5 ^ 4) == (4 ^ 5)
x = 5
console.log ++x == 6, --x == 5
########
banner "break and continue"
for i in [0..10]
continue if i % 2 == 0
console.log i
break if i == 5
i = 0
while true
i += 1
continue if i % 2 == 0
console.log i
break if i == 5
|
[
{
"context": "etUser\",\n include_docs: true\n key: Coconut.currentUser.get(\"_id\")\n .catch (error) =>\n @log \"Could not ret",
"end": 7801,
"score": 0.8030872344970703,
"start": 7778,
"tag": "KEY",
"value": "ut.currentUser.get(\"_id"
}
] | _attachments/SyncPlugins.coffee | ICTatRTI/coconut-mobile-plugin-zanzibar | 0 | Dialog = require './js-libraries/modal-dialog'
Sync::getFromCloud = (options) ->
$("#status").html "Getting data..."
@fetch
error: (error) =>
@log "Unable to fetch Sync doc: #{JSON.stringify(error)}"
options?.error?(error)
success: =>
Coconut.checkForInternet
error: (error)->
@save
last_send_error: true
options?.error?(error)
Coconut.noInternet()
success: =>
@fetch
success: =>
$("#status").html "Updating users and forms. Please wait."
@replicateApplicationDocs
error: (error) =>
@log "ERROR updating application: #{JSON.stringify(error)}"
@save
last_get_success: false
options?.error?(error)
success: =>
$("#status").html "Getting new notifications..."
@getNewNotifications
success: =>
@transferCasesIn()
.catch (error) => @log error
.then =>
@fetch
error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}"
success: =>
@save
last_get_success: true
last_get_time: new Date().getTime()
options?.success?()
Sync::getNewNotifications = (options) ->
new Promise (resolve, reject) =>
@log "Looking for most recent Case Notification on device. Please wait."
Coconut.database.query "rawNotificationsConvertedToCaseNotifications",
descending: true
include_docs: true
limit: 1
.catch (error) => @log "Unable to find the the most recent case notification: #{JSON.stringify(error)}"
.then (result) =>
mostRecentNotification = result.rows?[0]?.doc.date
if mostRecentNotification? and moment(mostRecentNotification).isBefore((new moment).subtract(3,'weeks'))
dateToStartLooking = mostRecentNotification
else
dateToStartLooking = (new moment).subtract(3,'months').format(Coconut.config.get("date_format"))
@log "Looking for USSD notifications without Case Notifications after #{dateToStartLooking}. Please wait."
Coconut.cloudDB.query "rawNotificationsNotConvertedToCaseNotifications",
include_docs: true
startkey: dateToStartLooking
skip: 1
.catch (error) => @log "ERROR, could not download USSD notifications: #{JSON.stringify error}"
.then (result) =>
currentUserDistricts = Coconut.currentUser.get("district") or []
# Make sure district is valid (shouldn't be necessary)
currentUserDistricts = for district in currentUserDistricts
GeoHierarchy.findFirst(district, "DISTRICT")?.name or alert "Invalid district #{district} for #{JSON.stringify Coconut.currentUser}"
@log "Found #{result.rows?.length} USSD notifications. Filtering for USSD notifications for district(s): #{currentUserDistricts}. Please wait."
acceptedNotificationIds = []
for row in result.rows
notification = row.doc
districtForNotification = notification.facility_district
districtForNotification = GeoHierarchy.findFirst(districtForNotification, "DISTRICT")?.name or alert "Invalid district for notification: #{districtForNotification}\n#{JSON.stringify notification}"
# Try and fix shehia, district and facility names. Use levenshein distance
unless _(GeoHierarchy.allDistricts()).contains districtForNotification
@log "#{districtForNotification} not valid district, trying to use health facility: #{notification.hf} to identify district"
if GeoHierarchy.getDistrict(notification.hf)?
districtForNotification = GeoHierarchy.getDistrict(notification.hf)
@log "Using district: #{districtForNotification} indicated by health facility."
else
@log "Can't find a valid district for health facility: #{notification.hf}"
# Check it again
unless _(GeoHierarchy.allDistricts()).contains districtForNotification
@log "#{districtForNotification} still not valid district, trying to use shehia name to identify district: #{notification.shehia}"
if GeoHierarchy.findOneShehia(notification.shehia)?
districtForNotification = GeoHierarchy.findOneShehia(notification.shehia).DISTRCT
@log "Using district: #{districtForNotification} indicated by shehia."
else
@log "Can't find a valid district using shehia for notification: #{JSON.stringify notification}."
if _(currentUserDistricts).contains districtForNotification
if confirm "Accept new case? Facility: #{notification.hf}, Shehia: #{notification.shehia}, District: #{districtForNotification}, Name: #{notification.name}, ID: #{notification.caseid}, date: #{notification.date}. You may need to coordinate with another DMSO."
acceptedNotificationIds.push(notification._id)
@log "Case notification #{notification.caseid}, accepted by #{Coconut.currentUser.username()}"
else
@log "Case notification #{notification.caseid}, not accepted by #{Coconut.currentUser.username()}"
@convertNotificationsToCaseNotification(acceptedNotificationIds).then =>
options.success?()
Sync::convertNotificationsToCaseNotification = (acceptedNotificationIds) ->
new Promise (resolve, reject) =>
console.log "Accepted: #{acceptedNotificationIds.join(',')}"
return resolve() if _(acceptedNotificationIds).isEmpty()
newCaseNotificationIds = []
for notificationId in acceptedNotificationIds
await Coconut.cloudDB.get notificationId
.then (notification) =>
result = new Result
question: "Case Notification"
MalariaCaseID: notification.caseid
DistrictForFacility: notification.facility_district
FacilityName: notification.hf
Shehia: notification.shehia
Name: notification.name
NotificationDocumentID: notificationId
result.save()
.catch (error) =>
@log "Could not save #{result.toJSON()}: #{JSON.stringify error}"
.then =>
notification.hasCaseNotification = true
notification.caseNotification = result.get "_id"
Coconut.cloudDB.put notification
.catch (error) =>
alert "Error marking notification as accepted (someone else may have accepted it), canceling acceptance of case #{notification.caseid}"
result.destroy() #Ideally would use callbacks or promises here but they don't work well
.then =>
newCaseNotificationIds.push result.get "_id"
Coconut.database.replicate.to Coconut.cloudDB,
doc_ids: newCaseNotificationIds
.catch (error) =>
@log "Error replicating #{newCaseNotificationIds} back to server: #{JSON.stringify error}"
.then (result) =>
@log "Sent docs: #{newCaseNotificationIds}"
@save
last_send_result: result
last_send_error: false
last_send_time: new Date().getTime()
resolve()
Sync::transferCasesIn = (options) ->
console.error "callback for transferCasesIn will be deprecated" if options?
new Promise (resolve, reject) =>
$("#status").html "Checking for transfer cases..."
@log "Checking cloud server for cases transferred to #{Coconut.currentUser.username()}"
Coconut.cloudDB.query "resultsAndNotificationsNotReceivedByTargetUser",
include_docs: true
key: Coconut.currentUser.get("_id")
.catch (error) =>
@log "Could not retrieve list of resultsAndNotificationsNotReceivedByTargetUser for #{Coconut.currentUser.get("_id")}"
@log error
console.error error
options?.error(error)
@save
last_send_error: true
.then (result) =>
transferCases = {}
_(result.rows).each (row) ->
caseId = row.value[1]
(transferCases[caseId] ?= []).push row.doc
if _(transferCases).isEmpty()
@log "No cases to transfer."
options?.success()
return resolve()
for caseID, caseResultDocs of transferCases
transferCase = new Case()
transferCase.loadFromResultDocs(caseResultDocs)
console.log transferCase
console.log "ZZZZ"
caseId = transferCase.MalariaCaseID()
if confirm "Accept transfer case #{caseId} #{transferCase.indexCasePatientName()} from facility #{transferCase.facility()} in #{transferCase.district()}?"
# Due to bug that breaks replication for crypto pouch documents when they are replicated in, edited and replicated back, we have to (see failCrypto.coffee)
#
# 1. Delete them on the cloud database
# 2. Create new docs without _rev numbers (this is the workaround hack which forces replication)
# 3. Add the transfered information
# 4. Save them as new local documents
# 5. Replicate them to the cloud database
caseResultIds = _(caseResultDocs).pluck "_id"
result = await Coconut.cloudDB.allDocs
keys: caseResultIds
include_docs: true
.catch (error) => console.error error
docsToSave = for row in result.rows
await Coconut.cloudDB.remove(row.doc) #1
delete row.doc._rev #2
row.doc.transferred[row.doc.transferred.length - 1].received = true #3
row.doc
await Coconut.database.bulkDocs docsToSave
.catch (error) => console.error error
await Coconut.database.replicate.to Coconut.cloudDB,
doc_ids: caseResultIds
.catch (error) =>
console.error error
@log "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
throw "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
options?.success()
resolve()
###
await Coconut.cloudDB.replicate.to Coconut.database,
doc_ids: caseResultIds
.catch (error) =>
console.error error
@log "Failed to replicate from cloud a transfered case: #{transferCase.MalariaCaseID()}"
throw "Failed to replicate from cloud a transfered case: #{transferCase.MalariaCaseID()}"
.then =>
for caseResultId in caseResultIds
await Coconut.database.upsert caseResultId, (caseResultDoc) =>
caseResultDoc.transferred[caseResultDoc.transferred.length - 1].received = true
caseResultDoc
Coconut.cloudDB.replicate.from Coconut.database,
doc_ids: caseResultIds
.catch (error) =>
console.error error
@log "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
throw "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
.then (replicationResult) =>
console.log replicationResult
@log "#{caseId} (#{caseResultIds.join()}): saved on device and updated in cloud"
Promise.resolve()
###
| 117434 | Dialog = require './js-libraries/modal-dialog'
Sync::getFromCloud = (options) ->
$("#status").html "Getting data..."
@fetch
error: (error) =>
@log "Unable to fetch Sync doc: #{JSON.stringify(error)}"
options?.error?(error)
success: =>
Coconut.checkForInternet
error: (error)->
@save
last_send_error: true
options?.error?(error)
Coconut.noInternet()
success: =>
@fetch
success: =>
$("#status").html "Updating users and forms. Please wait."
@replicateApplicationDocs
error: (error) =>
@log "ERROR updating application: #{JSON.stringify(error)}"
@save
last_get_success: false
options?.error?(error)
success: =>
$("#status").html "Getting new notifications..."
@getNewNotifications
success: =>
@transferCasesIn()
.catch (error) => @log error
.then =>
@fetch
error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}"
success: =>
@save
last_get_success: true
last_get_time: new Date().getTime()
options?.success?()
Sync::getNewNotifications = (options) ->
new Promise (resolve, reject) =>
@log "Looking for most recent Case Notification on device. Please wait."
Coconut.database.query "rawNotificationsConvertedToCaseNotifications",
descending: true
include_docs: true
limit: 1
.catch (error) => @log "Unable to find the the most recent case notification: #{JSON.stringify(error)}"
.then (result) =>
mostRecentNotification = result.rows?[0]?.doc.date
if mostRecentNotification? and moment(mostRecentNotification).isBefore((new moment).subtract(3,'weeks'))
dateToStartLooking = mostRecentNotification
else
dateToStartLooking = (new moment).subtract(3,'months').format(Coconut.config.get("date_format"))
@log "Looking for USSD notifications without Case Notifications after #{dateToStartLooking}. Please wait."
Coconut.cloudDB.query "rawNotificationsNotConvertedToCaseNotifications",
include_docs: true
startkey: dateToStartLooking
skip: 1
.catch (error) => @log "ERROR, could not download USSD notifications: #{JSON.stringify error}"
.then (result) =>
currentUserDistricts = Coconut.currentUser.get("district") or []
# Make sure district is valid (shouldn't be necessary)
currentUserDistricts = for district in currentUserDistricts
GeoHierarchy.findFirst(district, "DISTRICT")?.name or alert "Invalid district #{district} for #{JSON.stringify Coconut.currentUser}"
@log "Found #{result.rows?.length} USSD notifications. Filtering for USSD notifications for district(s): #{currentUserDistricts}. Please wait."
acceptedNotificationIds = []
for row in result.rows
notification = row.doc
districtForNotification = notification.facility_district
districtForNotification = GeoHierarchy.findFirst(districtForNotification, "DISTRICT")?.name or alert "Invalid district for notification: #{districtForNotification}\n#{JSON.stringify notification}"
# Try and fix shehia, district and facility names. Use levenshein distance
unless _(GeoHierarchy.allDistricts()).contains districtForNotification
@log "#{districtForNotification} not valid district, trying to use health facility: #{notification.hf} to identify district"
if GeoHierarchy.getDistrict(notification.hf)?
districtForNotification = GeoHierarchy.getDistrict(notification.hf)
@log "Using district: #{districtForNotification} indicated by health facility."
else
@log "Can't find a valid district for health facility: #{notification.hf}"
# Check it again
unless _(GeoHierarchy.allDistricts()).contains districtForNotification
@log "#{districtForNotification} still not valid district, trying to use shehia name to identify district: #{notification.shehia}"
if GeoHierarchy.findOneShehia(notification.shehia)?
districtForNotification = GeoHierarchy.findOneShehia(notification.shehia).DISTRCT
@log "Using district: #{districtForNotification} indicated by shehia."
else
@log "Can't find a valid district using shehia for notification: #{JSON.stringify notification}."
if _(currentUserDistricts).contains districtForNotification
if confirm "Accept new case? Facility: #{notification.hf}, Shehia: #{notification.shehia}, District: #{districtForNotification}, Name: #{notification.name}, ID: #{notification.caseid}, date: #{notification.date}. You may need to coordinate with another DMSO."
acceptedNotificationIds.push(notification._id)
@log "Case notification #{notification.caseid}, accepted by #{Coconut.currentUser.username()}"
else
@log "Case notification #{notification.caseid}, not accepted by #{Coconut.currentUser.username()}"
@convertNotificationsToCaseNotification(acceptedNotificationIds).then =>
options.success?()
Sync::convertNotificationsToCaseNotification = (acceptedNotificationIds) ->
new Promise (resolve, reject) =>
console.log "Accepted: #{acceptedNotificationIds.join(',')}"
return resolve() if _(acceptedNotificationIds).isEmpty()
newCaseNotificationIds = []
for notificationId in acceptedNotificationIds
await Coconut.cloudDB.get notificationId
.then (notification) =>
result = new Result
question: "Case Notification"
MalariaCaseID: notification.caseid
DistrictForFacility: notification.facility_district
FacilityName: notification.hf
Shehia: notification.shehia
Name: notification.name
NotificationDocumentID: notificationId
result.save()
.catch (error) =>
@log "Could not save #{result.toJSON()}: #{JSON.stringify error}"
.then =>
notification.hasCaseNotification = true
notification.caseNotification = result.get "_id"
Coconut.cloudDB.put notification
.catch (error) =>
alert "Error marking notification as accepted (someone else may have accepted it), canceling acceptance of case #{notification.caseid}"
result.destroy() #Ideally would use callbacks or promises here but they don't work well
.then =>
newCaseNotificationIds.push result.get "_id"
Coconut.database.replicate.to Coconut.cloudDB,
doc_ids: newCaseNotificationIds
.catch (error) =>
@log "Error replicating #{newCaseNotificationIds} back to server: #{JSON.stringify error}"
.then (result) =>
@log "Sent docs: #{newCaseNotificationIds}"
@save
last_send_result: result
last_send_error: false
last_send_time: new Date().getTime()
resolve()
Sync::transferCasesIn = (options) ->
console.error "callback for transferCasesIn will be deprecated" if options?
new Promise (resolve, reject) =>
$("#status").html "Checking for transfer cases..."
@log "Checking cloud server for cases transferred to #{Coconut.currentUser.username()}"
Coconut.cloudDB.query "resultsAndNotificationsNotReceivedByTargetUser",
include_docs: true
key: Cocon<KEY>")
.catch (error) =>
@log "Could not retrieve list of resultsAndNotificationsNotReceivedByTargetUser for #{Coconut.currentUser.get("_id")}"
@log error
console.error error
options?.error(error)
@save
last_send_error: true
.then (result) =>
transferCases = {}
_(result.rows).each (row) ->
caseId = row.value[1]
(transferCases[caseId] ?= []).push row.doc
if _(transferCases).isEmpty()
@log "No cases to transfer."
options?.success()
return resolve()
for caseID, caseResultDocs of transferCases
transferCase = new Case()
transferCase.loadFromResultDocs(caseResultDocs)
console.log transferCase
console.log "ZZZZ"
caseId = transferCase.MalariaCaseID()
if confirm "Accept transfer case #{caseId} #{transferCase.indexCasePatientName()} from facility #{transferCase.facility()} in #{transferCase.district()}?"
# Due to bug that breaks replication for crypto pouch documents when they are replicated in, edited and replicated back, we have to (see failCrypto.coffee)
#
# 1. Delete them on the cloud database
# 2. Create new docs without _rev numbers (this is the workaround hack which forces replication)
# 3. Add the transfered information
# 4. Save them as new local documents
# 5. Replicate them to the cloud database
caseResultIds = _(caseResultDocs).pluck "_id"
result = await Coconut.cloudDB.allDocs
keys: caseResultIds
include_docs: true
.catch (error) => console.error error
docsToSave = for row in result.rows
await Coconut.cloudDB.remove(row.doc) #1
delete row.doc._rev #2
row.doc.transferred[row.doc.transferred.length - 1].received = true #3
row.doc
await Coconut.database.bulkDocs docsToSave
.catch (error) => console.error error
await Coconut.database.replicate.to Coconut.cloudDB,
doc_ids: caseResultIds
.catch (error) =>
console.error error
@log "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
throw "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
options?.success()
resolve()
###
await Coconut.cloudDB.replicate.to Coconut.database,
doc_ids: caseResultIds
.catch (error) =>
console.error error
@log "Failed to replicate from cloud a transfered case: #{transferCase.MalariaCaseID()}"
throw "Failed to replicate from cloud a transfered case: #{transferCase.MalariaCaseID()}"
.then =>
for caseResultId in caseResultIds
await Coconut.database.upsert caseResultId, (caseResultDoc) =>
caseResultDoc.transferred[caseResultDoc.transferred.length - 1].received = true
caseResultDoc
Coconut.cloudDB.replicate.from Coconut.database,
doc_ids: caseResultIds
.catch (error) =>
console.error error
@log "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
throw "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
.then (replicationResult) =>
console.log replicationResult
@log "#{caseId} (#{caseResultIds.join()}): saved on device and updated in cloud"
Promise.resolve()
###
| true | Dialog = require './js-libraries/modal-dialog'
Sync::getFromCloud = (options) ->
$("#status").html "Getting data..."
@fetch
error: (error) =>
@log "Unable to fetch Sync doc: #{JSON.stringify(error)}"
options?.error?(error)
success: =>
Coconut.checkForInternet
error: (error)->
@save
last_send_error: true
options?.error?(error)
Coconut.noInternet()
success: =>
@fetch
success: =>
$("#status").html "Updating users and forms. Please wait."
@replicateApplicationDocs
error: (error) =>
@log "ERROR updating application: #{JSON.stringify(error)}"
@save
last_get_success: false
options?.error?(error)
success: =>
$("#status").html "Getting new notifications..."
@getNewNotifications
success: =>
@transferCasesIn()
.catch (error) => @log error
.then =>
@fetch
error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}"
success: =>
@save
last_get_success: true
last_get_time: new Date().getTime()
options?.success?()
Sync::getNewNotifications = (options) ->
new Promise (resolve, reject) =>
@log "Looking for most recent Case Notification on device. Please wait."
Coconut.database.query "rawNotificationsConvertedToCaseNotifications",
descending: true
include_docs: true
limit: 1
.catch (error) => @log "Unable to find the the most recent case notification: #{JSON.stringify(error)}"
.then (result) =>
mostRecentNotification = result.rows?[0]?.doc.date
if mostRecentNotification? and moment(mostRecentNotification).isBefore((new moment).subtract(3,'weeks'))
dateToStartLooking = mostRecentNotification
else
dateToStartLooking = (new moment).subtract(3,'months').format(Coconut.config.get("date_format"))
@log "Looking for USSD notifications without Case Notifications after #{dateToStartLooking}. Please wait."
Coconut.cloudDB.query "rawNotificationsNotConvertedToCaseNotifications",
include_docs: true
startkey: dateToStartLooking
skip: 1
.catch (error) => @log "ERROR, could not download USSD notifications: #{JSON.stringify error}"
.then (result) =>
currentUserDistricts = Coconut.currentUser.get("district") or []
# Make sure district is valid (shouldn't be necessary)
currentUserDistricts = for district in currentUserDistricts
GeoHierarchy.findFirst(district, "DISTRICT")?.name or alert "Invalid district #{district} for #{JSON.stringify Coconut.currentUser}"
@log "Found #{result.rows?.length} USSD notifications. Filtering for USSD notifications for district(s): #{currentUserDistricts}. Please wait."
acceptedNotificationIds = []
for row in result.rows
notification = row.doc
districtForNotification = notification.facility_district
districtForNotification = GeoHierarchy.findFirst(districtForNotification, "DISTRICT")?.name or alert "Invalid district for notification: #{districtForNotification}\n#{JSON.stringify notification}"
# Try and fix shehia, district and facility names. Use levenshein distance
unless _(GeoHierarchy.allDistricts()).contains districtForNotification
@log "#{districtForNotification} not valid district, trying to use health facility: #{notification.hf} to identify district"
if GeoHierarchy.getDistrict(notification.hf)?
districtForNotification = GeoHierarchy.getDistrict(notification.hf)
@log "Using district: #{districtForNotification} indicated by health facility."
else
@log "Can't find a valid district for health facility: #{notification.hf}"
# Check it again
unless _(GeoHierarchy.allDistricts()).contains districtForNotification
@log "#{districtForNotification} still not valid district, trying to use shehia name to identify district: #{notification.shehia}"
if GeoHierarchy.findOneShehia(notification.shehia)?
districtForNotification = GeoHierarchy.findOneShehia(notification.shehia).DISTRCT
@log "Using district: #{districtForNotification} indicated by shehia."
else
@log "Can't find a valid district using shehia for notification: #{JSON.stringify notification}."
if _(currentUserDistricts).contains districtForNotification
if confirm "Accept new case? Facility: #{notification.hf}, Shehia: #{notification.shehia}, District: #{districtForNotification}, Name: #{notification.name}, ID: #{notification.caseid}, date: #{notification.date}. You may need to coordinate with another DMSO."
acceptedNotificationIds.push(notification._id)
@log "Case notification #{notification.caseid}, accepted by #{Coconut.currentUser.username()}"
else
@log "Case notification #{notification.caseid}, not accepted by #{Coconut.currentUser.username()}"
@convertNotificationsToCaseNotification(acceptedNotificationIds).then =>
options.success?()
Sync::convertNotificationsToCaseNotification = (acceptedNotificationIds) ->
new Promise (resolve, reject) =>
console.log "Accepted: #{acceptedNotificationIds.join(',')}"
return resolve() if _(acceptedNotificationIds).isEmpty()
newCaseNotificationIds = []
for notificationId in acceptedNotificationIds
await Coconut.cloudDB.get notificationId
.then (notification) =>
result = new Result
question: "Case Notification"
MalariaCaseID: notification.caseid
DistrictForFacility: notification.facility_district
FacilityName: notification.hf
Shehia: notification.shehia
Name: notification.name
NotificationDocumentID: notificationId
result.save()
.catch (error) =>
@log "Could not save #{result.toJSON()}: #{JSON.stringify error}"
.then =>
notification.hasCaseNotification = true
notification.caseNotification = result.get "_id"
Coconut.cloudDB.put notification
.catch (error) =>
alert "Error marking notification as accepted (someone else may have accepted it), canceling acceptance of case #{notification.caseid}"
result.destroy() #Ideally would use callbacks or promises here but they don't work well
.then =>
newCaseNotificationIds.push result.get "_id"
Coconut.database.replicate.to Coconut.cloudDB,
doc_ids: newCaseNotificationIds
.catch (error) =>
@log "Error replicating #{newCaseNotificationIds} back to server: #{JSON.stringify error}"
.then (result) =>
@log "Sent docs: #{newCaseNotificationIds}"
@save
last_send_result: result
last_send_error: false
last_send_time: new Date().getTime()
resolve()
Sync::transferCasesIn = (options) ->
console.error "callback for transferCasesIn will be deprecated" if options?
new Promise (resolve, reject) =>
$("#status").html "Checking for transfer cases..."
@log "Checking cloud server for cases transferred to #{Coconut.currentUser.username()}"
Coconut.cloudDB.query "resultsAndNotificationsNotReceivedByTargetUser",
include_docs: true
key: CoconPI:KEY:<KEY>END_PI")
.catch (error) =>
@log "Could not retrieve list of resultsAndNotificationsNotReceivedByTargetUser for #{Coconut.currentUser.get("_id")}"
@log error
console.error error
options?.error(error)
@save
last_send_error: true
.then (result) =>
transferCases = {}
_(result.rows).each (row) ->
caseId = row.value[1]
(transferCases[caseId] ?= []).push row.doc
if _(transferCases).isEmpty()
@log "No cases to transfer."
options?.success()
return resolve()
for caseID, caseResultDocs of transferCases
transferCase = new Case()
transferCase.loadFromResultDocs(caseResultDocs)
console.log transferCase
console.log "ZZZZ"
caseId = transferCase.MalariaCaseID()
if confirm "Accept transfer case #{caseId} #{transferCase.indexCasePatientName()} from facility #{transferCase.facility()} in #{transferCase.district()}?"
# Due to bug that breaks replication for crypto pouch documents when they are replicated in, edited and replicated back, we have to (see failCrypto.coffee)
#
# 1. Delete them on the cloud database
# 2. Create new docs without _rev numbers (this is the workaround hack which forces replication)
# 3. Add the transfered information
# 4. Save them as new local documents
# 5. Replicate them to the cloud database
caseResultIds = _(caseResultDocs).pluck "_id"
result = await Coconut.cloudDB.allDocs
keys: caseResultIds
include_docs: true
.catch (error) => console.error error
docsToSave = for row in result.rows
await Coconut.cloudDB.remove(row.doc) #1
delete row.doc._rev #2
row.doc.transferred[row.doc.transferred.length - 1].received = true #3
row.doc
await Coconut.database.bulkDocs docsToSave
.catch (error) => console.error error
await Coconut.database.replicate.to Coconut.cloudDB,
doc_ids: caseResultIds
.catch (error) =>
console.error error
@log "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
throw "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
options?.success()
resolve()
###
await Coconut.cloudDB.replicate.to Coconut.database,
doc_ids: caseResultIds
.catch (error) =>
console.error error
@log "Failed to replicate from cloud a transfered case: #{transferCase.MalariaCaseID()}"
throw "Failed to replicate from cloud a transfered case: #{transferCase.MalariaCaseID()}"
.then =>
for caseResultId in caseResultIds
await Coconut.database.upsert caseResultId, (caseResultDoc) =>
caseResultDoc.transferred[caseResultDoc.transferred.length - 1].received = true
caseResultDoc
Coconut.cloudDB.replicate.from Coconut.database,
doc_ids: caseResultIds
.catch (error) =>
console.error error
@log "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
throw "Failed to replicate to cloud a transfered case: #{transferCase.MalariaCaseID()}"
.then (replicationResult) =>
console.log replicationResult
@log "#{caseId} (#{caseResultIds.join()}): saved on device and updated in cloud"
Promise.resolve()
###
|
[
{
"context": "'Start'\n\nmongoClient.connect 'mongodb://corkadmin:corkpassword@ds043190.mongolab.com:43190/birthday-corkboard', \n \n (err, db) ->\n\n ",
"end": 691,
"score": 0.9936500787734985,
"start": 657,
"tag": "EMAIL",
"value": "corkpassword@ds043190.mongolab.com"
}
] | server.coffee | eddnav/birthday-corkboard | 0 | mongoClient = require('mongodb').MongoClient
ObjectID = require('mongodb').ObjectID
express = require('express')
bodyParser = require('body-parser')
app = express()
app.use '/src', express.static __dirname + '/public/app/src/'
app.use '/element', express.static __dirname + '/public/element/'
app.use '/component', express.static __dirname + '/public/component/'
app.use '/css', express.static __dirname + '/public/app/css'
app.use '/img', express.static __dirname + '/public/app/img'
app.use '/js', express.static __dirname + '/public/app/js'
sendOptions = root: __dirname + '/public/app/'
console.log 'Start'
mongoClient.connect 'mongodb://corkadmin:corkpassword@ds043190.mongolab.com:43190/birthday-corkboard',
(err, db) ->
if not err
console.log 'Connected to mongo'
app.use bodyParser.json()
app.get '/', (req, res) ->
res.sendFile 'app.html', sendOptions
console.log 'App was served'
app.get '/birthdays', (req, res) ->
collection = db.collection 'birthdays'
options =
"sort": "birthday"
collection.find({}, options).toArray (err, birthdays) ->
res.format
json: ->
res.send(birthdays);
console.log 'Request fulfilled'
app.use (req, res) ->
res.sendFile '404.html', sendOptions
console.log 'Not found'
server = app.listen process.env.PORT or 5000, -> console.log 'Listening on port %d', server.address().port | 22706 | mongoClient = require('mongodb').MongoClient
ObjectID = require('mongodb').ObjectID
express = require('express')
bodyParser = require('body-parser')
app = express()
app.use '/src', express.static __dirname + '/public/app/src/'
app.use '/element', express.static __dirname + '/public/element/'
app.use '/component', express.static __dirname + '/public/component/'
app.use '/css', express.static __dirname + '/public/app/css'
app.use '/img', express.static __dirname + '/public/app/img'
app.use '/js', express.static __dirname + '/public/app/js'
sendOptions = root: __dirname + '/public/app/'
console.log 'Start'
mongoClient.connect 'mongodb://corkadmin:<EMAIL>:43190/birthday-corkboard',
(err, db) ->
if not err
console.log 'Connected to mongo'
app.use bodyParser.json()
app.get '/', (req, res) ->
res.sendFile 'app.html', sendOptions
console.log 'App was served'
app.get '/birthdays', (req, res) ->
collection = db.collection 'birthdays'
options =
"sort": "birthday"
collection.find({}, options).toArray (err, birthdays) ->
res.format
json: ->
res.send(birthdays);
console.log 'Request fulfilled'
app.use (req, res) ->
res.sendFile '404.html', sendOptions
console.log 'Not found'
server = app.listen process.env.PORT or 5000, -> console.log 'Listening on port %d', server.address().port | true | mongoClient = require('mongodb').MongoClient
ObjectID = require('mongodb').ObjectID
express = require('express')
bodyParser = require('body-parser')
app = express()
app.use '/src', express.static __dirname + '/public/app/src/'
app.use '/element', express.static __dirname + '/public/element/'
app.use '/component', express.static __dirname + '/public/component/'
app.use '/css', express.static __dirname + '/public/app/css'
app.use '/img', express.static __dirname + '/public/app/img'
app.use '/js', express.static __dirname + '/public/app/js'
sendOptions = root: __dirname + '/public/app/'
console.log 'Start'
mongoClient.connect 'mongodb://corkadmin:PI:EMAIL:<EMAIL>END_PI:43190/birthday-corkboard',
(err, db) ->
if not err
console.log 'Connected to mongo'
app.use bodyParser.json()
app.get '/', (req, res) ->
res.sendFile 'app.html', sendOptions
console.log 'App was served'
app.get '/birthdays', (req, res) ->
collection = db.collection 'birthdays'
options =
"sort": "birthday"
collection.find({}, options).toArray (err, birthdays) ->
res.format
json: ->
res.send(birthdays);
console.log 'Request fulfilled'
app.use (req, res) ->
res.sendFile '404.html', sendOptions
console.log 'Not found'
server = app.listen process.env.PORT or 5000, -> console.log 'Listening on port %d', server.address().port |
[
{
"context": " to each transaction here\n paramToAdd = \"api-key=23456\"\n if transaction.fullPath.indexOf('?') > -1\n ",
"end": 405,
"score": 0.9936407804489136,
"start": 400,
"tag": "KEY",
"value": "23456"
}
] | packages/dredd/test/fixtures/regression-152.coffee | tomoyamachi/dredd | 3,726 | hooks = require 'hooks'
# New hooks helper function
hooks.beforeEach = (hookFn) ->
hooks.beforeAll (done) ->
for transactionKey, transaction of hooks.transactions or {}
hooks.beforeHooks[transaction.name] ?= []
hooks.beforeHooks[transaction.name].unshift hookFn
done()
hooks.beforeEach (transaction) ->
# add query parameter to each transaction here
paramToAdd = "api-key=23456"
if transaction.fullPath.indexOf('?') > -1
transaction.fullPath += "&" + paramToAdd
else
transaction.fullPath += "?" + paramToAdd
| 107207 | hooks = require 'hooks'
# New hooks helper function
hooks.beforeEach = (hookFn) ->
hooks.beforeAll (done) ->
for transactionKey, transaction of hooks.transactions or {}
hooks.beforeHooks[transaction.name] ?= []
hooks.beforeHooks[transaction.name].unshift hookFn
done()
hooks.beforeEach (transaction) ->
# add query parameter to each transaction here
paramToAdd = "api-key=<KEY>"
if transaction.fullPath.indexOf('?') > -1
transaction.fullPath += "&" + paramToAdd
else
transaction.fullPath += "?" + paramToAdd
| true | hooks = require 'hooks'
# New hooks helper function
hooks.beforeEach = (hookFn) ->
hooks.beforeAll (done) ->
for transactionKey, transaction of hooks.transactions or {}
hooks.beforeHooks[transaction.name] ?= []
hooks.beforeHooks[transaction.name].unshift hookFn
done()
hooks.beforeEach (transaction) ->
# add query parameter to each transaction here
paramToAdd = "api-key=PI:KEY:<KEY>END_PI"
if transaction.fullPath.indexOf('?') > -1
transaction.fullPath += "&" + paramToAdd
else
transaction.fullPath += "?" + paramToAdd
|
[
{
"context": "orObject =\n value: null\n\n #https://github.com/petkaantonov/bluebird/wiki/Optimization-killers\n tryCatch = (",
"end": 431,
"score": 0.9995818138122559,
"start": 419,
"tag": "USERNAME",
"value": "petkaantonov"
},
{
"context": "ces.then ->\n fnPromise()\n\n... | public/javascripts/lib/angular-google-maps/src/coffee/directives/api/utils/_async.coffee | Javilete/front-end-rural-house | 0 | angular.module("uiGmapgoogle-maps.directives.api.utils")
.service("uiGmap_sync", [ ->
fakePromise: ->
_cb = undefined
then: (cb) ->
_cb = cb
resolve: () ->
_cb.apply(undefined, arguments)
])
.service "uiGmap_async", [ "$timeout", "uiGmapPromise", "uiGmapLogger", ($timeout, uiGmapPromise, $log) ->
defaultChunkSize = 20
errorObject =
value: null
#https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
tryCatch = (fn, ctx, args) ->
try
return fn.apply(ctx, args)
catch e
errorObject.value = e
return errorObject
logTryCatch = (fn, ctx, deferred, args) ->
result = tryCatch(fn, ctx, args)
if result == errorObject
msg = "error within chunking iterator: #{errorObject.value}"
$log.error msg
deferred.reject msg
###
utility to reduce code bloat. The whole point is to check if there is existing synchronous work going on.
If so we wait on it.
Note: This is fully intended to be mutable (ie existingPiecesObj is getting existingPieces prop slapped on)
###
waitOrGo = (existingPiecesObj, fnPromise) ->
unless existingPiecesObj.existingPieces
existingPiecesObj.existingPieces = fnPromise()
else
existingPiecesObj.existingPieces = existingPiecesObj.existingPieces.then ->
fnPromise()
###
Author: Nicholas McCready & jfriend00
_async 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
The design of any functionality of _async is to be like lodash/underscore and replicate it but call things
asynchronously underneath. Each should be sufficient for most things to be derived from.
Optional Asynchronous Chunking via promises.
###
doChunk = (array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index) ->
if chunkSizeOrDontChunk and chunkSizeOrDontChunk < array.length
cnt = chunkSizeOrDontChunk
else
cnt = array.length
i = index
while cnt-- and i < (if array then array.length else i + 1)
# process array[index] here
logTryCatch chunkCb, undefined, overallD, [array[i], i]
++i
if array
if i < array.length
index = i
if chunkSizeOrDontChunk
if pauseCb? and _.isFunction pauseCb
logTryCatch pauseCb, undefined, overallD, []
$timeout ->
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index
, pauseMilli, false
else
overallD.resolve()
each = (array, chunk, pauseCb, chunkSizeOrDontChunk = defaultChunkSize, index = 0, pauseMilli = 1) ->
ret = undefined
overallD = uiGmapPromise.defer()
ret = overallD.promise
unless pauseMilli
error = 'pause (delay) must be set from _async!'
$log.error error
overallD.reject error
return ret
if array == undefined or array?.length <= 0
overallD.resolve()
return ret
# set this to whatever number of items you can process at once
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index
return ret
#copied from underscore but w/ async each above
map = (objs, iterator, pauseCb, chunkSizeOrDontChunk, index, pauseMilli) ->
results = []
return uiGmapPromise.resolve(results) unless objs? and objs?.length > 0
each(objs, (o) ->
results.push iterator o
, pauseCb, chunkSizeOrDontChunk, index, pauseMilli)
.then ->
results
each: each
map: map
waitOrGo: waitOrGo
defaultChunkSize: defaultChunkSize
]
| 173219 | angular.module("uiGmapgoogle-maps.directives.api.utils")
.service("uiGmap_sync", [ ->
fakePromise: ->
_cb = undefined
then: (cb) ->
_cb = cb
resolve: () ->
_cb.apply(undefined, arguments)
])
.service "uiGmap_async", [ "$timeout", "uiGmapPromise", "uiGmapLogger", ($timeout, uiGmapPromise, $log) ->
defaultChunkSize = 20
errorObject =
value: null
#https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
tryCatch = (fn, ctx, args) ->
try
return fn.apply(ctx, args)
catch e
errorObject.value = e
return errorObject
logTryCatch = (fn, ctx, deferred, args) ->
result = tryCatch(fn, ctx, args)
if result == errorObject
msg = "error within chunking iterator: #{errorObject.value}"
$log.error msg
deferred.reject msg
###
utility to reduce code bloat. The whole point is to check if there is existing synchronous work going on.
If so we wait on it.
Note: This is fully intended to be mutable (ie existingPiecesObj is getting existingPieces prop slapped on)
###
waitOrGo = (existingPiecesObj, fnPromise) ->
unless existingPiecesObj.existingPieces
existingPiecesObj.existingPieces = fnPromise()
else
existingPiecesObj.existingPieces = existingPiecesObj.existingPieces.then ->
fnPromise()
###
Author: <NAME> & jfriend00
_async 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
The design of any functionality of _async is to be like lodash/underscore and replicate it but call things
asynchronously underneath. Each should be sufficient for most things to be derived from.
Optional Asynchronous Chunking via promises.
###
doChunk = (array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index) ->
if chunkSizeOrDontChunk and chunkSizeOrDontChunk < array.length
cnt = chunkSizeOrDontChunk
else
cnt = array.length
i = index
while cnt-- and i < (if array then array.length else i + 1)
# process array[index] here
logTryCatch chunkCb, undefined, overallD, [array[i], i]
++i
if array
if i < array.length
index = i
if chunkSizeOrDontChunk
if pauseCb? and _.isFunction pauseCb
logTryCatch pauseCb, undefined, overallD, []
$timeout ->
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index
, pauseMilli, false
else
overallD.resolve()
each = (array, chunk, pauseCb, chunkSizeOrDontChunk = defaultChunkSize, index = 0, pauseMilli = 1) ->
ret = undefined
overallD = uiGmapPromise.defer()
ret = overallD.promise
unless pauseMilli
error = 'pause (delay) must be set from _async!'
$log.error error
overallD.reject error
return ret
if array == undefined or array?.length <= 0
overallD.resolve()
return ret
# set this to whatever number of items you can process at once
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index
return ret
#copied from underscore but w/ async each above
map = (objs, iterator, pauseCb, chunkSizeOrDontChunk, index, pauseMilli) ->
results = []
return uiGmapPromise.resolve(results) unless objs? and objs?.length > 0
each(objs, (o) ->
results.push iterator o
, pauseCb, chunkSizeOrDontChunk, index, pauseMilli)
.then ->
results
each: each
map: map
waitOrGo: waitOrGo
defaultChunkSize: defaultChunkSize
]
| true | angular.module("uiGmapgoogle-maps.directives.api.utils")
.service("uiGmap_sync", [ ->
fakePromise: ->
_cb = undefined
then: (cb) ->
_cb = cb
resolve: () ->
_cb.apply(undefined, arguments)
])
.service "uiGmap_async", [ "$timeout", "uiGmapPromise", "uiGmapLogger", ($timeout, uiGmapPromise, $log) ->
defaultChunkSize = 20
errorObject =
value: null
#https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
tryCatch = (fn, ctx, args) ->
try
return fn.apply(ctx, args)
catch e
errorObject.value = e
return errorObject
logTryCatch = (fn, ctx, deferred, args) ->
result = tryCatch(fn, ctx, args)
if result == errorObject
msg = "error within chunking iterator: #{errorObject.value}"
$log.error msg
deferred.reject msg
###
utility to reduce code bloat. The whole point is to check if there is existing synchronous work going on.
If so we wait on it.
Note: This is fully intended to be mutable (ie existingPiecesObj is getting existingPieces prop slapped on)
###
waitOrGo = (existingPiecesObj, fnPromise) ->
unless existingPiecesObj.existingPieces
existingPiecesObj.existingPieces = fnPromise()
else
existingPiecesObj.existingPieces = existingPiecesObj.existingPieces.then ->
fnPromise()
###
Author: PI:NAME:<NAME>END_PI & jfriend00
_async 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
The design of any functionality of _async is to be like lodash/underscore and replicate it but call things
asynchronously underneath. Each should be sufficient for most things to be derived from.
Optional Asynchronous Chunking via promises.
###
doChunk = (array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index) ->
if chunkSizeOrDontChunk and chunkSizeOrDontChunk < array.length
cnt = chunkSizeOrDontChunk
else
cnt = array.length
i = index
while cnt-- and i < (if array then array.length else i + 1)
# process array[index] here
logTryCatch chunkCb, undefined, overallD, [array[i], i]
++i
if array
if i < array.length
index = i
if chunkSizeOrDontChunk
if pauseCb? and _.isFunction pauseCb
logTryCatch pauseCb, undefined, overallD, []
$timeout ->
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index
, pauseMilli, false
else
overallD.resolve()
each = (array, chunk, pauseCb, chunkSizeOrDontChunk = defaultChunkSize, index = 0, pauseMilli = 1) ->
ret = undefined
overallD = uiGmapPromise.defer()
ret = overallD.promise
unless pauseMilli
error = 'pause (delay) must be set from _async!'
$log.error error
overallD.reject error
return ret
if array == undefined or array?.length <= 0
overallD.resolve()
return ret
# set this to whatever number of items you can process at once
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index
return ret
#copied from underscore but w/ async each above
map = (objs, iterator, pauseCb, chunkSizeOrDontChunk, index, pauseMilli) ->
results = []
return uiGmapPromise.resolve(results) unless objs? and objs?.length > 0
each(objs, (o) ->
results.push iterator o
, pauseCb, chunkSizeOrDontChunk, index, pauseMilli)
.then ->
results
each: each
map: map
waitOrGo: waitOrGo
defaultChunkSize: defaultChunkSize
]
|
[
{
"context": "ationality: 'Choose you nationality'\n password: 'Minimum 6 characters, a-z A-Z 0-9'\n}",
"end": 245,
"score": 0.9909637570381165,
"start": 212,
"tag": "PASSWORD",
"value": "Minimum 6 characters, a-z A-Z 0-9"
}
] | src/common/directives/validation/errorMessage.coffee | Axeres/Vue-pug-coffee-sass | 0 | export default {
required: 'Required field'
dateTest: 'Date is not valid'
email: 'E-mail is not valid'
integer: 'Only numbers'
string: 'Only string'
nationality: 'Choose you nationality'
password: 'Minimum 6 characters, a-z A-Z 0-9'
} | 141672 | export default {
required: 'Required field'
dateTest: 'Date is not valid'
email: 'E-mail is not valid'
integer: 'Only numbers'
string: 'Only string'
nationality: 'Choose you nationality'
password: '<PASSWORD>'
} | true | export default {
required: 'Required field'
dateTest: 'Date is not valid'
email: 'E-mail is not valid'
integer: 'Only numbers'
string: 'Only string'
nationality: 'Choose you nationality'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
} |
[
{
"context": "11'\n cardYear : '2017'\n cardName : 'John Doe'\n\n actions.createStripeToken(options).then ({ ",
"end": 794,
"score": 0.999846339225769,
"start": 786,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "11'\n cardYear : '2017'\n cardName ... | client/app/lib/flux/payment/test.coffee | ezgikaysi/koding | 1 | expect = require 'expect'
Reactor = require 'app/flux/base/reactor'
PaymentFlux = require './'
describe 'PaymentFlux', ->
it 'loads stripe client', (done) ->
reactor = new Reactor
{ actions, getters } = PaymentFlux reactor
expect(global.Stripe).toNotExist()
expect(getters.paymentValues().get 'isStripeClientLoaded').toBe no
actions.loadStripeClient().then ->
expect(global.Stripe).toExist()
expect(getters.paymentValues().get 'isStripeClientLoaded').toBe yes
done()
it 'should create a stripe token', (done) ->
reactor = new Reactor
{ actions, getters } = PaymentFlux reactor
options =
cardNumber : '4111111111111111'
cardCVC : '111'
cardMonth : '11'
cardYear : '2017'
cardName : 'John Doe'
actions.createStripeToken(options).then ({ token }) ->
expect(getters.paymentValues().get 'stripeToken').toBe token
done()
.catch (err) -> done err
it 'should subscribe a group', (done) ->
reactor = new Reactor
{ actions, getters } = PaymentFlux reactor
options =
cardNumber : '4111111111111111'
cardCVC : '111'
cardMonth : '11'
cardYear : '2017'
cardName : 'John Doe'
actions.createStripeToken(options).then ({ token }) ->
actions.subscribeGroupPlan({ token }).then ({ response }) ->
expected = getters.paymentValues().get('groupPlan').toJS()
expect(expected).toEqual(response)
.catch (err) -> done err
.catch (err) -> done err
| 38401 | expect = require 'expect'
Reactor = require 'app/flux/base/reactor'
PaymentFlux = require './'
describe 'PaymentFlux', ->
it 'loads stripe client', (done) ->
reactor = new Reactor
{ actions, getters } = PaymentFlux reactor
expect(global.Stripe).toNotExist()
expect(getters.paymentValues().get 'isStripeClientLoaded').toBe no
actions.loadStripeClient().then ->
expect(global.Stripe).toExist()
expect(getters.paymentValues().get 'isStripeClientLoaded').toBe yes
done()
it 'should create a stripe token', (done) ->
reactor = new Reactor
{ actions, getters } = PaymentFlux reactor
options =
cardNumber : '4111111111111111'
cardCVC : '111'
cardMonth : '11'
cardYear : '2017'
cardName : '<NAME>'
actions.createStripeToken(options).then ({ token }) ->
expect(getters.paymentValues().get 'stripeToken').toBe token
done()
.catch (err) -> done err
it 'should subscribe a group', (done) ->
reactor = new Reactor
{ actions, getters } = PaymentFlux reactor
options =
cardNumber : '4111111111111111'
cardCVC : '111'
cardMonth : '11'
cardYear : '2017'
cardName : '<NAME>'
actions.createStripeToken(options).then ({ token }) ->
actions.subscribeGroupPlan({ token }).then ({ response }) ->
expected = getters.paymentValues().get('groupPlan').toJS()
expect(expected).toEqual(response)
.catch (err) -> done err
.catch (err) -> done err
| true | expect = require 'expect'
Reactor = require 'app/flux/base/reactor'
PaymentFlux = require './'
describe 'PaymentFlux', ->
it 'loads stripe client', (done) ->
reactor = new Reactor
{ actions, getters } = PaymentFlux reactor
expect(global.Stripe).toNotExist()
expect(getters.paymentValues().get 'isStripeClientLoaded').toBe no
actions.loadStripeClient().then ->
expect(global.Stripe).toExist()
expect(getters.paymentValues().get 'isStripeClientLoaded').toBe yes
done()
it 'should create a stripe token', (done) ->
reactor = new Reactor
{ actions, getters } = PaymentFlux reactor
options =
cardNumber : '4111111111111111'
cardCVC : '111'
cardMonth : '11'
cardYear : '2017'
cardName : 'PI:NAME:<NAME>END_PI'
actions.createStripeToken(options).then ({ token }) ->
expect(getters.paymentValues().get 'stripeToken').toBe token
done()
.catch (err) -> done err
it 'should subscribe a group', (done) ->
reactor = new Reactor
{ actions, getters } = PaymentFlux reactor
options =
cardNumber : '4111111111111111'
cardCVC : '111'
cardMonth : '11'
cardYear : '2017'
cardName : 'PI:NAME:<NAME>END_PI'
actions.createStripeToken(options).then ({ token }) ->
actions.subscribeGroupPlan({ token }).then ({ response }) ->
expected = getters.paymentValues().get('groupPlan').toJS()
expect(expected).toEqual(response)
.catch (err) -> done err
.catch (err) -> done err
|
[
{
"context": "# Copyright (C) 2017 Alexandre Pielucha & Marie Perin\n#\n# Permission to use, copy, modify",
"end": 39,
"score": 0.999855101108551,
"start": 21,
"tag": "NAME",
"value": "Alexandre Pielucha"
},
{
"context": "# Copyright (C) 2017 Alexandre Pielucha & Marie Perin\n#\n# Pe... | src/http/middlewares.coffee | Riemannn/AST_Final_Project | 0 | # Copyright (C) 2017 Alexandre Pielucha & Marie Perin
#
# 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.
env = require '../../.env.coffee'
module.exports =
# If no user logged in, redirect to login page
auth: (req, res, next) ->
unless req.session.loggedIn
res.redirect '/login'
else
next()
# Redirect HTTP requests to HTTPS
https: (req, res, next) ->
unless req.secure
host = req.headers.host
host = host.replace env.SERVER.HTTP_PORT, env.SERVER.HTTPS_PORT
url = req.url
res.redirect 'https://' + host + url
else
next()
| 142660 | # Copyright (C) 2017 <NAME> & <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.
env = require '../../.env.coffee'
module.exports =
# If no user logged in, redirect to login page
auth: (req, res, next) ->
unless req.session.loggedIn
res.redirect '/login'
else
next()
# Redirect HTTP requests to HTTPS
https: (req, res, next) ->
unless req.secure
host = req.headers.host
host = host.replace env.SERVER.HTTP_PORT, env.SERVER.HTTPS_PORT
url = req.url
res.redirect 'https://' + host + url
else
next()
| true | # Copyright (C) 2017 PI:NAME:<NAME>END_PI & 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.
env = require '../../.env.coffee'
module.exports =
# If no user logged in, redirect to login page
auth: (req, res, next) ->
unless req.session.loggedIn
res.redirect '/login'
else
next()
# Redirect HTTP requests to HTTPS
https: (req, res, next) ->
unless req.secure
host = req.headers.host
host = host.replace env.SERVER.HTTP_PORT, env.SERVER.HTTPS_PORT
url = req.url
res.redirect 'https://' + host + url
else
next()
|
[
{
"context": "it was called after their definition.\n alice: \"alice\"\n bob: \"bob\"\n\n ok finaliseCalled\n ok ToBeFin",
"end": 1302,
"score": 0.69361412525177,
"start": 1297,
"tag": "NAME",
"value": "alice"
},
{
"context": "er their definition.\n alice: \"alice\"\n b... | test/classhooks.coffee | QuanTemplate/coffee-script | 0 | # Test that class hooks work as expected.
test "extends hook is called", ->
extendsCalled = false
class Base
@__extends__ = (child, name)->
extendsCalled = true
# This is the CoffeeScript compiler's extends function translated into CoffeeScript
# minus hte logic I added to invoke the extends function!
for own key of this
child[key] = this[key]
ctor = ()->
@constructor = child
return
ctor.prototype = this.prototype
child.prototype = new ctor()
# need __super__ for coffeescript's super() call to work properly.
child.__super__ = this.prototype
child
alice: ()->
'Base::alice'
bob: ()->
'Base::bob'
class Derived extends Base
bob: ()->
'Derived::bob'
ok extendsCalled
d = new Derived()
ok d.alice() is 'Base::alice'
ok d.bob() is 'Derived::bob'
test "finalise hook is called", ->
finaliseCalled = false
class ToBeFinalised
@__finalise__ = (name)->
finaliseCalled = true
ok @::alice is "alice"
ok @::bob is "bob"
@__name__ = name
return this
# Just define some properties and make sure that they exist on the ctor's
# prototype. This shows that it was called after their definition.
alice: "alice"
bob: "bob"
ok finaliseCalled
ok ToBeFinalised.__name__ is "ToBeFinalised"
test "metaclass declaration is hoisted", ->
# In the generated code, CoffeeScript relies on the fact that all function delcaratiosn are hoisted to call
# __extends() on the contructor before it is defined.
# Given that the value of the __metaclass__ will be processed by the __extends() call and has to be as
# defined for the current class (not a parent)
extendsCalled = false
class Base
@__metaclass__ = 'baseMeta'
# This will get called when Foo is defined
@__extends__ = (child, name)->
ok name is 'Foo'
ok child.__metaclass__ is 'FooMeta'
extendsCalled = true
class Foo extends Base
@__metaclass__ = "FooMeta"
ok extendsCalled
| 40142 | # Test that class hooks work as expected.
test "extends hook is called", ->
extendsCalled = false
class Base
@__extends__ = (child, name)->
extendsCalled = true
# This is the CoffeeScript compiler's extends function translated into CoffeeScript
# minus hte logic I added to invoke the extends function!
for own key of this
child[key] = this[key]
ctor = ()->
@constructor = child
return
ctor.prototype = this.prototype
child.prototype = new ctor()
# need __super__ for coffeescript's super() call to work properly.
child.__super__ = this.prototype
child
alice: ()->
'Base::alice'
bob: ()->
'Base::bob'
class Derived extends Base
bob: ()->
'Derived::bob'
ok extendsCalled
d = new Derived()
ok d.alice() is 'Base::alice'
ok d.bob() is 'Derived::bob'
test "finalise hook is called", ->
finaliseCalled = false
class ToBeFinalised
@__finalise__ = (name)->
finaliseCalled = true
ok @::alice is "alice"
ok @::bob is "bob"
@__name__ = name
return this
# Just define some properties and make sure that they exist on the ctor's
# prototype. This shows that it was called after their definition.
alice: "<NAME>"
bob: "<NAME>"
ok finaliseCalled
ok ToBeFinalised.__name__ is "ToBeFinalised"
test "metaclass declaration is hoisted", ->
# In the generated code, CoffeeScript relies on the fact that all function delcaratiosn are hoisted to call
# __extends() on the contructor before it is defined.
# Given that the value of the __metaclass__ will be processed by the __extends() call and has to be as
# defined for the current class (not a parent)
extendsCalled = false
class Base
@__metaclass__ = 'baseMeta'
# This will get called when Foo is defined
@__extends__ = (child, name)->
ok name is 'Foo'
ok child.__metaclass__ is 'FooMeta'
extendsCalled = true
class Foo extends Base
@__metaclass__ = "FooMeta"
ok extendsCalled
| true | # Test that class hooks work as expected.
test "extends hook is called", ->
extendsCalled = false
class Base
@__extends__ = (child, name)->
extendsCalled = true
# This is the CoffeeScript compiler's extends function translated into CoffeeScript
# minus hte logic I added to invoke the extends function!
for own key of this
child[key] = this[key]
ctor = ()->
@constructor = child
return
ctor.prototype = this.prototype
child.prototype = new ctor()
# need __super__ for coffeescript's super() call to work properly.
child.__super__ = this.prototype
child
alice: ()->
'Base::alice'
bob: ()->
'Base::bob'
class Derived extends Base
bob: ()->
'Derived::bob'
ok extendsCalled
d = new Derived()
ok d.alice() is 'Base::alice'
ok d.bob() is 'Derived::bob'
test "finalise hook is called", ->
finaliseCalled = false
class ToBeFinalised
@__finalise__ = (name)->
finaliseCalled = true
ok @::alice is "alice"
ok @::bob is "bob"
@__name__ = name
return this
# Just define some properties and make sure that they exist on the ctor's
# prototype. This shows that it was called after their definition.
alice: "PI:NAME:<NAME>END_PI"
bob: "PI:NAME:<NAME>END_PI"
ok finaliseCalled
ok ToBeFinalised.__name__ is "ToBeFinalised"
test "metaclass declaration is hoisted", ->
# In the generated code, CoffeeScript relies on the fact that all function delcaratiosn are hoisted to call
# __extends() on the contructor before it is defined.
# Given that the value of the __metaclass__ will be processed by the __extends() call and has to be as
# defined for the current class (not a parent)
extendsCalled = false
class Base
@__metaclass__ = 'baseMeta'
# This will get called when Foo is defined
@__extends__ = (child, name)->
ok name is 'Foo'
ok child.__metaclass__ is 'FooMeta'
extendsCalled = true
class Foo extends Base
@__metaclass__ = "FooMeta"
ok extendsCalled
|
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998422265052795,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai... | library/membrane/skeleton.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL 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.
###
_ = require "lodash"
url = require "url"
http = require "http"
util = require "util"
assert = require "assert"
colors = require "colors"
logger = require "winston"
extendz = require "../nucleus/extends"
compose = require "../nucleus/compose"
{RestfulService} = require "../nucleus/restful"
# This is an abstract base class for every service in the system
# and in the end user application that provides a REST interface
# to some arbitrary resource, determined by HTTP path and guarded
# by the domain matching. This is the crucial piece of framework.
# It supports strictly methods defined in the HTTP specification.
module.exports.Barebones = class Barebones extends RestfulService
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# A hook that will be called once the Connect middleware writes
# off the headers. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
headers: (request, response, resource, domain, next) -> next()
# A hook that will be called prior to invoking the API method
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
processing: (request, response, resource, domain, next) -> next()
# This method should generally be used to obtain HTTP methods that
# are allowed on this resources. This is not the only possible way
# of implementing this method, because it usually can have a lot of
# different interpretations other than the one in the HTTP spec.
# The method is an HTTP verb, coherent with the REST interface.
# Lookup the `RestfulService` for meaning of other parameters.
OPTIONS: (request, response, resource, domain, session) ->
assert knowns = try @constructor.SUPPORTED
doesJson = response.accepts(/json/) or false
pathname = try url.parse(request.url).pathname
assert _.isString(pathname), "could not get path"
assert _.isObject(request), "got invalid request"
assert _.isObject(response), "got invalid response"
assert _.isArray(resource), "malformed resource"
assert _.isArray(domain), "malformed domain name"
checkIfSupported = (m) => @[m] isnt @unsupported
existing = _.filter knowns, (name) => this[name]?
supported = try _.filter existing, checkIfSupported
descriptor = methods: supported, resource: pathname
return this.push response, descriptor if doesJson
assert _.isString formatted = supported.join ", "
assert formatted = _.sprintf "%s\r\n", formatted
response.send formatted.toString(); return @
| 160306 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL 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.
###
_ = require "lodash"
url = require "url"
http = require "http"
util = require "util"
assert = require "assert"
colors = require "colors"
logger = require "winston"
extendz = require "../nucleus/extends"
compose = require "../nucleus/compose"
{RestfulService} = require "../nucleus/restful"
# This is an abstract base class for every service in the system
# and in the end user application that provides a REST interface
# to some arbitrary resource, determined by HTTP path and guarded
# by the domain matching. This is the crucial piece of framework.
# It supports strictly methods defined in the HTTP specification.
module.exports.Barebones = class Barebones extends RestfulService
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# A hook that will be called once the Connect middleware writes
# off the headers. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
headers: (request, response, resource, domain, next) -> next()
# A hook that will be called prior to invoking the API method
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
processing: (request, response, resource, domain, next) -> next()
# This method should generally be used to obtain HTTP methods that
# are allowed on this resources. This is not the only possible way
# of implementing this method, because it usually can have a lot of
# different interpretations other than the one in the HTTP spec.
# The method is an HTTP verb, coherent with the REST interface.
# Lookup the `RestfulService` for meaning of other parameters.
OPTIONS: (request, response, resource, domain, session) ->
assert knowns = try @constructor.SUPPORTED
doesJson = response.accepts(/json/) or false
pathname = try url.parse(request.url).pathname
assert _.isString(pathname), "could not get path"
assert _.isObject(request), "got invalid request"
assert _.isObject(response), "got invalid response"
assert _.isArray(resource), "malformed resource"
assert _.isArray(domain), "malformed domain name"
checkIfSupported = (m) => @[m] isnt @unsupported
existing = _.filter knowns, (name) => this[name]?
supported = try _.filter existing, checkIfSupported
descriptor = methods: supported, resource: pathname
return this.push response, descriptor if doesJson
assert _.isString formatted = supported.join ", "
assert formatted = _.sprintf "%s\r\n", formatted
response.send formatted.toString(); return @
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL 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.
###
_ = require "lodash"
url = require "url"
http = require "http"
util = require "util"
assert = require "assert"
colors = require "colors"
logger = require "winston"
extendz = require "../nucleus/extends"
compose = require "../nucleus/compose"
{RestfulService} = require "../nucleus/restful"
# This is an abstract base class for every service in the system
# and in the end user application that provides a REST interface
# to some arbitrary resource, determined by HTTP path and guarded
# by the domain matching. This is the crucial piece of framework.
# It supports strictly methods defined in the HTTP specification.
module.exports.Barebones = class Barebones extends RestfulService
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# A hook that will be called once the Connect middleware writes
# off the headers. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
headers: (request, response, resource, domain, next) -> next()
# A hook that will be called prior to invoking the API method
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
processing: (request, response, resource, domain, next) -> next()
# This method should generally be used to obtain HTTP methods that
# are allowed on this resources. This is not the only possible way
# of implementing this method, because it usually can have a lot of
# different interpretations other than the one in the HTTP spec.
# The method is an HTTP verb, coherent with the REST interface.
# Lookup the `RestfulService` for meaning of other parameters.
OPTIONS: (request, response, resource, domain, session) ->
assert knowns = try @constructor.SUPPORTED
doesJson = response.accepts(/json/) or false
pathname = try url.parse(request.url).pathname
assert _.isString(pathname), "could not get path"
assert _.isObject(request), "got invalid request"
assert _.isObject(response), "got invalid response"
assert _.isArray(resource), "malformed resource"
assert _.isArray(domain), "malformed domain name"
checkIfSupported = (m) => @[m] isnt @unsupported
existing = _.filter knowns, (name) => this[name]?
supported = try _.filter existing, checkIfSupported
descriptor = methods: supported, resource: pathname
return this.push response, descriptor if doesJson
assert _.isString formatted = supported.join ", "
assert formatted = _.sprintf "%s\r\n", formatted
response.send formatted.toString(); return @
|
[
{
"context": "nd their default value\n#\n# { \n# login: 'guest'\n# password: 'guest'\n# host:'localhos",
"end": 156,
"score": 0.9937252402305603,
"start": 151,
"tag": "USERNAME",
"value": "guest"
},
{
"context": " { \n# login: 'guest'\n# password... | examples/example-simple.coffee | FGRibreau/node-amqp-dsl | 2 | AmqpDsl = require 'amqp-dsl'
AmqpDsl
# First we log in, here the list of the available parameters and their default value
#
# {
# login: 'guest'
# password: 'guest'
# host:'localhost'
# port: 5672
# vhost: '/'
# }
#
.login(
login: 'legen'
password: 'dary'
)
# Bind listeners to some events (available events are `close`, `error` and `ready`)
.on('close', () -> console.error "RabbitMQ connection closed")
.on('error', (err) -> console.error "RabbitMQ error", err)
.on('ready', () -> console.log "Connected to RabbitMQ")
# We create a queue (`passive: false` see AMQP doc) with `.queue`
#
# * `.queue( name, options )`
# * `.queue( name, callback(queue) )`
# * `.queue( name, options, callback(queue) )`
.queue('testQueue', (queue) -> console.log "Connected to Queue", queue.name)
# (optional) ... and bind that queue to an exchange with `.bind`
#
# * `.bind( name, routingKey )`
.bind('stream', '#')
# (optional) ... and subscribe for messages (without `ack` in this example)
#
# * `.subscribe( callback(message, header, deliveryInfo) )`
# * `.subscribe( options, callback(message, header, deliveryInfo) )`
.subscribe((message, header, deliveryInfo) -> )
# Create another queue `queue2` that will be binded to `search` exchange with the routing key `#.ok`
.queue('queue2')
.bind('search', '#.ok')
# Connect to an existing queue `queue3`
.queue('queue3', passive:true, (queue)-> console.log "Connected to Queue", queue.name)
# And now it's time to connect !
# `amqp` contains:
#
# * `amqp.connections` == `[node-amqp::Connection]`
# * `amqp.queues` == `{}`
# * `amqp.exchanges` == `{}`
.connect((err, amqp) ->
if err
throw err
return
console.log 'We are connected !'
# Do other stuff with `amqp` like subscribing to a queue
queue3 = amqp.queues.queue3
queue3.subscribe(ack:true, (message) ->
console.log "Hey ! We got one new message !"
queue3.shift()
)
) | 29919 | AmqpDsl = require 'amqp-dsl'
AmqpDsl
# First we log in, here the list of the available parameters and their default value
#
# {
# login: 'guest'
# password: '<PASSWORD>'
# host:'localhost'
# port: 5672
# vhost: '/'
# }
#
.login(
login: 'legen'
password: '<PASSWORD>'
)
# Bind listeners to some events (available events are `close`, `error` and `ready`)
.on('close', () -> console.error "RabbitMQ connection closed")
.on('error', (err) -> console.error "RabbitMQ error", err)
.on('ready', () -> console.log "Connected to RabbitMQ")
# We create a queue (`passive: false` see AMQP doc) with `.queue`
#
# * `.queue( name, options )`
# * `.queue( name, callback(queue) )`
# * `.queue( name, options, callback(queue) )`
.queue('testQueue', (queue) -> console.log "Connected to Queue", queue.name)
# (optional) ... and bind that queue to an exchange with `.bind`
#
# * `.bind( name, routingKey )`
.bind('stream', '#')
# (optional) ... and subscribe for messages (without `ack` in this example)
#
# * `.subscribe( callback(message, header, deliveryInfo) )`
# * `.subscribe( options, callback(message, header, deliveryInfo) )`
.subscribe((message, header, deliveryInfo) -> )
# Create another queue `queue2` that will be binded to `search` exchange with the routing key `#.ok`
.queue('queue2')
.bind('search', '#.ok')
# Connect to an existing queue `queue3`
.queue('queue3', passive:true, (queue)-> console.log "Connected to Queue", queue.name)
# And now it's time to connect !
# `amqp` contains:
#
# * `amqp.connections` == `[node-amqp::Connection]`
# * `amqp.queues` == `{}`
# * `amqp.exchanges` == `{}`
.connect((err, amqp) ->
if err
throw err
return
console.log 'We are connected !'
# Do other stuff with `amqp` like subscribing to a queue
queue3 = amqp.queues.queue3
queue3.subscribe(ack:true, (message) ->
console.log "Hey ! We got one new message !"
queue3.shift()
)
) | true | AmqpDsl = require 'amqp-dsl'
AmqpDsl
# First we log in, here the list of the available parameters and their default value
#
# {
# login: 'guest'
# password: 'PI:PASSWORD:<PASSWORD>END_PI'
# host:'localhost'
# port: 5672
# vhost: '/'
# }
#
.login(
login: 'legen'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
)
# Bind listeners to some events (available events are `close`, `error` and `ready`)
.on('close', () -> console.error "RabbitMQ connection closed")
.on('error', (err) -> console.error "RabbitMQ error", err)
.on('ready', () -> console.log "Connected to RabbitMQ")
# We create a queue (`passive: false` see AMQP doc) with `.queue`
#
# * `.queue( name, options )`
# * `.queue( name, callback(queue) )`
# * `.queue( name, options, callback(queue) )`
.queue('testQueue', (queue) -> console.log "Connected to Queue", queue.name)
# (optional) ... and bind that queue to an exchange with `.bind`
#
# * `.bind( name, routingKey )`
.bind('stream', '#')
# (optional) ... and subscribe for messages (without `ack` in this example)
#
# * `.subscribe( callback(message, header, deliveryInfo) )`
# * `.subscribe( options, callback(message, header, deliveryInfo) )`
.subscribe((message, header, deliveryInfo) -> )
# Create another queue `queue2` that will be binded to `search` exchange with the routing key `#.ok`
.queue('queue2')
.bind('search', '#.ok')
# Connect to an existing queue `queue3`
.queue('queue3', passive:true, (queue)-> console.log "Connected to Queue", queue.name)
# And now it's time to connect !
# `amqp` contains:
#
# * `amqp.connections` == `[node-amqp::Connection]`
# * `amqp.queues` == `{}`
# * `amqp.exchanges` == `{}`
.connect((err, amqp) ->
if err
throw err
return
console.log 'We are connected !'
# Do other stuff with `amqp` like subscribing to a queue
queue3 = amqp.queues.queue3
queue3.subscribe(ack:true, (message) ->
console.log "Hey ! We got one new message !"
queue3.shift()
)
) |
[
{
"context": "y.createClient(null, null, url)\n key = utl.add0x(currentClient.secretKeyHex)\n id = utl.ad",
"end": 1829,
"score": 0.5533581972122192,
"start": 1826,
"tag": "KEY",
"value": "add"
},
{
"context": "ory.createClient(data, null, url)\n key = utl.add0x(... | source/unsafeinputpagemodule/unsafeinputpagemodule.coffee | JhonnyJason/secret-cockpit-sources | 0 | unsafeinputpagemodule = {name: "unsafeinputpagemodule"}
############################################################
#region printLogFunctions
log = (arg) ->
if allModules.debugmodule.modulesToDebug["unsafeinputpagemodule"]? then console.log "[unsafeinputpagemodule]: " + arg
return
ostr = (obj) -> JSON.stringify(obj, null, 4)
olog = (obj) -> log "\n" + ostr(obj)
print = (arg) -> console.log(arg)
#endregion
############################################################
#region localModules
clientFactory = require("secret-manager-client")
############################################################
utl = null
state = null
clientStore = null
autoDetect = null
slideinModule = null
qrReader = null
#endregion
############################################################
currentClient = null
############################################################
unsafeinputpagemodule.initialize = ->
log "unsafeinputpagemodule.initialize"
utl = allModules.utilmodule
state = allModules.statemodule
clientStore = allModules.clientstoremodule
autoDetect = allModules.autodetectkeysmodule
slideinModule = allModules.slideinframemodule
qrReader = allModules.qrreadermodule
# unsafeinputpageContent.
slideinModule.wireUp(unsafeinputpageContent, clearContent, applyContent)
createUnsafeButton.addEventListener("click", createUnsafeButtonClicked)
scanQrButton.addEventListener("click", scanQrButtonClicked)
unsafeKeyInput.addEventListener("change", secretInputChanged)
return
############################################################
#region internalFunctions
createUnsafeButtonClicked = ->
log "createUnsafeButtonClicked"
url = state.get("secretManagerURL")
try
currentClient = await clientFactory.createClient(null, null, url)
key = utl.add0x(currentClient.secretKeyHex)
id = utl.add0x(currentClient.publicKeyHex)
unsafeKeyInput.value = key
unsafeIdLine.textContent = id
catch err then log err
return
scanQrButtonClicked = ->
log "scanQrButtonClicked"
data = await qrReader.read()
return unless data?
url = state.get("secretManagerURL")
try
currentClient = await clientFactory.createClient(data, null, url)
key = utl.add0x(currentClient.secretKeyHex)
id = utl.add0x(currentClient.publicKeyHex)
unsafeKeyInput.value = key
unsafeIdLine.textContent = id
catch err then log err
return
secretInputChanged = ->
log "secretInputChanged"
url = state.get("secretManagerURL")
key = utl.strip0x(unsafeKeyInput.value)
try
currentClient = await clientFactory.createClient(key, null, url)
key = utl.add0x(currentClient.secretKeyHex)
id = utl.add0x(currentClient.publicKeyHex)
unsafeKeyInput.value = key
unsafeIdLine.textContent = id
catch err then log err
return
############################################################
clearContent = ->
log "clearContent"
unsafeKeyInput.value = "0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
unsafeIdLine.textContent = ""
currentClient = null
return
applyContent = ->
log "applyContent"
clientStore.storeNewClient(currentClient, "unsafe")
autoDetect.detectFor(currentClient)
clearContent()
return
#endregion
############################################################
#region exposedFunctions
unsafeinputpagemodule.slideOut = ->
log "unsafeinputpagemodule.slideOut"
slideinModule.slideoutForContentElement(unsafeinputpageContent)
return
unsafeinputpagemodule.slideIn = ->
log "unsafeinputpagemodule.slideIn"
slideinModule.slideinForContentElement(unsafeinputpageContent)
return
#endregion
module.exports = unsafeinputpagemodule | 84438 | unsafeinputpagemodule = {name: "unsafeinputpagemodule"}
############################################################
#region printLogFunctions
log = (arg) ->
if allModules.debugmodule.modulesToDebug["unsafeinputpagemodule"]? then console.log "[unsafeinputpagemodule]: " + arg
return
ostr = (obj) -> JSON.stringify(obj, null, 4)
olog = (obj) -> log "\n" + ostr(obj)
print = (arg) -> console.log(arg)
#endregion
############################################################
#region localModules
clientFactory = require("secret-manager-client")
############################################################
utl = null
state = null
clientStore = null
autoDetect = null
slideinModule = null
qrReader = null
#endregion
############################################################
currentClient = null
############################################################
unsafeinputpagemodule.initialize = ->
log "unsafeinputpagemodule.initialize"
utl = allModules.utilmodule
state = allModules.statemodule
clientStore = allModules.clientstoremodule
autoDetect = allModules.autodetectkeysmodule
slideinModule = allModules.slideinframemodule
qrReader = allModules.qrreadermodule
# unsafeinputpageContent.
slideinModule.wireUp(unsafeinputpageContent, clearContent, applyContent)
createUnsafeButton.addEventListener("click", createUnsafeButtonClicked)
scanQrButton.addEventListener("click", scanQrButtonClicked)
unsafeKeyInput.addEventListener("change", secretInputChanged)
return
############################################################
#region internalFunctions
createUnsafeButtonClicked = ->
log "createUnsafeButtonClicked"
url = state.get("secretManagerURL")
try
currentClient = await clientFactory.createClient(null, null, url)
key = utl.<KEY>0x(currentClient.secretKeyHex)
id = utl.add0x(currentClient.publicKeyHex)
unsafeKeyInput.value = key
unsafeIdLine.textContent = id
catch err then log err
return
scanQrButtonClicked = ->
log "scanQrButtonClicked"
data = await qrReader.read()
return unless data?
url = state.get("secretManagerURL")
try
currentClient = await clientFactory.createClient(data, null, url)
key = ut<KEY>(currentClient.secretKeyHex)
id = utl.add0x(currentClient.publicKeyHex)
unsafeKeyInput.value = key
unsafeIdLine.textContent = id
catch err then log err
return
secretInputChanged = ->
log "secretInputChanged"
url = state.get("secretManagerURL")
key = utl.strip0x(unsafeKeyInput.value)
try
currentClient = await clientFactory.createClient(key, null, url)
key = ut<KEY>(currentClient.secretKeyHex)
id = utl.add0x(currentClient.publicKeyHex)
unsafeKeyInput.value = key
unsafeIdLine.textContent = id
catch err then log err
return
############################################################
clearContent = ->
log "clearContent"
unsafeKeyInput.value = "<KEY>"
unsafeIdLine.textContent = ""
currentClient = null
return
applyContent = ->
log "applyContent"
clientStore.storeNewClient(currentClient, "unsafe")
autoDetect.detectFor(currentClient)
clearContent()
return
#endregion
############################################################
#region exposedFunctions
unsafeinputpagemodule.slideOut = ->
log "unsafeinputpagemodule.slideOut"
slideinModule.slideoutForContentElement(unsafeinputpageContent)
return
unsafeinputpagemodule.slideIn = ->
log "unsafeinputpagemodule.slideIn"
slideinModule.slideinForContentElement(unsafeinputpageContent)
return
#endregion
module.exports = unsafeinputpagemodule | true | unsafeinputpagemodule = {name: "unsafeinputpagemodule"}
############################################################
#region printLogFunctions
log = (arg) ->
if allModules.debugmodule.modulesToDebug["unsafeinputpagemodule"]? then console.log "[unsafeinputpagemodule]: " + arg
return
ostr = (obj) -> JSON.stringify(obj, null, 4)
olog = (obj) -> log "\n" + ostr(obj)
print = (arg) -> console.log(arg)
#endregion
############################################################
#region localModules
clientFactory = require("secret-manager-client")
############################################################
utl = null
state = null
clientStore = null
autoDetect = null
slideinModule = null
qrReader = null
#endregion
############################################################
currentClient = null
############################################################
unsafeinputpagemodule.initialize = ->
log "unsafeinputpagemodule.initialize"
utl = allModules.utilmodule
state = allModules.statemodule
clientStore = allModules.clientstoremodule
autoDetect = allModules.autodetectkeysmodule
slideinModule = allModules.slideinframemodule
qrReader = allModules.qrreadermodule
# unsafeinputpageContent.
slideinModule.wireUp(unsafeinputpageContent, clearContent, applyContent)
createUnsafeButton.addEventListener("click", createUnsafeButtonClicked)
scanQrButton.addEventListener("click", scanQrButtonClicked)
unsafeKeyInput.addEventListener("change", secretInputChanged)
return
############################################################
#region internalFunctions
createUnsafeButtonClicked = ->
log "createUnsafeButtonClicked"
url = state.get("secretManagerURL")
try
currentClient = await clientFactory.createClient(null, null, url)
key = utl.PI:KEY:<KEY>END_PI0x(currentClient.secretKeyHex)
id = utl.add0x(currentClient.publicKeyHex)
unsafeKeyInput.value = key
unsafeIdLine.textContent = id
catch err then log err
return
scanQrButtonClicked = ->
log "scanQrButtonClicked"
data = await qrReader.read()
return unless data?
url = state.get("secretManagerURL")
try
currentClient = await clientFactory.createClient(data, null, url)
key = utPI:KEY:<KEY>END_PI(currentClient.secretKeyHex)
id = utl.add0x(currentClient.publicKeyHex)
unsafeKeyInput.value = key
unsafeIdLine.textContent = id
catch err then log err
return
secretInputChanged = ->
log "secretInputChanged"
url = state.get("secretManagerURL")
key = utl.strip0x(unsafeKeyInput.value)
try
currentClient = await clientFactory.createClient(key, null, url)
key = utPI:KEY:<KEY>END_PI(currentClient.secretKeyHex)
id = utl.add0x(currentClient.publicKeyHex)
unsafeKeyInput.value = key
unsafeIdLine.textContent = id
catch err then log err
return
############################################################
clearContent = ->
log "clearContent"
unsafeKeyInput.value = "PI:KEY:<KEY>END_PI"
unsafeIdLine.textContent = ""
currentClient = null
return
applyContent = ->
log "applyContent"
clientStore.storeNewClient(currentClient, "unsafe")
autoDetect.detectFor(currentClient)
clearContent()
return
#endregion
############################################################
#region exposedFunctions
unsafeinputpagemodule.slideOut = ->
log "unsafeinputpagemodule.slideOut"
slideinModule.slideoutForContentElement(unsafeinputpageContent)
return
unsafeinputpagemodule.slideIn = ->
log "unsafeinputpagemodule.slideIn"
slideinModule.slideinForContentElement(unsafeinputpageContent)
return
#endregion
module.exports = unsafeinputpagemodule |
[
{
"context": "eout done, 10\n\n task =\n name : 'i-am-ready'\n status : 'ready'\n\n delayed =\n ",
"end": 1900,
"score": 0.8518457412719727,
"start": 1890,
"tag": "NAME",
"value": "i-am-ready"
},
{
"context": "us : 'ready'\n\n delayed =\n ... | test/index.spec.coffee | scull7/uow-store-rethink | 0 | crypto = require 'crypto'
bluebird = require 'bluebird'
DB = require '../lib/db.js'
LibStore = require 'uow-store'
Store = require '../index.js'
{ LockError } = LibStore
#LockError = LibStore.LockError
describe 'RethinkDB Store', ->
db = null
store = null
before ->
db = DB(rethinkConfig)
return db.install()
beforeEach ->
store = Store(rethinkConfig)
return db.run(db.r.table('uow_task').delete())
it 'should return a store object', ->
expect(store).to.be.an.instanceOf LibStore
describe '::handleReadyTask', ->
eStore = null
beforeEach ->
eStore = Store(rethinkConfig)
it 'should emit a ready event', (done) ->
task =
name : 'i-am-ready'
status : 'ready'
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
expect(ready_task.id).to.eql task.id
done()
store.createTask task
.then (task) -> eStore.handleReadyTask(task.id)
it 'should not emit an event for a locked task', (done) ->
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
setTimeout done, 10
task =
name : 'i-am-ready'
status : 'ready'
locked =
name : 'i-am-locked'
status : 'ready'
p1 = eStore.createTask locked
.then (task) -> eStore.lockTask('my-worker-id', task.id)
p2 = eStore.createTask task
bluebird.join p1, p2
.spread (lockedTask, readyTask) ->
eStore.handleReadyTask(lockedTask.id)
eStore.handleReadyTask(readyTask.id)
it 'should not emit an event for a delayed task', (done) ->
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
setTimeout done, 10
task =
name : 'i-am-ready'
status : 'ready'
delayed =
name : 'i-am-delayed'
status : 'ready'
after : new Date().getTime()
delay : 1000
p1 = eStore.createTask delayed
p2 = eStore.createTask task
bluebird.join p1, p2
.spread (delayedTask, readyTask) ->
eStore.handleReadyTask(delayedTask.id)
eStore.handleReadyTask(readyTask.id)
it 'should not emit an event for a future task', (done) ->
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
setTimeout done, 10
task =
name : 'i-am-ready'
status : 'ready'
future =
name : 'i-am-future'
status : 'ready'
after : new Date().getTime() + 10000
p1 = eStore.createTask future
p2 = eStore.createTask task
bluebird.join p1, p2
.spread (futureTask, readyTask) ->
eStore.handleReadyTask(futureTask.id)
eStore.handleReadyTask(readyTask.id)
describe '::createTask', ->
it 'should be a function with an arity of one', ->
expect(store.createTask).to.be.a 'function'
expect(store.createTask.length).to.eql 1
it 'should throw a TypeError if the task object has an ID', ->
task =
id : 'bad'
store.createTask task
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'InvalidTaskObject'
it 'should assign the task object a v4 UUID', ->
task =
name : 'create-task'
store.createTask task
.then (task) ->
expect(task.id).to.be.a 'string'
expect(task.id.length).to.eql 36
it 'should call the pickle function if it\'s available', ->
task =
name : 'create-task'
pickle : ->
id : this.id
name : 'pickled-task'
store.createTask task
.then (task) ->
expect(task.id).to.be.a 'string'
expect(task.id.length).to.eql 36
expect(task.name).to.eql 'pickled-task'
describe '::updateTask', ->
it 'should be a function with an arity of two', ->
expect(store.updateTask).to.be.a 'function'
expect(store.updateTask.length).to.eql 2
it 'should throw a TypeError if the task doesn\'t have an ID', ->
task =
name : 'bad-update-task'
store.updateTask 'my-worker-id', task
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'InvalidTaskObject'
it 'should throw a LockError if a lock key doesnt match ' +
' the lock holder', ->
task =
name : 'bad-worker-id'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) ->
task.updated = 1
store.updateTask 'my-other-id', task
.then -> throw new Error('UnexpectedSuccess')
.catch LockError, (e) -> expect(e.message).to.eql 'TaskLocked'
it 'should update a locked task given the correct worker ID', ->
task =
name : 'locked-task-to-update'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) ->
task.updated = 'success-for-locked-task'
store.updateTask 'my-worker-id', task
.then (task) ->
expect(task.name).to.eql 'locked-task-to-update'
expect(task.updated).to.eql 'success-for-locked-task'
describe '::getTaskById', ->
it 'should be a function with an arity of one', ->
expect(store.getTaskById).to.be.a 'function'
expect(store.getTaskById.length).to.eql 1
it 'should throw a TypeError if a task ID is not provided.', ->
store.getTaskById()
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'TaskIdNotProvided'
it 'should return the saved task', ->
task =
name : 'task-to-get'
store.createTask task
.then (task) -> store.getTaskById(task.id)
.then (task) ->
expect(task.id).to.be.a 'string'
expect(task.id.length).to.eql 36
expect(task.name).to.eql 'task-to-get'
describe '::lockTask', ->
it 'should be a function with an arity of three', ->
expect(store.lockTask).to.be.a 'function'
expect(store.lockTask.length).to.eql 3
it 'should throw a TypeError if the worker ID is not provided', ->
store.lockTask()
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'WorkerIdNotProvided'
it 'should throw a TypeError if the task ID is not provided', ->
store.lockTask('my-worker-id')
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'TaskIdNotProvided'
it 'should lock an unlocked task', ->
hash = crypto.createHash 'sha512'
task =
name : 'task-to-lock'
expected_key = null
store.createTask task
.then (task) ->
hash.update 'my-worker-id'
hash.update task.id
expected_key = hash.digest 'hex'
store.lockTask 'my-worker-id', task.id
.then (task) ->
expect(task.name).to.eql 'task-to-lock'
expect(task.semaphore.key).to.be.a 'string'
expect(task.semaphore.key).to.eql expected_key
it 'should throw a LockError if the task is already locked', ->
task =
name : 'task-check-lock'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) -> store.lockTask 'other-worker-id', task.id
.then -> throw new Error('UnexpectedSuccess')
.catch LockError, (e) -> expect(e.message).to.eql 'TaskAlreadyLocked'
describe '::unlockTask', ->
it 'should be a function with an arity of two', ->
expect(store.unlockTask).to.be.a 'function'
expect(store.unlockTask.length).to.eql 2
it 'should throw a TypeError if the worker ID is not provided', ->
store.unlockTask()
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'WorkerIdNotProvided'
it 'should throw a TypeError if the task ID is not provided', ->
store.unlockTask('my-worker-id')
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'TaskIdNotProvided'
it 'should unlock a locked task', ->
task =
name : 'task-to-unlock'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) -> store.unlockTask 'my-worker-id', task.id
.then (task) ->
expect(task.semaphore).to.be.null
it 'should throw a LockError if the worker ID is not the lock holder', ->
task =
name : 'task-to-unlock'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) -> store.unlockTask 'my-other-id', task.id
.then -> throw new Error('UnexpectedSuccess')
.catch LockError, (e) -> expect(e.message).to.eql 'KeyInvalid'
| 184568 | crypto = require 'crypto'
bluebird = require 'bluebird'
DB = require '../lib/db.js'
LibStore = require 'uow-store'
Store = require '../index.js'
{ LockError } = LibStore
#LockError = LibStore.LockError
describe 'RethinkDB Store', ->
db = null
store = null
before ->
db = DB(rethinkConfig)
return db.install()
beforeEach ->
store = Store(rethinkConfig)
return db.run(db.r.table('uow_task').delete())
it 'should return a store object', ->
expect(store).to.be.an.instanceOf LibStore
describe '::handleReadyTask', ->
eStore = null
beforeEach ->
eStore = Store(rethinkConfig)
it 'should emit a ready event', (done) ->
task =
name : 'i-am-ready'
status : 'ready'
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
expect(ready_task.id).to.eql task.id
done()
store.createTask task
.then (task) -> eStore.handleReadyTask(task.id)
it 'should not emit an event for a locked task', (done) ->
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
setTimeout done, 10
task =
name : 'i-am-ready'
status : 'ready'
locked =
name : 'i-am-locked'
status : 'ready'
p1 = eStore.createTask locked
.then (task) -> eStore.lockTask('my-worker-id', task.id)
p2 = eStore.createTask task
bluebird.join p1, p2
.spread (lockedTask, readyTask) ->
eStore.handleReadyTask(lockedTask.id)
eStore.handleReadyTask(readyTask.id)
it 'should not emit an event for a delayed task', (done) ->
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
setTimeout done, 10
task =
name : '<NAME>'
status : 'ready'
delayed =
name : '<NAME>'
status : 'ready'
after : new Date().getTime()
delay : 1000
p1 = eStore.createTask delayed
p2 = eStore.createTask task
bluebird.join p1, p2
.spread (delayedTask, readyTask) ->
eStore.handleReadyTask(delayedTask.id)
eStore.handleReadyTask(readyTask.id)
it 'should not emit an event for a future task', (done) ->
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
setTimeout done, 10
task =
name : '<NAME>'
status : 'ready'
future =
name : '<NAME>'
status : 'ready'
after : new Date().getTime() + 10000
p1 = eStore.createTask future
p2 = eStore.createTask task
bluebird.join p1, p2
.spread (futureTask, readyTask) ->
eStore.handleReadyTask(futureTask.id)
eStore.handleReadyTask(readyTask.id)
describe '::createTask', ->
it 'should be a function with an arity of one', ->
expect(store.createTask).to.be.a 'function'
expect(store.createTask.length).to.eql 1
it 'should throw a TypeError if the task object has an ID', ->
task =
id : 'bad'
store.createTask task
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'InvalidTaskObject'
it 'should assign the task object a v4 UUID', ->
task =
name : '<NAME>'
store.createTask task
.then (task) ->
expect(task.id).to.be.a 'string'
expect(task.id.length).to.eql 36
it 'should call the pickle function if it\'s available', ->
task =
name : 'create-task'
pickle : ->
id : this.id
name : 'pickled-task'
store.createTask task
.then (task) ->
expect(task.id).to.be.a 'string'
expect(task.id.length).to.eql 36
expect(task.name).to.eql 'pickled-task'
describe '::updateTask', ->
it 'should be a function with an arity of two', ->
expect(store.updateTask).to.be.a 'function'
expect(store.updateTask.length).to.eql 2
it 'should throw a TypeError if the task doesn\'t have an ID', ->
task =
name : 'bad-update-task'
store.updateTask 'my-worker-id', task
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'InvalidTaskObject'
it 'should throw a LockError if a lock key doesnt match ' +
' the lock holder', ->
task =
name : 'bad-worker-id'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) ->
task.updated = 1
store.updateTask 'my-other-id', task
.then -> throw new Error('UnexpectedSuccess')
.catch LockError, (e) -> expect(e.message).to.eql 'TaskLocked'
it 'should update a locked task given the correct worker ID', ->
task =
name : 'locked-task-to-update'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) ->
task.updated = 'success-for-locked-task'
store.updateTask 'my-worker-id', task
.then (task) ->
expect(task.name).to.eql 'locked-task-to-update'
expect(task.updated).to.eql 'success-for-locked-task'
describe '::getTaskById', ->
it 'should be a function with an arity of one', ->
expect(store.getTaskById).to.be.a 'function'
expect(store.getTaskById.length).to.eql 1
it 'should throw a TypeError if a task ID is not provided.', ->
store.getTaskById()
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'TaskIdNotProvided'
it 'should return the saved task', ->
task =
name : 'task-to-get'
store.createTask task
.then (task) -> store.getTaskById(task.id)
.then (task) ->
expect(task.id).to.be.a 'string'
expect(task.id.length).to.eql 36
expect(task.name).to.eql 'task-to-get'
describe '::lockTask', ->
it 'should be a function with an arity of three', ->
expect(store.lockTask).to.be.a 'function'
expect(store.lockTask.length).to.eql 3
it 'should throw a TypeError if the worker ID is not provided', ->
store.lockTask()
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'WorkerIdNotProvided'
it 'should throw a TypeError if the task ID is not provided', ->
store.lockTask('my-worker-id')
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'TaskIdNotProvided'
it 'should lock an unlocked task', ->
hash = crypto.createHash 'sha512'
task =
name : 'task-to-lock'
expected_key = null
store.createTask task
.then (task) ->
hash.update 'my-worker-id'
hash.update task.id
expected_key = hash.digest 'hex'
store.lockTask 'my-worker-id', task.id
.then (task) ->
expect(task.name).to.eql 'task-to-lock'
expect(task.semaphore.key).to.be.a 'string'
expect(task.semaphore.key).to.eql expected_key
it 'should throw a LockError if the task is already locked', ->
task =
name : 'task-check-lock'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) -> store.lockTask 'other-worker-id', task.id
.then -> throw new Error('UnexpectedSuccess')
.catch LockError, (e) -> expect(e.message).to.eql 'TaskAlreadyLocked'
describe '::unlockTask', ->
it 'should be a function with an arity of two', ->
expect(store.unlockTask).to.be.a 'function'
expect(store.unlockTask.length).to.eql 2
it 'should throw a TypeError if the worker ID is not provided', ->
store.unlockTask()
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'WorkerIdNotProvided'
it 'should throw a TypeError if the task ID is not provided', ->
store.unlockTask('my-worker-id')
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'TaskIdNotProvided'
it 'should unlock a locked task', ->
task =
name : 'task-to-unlock'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) -> store.unlockTask 'my-worker-id', task.id
.then (task) ->
expect(task.semaphore).to.be.null
it 'should throw a LockError if the worker ID is not the lock holder', ->
task =
name : 'task-to-unlock'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) -> store.unlockTask 'my-other-id', task.id
.then -> throw new Error('UnexpectedSuccess')
.catch LockError, (e) -> expect(e.message).to.eql 'KeyInvalid'
| true | crypto = require 'crypto'
bluebird = require 'bluebird'
DB = require '../lib/db.js'
LibStore = require 'uow-store'
Store = require '../index.js'
{ LockError } = LibStore
#LockError = LibStore.LockError
describe 'RethinkDB Store', ->
db = null
store = null
before ->
db = DB(rethinkConfig)
return db.install()
beforeEach ->
store = Store(rethinkConfig)
return db.run(db.r.table('uow_task').delete())
it 'should return a store object', ->
expect(store).to.be.an.instanceOf LibStore
describe '::handleReadyTask', ->
eStore = null
beforeEach ->
eStore = Store(rethinkConfig)
it 'should emit a ready event', (done) ->
task =
name : 'i-am-ready'
status : 'ready'
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
expect(ready_task.id).to.eql task.id
done()
store.createTask task
.then (task) -> eStore.handleReadyTask(task.id)
it 'should not emit an event for a locked task', (done) ->
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
setTimeout done, 10
task =
name : 'i-am-ready'
status : 'ready'
locked =
name : 'i-am-locked'
status : 'ready'
p1 = eStore.createTask locked
.then (task) -> eStore.lockTask('my-worker-id', task.id)
p2 = eStore.createTask task
bluebird.join p1, p2
.spread (lockedTask, readyTask) ->
eStore.handleReadyTask(lockedTask.id)
eStore.handleReadyTask(readyTask.id)
it 'should not emit an event for a delayed task', (done) ->
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
setTimeout done, 10
task =
name : 'PI:NAME:<NAME>END_PI'
status : 'ready'
delayed =
name : 'PI:NAME:<NAME>END_PI'
status : 'ready'
after : new Date().getTime()
delay : 1000
p1 = eStore.createTask delayed
p2 = eStore.createTask task
bluebird.join p1, p2
.spread (delayedTask, readyTask) ->
eStore.handleReadyTask(delayedTask.id)
eStore.handleReadyTask(readyTask.id)
it 'should not emit an event for a future task', (done) ->
eStore.on 'ready', (ready_task) ->
expect(ready_task.name).to.eql 'i-am-ready'
setTimeout done, 10
task =
name : 'PI:NAME:<NAME>END_PI'
status : 'ready'
future =
name : 'PI:NAME:<NAME>END_PI'
status : 'ready'
after : new Date().getTime() + 10000
p1 = eStore.createTask future
p2 = eStore.createTask task
bluebird.join p1, p2
.spread (futureTask, readyTask) ->
eStore.handleReadyTask(futureTask.id)
eStore.handleReadyTask(readyTask.id)
describe '::createTask', ->
it 'should be a function with an arity of one', ->
expect(store.createTask).to.be.a 'function'
expect(store.createTask.length).to.eql 1
it 'should throw a TypeError if the task object has an ID', ->
task =
id : 'bad'
store.createTask task
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'InvalidTaskObject'
it 'should assign the task object a v4 UUID', ->
task =
name : 'PI:NAME:<NAME>END_PI'
store.createTask task
.then (task) ->
expect(task.id).to.be.a 'string'
expect(task.id.length).to.eql 36
it 'should call the pickle function if it\'s available', ->
task =
name : 'create-task'
pickle : ->
id : this.id
name : 'pickled-task'
store.createTask task
.then (task) ->
expect(task.id).to.be.a 'string'
expect(task.id.length).to.eql 36
expect(task.name).to.eql 'pickled-task'
describe '::updateTask', ->
it 'should be a function with an arity of two', ->
expect(store.updateTask).to.be.a 'function'
expect(store.updateTask.length).to.eql 2
it 'should throw a TypeError if the task doesn\'t have an ID', ->
task =
name : 'bad-update-task'
store.updateTask 'my-worker-id', task
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'InvalidTaskObject'
it 'should throw a LockError if a lock key doesnt match ' +
' the lock holder', ->
task =
name : 'bad-worker-id'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) ->
task.updated = 1
store.updateTask 'my-other-id', task
.then -> throw new Error('UnexpectedSuccess')
.catch LockError, (e) -> expect(e.message).to.eql 'TaskLocked'
it 'should update a locked task given the correct worker ID', ->
task =
name : 'locked-task-to-update'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) ->
task.updated = 'success-for-locked-task'
store.updateTask 'my-worker-id', task
.then (task) ->
expect(task.name).to.eql 'locked-task-to-update'
expect(task.updated).to.eql 'success-for-locked-task'
describe '::getTaskById', ->
it 'should be a function with an arity of one', ->
expect(store.getTaskById).to.be.a 'function'
expect(store.getTaskById.length).to.eql 1
it 'should throw a TypeError if a task ID is not provided.', ->
store.getTaskById()
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'TaskIdNotProvided'
it 'should return the saved task', ->
task =
name : 'task-to-get'
store.createTask task
.then (task) -> store.getTaskById(task.id)
.then (task) ->
expect(task.id).to.be.a 'string'
expect(task.id.length).to.eql 36
expect(task.name).to.eql 'task-to-get'
describe '::lockTask', ->
it 'should be a function with an arity of three', ->
expect(store.lockTask).to.be.a 'function'
expect(store.lockTask.length).to.eql 3
it 'should throw a TypeError if the worker ID is not provided', ->
store.lockTask()
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'WorkerIdNotProvided'
it 'should throw a TypeError if the task ID is not provided', ->
store.lockTask('my-worker-id')
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'TaskIdNotProvided'
it 'should lock an unlocked task', ->
hash = crypto.createHash 'sha512'
task =
name : 'task-to-lock'
expected_key = null
store.createTask task
.then (task) ->
hash.update 'my-worker-id'
hash.update task.id
expected_key = hash.digest 'hex'
store.lockTask 'my-worker-id', task.id
.then (task) ->
expect(task.name).to.eql 'task-to-lock'
expect(task.semaphore.key).to.be.a 'string'
expect(task.semaphore.key).to.eql expected_key
it 'should throw a LockError if the task is already locked', ->
task =
name : 'task-check-lock'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) -> store.lockTask 'other-worker-id', task.id
.then -> throw new Error('UnexpectedSuccess')
.catch LockError, (e) -> expect(e.message).to.eql 'TaskAlreadyLocked'
describe '::unlockTask', ->
it 'should be a function with an arity of two', ->
expect(store.unlockTask).to.be.a 'function'
expect(store.unlockTask.length).to.eql 2
it 'should throw a TypeError if the worker ID is not provided', ->
store.unlockTask()
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'WorkerIdNotProvided'
it 'should throw a TypeError if the task ID is not provided', ->
store.unlockTask('my-worker-id')
.then -> throw new Error('UnexpectedSuccess')
.catch TypeError, (e) -> expect(e.message).to.eql 'TaskIdNotProvided'
it 'should unlock a locked task', ->
task =
name : 'task-to-unlock'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) -> store.unlockTask 'my-worker-id', task.id
.then (task) ->
expect(task.semaphore).to.be.null
it 'should throw a LockError if the worker ID is not the lock holder', ->
task =
name : 'task-to-unlock'
store.createTask task
.then (task) -> store.lockTask 'my-worker-id', task.id
.then (task) -> store.unlockTask 'my-other-id', task.id
.then -> throw new Error('UnexpectedSuccess')
.catch LockError, (e) -> expect(e.message).to.eql 'KeyInvalid'
|
[
{
"context": "eserved characters\", ()->\n context = {key1: 'value1', key2: 'valu\\e2', key3: 'val=u|e3', key4: 'val\\=",
"end": 9445,
"score": 0.9991768598556519,
"start": 9439,
"tag": "KEY",
"value": "value1"
},
{
"context": "rs\", ()->\n context = {key1: 'value1', key2: ... | test/uploader_spec.coffee | optune/cloudinary | 0 | require('dotenv').load(silent: true)
https = require('https')
http = require('http')
expect = require("expect.js")
sinon = require('sinon')
cloudinary = require("../cloudinary")
fs = require('fs')
Q = require('q')
path = require('path');
isFunction = require('lodash/isFunction')
at = require('lodash/at')
uniq = require('lodash/uniq')
ClientRequest = require('_http_client').ClientRequest
require('jsdom-global')()
helper = require("./spechelper")
TEST_TAG = helper.TEST_TAG
IMAGE_FILE = helper.IMAGE_FILE
LARGE_RAW_FILE = helper.LARGE_RAW_FILE
LARGE_VIDEO = helper.LARGE_VIDEO
EMPTY_IMAGE = helper.EMPTY_IMAGE
RAW_FILE = helper.RAW_FILE
UPLOAD_TAGS = helper.UPLOAD_TAGS
uploadImage = helper.uploadImage
describe "uploader", ->
before "Verify Configuration", ->
config = cloudinary.config(true)
if(!(config.api_key && config.api_secret))
expect().fail("Missing key and secret. Please set CLOUDINARY_URL.")
@timeout helper.TIMEOUT_LONG
after ->
config = cloudinary.config(true)
if(!(config.api_key && config.api_secret))
expect().fail("Missing key and secret. Please set CLOUDINARY_URL.")
Q.allSettled [
cloudinary.v2.api.delete_resources_by_tag(helper.TEST_TAG) unless cloudinary.config().keep_test_products
cloudinary.v2.api.delete_resources_by_tag(helper.TEST_TAG, resource_type: "video") unless cloudinary.config().keep_test_products
]
beforeEach ->
cloudinary.config(true)
it "should successfully upload file", () ->
@timeout helper.TIMEOUT_LONG
uploadImage()
.then (result)->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
it "should successfully upload url", () ->
cloudinary.v2.uploader.upload("http://cloudinary.com/images/old_logo.png", tags: UPLOAD_TAGS)
.then (result)->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
describe "rename", ()->
@timeout helper.TIMEOUT_LONG
it "should successfully rename a file", () ->
uploadImage()
.then (result)->
cloudinary.v2.uploader.rename(result.public_id, result.public_id+"2")
.then ()-> result.public_id
.then (public_id)->
cloudinary.v2.api.resource(public_id+"2")
it "should not rename to an existing public_id", ()->
Promise.all [
uploadImage()
uploadImage()
]
.then (results)->
cloudinary.v2.uploader.rename(results[0].public_id, results[1].public_id)
.then ()-> expect().fail()
.catch (error)-> expect(error).to.be.ok()
it "should allow to rename to an existing ID, if overwrite is true", ()->
Promise.all [
uploadImage()
uploadImage()
]
.then (results)->
cloudinary.v2.uploader.rename(results[0].public_id, results[1].public_id, overwrite: true)
.then ({public_id})->
cloudinary.v2.api.resource(public_id)
.then ({format})->
expect(format).to.eql "png"
context ":invalidate", ->
spy = undefined
xhr = undefined
end = undefined
before ->
xhr = sinon.useFakeXMLHttpRequest()
spy = sinon.spy(ClientRequest.prototype, 'write')
after ->
spy.restore()
xhr.restore()
it "should should pass the invalidate value in rename to the server", ()->
cloudinary.v2.uploader.rename("first_id", "second_id", invalidate: true)
expect(spy.calledWith(sinon.match((arg)-> arg.toString().match(/name="invalidate"/)))).to.be.ok()
describe "destroy", ()->
@timeout helper.TIMEOUT_MEDIUM
it "should delete a resource", ()->
uploadImage()
.then (result)->
public_id = result.public_id
cloudinary.v2.uploader.destroy(public_id)
.then (result)->
expect(result.result).to.eql("ok")
cloudinary.v2.api.resource(public_id)
.then ()-> expect().fail()
.catch (error)->
expect(error).to.be.ok()
it "should successfully call explicit api", () ->
cloudinary.v2.uploader.explicit("sample", type: "upload", eager: [crop: "scale", width: "2.0"])
.then (result)->
url = cloudinary.utils.url "sample",
type: "upload",
crop: "scale",
width: "2.0",
format: "jpg",
version: result["version"]
expect(result.eager[0].url).to.eql(url)
it "should support eager in upload", () ->
@timeout helper.TIMEOUT_SHORT
cloudinary.v2.uploader.upload(IMAGE_FILE, eager: [crop: "scale", width: "2.0"], tags: UPLOAD_TAGS)
describe "custom headers", ()->
it "should support custom headers in object format e.g. {Link: \"1\"}", () ->
cloudinary.v2.uploader.upload(IMAGE_FILE, headers: {Link: "1"}, tags: UPLOAD_TAGS)
it "should support custom headers as array of strings e.g. [\"Link: 1\"]", () ->
cloudinary.v2.uploader.upload(IMAGE_FILE, headers: ["Link: 1"], tags: UPLOAD_TAGS)
it "should successfully generate text image", () ->
cloudinary.v2.uploader.text("hello world", tags: UPLOAD_TAGS)
.then (result)->
expect(result.width).to.within(50,70)
expect(result.height).to.within(5,15)
it "should successfully upload stream", (done)->
stream = cloudinary.v2.uploader.upload_stream tags: UPLOAD_TAGS, (error, result) ->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
done()
file_reader = fs.createReadStream(IMAGE_FILE, {encoding: 'binary'})
file_reader.on 'data', (chunk)-> stream.write(chunk,'binary')
file_reader.on 'end', -> stream.end()
describe "tags", ()->
@timeout helper.TIMEOUT_MEDIUM
it "should add tags to existing resources", () ->
uploadImage()
.then (result)->
uploadImage().then (res)-> [result.public_id, res.public_id]
.then ([firstId, secondId])->
cloudinary.v2.uploader.add_tag("tag1", [firstId, secondId])
.then ()-> [firstId, secondId]
.then ([firstId, secondId])->
cloudinary.v2.api.resource(secondId)
.then (r1)->
expect(r1.tags).to.contain("tag1")
.then ()-> [firstId, secondId]
.then ([firstId, secondId])->
cloudinary.v2.uploader.remove_all_tags([firstId, secondId, 'noSuchId'])
.then (result)-> [firstId, secondId, result]
.then ([firstId, secondId, result])->
expect(result["public_ids"]).to.contain(firstId)
expect(result["public_ids"]).to.contain(secondId)
expect(result["public_ids"]).to.not.contain('noSuchId')
it "should keep existing tags when adding a new tag", ()->
uploadImage()
.then (result)->
cloudinary.v2.uploader.add_tag("tag1", result.public_id)
.then ()-> result.public_id
.then (publicId)->
cloudinary.v2.uploader.add_tag("tag2", publicId)
.then ()-> publicId
.then (publicId)->
cloudinary.v2.api.resource(publicId)
.then (result)->
expect(result.tags).to.contain("tag1").and.contain( "tag2")
it "should replace existing tag", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, tags: ["tag1", "tag2", TEST_TAG])
.then (result)->
public_id = result.public_id
cloudinary.v2.uploader.replace_tag( "tag3Å", public_id)
.then ()-> public_id
.then (public_id)-> # TODO this also tests non ascii characters
cloudinary.v2.api.resource(public_id)
.then (result)->
expect(result.tags).to.eql(["tag3Å"])
describe "context", ()->
second_id = first_id = ''
@timeout helper.TIMEOUT_MEDIUM
before ()->
Q.all [
uploadImage()
uploadImage()
]
.spread (result1, result2)->
first_id = result1.public_id
second_id = result2.public_id
it "should add context to existing resources", () ->
cloudinary.v2.uploader.add_context('alt=testAlt|custom=testCustom', [first_id, second_id])
.then ()->
cloudinary.v2.uploader.add_context({alt2: "testAlt2", custom2: "testCustom2"}, [first_id, second_id])
.then ()->
cloudinary.v2.api.resource(second_id)
.then ({context})->
expect(context.custom.alt).to.equal('testAlt')
expect(context.custom.alt2).to.equal('testAlt2')
expect(context.custom.custom).to.equal('testCustom')
expect(context.custom.custom2).to.equal('testCustom2')
cloudinary.v2.uploader.remove_all_context([first_id, second_id, 'noSuchId'])
.then ({public_ids})->
expect(public_ids).to.contain(first_id)
expect(public_ids).to.contain(second_id)
expect(public_ids).to.not.contain('noSuchId')
cloudinary.v2.api.resource(second_id)
.then ({context})->
expect(context).to.be undefined
it "should upload with context containing reserved characters", ()->
context = {key1: 'value1', key2: 'valu\e2', key3: 'val=u|e3', key4: 'val\=ue'}
cloudinary.v2.uploader.upload(IMAGE_FILE, context: context)
.then (result)->
cloudinary.v2.api.resource(result.public_id, context: true)
.then (result)->
expect(result.context.custom).to.eql(context)
it "should support timeouts", () ->
# testing a 1ms timeout, nobody is that fast.
cloudinary.v2.uploader.upload("http://cloudinary.com/images/old_logo.png", timeout: 1, tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch ({error})->
expect(error.http_code).to.eql(499)
expect(error.message).to.eql("Request Timeout")
it "should upload a file and base public id on the filename if use_filename is set to true", () ->
@timeout helper.TIMEOUT_MEDIUM
cloudinary.v2.uploader.upload(IMAGE_FILE, use_filename: yes, tags: UPLOAD_TAGS)
.then ({public_id})->
expect(public_id).to.match /logo_[a-zA-Z0-9]{6}/
it "should upload a file and set the filename as the public_id if use_filename is set to true and unique_filename is set to false", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, use_filename: yes, unique_filename: no, tags: UPLOAD_TAGS)
.then (result)->
expect(result.public_id).to.eql "logo"
describe "allowed_formats", ->
it "should allow whitelisted formats", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, allowed_formats: ["png"], tags: UPLOAD_TAGS)
.then (result)->
expect(result.format).to.eql("png")
it "should prevent non whitelisted formats from being uploaded", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, allowed_formats: ["jpg"], tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error.http_code).to.eql(400)
it "should allow non whitelisted formats if type is specified and convert to that type", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, allowed_formats: ["jpg"], format: "jpg", tags: UPLOAD_TAGS)
.then (result)->
expect(result.format).to.eql("jpg")
it "should allow sending face coordinates", ()->
@timeout helper.TIMEOUT_LONG
coordinates = [[120, 30, 109, 150], [121, 31, 110, 151]]
out_coordinates = [[120, 30, 109, 51], [121, 31, 110, 51]] # coordinates are limited to the image dimensions
different_coordinates = [[122, 32, 111, 152]]
custom_coordinates = [1,2,3,4]
cloudinary.v2.uploader.upload(IMAGE_FILE, face_coordinates: coordinates, faces: yes, tags: UPLOAD_TAGS)
.then (result)->
expect(result.faces).to.eql(out_coordinates)
cloudinary.v2.uploader.explicit(result.public_id, faces: true, face_coordinates: different_coordinates, custom_coordinates: custom_coordinates, type: "upload")
.then (result)->
expect(result.faces).not.to.be undefined
cloudinary.v2.api.resource(result.public_id, faces: yes, coordinates: yes)
.then (info)->
expect(info.faces).to.eql(different_coordinates)
expect(info.coordinates).to.eql(faces: different_coordinates, custom: [custom_coordinates])
it "should allow sending context", ()->
@timeout helper.TIMEOUT_LONG
cloudinary.v2.uploader.upload(IMAGE_FILE, context: {caption: "some caption", alt: "alternative"}, tags: UPLOAD_TAGS)
.then ({public_id})->
cloudinary.v2.api.resource(public_id, context: true)
.then ({context})->
expect(context.custom.caption).to.eql("some caption")
expect(context.custom.alt).to.eql("alternative")
it "should support requesting manual moderation", () ->
cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", tags: UPLOAD_TAGS)
.then (result)->
expect(result.moderation[0].status).to.eql("pending")
expect(result.moderation[0].kind).to.eql("manual")
it "should support requesting ocr analysis", ->
cloudinary.v2.uploader.upload(IMAGE_FILE, ocr: "adv_ocr", tags: UPLOAD_TAGS)
.then (result)->
expect(result.info.ocr).to.have.key("adv_ocr")
it "should support requesting raw conversion", ()->
cloudinary.v2.uploader.upload(RAW_FILE, raw_convert: "illegal", resource_type: "raw", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error?).to.be true
expect(error.message).to.contain "Raw convert is invalid"
it "should support requesting categorization", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, categorization: "illegal", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error?).to.be true
it "should support requesting detection", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, detection: "illegal", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error).not.to.be undefined
expect(error.message).to.contain "Detection is invalid"
it "should support requesting background_removal", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, background_removal: "illegal", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error?).to.be true
expect(error.message).to.contain "is invalid"
describe "upload_chunked", ()->
@timeout helper.TIMEOUT_LONG * 10
it "should specify chunk size", (done) ->
fs.stat LARGE_RAW_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_large LARGE_RAW_FILE, {chunk_size: 7000000, timeout: helper.TIMEOUT_LONG, tags: UPLOAD_TAGS}, (error, result) ->
return done(new Error error.message) if error?
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("4c13724e950abcb13ec480e10f8541f5")
done()
true
it "should return error if value is less than 5MB", (done)->
fs.stat LARGE_RAW_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_large LARGE_RAW_FILE, {chunk_size: 40000, tags: UPLOAD_TAGS}, (error, result) ->
expect(error.message).to.eql("All parts except EOF-chunk must be larger than 5mb")
done()
true
it "should support uploading a small raw file", (done) ->
fs.stat RAW_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_large RAW_FILE, tags: UPLOAD_TAGS, (error, result) ->
return done(new Error error.message) if error?
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("ffc265d8d1296247972b4d478048e448")
done()
true
it "should support uploading a small image file", (done) ->
fs.stat IMAGE_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_chunked IMAGE_FILE, tags: UPLOAD_TAGS, (error, result) ->
return done(new Error error.message) if error?
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("7dc60722d4653261648038b579fdb89e")
done()
true
it "should support uploading large video files", () ->
@timeout helper.TIMEOUT_LONG * 10
writeSpy = sinon.spy(ClientRequest.prototype, 'write')
stat = fs.statSync( LARGE_VIDEO)
expect(stat).to.be.ok()
Q.denodeify(cloudinary.v2.uploader.upload_chunked)( LARGE_VIDEO, {chunk_size: 6000000, resource_type: 'video', timeout: helper.TIMEOUT_LONG * 10, tags: UPLOAD_TAGS})
.then (result)->
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("ff6c391d26be0837ee5229885b5bd571")
timestamps = writeSpy.args.map((a)-> a[0].toString())
.filter((p) -> p.match(/timestamp/))
.map((p) -> p.match(/"timestamp"\s+(\d+)/)[1])
expect(timestamps.length).to.be.greaterThan(1)
if process.versions.node && process.versions.node[0] == '4'
timestamps.pop() # hack - node 4 duplicates the last entry
expect(uniq(timestamps)).to.eql(timestamps)
.finally ->
writeSpy.restore()
it "should update timestamp for each chuck", ()->
writeSpy = sinon.spy(ClientRequest.prototype, 'write')
Q.denodeify(cloudinary.v2.uploader.upload_chunked)( LARGE_VIDEO, {chunk_size: 6000000, resource_type: 'video', timeout: helper.TIMEOUT_LONG * 10, tags: UPLOAD_TAGS})
.then ->
timestamps = writeSpy.args.map((a)-> a[0].toString())
.filter((p) -> p.match(/timestamp/))
.map((p) -> p.match(/"timestamp"\s+(\d+)/)[1])
expect(timestamps.length).to.be.greaterThan(1)
expect(uniq(timestamps)).to.eql(timestamps)
.finally ->
writeSpy.restore()
it "should support uploading based on a url", (done) ->
@timeout helper.TIMEOUT_MEDIUM
cloudinary.v2.uploader.upload_large "http://cloudinary.com/images/old_logo.png", {tags: UPLOAD_TAGS}, (error, result) ->
return done(new Error error.message) if error?
expect(result.etag).to.eql("7dc60722d4653261648038b579fdb89e")
done()
true
it "should support unsigned uploading using presets", ()->
@timeout helper.TIMEOUT_LONG
cloudinary.v2.api.create_upload_preset(folder: "upload_folder", unsigned: true, tags: UPLOAD_TAGS)
.then (preset)->
cloudinary.v2.uploader.unsigned_upload(IMAGE_FILE, preset.name, tags: UPLOAD_TAGS)
.then (result)-> [preset.name, result.public_id]
.then ([presetName, public_id])->
expect(public_id).to.match /^upload_folder\/[a-z0-9]+$/
cloudinary.v2.api.delete_upload_preset(presetName)
it "should reject promise if error code is returned from the server", () ->
cloudinary.v2.uploader.upload(EMPTY_IMAGE, tags: UPLOAD_TAGS)
.then ->
expect().fail("server should return an error when uploading an empty file")
.catch (error)->
expect(error.message.toLowerCase()).to.contain "empty"
it "should successfully upload with pipes", (done) ->
@timeout helper.TIMEOUT_LONG
upload = cloudinary.v2.uploader.upload_stream tags: UPLOAD_TAGS, (error, result) ->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
done()
file_reader = fs.createReadStream(IMAGE_FILE)
file_reader.pipe(upload)
it "should fail with http.Agent (non secure)", () ->
@timeout helper.TIMEOUT_LONG
expect(cloudinary.v2.uploader.upload_stream).withArgs({agent:new http.Agent},(error, result) ->
).to.throwError()
it "should successfully override https agent", () ->
upload = cloudinary.v2.uploader.upload_stream agent:new https.Agent, tags: UPLOAD_TAGS, (error, result) ->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
file_reader = fs.createReadStream(IMAGE_FILE)
file_reader.pipe(upload)
context ":responsive_breakpoints", ->
context ":create_derived with different transformation settings", ->
before ->
helper.setupCache()
it 'should return a responsive_breakpoints in the response', ()->
cloudinary.v2.uploader.upload IMAGE_FILE, responsive_breakpoints: [{
transformation: {effect: "sepia"},
format: "jpg",
bytes_step: 20000,
create_derived: true,
min_width: 200,
max_width: 1000,
max_images: 20
}, {
transformation: {angle: 10},
format: "gif",
create_derived: true,
bytes_step: 20000,
min_width: 200,
max_width: 1000,
max_images: 20
}], tags: UPLOAD_TAGS
.then (result)->
expect(result).to.have.key('responsive_breakpoints')
expect(result.responsive_breakpoints).to.have.length(2)
expect(at(result, "responsive_breakpoints[0].transformation")[0]).to.eql("e_sepia")
expect(at(result, "responsive_breakpoints[0].breakpoints[0].url")[0]).to.match(/\.jpg$/)
expect(at(result, "responsive_breakpoints[1].transformation")[0]).to.eql("a_10")
expect(at(result, "responsive_breakpoints[1].breakpoints[0].url")[0]).to.match(/\.gif$/)
result.responsive_breakpoints.map (bp)->
format = path.extname(bp.breakpoints[0].url).slice(1)
cached = cloudinary.Cache.get(
result.public_id,
{raw_transformation: bp.transformation, format})
expect(cached).to.be.ok()
expect(cached.length).to.be(bp.breakpoints.length)
bp.breakpoints.forEach (o)->
expect(cached).to.contain(o.width)
describe "async upload", ->
mocked = helper.mockTest()
it "should pass `async` value to the server", ->
cloudinary.v2.uploader.upload IMAGE_FILE, {async: true, transformation: {effect: "sepia"}}
sinon.assert.calledWith mocked.write, sinon.match(helper.uploadParamMatcher("async", 1))
describe "explicit", ->
spy = undefined
xhr = undefined
before ->
xhr = sinon.useFakeXMLHttpRequest()
spy = sinon.spy(ClientRequest.prototype, 'write')
after ->
spy.restore()
xhr.restore()
describe ":invalidate", ->
it "should should pass the invalidate value to the server", ()->
cloudinary.v2.uploader.explicit "cloudinary", type: "twitter_name", eager: [crop: "scale", width: "2.0"], invalidate: true, tags: [TEST_TAG]
sinon.assert.calledWith(spy, sinon.match(helper.uploadParamMatcher('invalidate', 1)))
it "should support raw_convert", ->
cloudinary.v2.uploader.explicit "cloudinary", raw_convert: "google_speech", tags: [TEST_TAG]
sinon.assert.calledWith(spy, sinon.match(
helper.uploadParamMatcher('raw_convert', 'google_speech')
))
it "should create an image upload tag with required properties", () ->
@timeout helper.TIMEOUT_LONG
tag = cloudinary.v2.uploader.image_upload_tag "image_id", chunk_size: "1234"
expect(tag).to.match(/^<input/)
# Create an HTMLElement from the returned string to validate attributes
fakeDiv = document.createElement('div');
fakeDiv.innerHTML = tag;
input_element = fakeDiv.firstChild;
expect(input_element.tagName.toLowerCase()).to.be('input');
expect(input_element.getAttribute("data-url")).to.be.ok();
expect(input_element.getAttribute("data-form-data")).to.be.ok();
expect(input_element.getAttribute("data-cloudinary-field")).to.match(/image_id/);
expect(input_element.getAttribute("data-max-chunk-size")).to.match(/1234/);
expect(input_element.getAttribute("class")).to.match(/cloudinary-fileupload/);
expect(input_element.getAttribute("name")).to.be('file');
expect(input_element.getAttribute("type")).to.be('file');
describe "access_control", ()->
writeSpy = undefined
requestSpy = undefined
options = undefined
beforeEach ->
writeSpy = sinon.spy(ClientRequest.prototype, 'write')
requestSpy = sinon.spy(http, 'request')
options = {
public_id: helper.TEST_TAG,
tags: [helper.UPLOAD_TAGS..., 'access_control_test']
}
afterEach ->
requestSpy.restore()
writeSpy.restore()
acl = {
access_type: 'anonymous',
start: new Date(Date.UTC(2019,1,22, 16, 20, 57)),
end: '2019-03-22 00:00 +0200'
}
acl_string =
'{"access_type":"anonymous","start":"2019-02-22T16:20:57.000Z","end":"2019-03-22 00:00 +0200"}'
it "should allow the user to define ACL in the upload parameters", ()->
options.access_control = [acl]
uploadImage(options).then (resource)=>
sinon.assert.calledWith(writeSpy, sinon.match(
helper.uploadParamMatcher('access_control', "[#{acl_string}]")
))
expect(resource).to.have.key('access_control')
response_acl = resource["access_control"]
expect(response_acl.length).to.be(1)
expect(response_acl[0]["access_type"]).to.be("anonymous")
expect(Date.parse(response_acl[0]["start"])).to.be(Date.parse(acl.start))
expect(Date.parse(response_acl[0]["end"])).to.be(Date.parse(acl.end))
| 133846 | require('dotenv').load(silent: true)
https = require('https')
http = require('http')
expect = require("expect.js")
sinon = require('sinon')
cloudinary = require("../cloudinary")
fs = require('fs')
Q = require('q')
path = require('path');
isFunction = require('lodash/isFunction')
at = require('lodash/at')
uniq = require('lodash/uniq')
ClientRequest = require('_http_client').ClientRequest
require('jsdom-global')()
helper = require("./spechelper")
TEST_TAG = helper.TEST_TAG
IMAGE_FILE = helper.IMAGE_FILE
LARGE_RAW_FILE = helper.LARGE_RAW_FILE
LARGE_VIDEO = helper.LARGE_VIDEO
EMPTY_IMAGE = helper.EMPTY_IMAGE
RAW_FILE = helper.RAW_FILE
UPLOAD_TAGS = helper.UPLOAD_TAGS
uploadImage = helper.uploadImage
describe "uploader", ->
before "Verify Configuration", ->
config = cloudinary.config(true)
if(!(config.api_key && config.api_secret))
expect().fail("Missing key and secret. Please set CLOUDINARY_URL.")
@timeout helper.TIMEOUT_LONG
after ->
config = cloudinary.config(true)
if(!(config.api_key && config.api_secret))
expect().fail("Missing key and secret. Please set CLOUDINARY_URL.")
Q.allSettled [
cloudinary.v2.api.delete_resources_by_tag(helper.TEST_TAG) unless cloudinary.config().keep_test_products
cloudinary.v2.api.delete_resources_by_tag(helper.TEST_TAG, resource_type: "video") unless cloudinary.config().keep_test_products
]
beforeEach ->
cloudinary.config(true)
it "should successfully upload file", () ->
@timeout helper.TIMEOUT_LONG
uploadImage()
.then (result)->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
it "should successfully upload url", () ->
cloudinary.v2.uploader.upload("http://cloudinary.com/images/old_logo.png", tags: UPLOAD_TAGS)
.then (result)->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
describe "rename", ()->
@timeout helper.TIMEOUT_LONG
it "should successfully rename a file", () ->
uploadImage()
.then (result)->
cloudinary.v2.uploader.rename(result.public_id, result.public_id+"2")
.then ()-> result.public_id
.then (public_id)->
cloudinary.v2.api.resource(public_id+"2")
it "should not rename to an existing public_id", ()->
Promise.all [
uploadImage()
uploadImage()
]
.then (results)->
cloudinary.v2.uploader.rename(results[0].public_id, results[1].public_id)
.then ()-> expect().fail()
.catch (error)-> expect(error).to.be.ok()
it "should allow to rename to an existing ID, if overwrite is true", ()->
Promise.all [
uploadImage()
uploadImage()
]
.then (results)->
cloudinary.v2.uploader.rename(results[0].public_id, results[1].public_id, overwrite: true)
.then ({public_id})->
cloudinary.v2.api.resource(public_id)
.then ({format})->
expect(format).to.eql "png"
context ":invalidate", ->
spy = undefined
xhr = undefined
end = undefined
before ->
xhr = sinon.useFakeXMLHttpRequest()
spy = sinon.spy(ClientRequest.prototype, 'write')
after ->
spy.restore()
xhr.restore()
it "should should pass the invalidate value in rename to the server", ()->
cloudinary.v2.uploader.rename("first_id", "second_id", invalidate: true)
expect(spy.calledWith(sinon.match((arg)-> arg.toString().match(/name="invalidate"/)))).to.be.ok()
describe "destroy", ()->
@timeout helper.TIMEOUT_MEDIUM
it "should delete a resource", ()->
uploadImage()
.then (result)->
public_id = result.public_id
cloudinary.v2.uploader.destroy(public_id)
.then (result)->
expect(result.result).to.eql("ok")
cloudinary.v2.api.resource(public_id)
.then ()-> expect().fail()
.catch (error)->
expect(error).to.be.ok()
it "should successfully call explicit api", () ->
cloudinary.v2.uploader.explicit("sample", type: "upload", eager: [crop: "scale", width: "2.0"])
.then (result)->
url = cloudinary.utils.url "sample",
type: "upload",
crop: "scale",
width: "2.0",
format: "jpg",
version: result["version"]
expect(result.eager[0].url).to.eql(url)
it "should support eager in upload", () ->
@timeout helper.TIMEOUT_SHORT
cloudinary.v2.uploader.upload(IMAGE_FILE, eager: [crop: "scale", width: "2.0"], tags: UPLOAD_TAGS)
describe "custom headers", ()->
it "should support custom headers in object format e.g. {Link: \"1\"}", () ->
cloudinary.v2.uploader.upload(IMAGE_FILE, headers: {Link: "1"}, tags: UPLOAD_TAGS)
it "should support custom headers as array of strings e.g. [\"Link: 1\"]", () ->
cloudinary.v2.uploader.upload(IMAGE_FILE, headers: ["Link: 1"], tags: UPLOAD_TAGS)
it "should successfully generate text image", () ->
cloudinary.v2.uploader.text("hello world", tags: UPLOAD_TAGS)
.then (result)->
expect(result.width).to.within(50,70)
expect(result.height).to.within(5,15)
it "should successfully upload stream", (done)->
stream = cloudinary.v2.uploader.upload_stream tags: UPLOAD_TAGS, (error, result) ->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
done()
file_reader = fs.createReadStream(IMAGE_FILE, {encoding: 'binary'})
file_reader.on 'data', (chunk)-> stream.write(chunk,'binary')
file_reader.on 'end', -> stream.end()
describe "tags", ()->
@timeout helper.TIMEOUT_MEDIUM
it "should add tags to existing resources", () ->
uploadImage()
.then (result)->
uploadImage().then (res)-> [result.public_id, res.public_id]
.then ([firstId, secondId])->
cloudinary.v2.uploader.add_tag("tag1", [firstId, secondId])
.then ()-> [firstId, secondId]
.then ([firstId, secondId])->
cloudinary.v2.api.resource(secondId)
.then (r1)->
expect(r1.tags).to.contain("tag1")
.then ()-> [firstId, secondId]
.then ([firstId, secondId])->
cloudinary.v2.uploader.remove_all_tags([firstId, secondId, 'noSuchId'])
.then (result)-> [firstId, secondId, result]
.then ([firstId, secondId, result])->
expect(result["public_ids"]).to.contain(firstId)
expect(result["public_ids"]).to.contain(secondId)
expect(result["public_ids"]).to.not.contain('noSuchId')
it "should keep existing tags when adding a new tag", ()->
uploadImage()
.then (result)->
cloudinary.v2.uploader.add_tag("tag1", result.public_id)
.then ()-> result.public_id
.then (publicId)->
cloudinary.v2.uploader.add_tag("tag2", publicId)
.then ()-> publicId
.then (publicId)->
cloudinary.v2.api.resource(publicId)
.then (result)->
expect(result.tags).to.contain("tag1").and.contain( "tag2")
it "should replace existing tag", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, tags: ["tag1", "tag2", TEST_TAG])
.then (result)->
public_id = result.public_id
cloudinary.v2.uploader.replace_tag( "tag3Å", public_id)
.then ()-> public_id
.then (public_id)-> # TODO this also tests non ascii characters
cloudinary.v2.api.resource(public_id)
.then (result)->
expect(result.tags).to.eql(["tag3Å"])
describe "context", ()->
second_id = first_id = ''
@timeout helper.TIMEOUT_MEDIUM
before ()->
Q.all [
uploadImage()
uploadImage()
]
.spread (result1, result2)->
first_id = result1.public_id
second_id = result2.public_id
it "should add context to existing resources", () ->
cloudinary.v2.uploader.add_context('alt=testAlt|custom=testCustom', [first_id, second_id])
.then ()->
cloudinary.v2.uploader.add_context({alt2: "testAlt2", custom2: "testCustom2"}, [first_id, second_id])
.then ()->
cloudinary.v2.api.resource(second_id)
.then ({context})->
expect(context.custom.alt).to.equal('testAlt')
expect(context.custom.alt2).to.equal('testAlt2')
expect(context.custom.custom).to.equal('testCustom')
expect(context.custom.custom2).to.equal('testCustom2')
cloudinary.v2.uploader.remove_all_context([first_id, second_id, 'noSuchId'])
.then ({public_ids})->
expect(public_ids).to.contain(first_id)
expect(public_ids).to.contain(second_id)
expect(public_ids).to.not.contain('noSuchId')
cloudinary.v2.api.resource(second_id)
.then ({context})->
expect(context).to.be undefined
it "should upload with context containing reserved characters", ()->
context = {key1: '<KEY>', key2: '<KEY>', key3: '<KEY>', key4: '<KEY>'}
cloudinary.v2.uploader.upload(IMAGE_FILE, context: context)
.then (result)->
cloudinary.v2.api.resource(result.public_id, context: true)
.then (result)->
expect(result.context.custom).to.eql(context)
it "should support timeouts", () ->
# testing a 1ms timeout, nobody is that fast.
cloudinary.v2.uploader.upload("http://cloudinary.com/images/old_logo.png", timeout: 1, tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch ({error})->
expect(error.http_code).to.eql(499)
expect(error.message).to.eql("Request Timeout")
it "should upload a file and base public id on the filename if use_filename is set to true", () ->
@timeout helper.TIMEOUT_MEDIUM
cloudinary.v2.uploader.upload(IMAGE_FILE, use_filename: yes, tags: UPLOAD_TAGS)
.then ({public_id})->
expect(public_id).to.match /logo_[a-zA-Z0-9]{6}/
it "should upload a file and set the filename as the public_id if use_filename is set to true and unique_filename is set to false", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, use_filename: yes, unique_filename: no, tags: UPLOAD_TAGS)
.then (result)->
expect(result.public_id).to.eql "logo"
describe "allowed_formats", ->
it "should allow whitelisted formats", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, allowed_formats: ["png"], tags: UPLOAD_TAGS)
.then (result)->
expect(result.format).to.eql("png")
it "should prevent non whitelisted formats from being uploaded", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, allowed_formats: ["jpg"], tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error.http_code).to.eql(400)
it "should allow non whitelisted formats if type is specified and convert to that type", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, allowed_formats: ["jpg"], format: "jpg", tags: UPLOAD_TAGS)
.then (result)->
expect(result.format).to.eql("jpg")
it "should allow sending face coordinates", ()->
@timeout helper.TIMEOUT_LONG
coordinates = [[120, 30, 109, 150], [121, 31, 110, 151]]
out_coordinates = [[120, 30, 109, 51], [121, 31, 110, 51]] # coordinates are limited to the image dimensions
different_coordinates = [[122, 32, 111, 152]]
custom_coordinates = [1,2,3,4]
cloudinary.v2.uploader.upload(IMAGE_FILE, face_coordinates: coordinates, faces: yes, tags: UPLOAD_TAGS)
.then (result)->
expect(result.faces).to.eql(out_coordinates)
cloudinary.v2.uploader.explicit(result.public_id, faces: true, face_coordinates: different_coordinates, custom_coordinates: custom_coordinates, type: "upload")
.then (result)->
expect(result.faces).not.to.be undefined
cloudinary.v2.api.resource(result.public_id, faces: yes, coordinates: yes)
.then (info)->
expect(info.faces).to.eql(different_coordinates)
expect(info.coordinates).to.eql(faces: different_coordinates, custom: [custom_coordinates])
it "should allow sending context", ()->
@timeout helper.TIMEOUT_LONG
cloudinary.v2.uploader.upload(IMAGE_FILE, context: {caption: "some caption", alt: "alternative"}, tags: UPLOAD_TAGS)
.then ({public_id})->
cloudinary.v2.api.resource(public_id, context: true)
.then ({context})->
expect(context.custom.caption).to.eql("some caption")
expect(context.custom.alt).to.eql("alternative")
it "should support requesting manual moderation", () ->
cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", tags: UPLOAD_TAGS)
.then (result)->
expect(result.moderation[0].status).to.eql("pending")
expect(result.moderation[0].kind).to.eql("manual")
it "should support requesting ocr analysis", ->
cloudinary.v2.uploader.upload(IMAGE_FILE, ocr: "adv_ocr", tags: UPLOAD_TAGS)
.then (result)->
expect(result.info.ocr).to.have.key("adv_ocr")
it "should support requesting raw conversion", ()->
cloudinary.v2.uploader.upload(RAW_FILE, raw_convert: "illegal", resource_type: "raw", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error?).to.be true
expect(error.message).to.contain "Raw convert is invalid"
it "should support requesting categorization", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, categorization: "illegal", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error?).to.be true
it "should support requesting detection", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, detection: "illegal", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error).not.to.be undefined
expect(error.message).to.contain "Detection is invalid"
it "should support requesting background_removal", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, background_removal: "illegal", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error?).to.be true
expect(error.message).to.contain "is invalid"
describe "upload_chunked", ()->
@timeout helper.TIMEOUT_LONG * 10
it "should specify chunk size", (done) ->
fs.stat LARGE_RAW_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_large LARGE_RAW_FILE, {chunk_size: 7000000, timeout: helper.TIMEOUT_LONG, tags: UPLOAD_TAGS}, (error, result) ->
return done(new Error error.message) if error?
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("4c13724e950abcb13ec480e10f8541f5")
done()
true
it "should return error if value is less than 5MB", (done)->
fs.stat LARGE_RAW_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_large LARGE_RAW_FILE, {chunk_size: 40000, tags: UPLOAD_TAGS}, (error, result) ->
expect(error.message).to.eql("All parts except EOF-chunk must be larger than 5mb")
done()
true
it "should support uploading a small raw file", (done) ->
fs.stat RAW_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_large RAW_FILE, tags: UPLOAD_TAGS, (error, result) ->
return done(new Error error.message) if error?
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("ffc265d8d1296247972b4d478048e448")
done()
true
it "should support uploading a small image file", (done) ->
fs.stat IMAGE_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_chunked IMAGE_FILE, tags: UPLOAD_TAGS, (error, result) ->
return done(new Error error.message) if error?
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("7dc60722d4653261648038b579fdb89e")
done()
true
it "should support uploading large video files", () ->
@timeout helper.TIMEOUT_LONG * 10
writeSpy = sinon.spy(ClientRequest.prototype, 'write')
stat = fs.statSync( LARGE_VIDEO)
expect(stat).to.be.ok()
Q.denodeify(cloudinary.v2.uploader.upload_chunked)( LARGE_VIDEO, {chunk_size: 6000000, resource_type: 'video', timeout: helper.TIMEOUT_LONG * 10, tags: UPLOAD_TAGS})
.then (result)->
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("ff6c391d26be0837ee5229885b5bd571")
timestamps = writeSpy.args.map((a)-> a[0].toString())
.filter((p) -> p.match(/timestamp/))
.map((p) -> p.match(/"timestamp"\s+(\d+)/)[1])
expect(timestamps.length).to.be.greaterThan(1)
if process.versions.node && process.versions.node[0] == '4'
timestamps.pop() # hack - node 4 duplicates the last entry
expect(uniq(timestamps)).to.eql(timestamps)
.finally ->
writeSpy.restore()
it "should update timestamp for each chuck", ()->
writeSpy = sinon.spy(ClientRequest.prototype, 'write')
Q.denodeify(cloudinary.v2.uploader.upload_chunked)( LARGE_VIDEO, {chunk_size: 6000000, resource_type: 'video', timeout: helper.TIMEOUT_LONG * 10, tags: UPLOAD_TAGS})
.then ->
timestamps = writeSpy.args.map((a)-> a[0].toString())
.filter((p) -> p.match(/timestamp/))
.map((p) -> p.match(/"timestamp"\s+(\d+)/)[1])
expect(timestamps.length).to.be.greaterThan(1)
expect(uniq(timestamps)).to.eql(timestamps)
.finally ->
writeSpy.restore()
it "should support uploading based on a url", (done) ->
@timeout helper.TIMEOUT_MEDIUM
cloudinary.v2.uploader.upload_large "http://cloudinary.com/images/old_logo.png", {tags: UPLOAD_TAGS}, (error, result) ->
return done(new Error error.message) if error?
expect(result.etag).to.eql("7dc60722d4653261648038b579fdb89e")
done()
true
it "should support unsigned uploading using presets", ()->
@timeout helper.TIMEOUT_LONG
cloudinary.v2.api.create_upload_preset(folder: "upload_folder", unsigned: true, tags: UPLOAD_TAGS)
.then (preset)->
cloudinary.v2.uploader.unsigned_upload(IMAGE_FILE, preset.name, tags: UPLOAD_TAGS)
.then (result)-> [preset.name, result.public_id]
.then ([presetName, public_id])->
expect(public_id).to.match /^upload_folder\/[a-z0-9]+$/
cloudinary.v2.api.delete_upload_preset(presetName)
it "should reject promise if error code is returned from the server", () ->
cloudinary.v2.uploader.upload(EMPTY_IMAGE, tags: UPLOAD_TAGS)
.then ->
expect().fail("server should return an error when uploading an empty file")
.catch (error)->
expect(error.message.toLowerCase()).to.contain "empty"
it "should successfully upload with pipes", (done) ->
@timeout helper.TIMEOUT_LONG
upload = cloudinary.v2.uploader.upload_stream tags: UPLOAD_TAGS, (error, result) ->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
done()
file_reader = fs.createReadStream(IMAGE_FILE)
file_reader.pipe(upload)
it "should fail with http.Agent (non secure)", () ->
@timeout helper.TIMEOUT_LONG
expect(cloudinary.v2.uploader.upload_stream).withArgs({agent:new http.Agent},(error, result) ->
).to.throwError()
it "should successfully override https agent", () ->
upload = cloudinary.v2.uploader.upload_stream agent:new https.Agent, tags: UPLOAD_TAGS, (error, result) ->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
file_reader = fs.createReadStream(IMAGE_FILE)
file_reader.pipe(upload)
context ":responsive_breakpoints", ->
context ":create_derived with different transformation settings", ->
before ->
helper.setupCache()
it 'should return a responsive_breakpoints in the response', ()->
cloudinary.v2.uploader.upload IMAGE_FILE, responsive_breakpoints: [{
transformation: {effect: "sepia"},
format: "jpg",
bytes_step: 20000,
create_derived: true,
min_width: 200,
max_width: 1000,
max_images: 20
}, {
transformation: {angle: 10},
format: "gif",
create_derived: true,
bytes_step: 20000,
min_width: 200,
max_width: 1000,
max_images: 20
}], tags: UPLOAD_TAGS
.then (result)->
expect(result).to.have.key('responsive_breakpoints')
expect(result.responsive_breakpoints).to.have.length(2)
expect(at(result, "responsive_breakpoints[0].transformation")[0]).to.eql("e_sepia")
expect(at(result, "responsive_breakpoints[0].breakpoints[0].url")[0]).to.match(/\.jpg$/)
expect(at(result, "responsive_breakpoints[1].transformation")[0]).to.eql("a_10")
expect(at(result, "responsive_breakpoints[1].breakpoints[0].url")[0]).to.match(/\.gif$/)
result.responsive_breakpoints.map (bp)->
format = path.extname(bp.breakpoints[0].url).slice(1)
cached = cloudinary.Cache.get(
result.public_id,
{raw_transformation: bp.transformation, format})
expect(cached).to.be.ok()
expect(cached.length).to.be(bp.breakpoints.length)
bp.breakpoints.forEach (o)->
expect(cached).to.contain(o.width)
describe "async upload", ->
mocked = helper.mockTest()
it "should pass `async` value to the server", ->
cloudinary.v2.uploader.upload IMAGE_FILE, {async: true, transformation: {effect: "sepia"}}
sinon.assert.calledWith mocked.write, sinon.match(helper.uploadParamMatcher("async", 1))
describe "explicit", ->
spy = undefined
xhr = undefined
before ->
xhr = sinon.useFakeXMLHttpRequest()
spy = sinon.spy(ClientRequest.prototype, 'write')
after ->
spy.restore()
xhr.restore()
describe ":invalidate", ->
it "should should pass the invalidate value to the server", ()->
cloudinary.v2.uploader.explicit "cloudinary", type: "twitter_name", eager: [crop: "scale", width: "2.0"], invalidate: true, tags: [TEST_TAG]
sinon.assert.calledWith(spy, sinon.match(helper.uploadParamMatcher('invalidate', 1)))
it "should support raw_convert", ->
cloudinary.v2.uploader.explicit "cloudinary", raw_convert: "google_speech", tags: [TEST_TAG]
sinon.assert.calledWith(spy, sinon.match(
helper.uploadParamMatcher('raw_convert', 'google_speech')
))
it "should create an image upload tag with required properties", () ->
@timeout helper.TIMEOUT_LONG
tag = cloudinary.v2.uploader.image_upload_tag "image_id", chunk_size: "1234"
expect(tag).to.match(/^<input/)
# Create an HTMLElement from the returned string to validate attributes
fakeDiv = document.createElement('div');
fakeDiv.innerHTML = tag;
input_element = fakeDiv.firstChild;
expect(input_element.tagName.toLowerCase()).to.be('input');
expect(input_element.getAttribute("data-url")).to.be.ok();
expect(input_element.getAttribute("data-form-data")).to.be.ok();
expect(input_element.getAttribute("data-cloudinary-field")).to.match(/image_id/);
expect(input_element.getAttribute("data-max-chunk-size")).to.match(/1234/);
expect(input_element.getAttribute("class")).to.match(/cloudinary-fileupload/);
expect(input_element.getAttribute("name")).to.be('file');
expect(input_element.getAttribute("type")).to.be('file');
describe "access_control", ()->
writeSpy = undefined
requestSpy = undefined
options = undefined
beforeEach ->
writeSpy = sinon.spy(ClientRequest.prototype, 'write')
requestSpy = sinon.spy(http, 'request')
options = {
public_id: helper.TEST_TAG,
tags: [helper.UPLOAD_TAGS..., 'access_control_test']
}
afterEach ->
requestSpy.restore()
writeSpy.restore()
acl = {
access_type: 'anonymous',
start: new Date(Date.UTC(2019,1,22, 16, 20, 57)),
end: '2019-03-22 00:00 +0200'
}
acl_string =
'{"access_type":"anonymous","start":"2019-02-22T16:20:57.000Z","end":"2019-03-22 00:00 +0200"}'
it "should allow the user to define ACL in the upload parameters", ()->
options.access_control = [acl]
uploadImage(options).then (resource)=>
sinon.assert.calledWith(writeSpy, sinon.match(
helper.uploadParamMatcher('access_control', "[#{acl_string}]")
))
expect(resource).to.have.key('access_control')
response_acl = resource["access_control"]
expect(response_acl.length).to.be(1)
expect(response_acl[0]["access_type"]).to.be("anonymous")
expect(Date.parse(response_acl[0]["start"])).to.be(Date.parse(acl.start))
expect(Date.parse(response_acl[0]["end"])).to.be(Date.parse(acl.end))
| true | require('dotenv').load(silent: true)
https = require('https')
http = require('http')
expect = require("expect.js")
sinon = require('sinon')
cloudinary = require("../cloudinary")
fs = require('fs')
Q = require('q')
path = require('path');
isFunction = require('lodash/isFunction')
at = require('lodash/at')
uniq = require('lodash/uniq')
ClientRequest = require('_http_client').ClientRequest
require('jsdom-global')()
helper = require("./spechelper")
TEST_TAG = helper.TEST_TAG
IMAGE_FILE = helper.IMAGE_FILE
LARGE_RAW_FILE = helper.LARGE_RAW_FILE
LARGE_VIDEO = helper.LARGE_VIDEO
EMPTY_IMAGE = helper.EMPTY_IMAGE
RAW_FILE = helper.RAW_FILE
UPLOAD_TAGS = helper.UPLOAD_TAGS
uploadImage = helper.uploadImage
describe "uploader", ->
before "Verify Configuration", ->
config = cloudinary.config(true)
if(!(config.api_key && config.api_secret))
expect().fail("Missing key and secret. Please set CLOUDINARY_URL.")
@timeout helper.TIMEOUT_LONG
after ->
config = cloudinary.config(true)
if(!(config.api_key && config.api_secret))
expect().fail("Missing key and secret. Please set CLOUDINARY_URL.")
Q.allSettled [
cloudinary.v2.api.delete_resources_by_tag(helper.TEST_TAG) unless cloudinary.config().keep_test_products
cloudinary.v2.api.delete_resources_by_tag(helper.TEST_TAG, resource_type: "video") unless cloudinary.config().keep_test_products
]
beforeEach ->
cloudinary.config(true)
it "should successfully upload file", () ->
@timeout helper.TIMEOUT_LONG
uploadImage()
.then (result)->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
it "should successfully upload url", () ->
cloudinary.v2.uploader.upload("http://cloudinary.com/images/old_logo.png", tags: UPLOAD_TAGS)
.then (result)->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
describe "rename", ()->
@timeout helper.TIMEOUT_LONG
it "should successfully rename a file", () ->
uploadImage()
.then (result)->
cloudinary.v2.uploader.rename(result.public_id, result.public_id+"2")
.then ()-> result.public_id
.then (public_id)->
cloudinary.v2.api.resource(public_id+"2")
it "should not rename to an existing public_id", ()->
Promise.all [
uploadImage()
uploadImage()
]
.then (results)->
cloudinary.v2.uploader.rename(results[0].public_id, results[1].public_id)
.then ()-> expect().fail()
.catch (error)-> expect(error).to.be.ok()
it "should allow to rename to an existing ID, if overwrite is true", ()->
Promise.all [
uploadImage()
uploadImage()
]
.then (results)->
cloudinary.v2.uploader.rename(results[0].public_id, results[1].public_id, overwrite: true)
.then ({public_id})->
cloudinary.v2.api.resource(public_id)
.then ({format})->
expect(format).to.eql "png"
context ":invalidate", ->
spy = undefined
xhr = undefined
end = undefined
before ->
xhr = sinon.useFakeXMLHttpRequest()
spy = sinon.spy(ClientRequest.prototype, 'write')
after ->
spy.restore()
xhr.restore()
it "should should pass the invalidate value in rename to the server", ()->
cloudinary.v2.uploader.rename("first_id", "second_id", invalidate: true)
expect(spy.calledWith(sinon.match((arg)-> arg.toString().match(/name="invalidate"/)))).to.be.ok()
describe "destroy", ()->
@timeout helper.TIMEOUT_MEDIUM
it "should delete a resource", ()->
uploadImage()
.then (result)->
public_id = result.public_id
cloudinary.v2.uploader.destroy(public_id)
.then (result)->
expect(result.result).to.eql("ok")
cloudinary.v2.api.resource(public_id)
.then ()-> expect().fail()
.catch (error)->
expect(error).to.be.ok()
it "should successfully call explicit api", () ->
cloudinary.v2.uploader.explicit("sample", type: "upload", eager: [crop: "scale", width: "2.0"])
.then (result)->
url = cloudinary.utils.url "sample",
type: "upload",
crop: "scale",
width: "2.0",
format: "jpg",
version: result["version"]
expect(result.eager[0].url).to.eql(url)
it "should support eager in upload", () ->
@timeout helper.TIMEOUT_SHORT
cloudinary.v2.uploader.upload(IMAGE_FILE, eager: [crop: "scale", width: "2.0"], tags: UPLOAD_TAGS)
describe "custom headers", ()->
it "should support custom headers in object format e.g. {Link: \"1\"}", () ->
cloudinary.v2.uploader.upload(IMAGE_FILE, headers: {Link: "1"}, tags: UPLOAD_TAGS)
it "should support custom headers as array of strings e.g. [\"Link: 1\"]", () ->
cloudinary.v2.uploader.upload(IMAGE_FILE, headers: ["Link: 1"], tags: UPLOAD_TAGS)
it "should successfully generate text image", () ->
cloudinary.v2.uploader.text("hello world", tags: UPLOAD_TAGS)
.then (result)->
expect(result.width).to.within(50,70)
expect(result.height).to.within(5,15)
it "should successfully upload stream", (done)->
stream = cloudinary.v2.uploader.upload_stream tags: UPLOAD_TAGS, (error, result) ->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
done()
file_reader = fs.createReadStream(IMAGE_FILE, {encoding: 'binary'})
file_reader.on 'data', (chunk)-> stream.write(chunk,'binary')
file_reader.on 'end', -> stream.end()
describe "tags", ()->
@timeout helper.TIMEOUT_MEDIUM
it "should add tags to existing resources", () ->
uploadImage()
.then (result)->
uploadImage().then (res)-> [result.public_id, res.public_id]
.then ([firstId, secondId])->
cloudinary.v2.uploader.add_tag("tag1", [firstId, secondId])
.then ()-> [firstId, secondId]
.then ([firstId, secondId])->
cloudinary.v2.api.resource(secondId)
.then (r1)->
expect(r1.tags).to.contain("tag1")
.then ()-> [firstId, secondId]
.then ([firstId, secondId])->
cloudinary.v2.uploader.remove_all_tags([firstId, secondId, 'noSuchId'])
.then (result)-> [firstId, secondId, result]
.then ([firstId, secondId, result])->
expect(result["public_ids"]).to.contain(firstId)
expect(result["public_ids"]).to.contain(secondId)
expect(result["public_ids"]).to.not.contain('noSuchId')
it "should keep existing tags when adding a new tag", ()->
uploadImage()
.then (result)->
cloudinary.v2.uploader.add_tag("tag1", result.public_id)
.then ()-> result.public_id
.then (publicId)->
cloudinary.v2.uploader.add_tag("tag2", publicId)
.then ()-> publicId
.then (publicId)->
cloudinary.v2.api.resource(publicId)
.then (result)->
expect(result.tags).to.contain("tag1").and.contain( "tag2")
it "should replace existing tag", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, tags: ["tag1", "tag2", TEST_TAG])
.then (result)->
public_id = result.public_id
cloudinary.v2.uploader.replace_tag( "tag3Å", public_id)
.then ()-> public_id
.then (public_id)-> # TODO this also tests non ascii characters
cloudinary.v2.api.resource(public_id)
.then (result)->
expect(result.tags).to.eql(["tag3Å"])
describe "context", ()->
second_id = first_id = ''
@timeout helper.TIMEOUT_MEDIUM
before ()->
Q.all [
uploadImage()
uploadImage()
]
.spread (result1, result2)->
first_id = result1.public_id
second_id = result2.public_id
it "should add context to existing resources", () ->
cloudinary.v2.uploader.add_context('alt=testAlt|custom=testCustom', [first_id, second_id])
.then ()->
cloudinary.v2.uploader.add_context({alt2: "testAlt2", custom2: "testCustom2"}, [first_id, second_id])
.then ()->
cloudinary.v2.api.resource(second_id)
.then ({context})->
expect(context.custom.alt).to.equal('testAlt')
expect(context.custom.alt2).to.equal('testAlt2')
expect(context.custom.custom).to.equal('testCustom')
expect(context.custom.custom2).to.equal('testCustom2')
cloudinary.v2.uploader.remove_all_context([first_id, second_id, 'noSuchId'])
.then ({public_ids})->
expect(public_ids).to.contain(first_id)
expect(public_ids).to.contain(second_id)
expect(public_ids).to.not.contain('noSuchId')
cloudinary.v2.api.resource(second_id)
.then ({context})->
expect(context).to.be undefined
it "should upload with context containing reserved characters", ()->
context = {key1: 'PI:KEY:<KEY>END_PI', key2: 'PI:KEY:<KEY>END_PI', key3: 'PI:KEY:<KEY>END_PI', key4: 'PI:KEY:<KEY>END_PI'}
cloudinary.v2.uploader.upload(IMAGE_FILE, context: context)
.then (result)->
cloudinary.v2.api.resource(result.public_id, context: true)
.then (result)->
expect(result.context.custom).to.eql(context)
it "should support timeouts", () ->
# testing a 1ms timeout, nobody is that fast.
cloudinary.v2.uploader.upload("http://cloudinary.com/images/old_logo.png", timeout: 1, tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch ({error})->
expect(error.http_code).to.eql(499)
expect(error.message).to.eql("Request Timeout")
it "should upload a file and base public id on the filename if use_filename is set to true", () ->
@timeout helper.TIMEOUT_MEDIUM
cloudinary.v2.uploader.upload(IMAGE_FILE, use_filename: yes, tags: UPLOAD_TAGS)
.then ({public_id})->
expect(public_id).to.match /logo_[a-zA-Z0-9]{6}/
it "should upload a file and set the filename as the public_id if use_filename is set to true and unique_filename is set to false", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, use_filename: yes, unique_filename: no, tags: UPLOAD_TAGS)
.then (result)->
expect(result.public_id).to.eql "logo"
describe "allowed_formats", ->
it "should allow whitelisted formats", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, allowed_formats: ["png"], tags: UPLOAD_TAGS)
.then (result)->
expect(result.format).to.eql("png")
it "should prevent non whitelisted formats from being uploaded", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, allowed_formats: ["jpg"], tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error.http_code).to.eql(400)
it "should allow non whitelisted formats if type is specified and convert to that type", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, allowed_formats: ["jpg"], format: "jpg", tags: UPLOAD_TAGS)
.then (result)->
expect(result.format).to.eql("jpg")
it "should allow sending face coordinates", ()->
@timeout helper.TIMEOUT_LONG
coordinates = [[120, 30, 109, 150], [121, 31, 110, 151]]
out_coordinates = [[120, 30, 109, 51], [121, 31, 110, 51]] # coordinates are limited to the image dimensions
different_coordinates = [[122, 32, 111, 152]]
custom_coordinates = [1,2,3,4]
cloudinary.v2.uploader.upload(IMAGE_FILE, face_coordinates: coordinates, faces: yes, tags: UPLOAD_TAGS)
.then (result)->
expect(result.faces).to.eql(out_coordinates)
cloudinary.v2.uploader.explicit(result.public_id, faces: true, face_coordinates: different_coordinates, custom_coordinates: custom_coordinates, type: "upload")
.then (result)->
expect(result.faces).not.to.be undefined
cloudinary.v2.api.resource(result.public_id, faces: yes, coordinates: yes)
.then (info)->
expect(info.faces).to.eql(different_coordinates)
expect(info.coordinates).to.eql(faces: different_coordinates, custom: [custom_coordinates])
it "should allow sending context", ()->
@timeout helper.TIMEOUT_LONG
cloudinary.v2.uploader.upload(IMAGE_FILE, context: {caption: "some caption", alt: "alternative"}, tags: UPLOAD_TAGS)
.then ({public_id})->
cloudinary.v2.api.resource(public_id, context: true)
.then ({context})->
expect(context.custom.caption).to.eql("some caption")
expect(context.custom.alt).to.eql("alternative")
it "should support requesting manual moderation", () ->
cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", tags: UPLOAD_TAGS)
.then (result)->
expect(result.moderation[0].status).to.eql("pending")
expect(result.moderation[0].kind).to.eql("manual")
it "should support requesting ocr analysis", ->
cloudinary.v2.uploader.upload(IMAGE_FILE, ocr: "adv_ocr", tags: UPLOAD_TAGS)
.then (result)->
expect(result.info.ocr).to.have.key("adv_ocr")
it "should support requesting raw conversion", ()->
cloudinary.v2.uploader.upload(RAW_FILE, raw_convert: "illegal", resource_type: "raw", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error?).to.be true
expect(error.message).to.contain "Raw convert is invalid"
it "should support requesting categorization", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, categorization: "illegal", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error?).to.be true
it "should support requesting detection", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, detection: "illegal", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error).not.to.be undefined
expect(error.message).to.contain "Detection is invalid"
it "should support requesting background_removal", ()->
cloudinary.v2.uploader.upload(IMAGE_FILE, background_removal: "illegal", tags: UPLOAD_TAGS)
.then ()-> expect().fail()
.catch (error)->
expect(error?).to.be true
expect(error.message).to.contain "is invalid"
describe "upload_chunked", ()->
@timeout helper.TIMEOUT_LONG * 10
it "should specify chunk size", (done) ->
fs.stat LARGE_RAW_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_large LARGE_RAW_FILE, {chunk_size: 7000000, timeout: helper.TIMEOUT_LONG, tags: UPLOAD_TAGS}, (error, result) ->
return done(new Error error.message) if error?
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("4c13724e950abcb13ec480e10f8541f5")
done()
true
it "should return error if value is less than 5MB", (done)->
fs.stat LARGE_RAW_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_large LARGE_RAW_FILE, {chunk_size: 40000, tags: UPLOAD_TAGS}, (error, result) ->
expect(error.message).to.eql("All parts except EOF-chunk must be larger than 5mb")
done()
true
it "should support uploading a small raw file", (done) ->
fs.stat RAW_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_large RAW_FILE, tags: UPLOAD_TAGS, (error, result) ->
return done(new Error error.message) if error?
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("ffc265d8d1296247972b4d478048e448")
done()
true
it "should support uploading a small image file", (done) ->
fs.stat IMAGE_FILE, (err, stat) ->
cloudinary.v2.uploader.upload_chunked IMAGE_FILE, tags: UPLOAD_TAGS, (error, result) ->
return done(new Error error.message) if error?
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("7dc60722d4653261648038b579fdb89e")
done()
true
it "should support uploading large video files", () ->
@timeout helper.TIMEOUT_LONG * 10
writeSpy = sinon.spy(ClientRequest.prototype, 'write')
stat = fs.statSync( LARGE_VIDEO)
expect(stat).to.be.ok()
Q.denodeify(cloudinary.v2.uploader.upload_chunked)( LARGE_VIDEO, {chunk_size: 6000000, resource_type: 'video', timeout: helper.TIMEOUT_LONG * 10, tags: UPLOAD_TAGS})
.then (result)->
expect(result.bytes).to.eql(stat.size)
expect(result.etag).to.eql("ff6c391d26be0837ee5229885b5bd571")
timestamps = writeSpy.args.map((a)-> a[0].toString())
.filter((p) -> p.match(/timestamp/))
.map((p) -> p.match(/"timestamp"\s+(\d+)/)[1])
expect(timestamps.length).to.be.greaterThan(1)
if process.versions.node && process.versions.node[0] == '4'
timestamps.pop() # hack - node 4 duplicates the last entry
expect(uniq(timestamps)).to.eql(timestamps)
.finally ->
writeSpy.restore()
it "should update timestamp for each chuck", ()->
writeSpy = sinon.spy(ClientRequest.prototype, 'write')
Q.denodeify(cloudinary.v2.uploader.upload_chunked)( LARGE_VIDEO, {chunk_size: 6000000, resource_type: 'video', timeout: helper.TIMEOUT_LONG * 10, tags: UPLOAD_TAGS})
.then ->
timestamps = writeSpy.args.map((a)-> a[0].toString())
.filter((p) -> p.match(/timestamp/))
.map((p) -> p.match(/"timestamp"\s+(\d+)/)[1])
expect(timestamps.length).to.be.greaterThan(1)
expect(uniq(timestamps)).to.eql(timestamps)
.finally ->
writeSpy.restore()
it "should support uploading based on a url", (done) ->
@timeout helper.TIMEOUT_MEDIUM
cloudinary.v2.uploader.upload_large "http://cloudinary.com/images/old_logo.png", {tags: UPLOAD_TAGS}, (error, result) ->
return done(new Error error.message) if error?
expect(result.etag).to.eql("7dc60722d4653261648038b579fdb89e")
done()
true
it "should support unsigned uploading using presets", ()->
@timeout helper.TIMEOUT_LONG
cloudinary.v2.api.create_upload_preset(folder: "upload_folder", unsigned: true, tags: UPLOAD_TAGS)
.then (preset)->
cloudinary.v2.uploader.unsigned_upload(IMAGE_FILE, preset.name, tags: UPLOAD_TAGS)
.then (result)-> [preset.name, result.public_id]
.then ([presetName, public_id])->
expect(public_id).to.match /^upload_folder\/[a-z0-9]+$/
cloudinary.v2.api.delete_upload_preset(presetName)
it "should reject promise if error code is returned from the server", () ->
cloudinary.v2.uploader.upload(EMPTY_IMAGE, tags: UPLOAD_TAGS)
.then ->
expect().fail("server should return an error when uploading an empty file")
.catch (error)->
expect(error.message.toLowerCase()).to.contain "empty"
it "should successfully upload with pipes", (done) ->
@timeout helper.TIMEOUT_LONG
upload = cloudinary.v2.uploader.upload_stream tags: UPLOAD_TAGS, (error, result) ->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
done()
file_reader = fs.createReadStream(IMAGE_FILE)
file_reader.pipe(upload)
it "should fail with http.Agent (non secure)", () ->
@timeout helper.TIMEOUT_LONG
expect(cloudinary.v2.uploader.upload_stream).withArgs({agent:new http.Agent},(error, result) ->
).to.throwError()
it "should successfully override https agent", () ->
upload = cloudinary.v2.uploader.upload_stream agent:new https.Agent, tags: UPLOAD_TAGS, (error, result) ->
expect(result.width).to.eql(241)
expect(result.height).to.eql(51)
expected_signature = cloudinary.utils.api_sign_request({public_id: result.public_id, version: result.version}, cloudinary.config().api_secret)
expect(result.signature).to.eql(expected_signature)
file_reader = fs.createReadStream(IMAGE_FILE)
file_reader.pipe(upload)
context ":responsive_breakpoints", ->
context ":create_derived with different transformation settings", ->
before ->
helper.setupCache()
it 'should return a responsive_breakpoints in the response', ()->
cloudinary.v2.uploader.upload IMAGE_FILE, responsive_breakpoints: [{
transformation: {effect: "sepia"},
format: "jpg",
bytes_step: 20000,
create_derived: true,
min_width: 200,
max_width: 1000,
max_images: 20
}, {
transformation: {angle: 10},
format: "gif",
create_derived: true,
bytes_step: 20000,
min_width: 200,
max_width: 1000,
max_images: 20
}], tags: UPLOAD_TAGS
.then (result)->
expect(result).to.have.key('responsive_breakpoints')
expect(result.responsive_breakpoints).to.have.length(2)
expect(at(result, "responsive_breakpoints[0].transformation")[0]).to.eql("e_sepia")
expect(at(result, "responsive_breakpoints[0].breakpoints[0].url")[0]).to.match(/\.jpg$/)
expect(at(result, "responsive_breakpoints[1].transformation")[0]).to.eql("a_10")
expect(at(result, "responsive_breakpoints[1].breakpoints[0].url")[0]).to.match(/\.gif$/)
result.responsive_breakpoints.map (bp)->
format = path.extname(bp.breakpoints[0].url).slice(1)
cached = cloudinary.Cache.get(
result.public_id,
{raw_transformation: bp.transformation, format})
expect(cached).to.be.ok()
expect(cached.length).to.be(bp.breakpoints.length)
bp.breakpoints.forEach (o)->
expect(cached).to.contain(o.width)
describe "async upload", ->
mocked = helper.mockTest()
it "should pass `async` value to the server", ->
cloudinary.v2.uploader.upload IMAGE_FILE, {async: true, transformation: {effect: "sepia"}}
sinon.assert.calledWith mocked.write, sinon.match(helper.uploadParamMatcher("async", 1))
describe "explicit", ->
spy = undefined
xhr = undefined
before ->
xhr = sinon.useFakeXMLHttpRequest()
spy = sinon.spy(ClientRequest.prototype, 'write')
after ->
spy.restore()
xhr.restore()
describe ":invalidate", ->
it "should should pass the invalidate value to the server", ()->
cloudinary.v2.uploader.explicit "cloudinary", type: "twitter_name", eager: [crop: "scale", width: "2.0"], invalidate: true, tags: [TEST_TAG]
sinon.assert.calledWith(spy, sinon.match(helper.uploadParamMatcher('invalidate', 1)))
it "should support raw_convert", ->
cloudinary.v2.uploader.explicit "cloudinary", raw_convert: "google_speech", tags: [TEST_TAG]
sinon.assert.calledWith(spy, sinon.match(
helper.uploadParamMatcher('raw_convert', 'google_speech')
))
it "should create an image upload tag with required properties", () ->
@timeout helper.TIMEOUT_LONG
tag = cloudinary.v2.uploader.image_upload_tag "image_id", chunk_size: "1234"
expect(tag).to.match(/^<input/)
# Create an HTMLElement from the returned string to validate attributes
fakeDiv = document.createElement('div');
fakeDiv.innerHTML = tag;
input_element = fakeDiv.firstChild;
expect(input_element.tagName.toLowerCase()).to.be('input');
expect(input_element.getAttribute("data-url")).to.be.ok();
expect(input_element.getAttribute("data-form-data")).to.be.ok();
expect(input_element.getAttribute("data-cloudinary-field")).to.match(/image_id/);
expect(input_element.getAttribute("data-max-chunk-size")).to.match(/1234/);
expect(input_element.getAttribute("class")).to.match(/cloudinary-fileupload/);
expect(input_element.getAttribute("name")).to.be('file');
expect(input_element.getAttribute("type")).to.be('file');
describe "access_control", ()->
writeSpy = undefined
requestSpy = undefined
options = undefined
beforeEach ->
writeSpy = sinon.spy(ClientRequest.prototype, 'write')
requestSpy = sinon.spy(http, 'request')
options = {
public_id: helper.TEST_TAG,
tags: [helper.UPLOAD_TAGS..., 'access_control_test']
}
afterEach ->
requestSpy.restore()
writeSpy.restore()
acl = {
access_type: 'anonymous',
start: new Date(Date.UTC(2019,1,22, 16, 20, 57)),
end: '2019-03-22 00:00 +0200'
}
acl_string =
'{"access_type":"anonymous","start":"2019-02-22T16:20:57.000Z","end":"2019-03-22 00:00 +0200"}'
it "should allow the user to define ACL in the upload parameters", ()->
options.access_control = [acl]
uploadImage(options).then (resource)=>
sinon.assert.calledWith(writeSpy, sinon.match(
helper.uploadParamMatcher('access_control', "[#{acl_string}]")
))
expect(resource).to.have.key('access_control')
response_acl = resource["access_control"]
expect(response_acl.length).to.be(1)
expect(response_acl[0]["access_type"]).to.be("anonymous")
expect(Date.parse(response_acl[0]["start"])).to.be(Date.parse(acl.start))
expect(Date.parse(response_acl[0]["end"])).to.be(Date.parse(acl.end))
|
[
{
"context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Cof",
"end": 23,
"score": 0.9998796582221985,
"start": 13,
"tag": "NAME",
"value": "Mat Groves"
},
{
"context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/t... | src/Coffixi/textures/BaseTexture.coffee | namuol/Coffixi | 1 | ###*
@author Mat Groves http://matgroves.com/ @Doormat23
###
define 'Coffixi/textures/BaseTexture', [
'Coffixi/utils/Module'
'Coffixi/utils/HasSignals'
], (
Module
HasSignals
) ->
###*
A texture stores the information that represents an image. All textures have a base texture
@class BaseTexture
@extends Module
@uses HasSignals
@constructor
@param source {String} the source object (image or canvas)
###
class BaseTexture extends Module
@mixin HasSignals
@cache: {}
@texturesToUpdate: []
@texturesToDestroy: []
@filterModes:
LINEAR: 1
NEAREST: 2
constructor: (source) ->
super
###*
The width of the base texture set when the image has loaded
@property width
@type Number
@final
###
@width = 100
###*
The height of the base texture set when the image has loaded
@property height
@type Number
@final
###
@height = 100
###*
Describes if the base texture has loaded or not
@property hasLoaded
@type Boolean
@final
###
@hasLoaded = false
###*
The source that is loaded to create the texture
@property source
@type Image
###
@source = source
return unless source
if not (@source instanceof Image or @source instanceof HTMLImageElement)
@hasLoaded = true
@width = @source.width
@height = @source.height
@createCanvas @source if @source instanceof Image
else
if @source.complete
@hasLoaded = true
@width = @source.width
@height = @source.height
@createCanvas @source
@emit 'loaded', @
else
@source.onerror = =>
@emit 'error', @
@source.onload = =>
@hasLoaded = true
@width = @source.width
@height = @source.height
# add it to somewhere...
@createCanvas @source
@emit 'loaded', @
@_powerOf2 = false
@filterMode = undefined # Use renderer's default filter mode.
setFilterMode: (mode) ->
@filterMode = mode
BaseTexture.texturesToUpdate.push @
beginRead: ->
@_imageData ?= @_ctx.getImageData(0,0, @_ctx.canvas.width,@_ctx.canvas.height)
getPixel: (x, y) ->
idx = (x + y * @_imageData.width) * 4
return {
r: @_imageData.data[idx + 0]
g: @_imageData.data[idx + 1]
b: @_imageData.data[idx + 2]
a: @_imageData.data[idx + 3]
}
endRead: ->
# IF we change this back to EDIT, we'd need to update the texture like so:
# @_ctx.putImageData @_imageData, 0,0
BaseTexture.texturesToUpdate.push @
# Converts a loaded image to a canvas element and
# sets it as our source for easy pixel access.
createCanvas: (loadedImage) ->
@source = document.createElement 'canvas'
@source.width = loadedImage.width
@source.height = loadedImage.height
@_ctx = @source.getContext '2d'
@_ctx.drawImage loadedImage, 0,0
@beginRead()
@endRead()
###*
Destroys this base texture
@method destroy
###
destroy: ->
@source.src = null if @source instanceof Image
@source = null
BaseTexture.texturesToDestroy.push this
###*
Helper function that returns a base texture based on an image url
If the image is not in the base texture cache it will be created and loaded
@static
@method fromImage
@param imageUrl {String} The image url of the texture
@return BaseTexture
###
@fromImage: (imageUrl, crossorigin) ->
baseTexture = BaseTexture.cache[imageUrl]
unless baseTexture
# new Image() breaks tex loading in some versions of Chrome.
# See https://code.google.com/p/chromium/issues/detail?id=238071
image = new Image() #document.createElement('img');
image.crossOrigin = "" if crossorigin
image.src = imageUrl
baseTexture = new BaseTexture(image)
BaseTexture.cache[imageUrl] = baseTexture
baseTexture
| 161030 | ###*
@author <NAME> http://matgroves.com/ @Doormat23
###
define 'Coffixi/textures/BaseTexture', [
'Coffixi/utils/Module'
'Coffixi/utils/HasSignals'
], (
Module
HasSignals
) ->
###*
A texture stores the information that represents an image. All textures have a base texture
@class BaseTexture
@extends Module
@uses HasSignals
@constructor
@param source {String} the source object (image or canvas)
###
class BaseTexture extends Module
@mixin HasSignals
@cache: {}
@texturesToUpdate: []
@texturesToDestroy: []
@filterModes:
LINEAR: 1
NEAREST: 2
constructor: (source) ->
super
###*
The width of the base texture set when the image has loaded
@property width
@type Number
@final
###
@width = 100
###*
The height of the base texture set when the image has loaded
@property height
@type Number
@final
###
@height = 100
###*
Describes if the base texture has loaded or not
@property hasLoaded
@type Boolean
@final
###
@hasLoaded = false
###*
The source that is loaded to create the texture
@property source
@type Image
###
@source = source
return unless source
if not (@source instanceof Image or @source instanceof HTMLImageElement)
@hasLoaded = true
@width = @source.width
@height = @source.height
@createCanvas @source if @source instanceof Image
else
if @source.complete
@hasLoaded = true
@width = @source.width
@height = @source.height
@createCanvas @source
@emit 'loaded', @
else
@source.onerror = =>
@emit 'error', @
@source.onload = =>
@hasLoaded = true
@width = @source.width
@height = @source.height
# add it to somewhere...
@createCanvas @source
@emit 'loaded', @
@_powerOf2 = false
@filterMode = undefined # Use renderer's default filter mode.
setFilterMode: (mode) ->
@filterMode = mode
BaseTexture.texturesToUpdate.push @
beginRead: ->
@_imageData ?= @_ctx.getImageData(0,0, @_ctx.canvas.width,@_ctx.canvas.height)
getPixel: (x, y) ->
idx = (x + y * @_imageData.width) * 4
return {
r: @_imageData.data[idx + 0]
g: @_imageData.data[idx + 1]
b: @_imageData.data[idx + 2]
a: @_imageData.data[idx + 3]
}
endRead: ->
# IF we change this back to EDIT, we'd need to update the texture like so:
# @_ctx.putImageData @_imageData, 0,0
BaseTexture.texturesToUpdate.push @
# Converts a loaded image to a canvas element and
# sets it as our source for easy pixel access.
createCanvas: (loadedImage) ->
@source = document.createElement 'canvas'
@source.width = loadedImage.width
@source.height = loadedImage.height
@_ctx = @source.getContext '2d'
@_ctx.drawImage loadedImage, 0,0
@beginRead()
@endRead()
###*
Destroys this base texture
@method destroy
###
destroy: ->
@source.src = null if @source instanceof Image
@source = null
BaseTexture.texturesToDestroy.push this
###*
Helper function that returns a base texture based on an image url
If the image is not in the base texture cache it will be created and loaded
@static
@method fromImage
@param imageUrl {String} The image url of the texture
@return BaseTexture
###
@fromImage: (imageUrl, crossorigin) ->
baseTexture = BaseTexture.cache[imageUrl]
unless baseTexture
# new Image() breaks tex loading in some versions of Chrome.
# See https://code.google.com/p/chromium/issues/detail?id=238071
image = new Image() #document.createElement('img');
image.crossOrigin = "" if crossorigin
image.src = imageUrl
baseTexture = new BaseTexture(image)
BaseTexture.cache[imageUrl] = baseTexture
baseTexture
| true | ###*
@author PI:NAME:<NAME>END_PI http://matgroves.com/ @Doormat23
###
define 'Coffixi/textures/BaseTexture', [
'Coffixi/utils/Module'
'Coffixi/utils/HasSignals'
], (
Module
HasSignals
) ->
###*
A texture stores the information that represents an image. All textures have a base texture
@class BaseTexture
@extends Module
@uses HasSignals
@constructor
@param source {String} the source object (image or canvas)
###
class BaseTexture extends Module
@mixin HasSignals
@cache: {}
@texturesToUpdate: []
@texturesToDestroy: []
@filterModes:
LINEAR: 1
NEAREST: 2
constructor: (source) ->
super
###*
The width of the base texture set when the image has loaded
@property width
@type Number
@final
###
@width = 100
###*
The height of the base texture set when the image has loaded
@property height
@type Number
@final
###
@height = 100
###*
Describes if the base texture has loaded or not
@property hasLoaded
@type Boolean
@final
###
@hasLoaded = false
###*
The source that is loaded to create the texture
@property source
@type Image
###
@source = source
return unless source
if not (@source instanceof Image or @source instanceof HTMLImageElement)
@hasLoaded = true
@width = @source.width
@height = @source.height
@createCanvas @source if @source instanceof Image
else
if @source.complete
@hasLoaded = true
@width = @source.width
@height = @source.height
@createCanvas @source
@emit 'loaded', @
else
@source.onerror = =>
@emit 'error', @
@source.onload = =>
@hasLoaded = true
@width = @source.width
@height = @source.height
# add it to somewhere...
@createCanvas @source
@emit 'loaded', @
@_powerOf2 = false
@filterMode = undefined # Use renderer's default filter mode.
setFilterMode: (mode) ->
@filterMode = mode
BaseTexture.texturesToUpdate.push @
beginRead: ->
@_imageData ?= @_ctx.getImageData(0,0, @_ctx.canvas.width,@_ctx.canvas.height)
getPixel: (x, y) ->
idx = (x + y * @_imageData.width) * 4
return {
r: @_imageData.data[idx + 0]
g: @_imageData.data[idx + 1]
b: @_imageData.data[idx + 2]
a: @_imageData.data[idx + 3]
}
endRead: ->
# IF we change this back to EDIT, we'd need to update the texture like so:
# @_ctx.putImageData @_imageData, 0,0
BaseTexture.texturesToUpdate.push @
# Converts a loaded image to a canvas element and
# sets it as our source for easy pixel access.
createCanvas: (loadedImage) ->
@source = document.createElement 'canvas'
@source.width = loadedImage.width
@source.height = loadedImage.height
@_ctx = @source.getContext '2d'
@_ctx.drawImage loadedImage, 0,0
@beginRead()
@endRead()
###*
Destroys this base texture
@method destroy
###
destroy: ->
@source.src = null if @source instanceof Image
@source = null
BaseTexture.texturesToDestroy.push this
###*
Helper function that returns a base texture based on an image url
If the image is not in the base texture cache it will be created and loaded
@static
@method fromImage
@param imageUrl {String} The image url of the texture
@return BaseTexture
###
@fromImage: (imageUrl, crossorigin) ->
baseTexture = BaseTexture.cache[imageUrl]
unless baseTexture
# new Image() breaks tex loading in some versions of Chrome.
# See https://code.google.com/p/chromium/issues/detail?id=238071
image = new Image() #document.createElement('img');
image.crossOrigin = "" if crossorigin
image.src = imageUrl
baseTexture = new BaseTexture(image)
BaseTexture.cache[imageUrl] = baseTexture
baseTexture
|
[
{
"context": " undefined\n error = null\n result = { name: 'Test List' }\n testListID = 'test-list-id'\n\n beforeEac",
"end": 2553,
"score": 0.9213055968284607,
"start": 2544,
"tag": "NAME",
"value": "Test List"
}
] | test/test-superclass.coffee | Guilding/bpa-trello | 2 | expect = require('chai').expect
_un = require("underscore")
sinon = require('sinon')
require('sinon-as-promised')
trello = require('node-trello')
app = require('../app')
helpers = require('./test-helpers.js')
stages = helpers.expectedStageObject.stages[0].substages
stageMgr = new app.StageManager(helpers.mockfile, helpers.board) # The trello super class is not directly accessible
describe 'app.TrelloSuper', ->
describe '.readYAML()', ->
it 'maps a yaml to an object with a stages key', ->
yamlObject = stageMgr.readYaml()
expect(yamlObject).to.eql(helpers.expectedStageObject)
return
it 'returns null if the YAML file doesn\'t exist', ->
sm = new app.StageManager('', helpers.board)
preaward = sm.readYaml()
expect(preaward).to.eql null
return
describe '.getPreAward()', ->
it 'will grab the Pre-Award stage from a file', ->
preaward = stageMgr.getPreAward()
expect(preaward).to.eql(helpers.expectedStageObject.stages[0].substages)
return
it 'returns an empty array if readYAML returns invalid data', ->
sm = new app.StageManager('', helpers.board)
preaward = sm.getPreAward()
expect(preaward).to.eql [ ]
return
describe 'getListIDbyName(ListName)', ->
sandbox = undefined
stub = undefined
error = null
run = 0
result = [{ id: 'test-list-1', name: 'Test List #1' }, { id: 'test-list-2', name: 'Test List #2' }]
beforeEach ->
sandbox = sinon.sandbox.create()
stub = sandbox.stub(trello.prototype, 'get').withArgs('/1/boards/' + helpers.board + '/lists').yieldsAsync(error, result)
return
afterEach ->
sandbox.restore()
if ++run == 2 # after end of second run...
error = new Error('Test Error')
result = null
return
it 'will ping Trello to grab a list ID given a list name', (done) ->
stageMgr.getListIDbyName(result[1].name).then (id) ->
expect(id).to.eql(result[1].id);
done()
return
return
it 'will return the first list ID if no name is specified', (done) ->
stageMgr.getListIDbyName(null).then (id) ->
expect(id).to.eql(result[0].id);
done()
return
return
it 'will survive a Trello error', (done) ->
stageMgr.getListIDbyName(null).catch (err) ->
expect(err).to.eql(error);
done()
return
return
return
describe 'getListNameByID', ->
sandbox = undefined
stub = undefined
error = null
result = { name: 'Test List' }
testListID = 'test-list-id'
beforeEach ->
sandbox = sinon.sandbox.create()
stub = sandbox.stub(trello.prototype, 'get').withArgs('/1/lists/' + testListID).yieldsAsync(error, result)
return
afterEach ->
sandbox.restore()
error = new Error('Test Error')
result = null
return
it 'will ping Trello to grab a list name given a list ID', (done) ->
stageMgr.getListNameByID(testListID).then (list) ->
expect(list).to.eql(result.name);
done()
return
return
it 'will survive a Trello error', (done) ->
stageMgr.getListNameByID(testListID).catch (err) ->
expect(err).to.eql(error);
done()
return
return
return
return
| 24367 | expect = require('chai').expect
_un = require("underscore")
sinon = require('sinon')
require('sinon-as-promised')
trello = require('node-trello')
app = require('../app')
helpers = require('./test-helpers.js')
stages = helpers.expectedStageObject.stages[0].substages
stageMgr = new app.StageManager(helpers.mockfile, helpers.board) # The trello super class is not directly accessible
describe 'app.TrelloSuper', ->
describe '.readYAML()', ->
it 'maps a yaml to an object with a stages key', ->
yamlObject = stageMgr.readYaml()
expect(yamlObject).to.eql(helpers.expectedStageObject)
return
it 'returns null if the YAML file doesn\'t exist', ->
sm = new app.StageManager('', helpers.board)
preaward = sm.readYaml()
expect(preaward).to.eql null
return
describe '.getPreAward()', ->
it 'will grab the Pre-Award stage from a file', ->
preaward = stageMgr.getPreAward()
expect(preaward).to.eql(helpers.expectedStageObject.stages[0].substages)
return
it 'returns an empty array if readYAML returns invalid data', ->
sm = new app.StageManager('', helpers.board)
preaward = sm.getPreAward()
expect(preaward).to.eql [ ]
return
describe 'getListIDbyName(ListName)', ->
sandbox = undefined
stub = undefined
error = null
run = 0
result = [{ id: 'test-list-1', name: 'Test List #1' }, { id: 'test-list-2', name: 'Test List #2' }]
beforeEach ->
sandbox = sinon.sandbox.create()
stub = sandbox.stub(trello.prototype, 'get').withArgs('/1/boards/' + helpers.board + '/lists').yieldsAsync(error, result)
return
afterEach ->
sandbox.restore()
if ++run == 2 # after end of second run...
error = new Error('Test Error')
result = null
return
it 'will ping Trello to grab a list ID given a list name', (done) ->
stageMgr.getListIDbyName(result[1].name).then (id) ->
expect(id).to.eql(result[1].id);
done()
return
return
it 'will return the first list ID if no name is specified', (done) ->
stageMgr.getListIDbyName(null).then (id) ->
expect(id).to.eql(result[0].id);
done()
return
return
it 'will survive a Trello error', (done) ->
stageMgr.getListIDbyName(null).catch (err) ->
expect(err).to.eql(error);
done()
return
return
return
describe 'getListNameByID', ->
sandbox = undefined
stub = undefined
error = null
result = { name: '<NAME>' }
testListID = 'test-list-id'
beforeEach ->
sandbox = sinon.sandbox.create()
stub = sandbox.stub(trello.prototype, 'get').withArgs('/1/lists/' + testListID).yieldsAsync(error, result)
return
afterEach ->
sandbox.restore()
error = new Error('Test Error')
result = null
return
it 'will ping Trello to grab a list name given a list ID', (done) ->
stageMgr.getListNameByID(testListID).then (list) ->
expect(list).to.eql(result.name);
done()
return
return
it 'will survive a Trello error', (done) ->
stageMgr.getListNameByID(testListID).catch (err) ->
expect(err).to.eql(error);
done()
return
return
return
return
| true | expect = require('chai').expect
_un = require("underscore")
sinon = require('sinon')
require('sinon-as-promised')
trello = require('node-trello')
app = require('../app')
helpers = require('./test-helpers.js')
stages = helpers.expectedStageObject.stages[0].substages
stageMgr = new app.StageManager(helpers.mockfile, helpers.board) # The trello super class is not directly accessible
describe 'app.TrelloSuper', ->
describe '.readYAML()', ->
it 'maps a yaml to an object with a stages key', ->
yamlObject = stageMgr.readYaml()
expect(yamlObject).to.eql(helpers.expectedStageObject)
return
it 'returns null if the YAML file doesn\'t exist', ->
sm = new app.StageManager('', helpers.board)
preaward = sm.readYaml()
expect(preaward).to.eql null
return
describe '.getPreAward()', ->
it 'will grab the Pre-Award stage from a file', ->
preaward = stageMgr.getPreAward()
expect(preaward).to.eql(helpers.expectedStageObject.stages[0].substages)
return
it 'returns an empty array if readYAML returns invalid data', ->
sm = new app.StageManager('', helpers.board)
preaward = sm.getPreAward()
expect(preaward).to.eql [ ]
return
describe 'getListIDbyName(ListName)', ->
sandbox = undefined
stub = undefined
error = null
run = 0
result = [{ id: 'test-list-1', name: 'Test List #1' }, { id: 'test-list-2', name: 'Test List #2' }]
beforeEach ->
sandbox = sinon.sandbox.create()
stub = sandbox.stub(trello.prototype, 'get').withArgs('/1/boards/' + helpers.board + '/lists').yieldsAsync(error, result)
return
afterEach ->
sandbox.restore()
if ++run == 2 # after end of second run...
error = new Error('Test Error')
result = null
return
it 'will ping Trello to grab a list ID given a list name', (done) ->
stageMgr.getListIDbyName(result[1].name).then (id) ->
expect(id).to.eql(result[1].id);
done()
return
return
it 'will return the first list ID if no name is specified', (done) ->
stageMgr.getListIDbyName(null).then (id) ->
expect(id).to.eql(result[0].id);
done()
return
return
it 'will survive a Trello error', (done) ->
stageMgr.getListIDbyName(null).catch (err) ->
expect(err).to.eql(error);
done()
return
return
return
describe 'getListNameByID', ->
sandbox = undefined
stub = undefined
error = null
result = { name: 'PI:NAME:<NAME>END_PI' }
testListID = 'test-list-id'
beforeEach ->
sandbox = sinon.sandbox.create()
stub = sandbox.stub(trello.prototype, 'get').withArgs('/1/lists/' + testListID).yieldsAsync(error, result)
return
afterEach ->
sandbox.restore()
error = new Error('Test Error')
result = null
return
it 'will ping Trello to grab a list name given a list ID', (done) ->
stageMgr.getListNameByID(testListID).then (list) ->
expect(list).to.eql(result.name);
done()
return
return
it 'will survive a Trello error', (done) ->
stageMgr.getListNameByID(testListID).catch (err) ->
expect(err).to.eql(error);
done()
return
return
return
return
|
[
{
"context": "ages\n# used resources from : https://github.com/sagargp/trollicons Adium extension\n#\n# Dependencies:\n# ",
"end": 96,
"score": 0.9976496696472168,
"start": 89,
"tag": "USERNAME",
"value": "sagargp"
},
{
"context": "lid example of multiple trollicons\n#\n# Author:... | src/scripts/trollicon.coffee | Reelhouse/hubot-scripts | 1,450 | # Description:
# Return trollicon images
# used resources from : https://github.com/sagargp/trollicons Adium extension
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# :<trollicon>: - outputs <trollicon> image
# :isee: what you did there, and :megusta: - is a valid example of multiple trollicons
#
# Author:
# Adan Alvarado and Enrique Vidal
trollicons = {
'gasp' : 'http://i.imgur.com/tYmuZ.png',
'challenge' : 'http://i.imgur.com/jbKmr.png',
'lol' : 'http://i.imgur.com/WjI3L.png',
'no' : 'http://i.imgur.com/loC5s.png',
'yao' : 'http://i.imgur.com/wTAP3.png',
'kidding' : 'http://i.imgur.com/0uCcv.png',
'megusta' : 'http://i.imgur.com/QfeUB.png',
'isee' : 'http://i.imgur.com/M4bcv.png',
'fuckyeah' : 'http://i.imgur.com/m7mEZ.png',
'problem' : 'http://i.imgur.com/oLlJm.png',
'dissapoint' : 'http://i.imgur.com/EwBi7.png',
'nothing' : 'http://i.imgur.com/Nwos9.png',
'pokerface' : 'http://i.imgur.com/dDjvG.png',
'ok' : 'http://i.imgur.com/QRCoI.png',
'sadtroll' : 'http://i.imgur.com/gYsxd.png',
'yuno' : 'http://i.imgur.com/sZMnV.png',
'true' : 'http://i.imgur.com/oealL.png',
'freddie' : 'http://i.imgur.com/zszUl.png',
'forever' : 'http://i.imgur.com/5MBi2.png',
'jackie' : 'http://i.imgur.com/63oaA.png',
'fu' : 'http://i.imgur.com/YHYTg.png',
'rage' : 'http://i.imgur.com/itXDM.png',
'areyoukiddingme' : 'http://i.imgur.com/0uCcv.png',
'nothingtodo' : 'http://i.imgur.com/Nwos9.png',
'moonshot' : 'http://i.imgur.com/E8Dq3.png',
'cerealguy' : 'http://i.imgur.com/sD2jS.png',
'gtfo' : 'http://i.imgur.com/kSxyw.png',
'youdontsay' : 'http://i.imgur.com/xq9Ix.png',
'motherofgod' : 'http://i.imgur.com/CxL3b.png',
'likeasir' : 'http://i.imgur.com/CqBdw.png'
}
module.exports = (robot)->
robot.hear /:(\w+):/g, (message)->
build_response message
build_response = (message)->
orig_response = message.message.text
response = orig_response
return if message.match.length == 0
for icon in message.match
expr = new RegExp( icon, 'g' )
image = trollicons[ icon.replace( /:/g, '' ) ]
response = response.replace( expr, image ) if image != undefined
message.send response if response != undefined and response != orig_response
| 173186 | # Description:
# Return trollicon images
# used resources from : https://github.com/sagargp/trollicons Adium extension
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# :<trollicon>: - outputs <trollicon> image
# :isee: what you did there, and :megusta: - is a valid example of multiple trollicons
#
# Author:
# <NAME> and <NAME>
trollicons = {
'gasp' : 'http://i.imgur.com/tYmuZ.png',
'challenge' : 'http://i.imgur.com/jbKmr.png',
'lol' : 'http://i.imgur.com/WjI3L.png',
'no' : 'http://i.imgur.com/loC5s.png',
'yao' : 'http://i.imgur.com/wTAP3.png',
'kidding' : 'http://i.imgur.com/0uCcv.png',
'megusta' : 'http://i.imgur.com/QfeUB.png',
'isee' : 'http://i.imgur.com/M4bcv.png',
'fuckyeah' : 'http://i.imgur.com/m7mEZ.png',
'problem' : 'http://i.imgur.com/oLlJm.png',
'dissapoint' : 'http://i.imgur.com/EwBi7.png',
'nothing' : 'http://i.imgur.com/Nwos9.png',
'pokerface' : 'http://i.imgur.com/dDjvG.png',
'ok' : 'http://i.imgur.com/QRCoI.png',
'sadtroll' : 'http://i.imgur.com/gYsxd.png',
'yuno' : 'http://i.imgur.com/sZMnV.png',
'true' : 'http://i.imgur.com/oealL.png',
'<NAME>' : 'http://i.imgur.com/zszUl.png',
'forever' : 'http://i.imgur.com/5MBi2.png',
'jackie' : 'http://i.imgur.com/63oaA.png',
'fu' : 'http://i.imgur.com/YHYTg.png',
'rage' : 'http://i.imgur.com/itXDM.png',
'areyoukiddingme' : 'http://i.imgur.com/0uCcv.png',
'nothingtodo' : 'http://i.imgur.com/Nwos9.png',
'moonshot' : 'http://i.imgur.com/E8Dq3.png',
'cerealguy' : 'http://i.imgur.com/sD2jS.png',
'gtfo' : 'http://i.imgur.com/kSxyw.png',
'youdontsay' : 'http://i.imgur.com/xq9Ix.png',
'motherofgod' : 'http://i.imgur.com/CxL3b.png',
'likeasir' : 'http://i.imgur.com/CqBdw.png'
}
module.exports = (robot)->
robot.hear /:(\w+):/g, (message)->
build_response message
build_response = (message)->
orig_response = message.message.text
response = orig_response
return if message.match.length == 0
for icon in message.match
expr = new RegExp( icon, 'g' )
image = trollicons[ icon.replace( /:/g, '' ) ]
response = response.replace( expr, image ) if image != undefined
message.send response if response != undefined and response != orig_response
| true | # Description:
# Return trollicon images
# used resources from : https://github.com/sagargp/trollicons Adium extension
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# :<trollicon>: - outputs <trollicon> image
# :isee: what you did there, and :megusta: - is a valid example of multiple trollicons
#
# Author:
# PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI
trollicons = {
'gasp' : 'http://i.imgur.com/tYmuZ.png',
'challenge' : 'http://i.imgur.com/jbKmr.png',
'lol' : 'http://i.imgur.com/WjI3L.png',
'no' : 'http://i.imgur.com/loC5s.png',
'yao' : 'http://i.imgur.com/wTAP3.png',
'kidding' : 'http://i.imgur.com/0uCcv.png',
'megusta' : 'http://i.imgur.com/QfeUB.png',
'isee' : 'http://i.imgur.com/M4bcv.png',
'fuckyeah' : 'http://i.imgur.com/m7mEZ.png',
'problem' : 'http://i.imgur.com/oLlJm.png',
'dissapoint' : 'http://i.imgur.com/EwBi7.png',
'nothing' : 'http://i.imgur.com/Nwos9.png',
'pokerface' : 'http://i.imgur.com/dDjvG.png',
'ok' : 'http://i.imgur.com/QRCoI.png',
'sadtroll' : 'http://i.imgur.com/gYsxd.png',
'yuno' : 'http://i.imgur.com/sZMnV.png',
'true' : 'http://i.imgur.com/oealL.png',
'PI:NAME:<NAME>END_PI' : 'http://i.imgur.com/zszUl.png',
'forever' : 'http://i.imgur.com/5MBi2.png',
'jackie' : 'http://i.imgur.com/63oaA.png',
'fu' : 'http://i.imgur.com/YHYTg.png',
'rage' : 'http://i.imgur.com/itXDM.png',
'areyoukiddingme' : 'http://i.imgur.com/0uCcv.png',
'nothingtodo' : 'http://i.imgur.com/Nwos9.png',
'moonshot' : 'http://i.imgur.com/E8Dq3.png',
'cerealguy' : 'http://i.imgur.com/sD2jS.png',
'gtfo' : 'http://i.imgur.com/kSxyw.png',
'youdontsay' : 'http://i.imgur.com/xq9Ix.png',
'motherofgod' : 'http://i.imgur.com/CxL3b.png',
'likeasir' : 'http://i.imgur.com/CqBdw.png'
}
module.exports = (robot)->
robot.hear /:(\w+):/g, (message)->
build_response message
build_response = (message)->
orig_response = message.message.text
response = orig_response
return if message.match.length == 0
for icon in message.match
expr = new RegExp( icon, 'g' )
image = trollicons[ icon.replace( /:/g, '' ) ]
response = response.replace( expr, image ) if image != undefined
message.send response if response != undefined and response != orig_response
|
[
{
"context": "gExp \"#{str}$\") then true else false\n\n REQ_TOKEN: \"#_require\"\n REQ_MAIN_NODE: \"__MAIN__\"\n\n process: (folder)",
"end": 312,
"score": 0.7806705832481384,
"start": 302,
"tag": "PASSWORD",
"value": "\"#_require"
}
] | src/rehab.coffee | Vizir/rehab | 4 | #_require ./tsort
wrench = require('wrench')
fs = require('fs')
path = require('path')
module.exports = class Rehab
String::beginsWith = (str) -> if @match(new RegExp "^#{str}") then true else false
String::endsWith = (str) -> if @match(new RegExp "#{str}$") then true else false
REQ_TOKEN: "#_require"
REQ_MAIN_NODE: "__MAIN__"
process: (folder) ->
# create a graph from a folder name:
# src/C <- A -> B.coffee -> C
depGraph = @processDependencyGraph(folder)
#console.log "1: processDependencyGraph", depGraph
# normalize filenames:
# src/C.coffee <- src/A.coffee -> src/B.coffee -> src/C.coffee
depGraph = @normalizeFilename(folder, depGraph)
#console.log "2: normalizeFilename", depGraph
# create a list from a graph:
# A.coffee -> B.coffee -> C.coffee
depList = @processDependencyList depGraph
#console.log "3: processDependencyList", depList
depList.reverse() #yeah!
processDependencyGraph: (folder) ->
depGraph = []
for f in (@getSourceFiles folder)
@parseRequiredFile folder, f, depGraph
depGraph
normalizeFilename: (folder, depGraph) ->
for edge in depGraph
continue if edge[1] == @REQ_MAIN_NODE
fileDep = @normalizeCoffeeFilename(edge[0])
file = @normalizeCoffeeFilename(edge[1])
fullPath = path.resolve path.dirname(fileDep), file
file = path.join(folder, path.relative(folder, fullPath))
edge[0..1] = [fileDep, file]
depGraph
normalizeCoffeeFilename: (file) ->
file = "#{file}.coffee" unless file.endsWith ".coffee"
file = path.normalize file
file
processDependencyList: (depGraph) ->
depList = tsort(depGraph)
depList.filter (i) => not i.beginsWith @REQ_MAIN_NODE
getSourceFiles: (folder) ->
files = wrench.readdirSyncRecursive folder
(file for file in files when file.endsWith '.coffee')
parseRequiredLine: (line) ->
line.replace "#{@REQ_TOKEN} ", ""
parseRequiredFile: (folder, file, depGraph) ->
fileName = path.join(folder, file)
depGraph.push [fileName, @REQ_MAIN_NODE] #every file depends on MAIN (a fake file)
content = fs.readFileSync(fileName, 'utf8')
lines = content.split '\n'
for line in lines
line = line.slice(0, -1) if line.slice(-1) == '\r'
line = line.trim()
depGraph.push [fileName, @parseRequiredLine(line)] if line.beginsWith @REQ_TOKEN
| 4769 | #_require ./tsort
wrench = require('wrench')
fs = require('fs')
path = require('path')
module.exports = class Rehab
String::beginsWith = (str) -> if @match(new RegExp "^#{str}") then true else false
String::endsWith = (str) -> if @match(new RegExp "#{str}$") then true else false
REQ_TOKEN: <PASSWORD>"
REQ_MAIN_NODE: "__MAIN__"
process: (folder) ->
# create a graph from a folder name:
# src/C <- A -> B.coffee -> C
depGraph = @processDependencyGraph(folder)
#console.log "1: processDependencyGraph", depGraph
# normalize filenames:
# src/C.coffee <- src/A.coffee -> src/B.coffee -> src/C.coffee
depGraph = @normalizeFilename(folder, depGraph)
#console.log "2: normalizeFilename", depGraph
# create a list from a graph:
# A.coffee -> B.coffee -> C.coffee
depList = @processDependencyList depGraph
#console.log "3: processDependencyList", depList
depList.reverse() #yeah!
processDependencyGraph: (folder) ->
depGraph = []
for f in (@getSourceFiles folder)
@parseRequiredFile folder, f, depGraph
depGraph
normalizeFilename: (folder, depGraph) ->
for edge in depGraph
continue if edge[1] == @REQ_MAIN_NODE
fileDep = @normalizeCoffeeFilename(edge[0])
file = @normalizeCoffeeFilename(edge[1])
fullPath = path.resolve path.dirname(fileDep), file
file = path.join(folder, path.relative(folder, fullPath))
edge[0..1] = [fileDep, file]
depGraph
normalizeCoffeeFilename: (file) ->
file = "#{file}.coffee" unless file.endsWith ".coffee"
file = path.normalize file
file
processDependencyList: (depGraph) ->
depList = tsort(depGraph)
depList.filter (i) => not i.beginsWith @REQ_MAIN_NODE
getSourceFiles: (folder) ->
files = wrench.readdirSyncRecursive folder
(file for file in files when file.endsWith '.coffee')
parseRequiredLine: (line) ->
line.replace "#{@REQ_TOKEN} ", ""
parseRequiredFile: (folder, file, depGraph) ->
fileName = path.join(folder, file)
depGraph.push [fileName, @REQ_MAIN_NODE] #every file depends on MAIN (a fake file)
content = fs.readFileSync(fileName, 'utf8')
lines = content.split '\n'
for line in lines
line = line.slice(0, -1) if line.slice(-1) == '\r'
line = line.trim()
depGraph.push [fileName, @parseRequiredLine(line)] if line.beginsWith @REQ_TOKEN
| true | #_require ./tsort
wrench = require('wrench')
fs = require('fs')
path = require('path')
module.exports = class Rehab
String::beginsWith = (str) -> if @match(new RegExp "^#{str}") then true else false
String::endsWith = (str) -> if @match(new RegExp "#{str}$") then true else false
REQ_TOKEN: PI:PASSWORD:<PASSWORD>END_PI"
REQ_MAIN_NODE: "__MAIN__"
process: (folder) ->
# create a graph from a folder name:
# src/C <- A -> B.coffee -> C
depGraph = @processDependencyGraph(folder)
#console.log "1: processDependencyGraph", depGraph
# normalize filenames:
# src/C.coffee <- src/A.coffee -> src/B.coffee -> src/C.coffee
depGraph = @normalizeFilename(folder, depGraph)
#console.log "2: normalizeFilename", depGraph
# create a list from a graph:
# A.coffee -> B.coffee -> C.coffee
depList = @processDependencyList depGraph
#console.log "3: processDependencyList", depList
depList.reverse() #yeah!
processDependencyGraph: (folder) ->
depGraph = []
for f in (@getSourceFiles folder)
@parseRequiredFile folder, f, depGraph
depGraph
normalizeFilename: (folder, depGraph) ->
for edge in depGraph
continue if edge[1] == @REQ_MAIN_NODE
fileDep = @normalizeCoffeeFilename(edge[0])
file = @normalizeCoffeeFilename(edge[1])
fullPath = path.resolve path.dirname(fileDep), file
file = path.join(folder, path.relative(folder, fullPath))
edge[0..1] = [fileDep, file]
depGraph
normalizeCoffeeFilename: (file) ->
file = "#{file}.coffee" unless file.endsWith ".coffee"
file = path.normalize file
file
processDependencyList: (depGraph) ->
depList = tsort(depGraph)
depList.filter (i) => not i.beginsWith @REQ_MAIN_NODE
getSourceFiles: (folder) ->
files = wrench.readdirSyncRecursive folder
(file for file in files when file.endsWith '.coffee')
parseRequiredLine: (line) ->
line.replace "#{@REQ_TOKEN} ", ""
parseRequiredFile: (folder, file, depGraph) ->
fileName = path.join(folder, file)
depGraph.push [fileName, @REQ_MAIN_NODE] #every file depends on MAIN (a fake file)
content = fs.readFileSync(fileName, 'utf8')
lines = content.split '\n'
for line in lines
line = line.slice(0, -1) if line.slice(-1) == '\r'
line = line.trim()
depGraph.push [fileName, @parseRequiredLine(line)] if line.beginsWith @REQ_TOKEN
|
[
{
"context": "ection.insert({\n fleet: fleet\n name: shipName\n online: true\n workers: bays\n ",
"end": 2129,
"score": 0.9859277009963989,
"start": 2125,
"tag": "NAME",
"value": "ship"
},
{
"context": "n.insert({\n fleet: fleet\n name: ship... | _source/server/armada.coffee | normajs/Heighliner | 0 |
class Armada
constructor: ->
self = @
self.collection = Heighliner.ships
statusReport: (fleet, cb) ->
if not cb then cb = ->
self = @
fleet = self.collection.find({fleet: fleet}).fetch()
if not fleet.length
cb([])
return
for ship, index in fleet by -1
console.log ship
alive = self.hail(ship)
if alive
continue
fleet.slice(index, 1)
cb fleet
hail: (ship, cb) ->
self = @
cb or= -> return
if not ship
cb false
return
if not ship.endpoint
self.collection.remove(ship._id, (err, count) ->
if err
throw new Meteor.Error err
)
cb false
return
try
alive = HTTP.get(ship.endpoint)
catch e
self.collection.remove(ship._id, (err, count) ->
if err
throw new Meteor.Error err
)
cb false
return
if alive.statusCode is 200
cb true
return
self.collection.remove(ship._id, (err, count) ->
if err
throw new Meteor.Error err
)
cb false
hashEndpoint: ->
return process.env.ROOT_URL
watchFleet: (fleet) ->
self = @
getReport = ->
ships = self.collection.find({fleet: fleet}).fetch()
for ship in ships
self.hail ship
Meteor.setInterval(getReport, 5000)
enlist: (fleet, cb) ->
self = @
# remove previous ship instances of this app
oldShips = self.collection.find({endpoint: self.hashEndpoint()}).fetch()
# sync clean up before we get going
for ship in oldShips
self.collection.remove(ship._id)
# make sure all ships are still reporting
self.statusReport(fleet, (ships) ->
# ships are disposable so lets give this one a new name
shipName = Random.id()
# the number of cores on this instance will inform how
# many bays of cargo this ship can carry
# each bay (worker) will get a new id once the worker starts
bays = []
# add a new ship sync so we can get the id
self.collection.insert({
fleet: fleet
name: shipName
online: true
workers: bays
endpoint: self.hashEndpoint()
}, (err, id) ->
console.log err, id, process.env.MONGO_URL
if err
throw new Meteor.Error err
if not cb
return
self.watchFleet(fleet)
cb id
)
)
Heighliner.armada = new Armada()
| 29293 |
class Armada
constructor: ->
self = @
self.collection = Heighliner.ships
statusReport: (fleet, cb) ->
if not cb then cb = ->
self = @
fleet = self.collection.find({fleet: fleet}).fetch()
if not fleet.length
cb([])
return
for ship, index in fleet by -1
console.log ship
alive = self.hail(ship)
if alive
continue
fleet.slice(index, 1)
cb fleet
hail: (ship, cb) ->
self = @
cb or= -> return
if not ship
cb false
return
if not ship.endpoint
self.collection.remove(ship._id, (err, count) ->
if err
throw new Meteor.Error err
)
cb false
return
try
alive = HTTP.get(ship.endpoint)
catch e
self.collection.remove(ship._id, (err, count) ->
if err
throw new Meteor.Error err
)
cb false
return
if alive.statusCode is 200
cb true
return
self.collection.remove(ship._id, (err, count) ->
if err
throw new Meteor.Error err
)
cb false
hashEndpoint: ->
return process.env.ROOT_URL
watchFleet: (fleet) ->
self = @
getReport = ->
ships = self.collection.find({fleet: fleet}).fetch()
for ship in ships
self.hail ship
Meteor.setInterval(getReport, 5000)
enlist: (fleet, cb) ->
self = @
# remove previous ship instances of this app
oldShips = self.collection.find({endpoint: self.hashEndpoint()}).fetch()
# sync clean up before we get going
for ship in oldShips
self.collection.remove(ship._id)
# make sure all ships are still reporting
self.statusReport(fleet, (ships) ->
# ships are disposable so lets give this one a new name
shipName = Random.id()
# the number of cores on this instance will inform how
# many bays of cargo this ship can carry
# each bay (worker) will get a new id once the worker starts
bays = []
# add a new ship sync so we can get the id
self.collection.insert({
fleet: fleet
name: <NAME> <NAME>
online: true
workers: bays
endpoint: self.hashEndpoint()
}, (err, id) ->
console.log err, id, process.env.MONGO_URL
if err
throw new Meteor.Error err
if not cb
return
self.watchFleet(fleet)
cb id
)
)
Heighliner.armada = new Armada()
| true |
class Armada
constructor: ->
self = @
self.collection = Heighliner.ships
statusReport: (fleet, cb) ->
if not cb then cb = ->
self = @
fleet = self.collection.find({fleet: fleet}).fetch()
if not fleet.length
cb([])
return
for ship, index in fleet by -1
console.log ship
alive = self.hail(ship)
if alive
continue
fleet.slice(index, 1)
cb fleet
hail: (ship, cb) ->
self = @
cb or= -> return
if not ship
cb false
return
if not ship.endpoint
self.collection.remove(ship._id, (err, count) ->
if err
throw new Meteor.Error err
)
cb false
return
try
alive = HTTP.get(ship.endpoint)
catch e
self.collection.remove(ship._id, (err, count) ->
if err
throw new Meteor.Error err
)
cb false
return
if alive.statusCode is 200
cb true
return
self.collection.remove(ship._id, (err, count) ->
if err
throw new Meteor.Error err
)
cb false
hashEndpoint: ->
return process.env.ROOT_URL
watchFleet: (fleet) ->
self = @
getReport = ->
ships = self.collection.find({fleet: fleet}).fetch()
for ship in ships
self.hail ship
Meteor.setInterval(getReport, 5000)
enlist: (fleet, cb) ->
self = @
# remove previous ship instances of this app
oldShips = self.collection.find({endpoint: self.hashEndpoint()}).fetch()
# sync clean up before we get going
for ship in oldShips
self.collection.remove(ship._id)
# make sure all ships are still reporting
self.statusReport(fleet, (ships) ->
# ships are disposable so lets give this one a new name
shipName = Random.id()
# the number of cores on this instance will inform how
# many bays of cargo this ship can carry
# each bay (worker) will get a new id once the worker starts
bays = []
# add a new ship sync so we can get the id
self.collection.insert({
fleet: fleet
name: PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI
online: true
workers: bays
endpoint: self.hashEndpoint()
}, (err, id) ->
console.log err, id, process.env.MONGO_URL
if err
throw new Meteor.Error err
if not cb
return
self.watchFleet(fleet)
cb id
)
)
Heighliner.armada = new Armada()
|
[
{
"context": "member-Me').returns('{\"dummy\": \"value\", \"token\": \"token 1\"}');\n res = {}\n rememberme( configs )",
"end": 1933,
"score": 0.8558914661407471,
"start": 1928,
"tag": "KEY",
"value": "token"
},
{
"context": "r-Me').returns('{\"dummy\": \"value\", \"token\... | test/middleware.coffee | mdarveau/session-rememberme | 2 | chai = require("chai")
sinon = require("sinon")
sinonChai = require("sinon-chai")
crypto = require( 'crypto' )
chai.should()
chai.use(sinonChai)
rememberme = require('..')
randomBuffer = new Buffer(32)
describe 'rememberme-middleware', ->
it 'should do nothing if authenticated', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( true )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req = {}
res = {}
rememberme( configs ).middleware req, res, () ->
configs.checkAuthenticated.should.have.been.calledOnce
configs.checkAuthenticated.should.have.been.calledWith( req )
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
describe 'cookie-test', ->
it 'should do nothing if cookie not set', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns(null);
res = {}
rememberme( configs ).middleware req, res, () ->
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
it 'should do nothing if user not set in cookie', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"dummy": "value", "token": "token 1"}');
res = {}
rememberme( configs ).middleware req, res, () ->
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
it 'should do nothing if token not set in cookie', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req = {cookies:[]}
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "dummy": "value"}');
res = {}
rememberme( configs ).middleware req, res, () ->
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
it 'should load user with cookie info', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy ( cookieUser ) ->
done()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "token": "token 1"}');
res = {}
rememberme( configs ).middleware req, res, null
return
it 'should clear all tokens when provided token is not found', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy ( cookieUser ) -> Promise.resolve([['token 2'], {id:"1"}])
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy ( user ) -> Promise.resolve()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "token": "token 1"}');
res = {}
rememberme( configs ).middleware req, res, () ->
configs.deleteAllTokens.should.have.been.calledOnce
configs.deleteAllTokens.should.have.been.calledWith( {id:"1"} )
done()
return
it 'should set user in session when provided token is found', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy ( cookieUser ) -> Promise.resolve([[crypto.createHash('md5').update('token 1').digest('hex')], {id:"1"}])
setUserInSession: sinon.spy()
deleteToken: sinon.spy ( sessionUser, currentToken ) -> Promise.resolve()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy ( sessionUser, newToken ) -> Promise.resolve()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "token": "token 1"}');
res = {
set: sinon.spy()
}
sinon.stub(crypto, "randomBytes").callsFake -> randomBuffer
rememberme( configs ).middleware req, res, () ->
configs.setUserInSession.should.have.been.calledOnce
configs.setUserInSession.should.have.been.calledWith( req, {id:"1"} )
configs.deleteToken.should.have.been.calledOnce
configs.deleteToken.should.have.been.calledWith( {id:"1"}, crypto.createHash('md5').update("token 1").digest('hex') )
configs.saveNewToken.should.have.been.calledOnce
configs.saveNewToken.should.have.been.calledWith( {id:"1"} )
res.set.should.have.been.calledOnce
res.set.should.have.been.calledWith( "X-Remember-Me", "{\"user\":\"user 1\",\"token\":\"#{randomBuffer.toString( 'hex' )}\"}" )
crypto.randomBytes.restore()
done()
return | 216023 | chai = require("chai")
sinon = require("sinon")
sinonChai = require("sinon-chai")
crypto = require( 'crypto' )
chai.should()
chai.use(sinonChai)
rememberme = require('..')
randomBuffer = new Buffer(32)
describe 'rememberme-middleware', ->
it 'should do nothing if authenticated', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( true )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req = {}
res = {}
rememberme( configs ).middleware req, res, () ->
configs.checkAuthenticated.should.have.been.calledOnce
configs.checkAuthenticated.should.have.been.calledWith( req )
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
describe 'cookie-test', ->
it 'should do nothing if cookie not set', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns(null);
res = {}
rememberme( configs ).middleware req, res, () ->
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
it 'should do nothing if user not set in cookie', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"dummy": "value", "token": "<KEY> <PASSWORD>"}');
res = {}
rememberme( configs ).middleware req, res, () ->
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
it 'should do nothing if token not set in cookie', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req = {cookies:[]}
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "dummy": "value"}');
res = {}
rememberme( configs ).middleware req, res, () ->
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
it 'should load user with cookie info', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy ( cookieUser ) ->
done()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "token": "token 1"}');
res = {}
rememberme( configs ).middleware req, res, null
return
it 'should clear all tokens when provided token is not found', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy ( cookieUser ) -> Promise.resolve([['token 2'], {id:"1"}])
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy ( user ) -> Promise.resolve()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "token": "token 1"}');
res = {}
rememberme( configs ).middleware req, res, () ->
configs.deleteAllTokens.should.have.been.calledOnce
configs.deleteAllTokens.should.have.been.calledWith( {id:"1"} )
done()
return
it 'should set user in session when provided token is found', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy ( cookieUser ) -> Promise.resolve([[crypto.createHash('md5').update('token 1').digest('hex')], {id:"1"}])
setUserInSession: sinon.spy()
deleteToken: sinon.spy ( sessionUser, currentToken ) -> Promise.resolve()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy ( sessionUser, newToken ) -> Promise.resolve()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "token": "token <PASSWORD>"}');
res = {
set: sinon.spy()
}
sinon.stub(crypto, "randomBytes").callsFake -> randomBuffer
rememberme( configs ).middleware req, res, () ->
configs.setUserInSession.should.have.been.calledOnce
configs.setUserInSession.should.have.been.calledWith( req, {id:"1"} )
configs.deleteToken.should.have.been.calledOnce
configs.deleteToken.should.have.been.calledWith( {id:"1"}, crypto.createHash('md5').update("token 1").digest('hex') )
configs.saveNewToken.should.have.been.calledOnce
configs.saveNewToken.should.have.been.calledWith( {id:"1"} )
res.set.should.have.been.calledOnce
res.set.should.have.been.calledWith( "X-Remember-Me", "{\"user\":\"user 1\",\"token\":\"#{randomBuffer.toString( 'hex' )}\"}" )
crypto.randomBytes.restore()
done()
return | true | chai = require("chai")
sinon = require("sinon")
sinonChai = require("sinon-chai")
crypto = require( 'crypto' )
chai.should()
chai.use(sinonChai)
rememberme = require('..')
randomBuffer = new Buffer(32)
describe 'rememberme-middleware', ->
it 'should do nothing if authenticated', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( true )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req = {}
res = {}
rememberme( configs ).middleware req, res, () ->
configs.checkAuthenticated.should.have.been.calledOnce
configs.checkAuthenticated.should.have.been.calledWith( req )
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
describe 'cookie-test', ->
it 'should do nothing if cookie not set', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns(null);
res = {}
rememberme( configs ).middleware req, res, () ->
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
it 'should do nothing if user not set in cookie', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"dummy": "value", "token": "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI"}');
res = {}
rememberme( configs ).middleware req, res, () ->
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
it 'should do nothing if token not set in cookie', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req = {cookies:[]}
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "dummy": "value"}');
res = {}
rememberme( configs ).middleware req, res, () ->
configs.loadUser.should.have.not.been.called
configs.setUserInSession.should.have.not.been.called
done()
return
it 'should load user with cookie info', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy ( cookieUser ) ->
done()
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "token": "token 1"}');
res = {}
rememberme( configs ).middleware req, res, null
return
it 'should clear all tokens when provided token is not found', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy ( cookieUser ) -> Promise.resolve([['token 2'], {id:"1"}])
setUserInSession: sinon.spy()
deleteToken: sinon.spy()
deleteAllTokens: sinon.spy ( user ) -> Promise.resolve()
saveNewToken: sinon.spy()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "token": "token 1"}');
res = {}
rememberme( configs ).middleware req, res, () ->
configs.deleteAllTokens.should.have.been.calledOnce
configs.deleteAllTokens.should.have.been.calledWith( {id:"1"} )
done()
return
it 'should set user in session when provided token is found', ( done ) ->
configs =
checkAuthenticated: sinon.stub().returns( false )
loadUser: sinon.spy ( cookieUser ) -> Promise.resolve([[crypto.createHash('md5').update('token 1').digest('hex')], {id:"1"}])
setUserInSession: sinon.spy()
deleteToken: sinon.spy ( sessionUser, currentToken ) -> Promise.resolve()
deleteAllTokens: sinon.spy()
saveNewToken: sinon.spy ( sessionUser, newToken ) -> Promise.resolve()
req =
get: sinon.stub().withArgs('X-Remember-Me').returns('{"user": "user 1", "token": "token PI:PASSWORD:<PASSWORD>END_PI"}');
res = {
set: sinon.spy()
}
sinon.stub(crypto, "randomBytes").callsFake -> randomBuffer
rememberme( configs ).middleware req, res, () ->
configs.setUserInSession.should.have.been.calledOnce
configs.setUserInSession.should.have.been.calledWith( req, {id:"1"} )
configs.deleteToken.should.have.been.calledOnce
configs.deleteToken.should.have.been.calledWith( {id:"1"}, crypto.createHash('md5').update("token 1").digest('hex') )
configs.saveNewToken.should.have.been.calledOnce
configs.saveNewToken.should.have.been.calledWith( {id:"1"} )
res.set.should.have.been.calledOnce
res.set.should.have.been.calledWith( "X-Remember-Me", "{\"user\":\"user 1\",\"token\":\"#{randomBuffer.toString( 'hex' )}\"}" )
crypto.randomBytes.restore()
done()
return |
[
{
"context": "AND>]...\n\t\tversion #{version}\n\t\tCopyright(c) 2017,kssfilo(https://kanasys.com/gtech/)\n\n\t\tApplying unix filt",
"end": 1012,
"score": 0.9942847490310669,
"start": 1005,
"tag": "USERNAME",
"value": "kssfilo"
},
{
"context": "}\n\t\tCopyright(c) 2017,kssfilo(https... | cli.coffee | kssfilo/partpipe | 0 | #!/usr/bin/env coffee
opt=require 'getopt'
debugConsole=null
marker=null
command='normal'
processIndent=true
unknownTag='bypass'
tags={}
readline=require('readline').createInterface
input:process.stdin
T=console.log
E=console.error
appName=require('path').basename process.argv[1]
opt.setopt 'hdf:ics'
opt.getopt (o,p)->
switch o
when 'h','?'
command='usage'
when 'd'
debugConsole=console.error
when 'f'
marker=p[0]
when 'i'
processIndent=false
when 'c'
unknownTag='remove'
when 's'
unknownTag='show'
params=opt.params().splice 1
params.forEach (p)->
m=p.match /^([^@=]+)@(.*)$/
if m
if m[2]
tags[m[1]]="echo #{m[2]}"
else
tags[m[1]]=""
else
m=p.match /^([^@=]+)=(.*)$/
if m
tags[m[1]]=m[2] if m
else
if p.match /^([^@=]+)$/
tags[p]='cat'
switch command
when 'usage'
pjson=require './package.json'
version=pjson.version ? '-'
console.log """
#{appName} [<options>] [<TAG>=<COMMAND>]...
version #{version}
Copyright(c) 2017,kssfilo(https://kanasys.com/gtech/)
Applying unix filter to parts of input stream.
options:
-d:debug
-f<string>:use <string> as block seperator(default:@PARTPIPE@)
-i:don't process indents
-c:remove unknown tag
-s:bypass unknown tag
example:
>cat example.js
var html=`
@PARTPIPE@|md2html
# Hello World
This is a greeting application.
@PARTPIPE@
`;
>cat example.js|partpipe
var html=`
<H1>Hello World</H1>
<p>This is a greeting application.</p>
`;
inline:
>cat example.text
Name: @PARTPIPE@|sed 's/World/Earth/';Hello World@PARTPIPE@
>cat example.text|partpipe
Name: Hellow Earth
tag:(specify filter in command line,remove |):
>cat example.js
var html=`
@PARTPIPE@MARKDOWN
# Hello World
This is a greeting application.
@PARTPIPE@
`;
>cat example.js|partpipe 'MARKDOWN=md2html'
var html=`
<H1>Hello World</H1>
<p>This is a greeting application.</p>
`;
show/remove by tag
>cat example.js
@PARTPIPE@RELEASE;console.log('release build');@PARTPIPE@
@PARTPIPE@DEBUG;console.log('debug build');@PARTPIPE@
>cat example.js|partpipe -c RELEASE #-c option:remove unknown tag/<tag>:just show content
console.log('release build');
>cat example.js|partpipe -c DEBUG
console.log('debug build');
>cat example.js|partpipe RELESE@ DEBUG # <tag>@:remove
console.log('debug build');
replace by tag
>cat example.js
console.log("version is @PARTPIPE@VERSION@PARTPIPE@");
>cat example.js|partpipe VERSION@1.2.0 #<tag>@<text> replace with <text>
console.log('version is 1.2.0');
"""
process.exit 0
else
inputLines=[]
readline.on 'line',(line)->inputLines.push line
readline.on 'close',->
require('./partpipe') inputLines.join("\n"),
debugConsole:debugConsole
marker:marker
processIndent:processIndent
tags:tags
unknownTag:unknownTag
.then (r)->
process.stdout.write r
.catch (e)->
E e
process.exit 1
| 202266 | #!/usr/bin/env coffee
opt=require 'getopt'
debugConsole=null
marker=null
command='normal'
processIndent=true
unknownTag='bypass'
tags={}
readline=require('readline').createInterface
input:process.stdin
T=console.log
E=console.error
appName=require('path').basename process.argv[1]
opt.setopt 'hdf:ics'
opt.getopt (o,p)->
switch o
when 'h','?'
command='usage'
when 'd'
debugConsole=console.error
when 'f'
marker=p[0]
when 'i'
processIndent=false
when 'c'
unknownTag='remove'
when 's'
unknownTag='show'
params=opt.params().splice 1
params.forEach (p)->
m=p.match /^([^@=]+)@(.*)$/
if m
if m[2]
tags[m[1]]="echo #{m[2]}"
else
tags[m[1]]=""
else
m=p.match /^([^@=]+)=(.*)$/
if m
tags[m[1]]=m[2] if m
else
if p.match /^([^@=]+)$/
tags[p]='cat'
switch command
when 'usage'
pjson=require './package.json'
version=pjson.version ? '-'
console.log """
#{appName} [<options>] [<TAG>=<COMMAND>]...
version #{version}
Copyright(c) 2017,kssfilo(https://kanasys.com/gtech/)
Applying unix filter to parts of input stream.
options:
-d:debug
-f<string>:use <string> as block seperator(default:@PARTPIPE@)
-i:don't process indents
-c:remove unknown tag
-s:bypass unknown tag
example:
>cat example.js
var html=`
@PARTPIPE@|md2html
# Hello World
This is a greeting application.
@PARTPIPE@
`;
>cat example.js|partpipe
var html=`
<H1>Hello World</H1>
<p>This is a greeting application.</p>
`;
inline:
>cat example.text
Name: @PARTPIPE@|sed 's/World/Earth/';Hello World@PARTPIPE@
>cat example.text|partpipe
Name: <NAME>
tag:(specify filter in command line,remove |):
>cat example.js
var html=`
@PARTPIPE@MARKDOWN
# Hello World
This is a greeting application.
@PARTPIPE@
`;
>cat example.js|partpipe 'MARKDOWN=md2html'
var html=`
<H1>Hello World</H1>
<p>This is a greeting application.</p>
`;
show/remove by tag
>cat example.js
@PARTPIPE@RELEASE;console.log('release build');@PARTPIPE@
@PARTPIPE@DEBUG;console.log('debug build');@PARTPIPE@
>cat example.js|partpipe -c RELEASE #-c option:remove unknown tag/<tag>:just show content
console.log('release build');
>cat example.js|partpipe -c DEBUG
console.log('debug build');
>cat example.js|partpipe RELESE@ DEBUG # <tag>@:remove
console.log('debug build');
replace by tag
>cat example.js
console.log("version is @PARTPIPE@VERSION@PARTPIPE@");
>cat example.js|partpipe VERSION@1.2.0 #<tag>@<text> replace with <text>
console.log('version is 1.2.0');
"""
process.exit 0
else
inputLines=[]
readline.on 'line',(line)->inputLines.push line
readline.on 'close',->
require('./partpipe') inputLines.join("\n"),
debugConsole:debugConsole
marker:marker
processIndent:processIndent
tags:tags
unknownTag:unknownTag
.then (r)->
process.stdout.write r
.catch (e)->
E e
process.exit 1
| true | #!/usr/bin/env coffee
opt=require 'getopt'
debugConsole=null
marker=null
command='normal'
processIndent=true
unknownTag='bypass'
tags={}
readline=require('readline').createInterface
input:process.stdin
T=console.log
E=console.error
appName=require('path').basename process.argv[1]
opt.setopt 'hdf:ics'
opt.getopt (o,p)->
switch o
when 'h','?'
command='usage'
when 'd'
debugConsole=console.error
when 'f'
marker=p[0]
when 'i'
processIndent=false
when 'c'
unknownTag='remove'
when 's'
unknownTag='show'
params=opt.params().splice 1
params.forEach (p)->
m=p.match /^([^@=]+)@(.*)$/
if m
if m[2]
tags[m[1]]="echo #{m[2]}"
else
tags[m[1]]=""
else
m=p.match /^([^@=]+)=(.*)$/
if m
tags[m[1]]=m[2] if m
else
if p.match /^([^@=]+)$/
tags[p]='cat'
switch command
when 'usage'
pjson=require './package.json'
version=pjson.version ? '-'
console.log """
#{appName} [<options>] [<TAG>=<COMMAND>]...
version #{version}
Copyright(c) 2017,kssfilo(https://kanasys.com/gtech/)
Applying unix filter to parts of input stream.
options:
-d:debug
-f<string>:use <string> as block seperator(default:@PARTPIPE@)
-i:don't process indents
-c:remove unknown tag
-s:bypass unknown tag
example:
>cat example.js
var html=`
@PARTPIPE@|md2html
# Hello World
This is a greeting application.
@PARTPIPE@
`;
>cat example.js|partpipe
var html=`
<H1>Hello World</H1>
<p>This is a greeting application.</p>
`;
inline:
>cat example.text
Name: @PARTPIPE@|sed 's/World/Earth/';Hello World@PARTPIPE@
>cat example.text|partpipe
Name: PI:NAME:<NAME>END_PI
tag:(specify filter in command line,remove |):
>cat example.js
var html=`
@PARTPIPE@MARKDOWN
# Hello World
This is a greeting application.
@PARTPIPE@
`;
>cat example.js|partpipe 'MARKDOWN=md2html'
var html=`
<H1>Hello World</H1>
<p>This is a greeting application.</p>
`;
show/remove by tag
>cat example.js
@PARTPIPE@RELEASE;console.log('release build');@PARTPIPE@
@PARTPIPE@DEBUG;console.log('debug build');@PARTPIPE@
>cat example.js|partpipe -c RELEASE #-c option:remove unknown tag/<tag>:just show content
console.log('release build');
>cat example.js|partpipe -c DEBUG
console.log('debug build');
>cat example.js|partpipe RELESE@ DEBUG # <tag>@:remove
console.log('debug build');
replace by tag
>cat example.js
console.log("version is @PARTPIPE@VERSION@PARTPIPE@");
>cat example.js|partpipe VERSION@1.2.0 #<tag>@<text> replace with <text>
console.log('version is 1.2.0');
"""
process.exit 0
else
inputLines=[]
readline.on 'line',(line)->inputLines.push line
readline.on 'close',->
require('./partpipe') inputLines.join("\n"),
debugConsole:debugConsole
marker:marker
processIndent:processIndent
tags:tags
unknownTag:unknownTag
.then (r)->
process.stdout.write r
.catch (e)->
E e
process.exit 1
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9986999034881592,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-https-timeout.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.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
common = require("../common")
assert = require("assert")
fs = require("fs")
exec = require("child_process").exec
https = require("https")
options =
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
# a server that never replies
server = https.createServer(options, ->
console.log "Got request. Doing nothing."
return
).listen(common.PORT, ->
req = https.request(
host: "localhost"
port: common.PORT
path: "/"
method: "GET"
rejectUnauthorized: false
)
req.setTimeout 10
req.end()
req.on "response", (res) ->
console.log "got response"
return
req.on "socket", ->
console.log "got a socket"
req.socket.on "connect", ->
console.log "socket connected"
return
setTimeout (->
throw new Error("Did not get timeout event")return
), 200
return
req.on "timeout", ->
console.log "timeout occurred outside"
req.destroy()
server.close()
process.exit 0
return
return
)
| 35406 | # 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.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
common = require("../common")
assert = require("assert")
fs = require("fs")
exec = require("child_process").exec
https = require("https")
options =
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
# a server that never replies
server = https.createServer(options, ->
console.log "Got request. Doing nothing."
return
).listen(common.PORT, ->
req = https.request(
host: "localhost"
port: common.PORT
path: "/"
method: "GET"
rejectUnauthorized: false
)
req.setTimeout 10
req.end()
req.on "response", (res) ->
console.log "got response"
return
req.on "socket", ->
console.log "got a socket"
req.socket.on "connect", ->
console.log "socket connected"
return
setTimeout (->
throw new Error("Did not get timeout event")return
), 200
return
req.on "timeout", ->
console.log "timeout occurred outside"
req.destroy()
server.close()
process.exit 0
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.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
common = require("../common")
assert = require("assert")
fs = require("fs")
exec = require("child_process").exec
https = require("https")
options =
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
# a server that never replies
server = https.createServer(options, ->
console.log "Got request. Doing nothing."
return
).listen(common.PORT, ->
req = https.request(
host: "localhost"
port: common.PORT
path: "/"
method: "GET"
rejectUnauthorized: false
)
req.setTimeout 10
req.end()
req.on "response", (res) ->
console.log "got response"
return
req.on "socket", ->
console.log "got a socket"
req.socket.on "connect", ->
console.log "socket connected"
return
setTimeout (->
throw new Error("Did not get timeout event")return
), 200
return
req.on "timeout", ->
console.log "timeout occurred outside"
req.destroy()
server.close()
process.exit 0
return
return
)
|
[
{
"context": "ttings.degree + ')'\n\n\t\t\tprofile = {\n\t\t\t\tfirstName: firstName\n\t\t\t\tlastName: lastName\n\t\t\t\tdisplayName: displayNa",
"end": 647,
"score": 0.9987391829490662,
"start": 638,
"tag": "NAME",
"value": "firstName"
},
{
"context": "profile = {\n\t\t\t\tfirstNam... | server/methods/saveUserProfile.coffee | akio46/Stitch | 0 | Meteor.methods
saveUserProfile: (settings) ->
unless RocketChat.settings.get("Accounts_AllowUserProfileChange")
throw new Meteor.Error(403, "[methods] resetAvatar -> Invalid access")
if Meteor.userId()
if settings.language?
RocketChat.models.Users.setLanguage Meteor.userId(), settings.language
# if settings.password?
# Accounts.setPassword Meteor.userId(), settings.password, { logout: false }
firstName = capitalizeFirstLetter settings.firstName
lastName = capitalizeFirstLetter settings.lastName
displayName = firstName + ' ' + lastName + ' (' + settings.degree + ')'
profile = {
firstName: firstName
lastName: lastName
displayName: displayName
degree: settings.degree
phone: settings.phone
}
RocketChat.models.Users.setProfile Meteor.userId(), profile
RocketChat.models.Messages.updateAllDisplayNamesByUserId Meteor.userId(), displayName
RocketChat.models.Subscriptions.updateAllNamesByUserId Meteor.userId(), settings.firstName + ' ' + settings.lastName
RocketChat.models.Subscriptions.updateAllReceiverNamesByUsername Meteor.user().username, settings.firstName + ' ' + settings.lastName
return true
| 144879 | Meteor.methods
saveUserProfile: (settings) ->
unless RocketChat.settings.get("Accounts_AllowUserProfileChange")
throw new Meteor.Error(403, "[methods] resetAvatar -> Invalid access")
if Meteor.userId()
if settings.language?
RocketChat.models.Users.setLanguage Meteor.userId(), settings.language
# if settings.password?
# Accounts.setPassword Meteor.userId(), settings.password, { logout: false }
firstName = capitalizeFirstLetter settings.firstName
lastName = capitalizeFirstLetter settings.lastName
displayName = firstName + ' ' + lastName + ' (' + settings.degree + ')'
profile = {
firstName: <NAME>
lastName: <NAME>
displayName: displayName
degree: settings.degree
phone: settings.phone
}
RocketChat.models.Users.setProfile Meteor.userId(), profile
RocketChat.models.Messages.updateAllDisplayNamesByUserId Meteor.userId(), displayName
RocketChat.models.Subscriptions.updateAllNamesByUserId Meteor.userId(), settings.firstName + ' ' + settings.lastName
RocketChat.models.Subscriptions.updateAllReceiverNamesByUsername Meteor.user().username, settings.firstName + ' ' + settings.lastName
return true
| true | Meteor.methods
saveUserProfile: (settings) ->
unless RocketChat.settings.get("Accounts_AllowUserProfileChange")
throw new Meteor.Error(403, "[methods] resetAvatar -> Invalid access")
if Meteor.userId()
if settings.language?
RocketChat.models.Users.setLanguage Meteor.userId(), settings.language
# if settings.password?
# Accounts.setPassword Meteor.userId(), settings.password, { logout: false }
firstName = capitalizeFirstLetter settings.firstName
lastName = capitalizeFirstLetter settings.lastName
displayName = firstName + ' ' + lastName + ' (' + settings.degree + ')'
profile = {
firstName: PI:NAME:<NAME>END_PI
lastName: PI:NAME:<NAME>END_PI
displayName: displayName
degree: settings.degree
phone: settings.phone
}
RocketChat.models.Users.setProfile Meteor.userId(), profile
RocketChat.models.Messages.updateAllDisplayNamesByUserId Meteor.userId(), displayName
RocketChat.models.Subscriptions.updateAllNamesByUserId Meteor.userId(), settings.firstName + ' ' + settings.lastName
RocketChat.models.Subscriptions.updateAllReceiverNamesByUsername Meteor.user().username, settings.firstName + ' ' + settings.lastName
return true
|
[
{
"context": "sc : 'AWS region (like \"us-west-2\")'\n key : 'aws.region'\n },{\n name : 'vault'\n desc : 'vault",
"end": 1569,
"score": 0.9840922951698303,
"start": 1559,
"tag": "KEY",
"value": "aws.region"
},
{
"context": "key_id'\n desc : 'access key id'\n ... | src/attic/command/init.iced | AngelKey/Angelkey.nodeclient | 151 |
{Base} = require './base'
{add_option_dict} = require './argparse'
read = require 'read'
log = require '../log'
#=========================================================================
exports.Command = class Command extends Base
#------------------------------
OPTS :
o :
alias : 'output'
help : 'the output config file to write (defaults to ~/.keybase.conf)'
A :
alias : 'access-key-id'
help : 'the accessKeyId for an admin AWS user'
r :
alias : 'region'
help : 'the AWS region to work in'
S :
alias : 'secret-access-key'
help : 'the secreteAccessKey for an admin AWS user'
v :
alias : 'vault'
help : 'the vault name to create'
#------------------------------
get_opt_or_prompt : ({name, desc}, cb) ->
desc = name unless desc?
val = @argv[name]
err = null
until val? or err?
await read { prompt: "#{desc}> " }, defer err, val
if err?
log.error "Error in getting #{desc}: #{err}"
cb err, val
#------------------------------
load_config_value : ({name, desc, key, val_prefix}, cb) ->
await @get_opt_or_prompt {name, desc}, defer err, val
if val?
val = [ val_prefix, val ].join '' if val_prefix?
@config.set key, val
cb not err?
#------------------------------
load_config : (cb) ->
ok = true
fields = [{
name : 'email'
desc : 'your primary email address'
key : 'email'
},{
name : 'region'
desc : 'AWS region (like "us-west-2")'
key : 'aws.region'
},{
name : 'vault'
desc : 'vault name'
key : 'vault'
val_prefix : "mkb-"
},{
name : 'access_key_id'
desc : 'access key id'
key : 'aws.accessKeyId'
},{
name : 'secret_access_key'
desc : 'secret access key'
key : 'aws.secretAccessKey'
}]
for d in fields
await @load_config_value d, defer ok
@config.loaded = ok
cb ok
#------------------------------
add_subcommand_parser : (scp) ->
opts =
help : 'initialize AWS for this user'
name = 'init'
sub = scp.addParser name, opts
add_option_dict sub, @OPTS
return [ name ]
#------------------------------
check_config : (cb) ->
await @config.find @argv.output, defer found
if found
log.error "Config file #{@config.filename} exists; refusing to overwrite"
cb (not found)
#------------------------------
init : (cb) ->
ok = true
await @check_config defer ok
await @load_config defer ok if ok
await super defer ok if ok
if ok
@vault = @config.vault()
@name = @vault
cb ok
#--------------
make_iam_user : (cb) ->
arg = { UserName : @name }
await @aws.iam.createUser arg, defer err
ok = true
if err?
ok = false
log.error "Error in making user '#{@name}': #{err}"
if ok
await @aws.iam.createAccessKey arg, defer err, res
if err?
ok = false
log.error "Error in creating access key: #{err}"
else if (not res?.AccessKey?) or (res?.AccessKey.Status isnt 'Active')
ok = false
log.error "Didn't get expected fields back from IAM; got #{JSON.stringify res}"
else
# Now we update the config obj, so that we're using
# the new, lower-privleged IAM. We'll then write this version
# out to the FS.
@config.set "aws.accessKeyId", res.AccessKey.AccessKeyId
@config.set "aws.secretAccessKey", res.AccessKey.SecretAccessKey
cb ok
#--------------
make_sns : (cb) ->
await @aws.sns.createTopic { Name : @name }, defer err, res
ok = true
if err?
log.error "Error making notification queue: #{err}"
ok = false
else
@sns = @aws.new_resource { arn : res.TopicArn }
log.info "+> Created SNS topic #{@sns.toString()}"
cb ok
#--------------
make_sqs : (cb) ->
# First make the queue
await @aws.sqs.createQueue { QueueName : @name }, defer err, res
ok = true
if err?
ok = false
log.error "Error creating queue #{@name}: #{err}"
else
@sqs = @aws.new_resource { url : res.QueueUrl }
log.info "+> Created SQS queue #{@sqs.toString()}"
# Allow the SNS service to write to this...
if ok
policy =
Version : "2008-10-17"
Id : "@{sqs.arn}/SQSDefaultPolicy"
Statement: [{
Sid : "Stmt#{Date.now()}"
Effect : "Allow"
Principal : AWS : "*"
Action : "SQS:SendMessage"
Resource : @sqs.arn
Condition : ArnEquals : "aws:SourceArn" : @sns.arn
}]
arg =
QueueUrl : @sqs.url
Attributes:
Policy : JSON.stringify policy
await @aws.sqs.setQueueAttributes arg, defer err, res
if err?
log.error "Error setting Queue attributes with #{JSON.stringify arg}: #{err}"
ok = false
if ok
arg =
TopicArn : @sns.arn
Protocol : 'sqs'
Endpoint : @sqs.arn
await @aws.sns.subscribe arg, defer err, res
if err?
log.error "Failed to establish subscription from #{@sqs.toString()} to #{@sns.toString()}: #{err}"
ok = false
cb ok
#------------------------------
grant_permissions : (cb) ->
svcs = [ 'sqs', 'glacier', 'sdb' ]
ok = true
for v in svcs when ok
await @grant v, defer ok
if ok
log.info "+> Granted permissions to IAM #{@config.aws().accessKeyId}"
cb ok
#------------------------------
grant : (svc, cb) ->
policy =
Statement : [{
Sid : "Stmt#{Date.now()}#{svc}"
Action : [ "#{svc}:*" ]
Effect : "Allow"
Resource : [ @[svc].arn ]
}]
policy_name = "#{@name}-#{svc}-access-policy"
arg =
UserName : @name
PolicyName : policy_name
PolicyDocument : JSON.stringify policy
await @aws.iam.putUserPolicy arg, defer err, data
if err?
log.error "Error setting policy #{JSON.stringify arg}: #{err}"
ok = false
else
ok = true
cb ok
#------------------------------
make_glacier : (cb) ->
arg =
vaultName : @name
await @aws.glacier.createVault arg, defer err, res
if err?
log.error "Error creating vault #{JSON.stringify arg}: #{err}"
ok = false
else
ok = true
lparts = res.location.split '/'
@account_id = lparts[1]
aparts = [ 'arn', 'aws', 'glacier', @config.aws().region, lparts[1] ]
aparts.push lparts[2...].join '/'
arn = aparts.join ":"
@glacier = @aws.new_resource { arn }
log.info "+> Created Glacier Vault #{@glacier.toString()}"
cb ok
#------------------------------
make_simpledb : (cb) ->
arg =
DomainName : @name
await @aws.sdb.createDomain arg, defer err, res
if err?
log.error "Error creatingDomain #{JSON.stringify arg}: #{err}"
ok = false
else
ok = true
aparts = [ 'arn', 'aws', 'sdb', @config.aws().region, @account_id,
"domain/#{@name}" ]
arn = aparts.join ":"
@sdb = @aws.new_resource { arn }
log.info "+> Created SimpleDB domain #{@sdb.toString()}"
cb ok
#------------------------------
write_config : (cb) ->
await @config.write defer ok
if not ok
log.error "Bailing out, since can't write out config file"
else
log.info "+> Writing out config file: #{@config.filename}"
cb ok
#------------------------------
update_config : (cb) ->
for svc in [ "sns", "sqs", "glacier", "sdb" ]
@config.set "arns.#{svc}", @[svc].arn.toString()
@config.set "account_id" , @account_id
cb true
#------------------------------
run : (cb) ->
await @init defer ok
await @make_iam_user defer ok if ok
await @write_config defer ok if ok
await @make_sns defer ok if ok
await @make_sqs defer ok if ok
await @make_glacier defer ok if ok
await @make_simpledb defer ok if ok
await @grant_permissions defer ok if ok
await @update_config defer ok if ok
await @write_config defer ok if ok
cb ok
#------------------------------
#=========================================================================
| 139387 |
{Base} = require './base'
{add_option_dict} = require './argparse'
read = require 'read'
log = require '../log'
#=========================================================================
exports.Command = class Command extends Base
#------------------------------
OPTS :
o :
alias : 'output'
help : 'the output config file to write (defaults to ~/.keybase.conf)'
A :
alias : 'access-key-id'
help : 'the accessKeyId for an admin AWS user'
r :
alias : 'region'
help : 'the AWS region to work in'
S :
alias : 'secret-access-key'
help : 'the secreteAccessKey for an admin AWS user'
v :
alias : 'vault'
help : 'the vault name to create'
#------------------------------
get_opt_or_prompt : ({name, desc}, cb) ->
desc = name unless desc?
val = @argv[name]
err = null
until val? or err?
await read { prompt: "#{desc}> " }, defer err, val
if err?
log.error "Error in getting #{desc}: #{err}"
cb err, val
#------------------------------
load_config_value : ({name, desc, key, val_prefix}, cb) ->
await @get_opt_or_prompt {name, desc}, defer err, val
if val?
val = [ val_prefix, val ].join '' if val_prefix?
@config.set key, val
cb not err?
#------------------------------
load_config : (cb) ->
ok = true
fields = [{
name : 'email'
desc : 'your primary email address'
key : 'email'
},{
name : 'region'
desc : 'AWS region (like "us-west-2")'
key : '<KEY>'
},{
name : 'vault'
desc : 'vault name'
key : 'vault'
val_prefix : "mkb-"
},{
name : 'access_key_id'
desc : 'access key id'
key : '<KEY>'
},{
name : 'secret_access_key'
desc : 'secret access key'
key : '<KEY>'
}]
for d in fields
await @load_config_value d, defer ok
@config.loaded = ok
cb ok
#------------------------------
add_subcommand_parser : (scp) ->
opts =
help : 'initialize AWS for this user'
name = 'init'
sub = scp.addParser name, opts
add_option_dict sub, @OPTS
return [ name ]
#------------------------------
check_config : (cb) ->
await @config.find @argv.output, defer found
if found
log.error "Config file #{@config.filename} exists; refusing to overwrite"
cb (not found)
#------------------------------
init : (cb) ->
ok = true
await @check_config defer ok
await @load_config defer ok if ok
await super defer ok if ok
if ok
@vault = @config.vault()
@name = @vault
cb ok
#--------------
make_iam_user : (cb) ->
arg = { UserName : @name }
await @aws.iam.createUser arg, defer err
ok = true
if err?
ok = false
log.error "Error in making user '#{@name}': #{err}"
if ok
await @aws.iam.createAccessKey arg, defer err, res
if err?
ok = false
log.error "Error in creating access key: #{err}"
else if (not res?.AccessKey?) or (res?.AccessKey.Status isnt 'Active')
ok = false
log.error "Didn't get expected fields back from IAM; got #{JSON.stringify res}"
else
# Now we update the config obj, so that we're using
# the new, lower-privleged IAM. We'll then write this version
# out to the FS.
@config.set "aws.accessKeyId", res.AccessKey.AccessKeyId
@config.set "aws.secretAccessKey", res.AccessKey.SecretAccessKey
cb ok
#--------------
make_sns : (cb) ->
await @aws.sns.createTopic { Name : @name }, defer err, res
ok = true
if err?
log.error "Error making notification queue: #{err}"
ok = false
else
@sns = @aws.new_resource { arn : res.TopicArn }
log.info "+> Created SNS topic #{@sns.toString()}"
cb ok
#--------------
make_sqs : (cb) ->
# First make the queue
await @aws.sqs.createQueue { QueueName : @name }, defer err, res
ok = true
if err?
ok = false
log.error "Error creating queue #{@name}: #{err}"
else
@sqs = @aws.new_resource { url : res.QueueUrl }
log.info "+> Created SQS queue #{@sqs.toString()}"
# Allow the SNS service to write to this...
if ok
policy =
Version : "2008-10-17"
Id : "@{sqs.arn}/SQSDefaultPolicy"
Statement: [{
Sid : "Stmt#{Date.now()}"
Effect : "Allow"
Principal : AWS : "*"
Action : "SQS:SendMessage"
Resource : @sqs.arn
Condition : ArnEquals : "aws:SourceArn" : @sns.arn
}]
arg =
QueueUrl : @sqs.url
Attributes:
Policy : JSON.stringify policy
await @aws.sqs.setQueueAttributes arg, defer err, res
if err?
log.error "Error setting Queue attributes with #{JSON.stringify arg}: #{err}"
ok = false
if ok
arg =
TopicArn : @sns.arn
Protocol : 'sqs'
Endpoint : @sqs.arn
await @aws.sns.subscribe arg, defer err, res
if err?
log.error "Failed to establish subscription from #{@sqs.toString()} to #{@sns.toString()}: #{err}"
ok = false
cb ok
#------------------------------
grant_permissions : (cb) ->
svcs = [ 'sqs', 'glacier', 'sdb' ]
ok = true
for v in svcs when ok
await @grant v, defer ok
if ok
log.info "+> Granted permissions to IAM #{@config.aws().accessKeyId}"
cb ok
#------------------------------
grant : (svc, cb) ->
policy =
Statement : [{
Sid : "Stmt#{Date.now()}#{svc}"
Action : [ "#{svc}:*" ]
Effect : "Allow"
Resource : [ @[svc].arn ]
}]
policy_name = "#{@name}-#{svc}-access-policy"
arg =
UserName : @name
PolicyName : policy_name
PolicyDocument : JSON.stringify policy
await @aws.iam.putUserPolicy arg, defer err, data
if err?
log.error "Error setting policy #{JSON.stringify arg}: #{err}"
ok = false
else
ok = true
cb ok
#------------------------------
make_glacier : (cb) ->
arg =
vaultName : @name
await @aws.glacier.createVault arg, defer err, res
if err?
log.error "Error creating vault #{JSON.stringify arg}: #{err}"
ok = false
else
ok = true
lparts = res.location.split '/'
@account_id = lparts[1]
aparts = [ 'arn', 'aws', 'glacier', @config.aws().region, lparts[1] ]
aparts.push lparts[2...].join '/'
arn = aparts.join ":"
@glacier = @aws.new_resource { arn }
log.info "+> Created Glacier Vault #{@glacier.toString()}"
cb ok
#------------------------------
make_simpledb : (cb) ->
arg =
DomainName : @name
await @aws.sdb.createDomain arg, defer err, res
if err?
log.error "Error creatingDomain #{JSON.stringify arg}: #{err}"
ok = false
else
ok = true
aparts = [ 'arn', 'aws', 'sdb', @config.aws().region, @account_id,
"domain/#{@name}" ]
arn = aparts.join ":"
@sdb = @aws.new_resource { arn }
log.info "+> Created SimpleDB domain #{@sdb.toString()}"
cb ok
#------------------------------
write_config : (cb) ->
await @config.write defer ok
if not ok
log.error "Bailing out, since can't write out config file"
else
log.info "+> Writing out config file: #{@config.filename}"
cb ok
#------------------------------
update_config : (cb) ->
for svc in [ "sns", "sqs", "glacier", "sdb" ]
@config.set "arns.#{svc}", @[svc].arn.toString()
@config.set "account_id" , @account_id
cb true
#------------------------------
run : (cb) ->
await @init defer ok
await @make_iam_user defer ok if ok
await @write_config defer ok if ok
await @make_sns defer ok if ok
await @make_sqs defer ok if ok
await @make_glacier defer ok if ok
await @make_simpledb defer ok if ok
await @grant_permissions defer ok if ok
await @update_config defer ok if ok
await @write_config defer ok if ok
cb ok
#------------------------------
#=========================================================================
| true |
{Base} = require './base'
{add_option_dict} = require './argparse'
read = require 'read'
log = require '../log'
#=========================================================================
exports.Command = class Command extends Base
#------------------------------
OPTS :
o :
alias : 'output'
help : 'the output config file to write (defaults to ~/.keybase.conf)'
A :
alias : 'access-key-id'
help : 'the accessKeyId for an admin AWS user'
r :
alias : 'region'
help : 'the AWS region to work in'
S :
alias : 'secret-access-key'
help : 'the secreteAccessKey for an admin AWS user'
v :
alias : 'vault'
help : 'the vault name to create'
#------------------------------
get_opt_or_prompt : ({name, desc}, cb) ->
desc = name unless desc?
val = @argv[name]
err = null
until val? or err?
await read { prompt: "#{desc}> " }, defer err, val
if err?
log.error "Error in getting #{desc}: #{err}"
cb err, val
#------------------------------
load_config_value : ({name, desc, key, val_prefix}, cb) ->
await @get_opt_or_prompt {name, desc}, defer err, val
if val?
val = [ val_prefix, val ].join '' if val_prefix?
@config.set key, val
cb not err?
#------------------------------
load_config : (cb) ->
ok = true
fields = [{
name : 'email'
desc : 'your primary email address'
key : 'email'
},{
name : 'region'
desc : 'AWS region (like "us-west-2")'
key : 'PI:KEY:<KEY>END_PI'
},{
name : 'vault'
desc : 'vault name'
key : 'vault'
val_prefix : "mkb-"
},{
name : 'access_key_id'
desc : 'access key id'
key : 'PI:KEY:<KEY>END_PI'
},{
name : 'secret_access_key'
desc : 'secret access key'
key : 'PI:KEY:<KEY>END_PI'
}]
for d in fields
await @load_config_value d, defer ok
@config.loaded = ok
cb ok
#------------------------------
add_subcommand_parser : (scp) ->
opts =
help : 'initialize AWS for this user'
name = 'init'
sub = scp.addParser name, opts
add_option_dict sub, @OPTS
return [ name ]
#------------------------------
check_config : (cb) ->
await @config.find @argv.output, defer found
if found
log.error "Config file #{@config.filename} exists; refusing to overwrite"
cb (not found)
#------------------------------
init : (cb) ->
ok = true
await @check_config defer ok
await @load_config defer ok if ok
await super defer ok if ok
if ok
@vault = @config.vault()
@name = @vault
cb ok
#--------------
make_iam_user : (cb) ->
arg = { UserName : @name }
await @aws.iam.createUser arg, defer err
ok = true
if err?
ok = false
log.error "Error in making user '#{@name}': #{err}"
if ok
await @aws.iam.createAccessKey arg, defer err, res
if err?
ok = false
log.error "Error in creating access key: #{err}"
else if (not res?.AccessKey?) or (res?.AccessKey.Status isnt 'Active')
ok = false
log.error "Didn't get expected fields back from IAM; got #{JSON.stringify res}"
else
# Now we update the config obj, so that we're using
# the new, lower-privleged IAM. We'll then write this version
# out to the FS.
@config.set "aws.accessKeyId", res.AccessKey.AccessKeyId
@config.set "aws.secretAccessKey", res.AccessKey.SecretAccessKey
cb ok
#--------------
make_sns : (cb) ->
await @aws.sns.createTopic { Name : @name }, defer err, res
ok = true
if err?
log.error "Error making notification queue: #{err}"
ok = false
else
@sns = @aws.new_resource { arn : res.TopicArn }
log.info "+> Created SNS topic #{@sns.toString()}"
cb ok
#--------------
make_sqs : (cb) ->
# First make the queue
await @aws.sqs.createQueue { QueueName : @name }, defer err, res
ok = true
if err?
ok = false
log.error "Error creating queue #{@name}: #{err}"
else
@sqs = @aws.new_resource { url : res.QueueUrl }
log.info "+> Created SQS queue #{@sqs.toString()}"
# Allow the SNS service to write to this...
if ok
policy =
Version : "2008-10-17"
Id : "@{sqs.arn}/SQSDefaultPolicy"
Statement: [{
Sid : "Stmt#{Date.now()}"
Effect : "Allow"
Principal : AWS : "*"
Action : "SQS:SendMessage"
Resource : @sqs.arn
Condition : ArnEquals : "aws:SourceArn" : @sns.arn
}]
arg =
QueueUrl : @sqs.url
Attributes:
Policy : JSON.stringify policy
await @aws.sqs.setQueueAttributes arg, defer err, res
if err?
log.error "Error setting Queue attributes with #{JSON.stringify arg}: #{err}"
ok = false
if ok
arg =
TopicArn : @sns.arn
Protocol : 'sqs'
Endpoint : @sqs.arn
await @aws.sns.subscribe arg, defer err, res
if err?
log.error "Failed to establish subscription from #{@sqs.toString()} to #{@sns.toString()}: #{err}"
ok = false
cb ok
#------------------------------
grant_permissions : (cb) ->
svcs = [ 'sqs', 'glacier', 'sdb' ]
ok = true
for v in svcs when ok
await @grant v, defer ok
if ok
log.info "+> Granted permissions to IAM #{@config.aws().accessKeyId}"
cb ok
#------------------------------
grant : (svc, cb) ->
policy =
Statement : [{
Sid : "Stmt#{Date.now()}#{svc}"
Action : [ "#{svc}:*" ]
Effect : "Allow"
Resource : [ @[svc].arn ]
}]
policy_name = "#{@name}-#{svc}-access-policy"
arg =
UserName : @name
PolicyName : policy_name
PolicyDocument : JSON.stringify policy
await @aws.iam.putUserPolicy arg, defer err, data
if err?
log.error "Error setting policy #{JSON.stringify arg}: #{err}"
ok = false
else
ok = true
cb ok
#------------------------------
make_glacier : (cb) ->
arg =
vaultName : @name
await @aws.glacier.createVault arg, defer err, res
if err?
log.error "Error creating vault #{JSON.stringify arg}: #{err}"
ok = false
else
ok = true
lparts = res.location.split '/'
@account_id = lparts[1]
aparts = [ 'arn', 'aws', 'glacier', @config.aws().region, lparts[1] ]
aparts.push lparts[2...].join '/'
arn = aparts.join ":"
@glacier = @aws.new_resource { arn }
log.info "+> Created Glacier Vault #{@glacier.toString()}"
cb ok
#------------------------------
make_simpledb : (cb) ->
arg =
DomainName : @name
await @aws.sdb.createDomain arg, defer err, res
if err?
log.error "Error creatingDomain #{JSON.stringify arg}: #{err}"
ok = false
else
ok = true
aparts = [ 'arn', 'aws', 'sdb', @config.aws().region, @account_id,
"domain/#{@name}" ]
arn = aparts.join ":"
@sdb = @aws.new_resource { arn }
log.info "+> Created SimpleDB domain #{@sdb.toString()}"
cb ok
#------------------------------
write_config : (cb) ->
await @config.write defer ok
if not ok
log.error "Bailing out, since can't write out config file"
else
log.info "+> Writing out config file: #{@config.filename}"
cb ok
#------------------------------
update_config : (cb) ->
for svc in [ "sns", "sqs", "glacier", "sdb" ]
@config.set "arns.#{svc}", @[svc].arn.toString()
@config.set "account_id" , @account_id
cb true
#------------------------------
run : (cb) ->
await @init defer ok
await @make_iam_user defer ok if ok
await @write_config defer ok if ok
await @make_sns defer ok if ok
await @make_sqs defer ok if ok
await @make_glacier defer ok if ok
await @make_simpledb defer ok if ok
await @grant_permissions defer ok if ok
await @update_config defer ok if ok
await @write_config defer ok if ok
cb ok
#------------------------------
#=========================================================================
|
[
{
"context": " _.extend(fixtures().users,\n name: 'A Girl'\n ),\n [ { id: '4d8cd73191a5c50c",
"end": 3561,
"score": 0.8181924223899841,
"start": 3555,
"tag": "NAME",
"value": "A Girl"
},
{
"context": " User _.extend fixtures().users, {\n name: '... | src/client/test/models/user.test.coffee | artsyjian/positron | 76 | _ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
fixtures = require '../../../test/helpers/fixtures'
rewire = require 'rewire'
request = require 'superagent'
async = require 'async'
User = rewire '../../models/user'
Article = require '../../models/article.coffee'
{ fabricate } = require '@artsy/antigravity'
describe "User", ->
beforeEach ->
sinon.stub Backbone, 'sync'
User.__set__ 'jwtDecode', sinon.stub().returns({
partner_ids: ['4d8cd73191a5c50ce2000021']
})
afterEach ->
Backbone.sync.restore()
describe '#isAdmin', ->
it 'returns true for an Admin user', ->
@user = new User fixtures().users
@user.isAdmin().should.be.true()
it 'returns false for a non-Admin user', ->
@user = new User _.extend fixtures().users, type: 'User'
@user.isAdmin().should.be.false()
describe '#hasChannel', ->
it 'returns true for a member of a channel', ->
@user = new User _.extend fixtures().users, { channel_ids: ['1234'] }
@user.hasChannel('1234').should.be.true()
it 'returns false for a non-member of a channel', ->
@user = new User _.extend fixtures().users, { channel_ids: [] }
@user.hasChannel('1234').should.be.false()
describe '#hasPartner', ->
it 'returns true for a user with partner permissions', ->
@user = new User _.extend fixtures().users, { partner_ids: ['1234'] }
@user.hasPartner('1234').should.be.true()
it 'returns true for a user that is an Admin', ->
@user = new User fixtures().users
@user.hasPartner('1234').should.be.true()
it 'returns false for a user that does not have partner permissions', ->
@user = new User _.extend fixtures().users, { type: 'User', partner_ids: [] }
@user.hasPartner('1234').should.be.false()
describe '#hasArticleAccess', ->
it 'returns true for a member of a channel on a channel article', ->
@article = new Article fixtures().articles
@user = new User _.extend fixtures().users, { channel_ids: ['5aa99c11da4c00d6bc33a816'] }
@user.hasArticleAccess(@article).should.be.true()
it 'returns true for a member of a partner on a partner article', ->
@article = new Article _.extend fixtures().articles, {
partner_channel_id: '1234'
channel_id: null
}
@user = new User _.extend fixtures().users, { partner_ids: ['1234'] }
@user.hasArticleAccess(@article).should.be.true()
it 'returns true for a member of an Admin on a partner article', ->
@article = new Article fixtures().articles
@user = new User _.extend fixtures().users, { channel_ids: ['5aa99c11da4c00d6bc33a816'] }
@user.hasArticleAccess(@article).should.be.true()
it 'returns false for a member of a channel on a partner article', ->
@article = new Article _.extend fixtures().articles, { partner_channel_id: '1234' }
@user = new User _.extend fixtures().users, { channel_ids: ['12345'], type: 'User' }
@user.hasArticleAccess(@article).should.be.false()
it 'returns false for a member of a partner on a channel article', ->
@article = new Article _.extend fixtures().articles, { channel_id: '1234' }
@user = new User _.extend fixtures().users, { partner_ids: ['12345'] }
@user.hasArticleAccess(@article).should.be.false()
describe '#isOutdated', ->
it 'returns true if the name has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend(fixtures().users,
name: 'A Girl'
),
[ { id: '4d8cd73191a5c50ce200002b' } ]
])
@user = new User _.extend fixtures().users, {
name: 'Arya Stark'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if the type has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: 'Jon Snow'
type: 'King in the North'
[ { id: '4d8cd73191a5c50ce200002b' } ]
])
@user = new User _.extend fixtures().users, {
name: 'Jon Snow'
type: 'Lord Commander of the Night\'s Watch'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if the email has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: 'Cersi Lannister'
email: 'madkween@got'
[ { id: '4d8cd73191a5c50ce200002b' } ]
])
@user = new User _.extend fixtures().users, {
name: 'Cersi Lannister'
email: 'seekingrevenge@got'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if channel permissions have changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: 'Cersi Lannister'
[ { _id: '4d8cd73191a5c50ce2000022' } ]
[]
])
@user = new User _.extend fixtures().users, {
name: 'Cersi Lannister'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if partner permissions have changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: 'Cersi Lannister'
[{ id: '4d8cd73191a5c50ce200002b' }]
])
@user = new User _.extend fixtures().users, {
name: 'Cersi Lannister'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '456' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns false if nothing has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: 'Cersi Lannister'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
[ id: '4d8cd73191a5c50ce200002b' ]
])
@user = new User _.extend fixtures().users, {
name: 'Cersi Lannister'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.false()
describe '#fetchPartners', ->
it 'returns empty array for no partner access', ->
@user = new User fixtures().users
@user.fetchPartners (partners) ->
partners.length.should.equal 0
it 'fetches the partners that a user has permission to', ->
request.get = sinon.stub().returns
set: sinon.stub().returns
end: (cb) -> cb( null, body: [ fabricate 'partner' ] )
User.__set__ 'request', request
@user = new User _.extend fixtures().users,
partner_ids: ['123']
@user.fetchPartners (partners) ->
partners.length.should.equal 1
partners[0].name.should.equal 'Gagosian Gallery'
partners[0].type.should.equal 'Gallery'
| 58764 | _ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
fixtures = require '../../../test/helpers/fixtures'
rewire = require 'rewire'
request = require 'superagent'
async = require 'async'
User = rewire '../../models/user'
Article = require '../../models/article.coffee'
{ fabricate } = require '@artsy/antigravity'
describe "User", ->
beforeEach ->
sinon.stub Backbone, 'sync'
User.__set__ 'jwtDecode', sinon.stub().returns({
partner_ids: ['4d8cd73191a5c50ce2000021']
})
afterEach ->
Backbone.sync.restore()
describe '#isAdmin', ->
it 'returns true for an Admin user', ->
@user = new User fixtures().users
@user.isAdmin().should.be.true()
it 'returns false for a non-Admin user', ->
@user = new User _.extend fixtures().users, type: 'User'
@user.isAdmin().should.be.false()
describe '#hasChannel', ->
it 'returns true for a member of a channel', ->
@user = new User _.extend fixtures().users, { channel_ids: ['1234'] }
@user.hasChannel('1234').should.be.true()
it 'returns false for a non-member of a channel', ->
@user = new User _.extend fixtures().users, { channel_ids: [] }
@user.hasChannel('1234').should.be.false()
describe '#hasPartner', ->
it 'returns true for a user with partner permissions', ->
@user = new User _.extend fixtures().users, { partner_ids: ['1234'] }
@user.hasPartner('1234').should.be.true()
it 'returns true for a user that is an Admin', ->
@user = new User fixtures().users
@user.hasPartner('1234').should.be.true()
it 'returns false for a user that does not have partner permissions', ->
@user = new User _.extend fixtures().users, { type: 'User', partner_ids: [] }
@user.hasPartner('1234').should.be.false()
describe '#hasArticleAccess', ->
it 'returns true for a member of a channel on a channel article', ->
@article = new Article fixtures().articles
@user = new User _.extend fixtures().users, { channel_ids: ['5aa99c11da4c00d6bc33a816'] }
@user.hasArticleAccess(@article).should.be.true()
it 'returns true for a member of a partner on a partner article', ->
@article = new Article _.extend fixtures().articles, {
partner_channel_id: '1234'
channel_id: null
}
@user = new User _.extend fixtures().users, { partner_ids: ['1234'] }
@user.hasArticleAccess(@article).should.be.true()
it 'returns true for a member of an Admin on a partner article', ->
@article = new Article fixtures().articles
@user = new User _.extend fixtures().users, { channel_ids: ['5aa99c11da4c00d6bc33a816'] }
@user.hasArticleAccess(@article).should.be.true()
it 'returns false for a member of a channel on a partner article', ->
@article = new Article _.extend fixtures().articles, { partner_channel_id: '1234' }
@user = new User _.extend fixtures().users, { channel_ids: ['12345'], type: 'User' }
@user.hasArticleAccess(@article).should.be.false()
it 'returns false for a member of a partner on a channel article', ->
@article = new Article _.extend fixtures().articles, { channel_id: '1234' }
@user = new User _.extend fixtures().users, { partner_ids: ['12345'] }
@user.hasArticleAccess(@article).should.be.false()
describe '#isOutdated', ->
it 'returns true if the name has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend(fixtures().users,
name: '<NAME>'
),
[ { id: '4d8cd73191a5c50ce200002b' } ]
])
@user = new User _.extend fixtures().users, {
name: '<NAME>'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if the type has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: '<NAME>'
type: 'King in the North'
[ { id: '4d8cd73191a5c50ce200002b' } ]
])
@user = new User _.extend fixtures().users, {
name: '<NAME>'
type: 'Lord Commander of the Night\'s Watch'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if the email has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: '<NAME>'
email: '<EMAIL>'
[ { id: '4d8cd73191a5c50ce200002b' } ]
])
@user = new User _.extend fixtures().users, {
name: '<NAME>'
email: '<EMAIL>'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if channel permissions have changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: '<NAME>'
[ { _id: '4d8cd73191a5c50ce2000022' } ]
[]
])
@user = new User _.extend fixtures().users, {
name: '<NAME>'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if partner permissions have changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: '<NAME>'
[{ id: '4d8cd73191a5c50ce200002b' }]
])
@user = new User _.extend fixtures().users, {
name: '<NAME>'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '456' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns false if nothing has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: '<NAME>'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
[ id: '4d8cd73191a5c50ce200002b' ]
])
@user = new User _.extend fixtures().users, {
name: '<NAME>'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.false()
describe '#fetchPartners', ->
it 'returns empty array for no partner access', ->
@user = new User fixtures().users
@user.fetchPartners (partners) ->
partners.length.should.equal 0
it 'fetches the partners that a user has permission to', ->
request.get = sinon.stub().returns
set: sinon.stub().returns
end: (cb) -> cb( null, body: [ fabricate 'partner' ] )
User.__set__ 'request', request
@user = new User _.extend fixtures().users,
partner_ids: ['123']
@user.fetchPartners (partners) ->
partners.length.should.equal 1
partners[0].name.should.equal 'Gagosian Gallery'
partners[0].type.should.equal 'Gallery'
| true | _ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
fixtures = require '../../../test/helpers/fixtures'
rewire = require 'rewire'
request = require 'superagent'
async = require 'async'
User = rewire '../../models/user'
Article = require '../../models/article.coffee'
{ fabricate } = require '@artsy/antigravity'
describe "User", ->
beforeEach ->
sinon.stub Backbone, 'sync'
User.__set__ 'jwtDecode', sinon.stub().returns({
partner_ids: ['4d8cd73191a5c50ce2000021']
})
afterEach ->
Backbone.sync.restore()
describe '#isAdmin', ->
it 'returns true for an Admin user', ->
@user = new User fixtures().users
@user.isAdmin().should.be.true()
it 'returns false for a non-Admin user', ->
@user = new User _.extend fixtures().users, type: 'User'
@user.isAdmin().should.be.false()
describe '#hasChannel', ->
it 'returns true for a member of a channel', ->
@user = new User _.extend fixtures().users, { channel_ids: ['1234'] }
@user.hasChannel('1234').should.be.true()
it 'returns false for a non-member of a channel', ->
@user = new User _.extend fixtures().users, { channel_ids: [] }
@user.hasChannel('1234').should.be.false()
describe '#hasPartner', ->
it 'returns true for a user with partner permissions', ->
@user = new User _.extend fixtures().users, { partner_ids: ['1234'] }
@user.hasPartner('1234').should.be.true()
it 'returns true for a user that is an Admin', ->
@user = new User fixtures().users
@user.hasPartner('1234').should.be.true()
it 'returns false for a user that does not have partner permissions', ->
@user = new User _.extend fixtures().users, { type: 'User', partner_ids: [] }
@user.hasPartner('1234').should.be.false()
describe '#hasArticleAccess', ->
it 'returns true for a member of a channel on a channel article', ->
@article = new Article fixtures().articles
@user = new User _.extend fixtures().users, { channel_ids: ['5aa99c11da4c00d6bc33a816'] }
@user.hasArticleAccess(@article).should.be.true()
it 'returns true for a member of a partner on a partner article', ->
@article = new Article _.extend fixtures().articles, {
partner_channel_id: '1234'
channel_id: null
}
@user = new User _.extend fixtures().users, { partner_ids: ['1234'] }
@user.hasArticleAccess(@article).should.be.true()
it 'returns true for a member of an Admin on a partner article', ->
@article = new Article fixtures().articles
@user = new User _.extend fixtures().users, { channel_ids: ['5aa99c11da4c00d6bc33a816'] }
@user.hasArticleAccess(@article).should.be.true()
it 'returns false for a member of a channel on a partner article', ->
@article = new Article _.extend fixtures().articles, { partner_channel_id: '1234' }
@user = new User _.extend fixtures().users, { channel_ids: ['12345'], type: 'User' }
@user.hasArticleAccess(@article).should.be.false()
it 'returns false for a member of a partner on a channel article', ->
@article = new Article _.extend fixtures().articles, { channel_id: '1234' }
@user = new User _.extend fixtures().users, { partner_ids: ['12345'] }
@user.hasArticleAccess(@article).should.be.false()
describe '#isOutdated', ->
it 'returns true if the name has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend(fixtures().users,
name: 'PI:NAME:<NAME>END_PI'
),
[ { id: '4d8cd73191a5c50ce200002b' } ]
])
@user = new User _.extend fixtures().users, {
name: 'PI:NAME:<NAME>END_PI'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if the type has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: 'PI:NAME:<NAME>END_PI'
type: 'King in the North'
[ { id: '4d8cd73191a5c50ce200002b' } ]
])
@user = new User _.extend fixtures().users, {
name: 'PI:NAME:<NAME>END_PI'
type: 'Lord Commander of the Night\'s Watch'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if the email has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
[ { id: '4d8cd73191a5c50ce200002b' } ]
])
@user = new User _.extend fixtures().users, {
name: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if channel permissions have changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: 'PI:NAME:<NAME>END_PI'
[ { _id: '4d8cd73191a5c50ce2000022' } ]
[]
])
@user = new User _.extend fixtures().users, {
name: 'PI:NAME:<NAME>END_PI'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns true if partner permissions have changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: 'PI:NAME:<NAME>END_PI'
[{ id: '4d8cd73191a5c50ce200002b' }]
])
@user = new User _.extend fixtures().users, {
name: 'PI:NAME:<NAME>END_PI'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '456' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.true()
it 'returns false if nothing has changed', ->
User.__set__ 'async',
waterfall: sinon.stub().yields(null, [
_.extend fixtures().users,
name: 'PI:NAME:<NAME>END_PI'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
[ id: '4d8cd73191a5c50ce200002b' ]
])
@user = new User _.extend fixtures().users, {
name: 'PI:NAME:<NAME>END_PI'
channel_ids: [ '4d8cd73191a5c50ce200002b' ]
partner_ids: [ '4d8cd73191a5c50ce2000021' ]
}
@user.isOutdated (outdated) ->
outdated.should.be.false()
describe '#fetchPartners', ->
it 'returns empty array for no partner access', ->
@user = new User fixtures().users
@user.fetchPartners (partners) ->
partners.length.should.equal 0
it 'fetches the partners that a user has permission to', ->
request.get = sinon.stub().returns
set: sinon.stub().returns
end: (cb) -> cb( null, body: [ fabricate 'partner' ] )
User.__set__ 'request', request
@user = new User _.extend fixtures().users,
partner_ids: ['123']
@user.fetchPartners (partners) ->
partners.length.should.equal 1
partners[0].name.should.equal 'Gagosian Gallery'
partners[0].type.should.equal 'Gallery'
|
[
{
"context": "ext: \"Old Password\"\n }, {\n type: \"password\"\n id: \"new_password\"\n floatingL",
"end": 741,
"score": 0.7152242064476013,
"start": 733,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " }, {\n type: \"password\"\... | src/components/app/pages/user/change_password.coffee | dwetterau/base-node-app | 0 | React = require 'react'
FormPage = require './form_page'
Notifier = require '../../utils/notifier'
ChangePassword = React.createClass
_onSubmit: (fields) ->
$.post('/user/password', fields).done (response) =>
if response.ok
Notifier.info 'Password changed!'
@_clearFields fields
else
Notifier.error response.error
.fail Notifier.error
_clearFields: ->
@refs.FormPage.clearValues()
render: () ->
React.createElement FormPage,
ref: 'FormPage'
pageHeader: 'Change Password'
action: '/user/password'
inputs: [
{
type: "password"
id: "old_password"
floatingLabelText: "Old Password"
}, {
type: "password"
id: "new_password"
floatingLabelText: "New Password"
}, {
type: "password"
id: "confirm_password"
floatingLabelText: "Confirm Password"
}
]
submitLabel: 'Change password'
onSubmit: @_onSubmit
module.exports = ChangePassword
| 45414 | React = require 'react'
FormPage = require './form_page'
Notifier = require '../../utils/notifier'
ChangePassword = React.createClass
_onSubmit: (fields) ->
$.post('/user/password', fields).done (response) =>
if response.ok
Notifier.info 'Password changed!'
@_clearFields fields
else
Notifier.error response.error
.fail Notifier.error
_clearFields: ->
@refs.FormPage.clearValues()
render: () ->
React.createElement FormPage,
ref: 'FormPage'
pageHeader: 'Change Password'
action: '/user/password'
inputs: [
{
type: "password"
id: "old_password"
floatingLabelText: "Old Password"
}, {
type: "<PASSWORD>"
id: "<PASSWORD>_password"
floatingLabelText: "New Password"
}, {
type: "<PASSWORD>"
id: "<PASSWORD>_password"
floatingLabelText: "Confirm Password"
}
]
submitLabel: 'Change password'
onSubmit: @_onSubmit
module.exports = ChangePassword
| true | React = require 'react'
FormPage = require './form_page'
Notifier = require '../../utils/notifier'
ChangePassword = React.createClass
_onSubmit: (fields) ->
$.post('/user/password', fields).done (response) =>
if response.ok
Notifier.info 'Password changed!'
@_clearFields fields
else
Notifier.error response.error
.fail Notifier.error
_clearFields: ->
@refs.FormPage.clearValues()
render: () ->
React.createElement FormPage,
ref: 'FormPage'
pageHeader: 'Change Password'
action: '/user/password'
inputs: [
{
type: "password"
id: "old_password"
floatingLabelText: "Old Password"
}, {
type: "PI:PASSWORD:<PASSWORD>END_PI"
id: "PI:PASSWORD:<PASSWORD>END_PI_password"
floatingLabelText: "New Password"
}, {
type: "PI:PASSWORD:<PASSWORD>END_PI"
id: "PI:PASSWORD:<PASSWORD>END_PI_password"
floatingLabelText: "Confirm Password"
}
]
submitLabel: 'Change password'
onSubmit: @_onSubmit
module.exports = ChangePassword
|
[
{
"context": "12-L Кимогила'\n\n pilot_translations =\n \"Wedge Antilles\":\n name: \"Ведж Антиллес\"\n t",
"end": 12634,
"score": 0.8606792688369751,
"start": 12620,
"tag": "NAME",
"value": "Wedge Antilles"
},
{
"context": "ns =\n \"Wedge Antil... | coffeescripts/cards-ru.coffee | idavidka/xwing | 100 | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.ru = 'Русский'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations['Русский'] =
action:
"Barrel Roll": "Бочка"
"Boost": "Ускорение"
"Evade": "Уклонение"
"Focus": "Концентрация"
"Target Lock": "Захват цели"
"Recover": "Восстановление"
"Reinforce": "Усиление"
"Jam": "Заклинивание"
"Coordinate": "Координирование"
"Cloak": "Маскировка"
slot:
"Astromech": "Дроид-астромех"
"Bomb": "Бомба"
"Cannon": "Пушка"
"Crew": "Экипаж"
"Elite": "Элитный навык"
"Missile": "Ракета"
"System": "Система"
"Torpedo": "Торпеда"
"Turret": "Турель"
"Cargo": "Груз"
"Hardpoint": "Тяжелая установка"
"Team": "Команда"
"Illicit": "Незаконное"
"Salvaged Astromech": "Трофейный астромех"
"Tech": "Техника"
sources: # needed?
"Core": "Базовый набор"
"A-Wing Expansion Pack": "Дополнение А-Крыл"
"B-Wing Expansion Pack": "Дополнение Б-Крыл"
"X-Wing Expansion Pack": "Дополнение Икс-Крыл"
"Y-Wing Expansion Pack": "Дополнение У-Крыл"
"Millennium Falcon Expansion Pack": "Дополнение Тысячелетний Сокол"
"HWK-290 Expansion Pack": "Дополнение HWK-290"
"TIE Fighter Expansion Pack": "Дополнение TIE-истребитель"
"TIE Interceptor Expansion Pack": "Дополнение TIE-перехватчик"
"TIE Bomber Expansion Pack": "Дополнение TIE-бомбардировщик"
"TIE Advanced Expansion Pack": "Дополнение TIE-улучшенный"
"Lambda-Class Shuttle Expansion Pack": "Дополнение Шаттл класса Лямбда"
"Slave I Expansion Pack": "Дополнение Раб-1"
"Imperial Aces Expansion Pack": "Дополнение Имперские асы"
"Rebel Transport Expansion Pack": "Дополнение Транспорт повстанцев"
"Z-95 Headhunter Expansion Pack": "Дополнение Z-95 Охотник за головами"
"TIE Defender Expansion Pack": "Дополнение TIE-защитник"
"E-Wing Expansion Pack": "Дополнение Е-Крыл"
"TIE Phantom Expansion Pack": "Дополнение TIE-фантом"
"Tantive IV Expansion Pack": "Дополнение Тантив IV"
"Rebel Aces Expansion Pack": "Дополнение Асы повстанцев"
"YT-2400 Freighter Expansion Pack": "Дополнение Грузовоз YT-2400"
"VT-49 Decimator Expansion Pack": "Дополнение VT-49 Дециматор"
"StarViper Expansion Pack": "Дополнение Звездная Гадюка"
"M3-A Interceptor Expansion Pack": "Дополнение Перехватчик M3-A"
"IG-2000 Expansion Pack": "Дополнение IG-2000"
"Most Wanted Expansion Pack": "Дополнение Самые разыскиваемые"
"Imperial Raider Expansion Pack": "Дополнение Имперский рейдер"
"K-Wing Expansion Pack": "Дополнение К-Крыл"
"TIE Punisher Expansion Pack": "Дополнение TIE-каратель"
"Kihraxz Fighter Expansion Pack": "Дополнение Истребитель Кихраксз"
"Hound's Tooth Expansion Pack": "Дополнение Зуб Гончей"
"The Force Awakens Core Set": "Базовый набор Пробуждение Силы"
"T-70 X-Wing Expansion Pack": "Дополнение Икс-Крыл T-70"
"TIE/fo Fighter Expansion Pack": "Дополнение Истребитель TIE/пп"
"Imperial Assault Carrier Expansion Pack": "Дополнение Имперский штурмовой носитель"
"Ghost Expansion Pack": "Дополнение Призрак"
"Inquisitor's TIE Expansion Pack": "Дополнение TIE инквизитора"
"Mist Hunter Expansion Pack": "Дополнение Туманный охотник"
"Punishing One Expansion Pack": "Дополнение Карающий Один"
"Imperial Veterans Expansion Pack": "Дополнение Имперские ветераны"
"Protectorate Starfighter Expansion Pack": "Дополнение Звездный истребитель Протектората"
"Shadow Caster Expansion Pack": "Дополнение Наводящий Тень"
"Special Forces TIE Expansion Pack": "Дополнение TIE специальных сил"
"ARC-170 Expansion Pack": "Дополнение ARC-170"
"U-Wing Expansion Pack": "Дополнение Ю-Крыл"
"TIE Striker Expansion Pack": "Дополнение TIE-ударник"
"Upsilon-class Shuttle Expansion Pack": "Дополнение Шаттл класса Ипсилон"
"Sabine's TIE Fighter Expansion Pack": "Дополнение TIE-истребитель Сабины"
"Quadjumper Expansion Pack": "Дополнение Квадджампер"
"C-ROC Cruiser Expansion Pack": "Дополнение Крейсер C-ROC"
"TIE Aggressor Expansion Pack": "Дополнение TIE-агрессор"
"Scurrg H-6 Bomber Expansion Pack": "Дополнение Бомбардировщик Скуррг H-6"
"Auzituck Gunship Expansion Pack": "Дополнение Канонерка Озитук"
"TIE Silencer Expansion Pack": "Дополнение TIE-глушитель"
"Alpha-class Star Wing Expansion Pack": "Pасширение Звездноое Крыло Альфа-класса"
"Resistance Bomber Expansion Pack": "Дополнение Бомбардировщик сопротивления"
"Phantom II Expansion Pack": "Дополнение Фантом II"
"Kimogila Fighter Expansion Pack": "Дополнение Истребитель Кимогила"
ui:
shipSelectorPlaceholder: "Выбор корабля"
pilotSelectorPlaceholder: "Выбор пилота"
upgradePlaceholder: (translator, language, slot) ->
switch slot
when 'Elite'
"Элитный навык"
when 'Astromech'
"Астромех"
when 'Illicit'
"Незаконное"
when 'Salvaged Astromech'
"Трофейный астромех"
else
"Нет улучшения #{translator language, 'slot', slot}"
modificationPlaceholder: "Модификация"
titlePlaceholder: "Название"
upgradeHeader: (translator, language, slot) ->
switch slot
when 'Elite'
"Элитный навык"
when 'Astromech'
"Дроид-астромех"
when 'Illicit'
"Незаконное"
when 'Salvaged Astromech'
"Трофейный дроид-астромех"
else
"Улучшение #{translator language, 'slot', slot}"
unreleased: "не выпущено"
epic: "эпик"
byCSSSelector:
# Warnings
'.unreleased-content-used .translated': 'Этот отряд использует неизданный контент!'
'.epic-content-used .translated': 'Этот отряд использует эпический контент!'
'.illegal-epic-too-many-small-ships .translated': 'Вы не можете использовать более 12 малых кораблей одного типа!'
'.illegal-epic-too-many-large-ships .translated': 'Вы не можете использовать более 6 больших кораблей одного типа!'
'.collection-invalid .translated': 'Вы не можете использовать этот лист с вашей коллекцией!'
# Type selector
'.game-type-selector option[value="standard"]': 'Стандарт'
'.game-type-selector option[value="custom"]': 'Свой'
'.game-type-selector option[value="epic"]': 'Эпик'
'.game-type-selector option[value="team-epic"]': 'Командный эпик'
'.xwing-card-browser .translate.sort-cards-by': 'Сортировать по'
'.xwing-card-browser option[value="name"]': 'Названию'
'.xwing-card-browser option[value="source"]': 'Источнику'
'.xwing-card-browser option[value="type-by-points"]': 'Типу (по очкам)'
'.xwing-card-browser option[value="type-by-name"]': 'Типу (по названию)'
'.xwing-card-browser .translate.select-a-card': 'Выберите карту из списка слева.'
# Info well
'.info-well .info-ship td.info-header': 'Корабль'
'.info-well .info-skill td.info-header': 'Умение'
'.info-well .info-actions td.info-header': 'Действия'
'.info-well .info-upgrades td.info-header': 'Улучшения'
'.info-well .info-range td.info-header': 'Дистанция'
# Squadron edit buttons
'.clear-squad' : 'Новая эскадрилья'
'.save-list' : 'Сохранить'
'.save-list-as' : 'Сохранить как...'
'.delete-list' : 'Удалить'
'.backend-list-my-squads' : 'Загрузить эскадрилью'
'.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i> Imprimir/Ver como </span>Text'
'.randomize' : 'Случайный'
'.randomize-options' : 'Случайные опции…'
'.notes-container > span' : 'Примечания отряда'
# Print/View modal
'.bbcode-list' : 'Скопируйте BBCode ниже и вставьте его в сообщение своего форума.<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.html-list' : '<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.vertical-space-checkbox' : """Добавить место для письма с ухудшением / улучшением при печати. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Цветная печать. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="fa fa-print"></i> Imprimir'
# Randomizer options
'.do-randomize' : 'Сгенерировать случайным образом'
# Top tab bar
'#empireTab' : 'Галактическая Империя'
'#rebelTab' : 'Альянс повстанцев'
'#scumTab' : 'Пираты'
'#browserTab' : 'Поиск по картам'
'#aboutTab' : 'О нас'
singular:
'pilots': 'Пилоты'
'modifications': 'Модификации'
'titles': 'Названия'
types:
'Pilot': 'Пилот'
'Modification': 'Модификация'
'Title': 'Название'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders['Русский'] = () ->
exportObj.cardLanguage = 'Русский'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
# ship translations
exportObj.renameShip 'Lambda-Class Shuttle', 'Шаттл класса Лямбда'
exportObj.renameShip 'TIE Advanced', 'TIE улучшенный'
exportObj.renameShip 'TIE Bomber', 'TIE бомбардировщик'
exportObj.renameShip 'TIE Fighter', 'TIE истребитель'
exportObj.renameShip 'TIE Interceptor', 'TIE перехватчик'
exportObj.renameShip 'TIE Phantom', 'TIE фантом'
exportObj.renameShip 'TIE Defender', 'TIE защитник'
exportObj.renameShip 'TIE Punisher', 'TIE каратель'
exportObj.renameShip 'TIE Advanced Prototype', 'TIE улучшенный прототип'
exportObj.renameShip 'VT-49 Decimator', 'VT-49 Дециматор'
exportObj.renameShip 'TIE/fo Fighter', 'Истребитель TIE/пп'
exportObj.renameShip 'TIE/sf Fighter', 'Истребитель TIE/сс'
exportObj.renameShip 'TIE Striker', 'TIE ударник'
exportObj.renameShip 'Upsilon-class Shuttle', 'Шаттл класса Ипсилон'
exportObj.renameShip 'TIE Aggressor', 'TIE агрессор'
exportObj.renameShip 'TIE Silencer', 'TIE глушитель'
exportObj.renameShip 'Alpha-class Star Wing', 'Звездное Крыло класса Альфа'
exportObj.renameShip 'A-Wing', 'А-Крыл'
exportObj.renameShip 'B-Wing', 'Б-Крыл'
exportObj.renameShip 'E-Wing', 'Е-Крыл'
exportObj.renameShip 'X-Wing', 'Икс-Крыл'
exportObj.renameShip 'Y-Wing', 'У-Крыл'
exportObj.renameShip 'K-Wing', 'К-Крыл'
exportObj.renameShip 'Z-95 Headhunter', 'Z-95 охотник за головами'
exportObj.renameShip 'Attack Shuttle', 'Атакующий шаттл'
exportObj.renameShip 'CR90 Corvette (Aft)', 'Корвет CR90 (Корма)'
exportObj.renameShip 'CR90 Corvette (Fore)', 'Корвет CR90 (Нос)'
exportObj.renameShip 'GR-75 Medium Transport', 'Средний транспорт GR-75'
exportObj.renameShip 'T-70 X-Wing', 'Икс-Крыл T-70'
exportObj.renameShip 'U-Wing', 'Ю-Крыл'
exportObj.renameShip 'Auzituck Gunship', 'Канонерка Озитук'
exportObj.renameShip 'B/SF-17 Bomber', 'Бомбардировщик B/SF-17'
exportObj.renameShip 'Sheathipede-class Shuttle', 'Шаттл класса Колчан'
exportObj.renameShip 'M3-A Interceptor', 'Перехватчик M3-A'
exportObj.renameShip 'StarViper', 'Звездная Гадюка'
exportObj.renameShip 'Aggressor', 'Агрессор'
exportObj.renameShip 'Kihraxz Fighter', 'Истребитель Кихраксз'
exportObj.renameShip 'G-1A Starfighter', 'Звездный истребитель G-1A'
exportObj.renameShip 'JumpMaster 5000', 'Джампмастер 5000'
exportObj.renameShip 'Protectorate Starfighter', 'Звездный истребитель Протектората'
exportObj.renameShip 'Lancer-class Pursuit Craft', 'Транспорт преследования класса Копьеносец'
exportObj.renameShip 'Quadjumper', 'Квадджампер'
exportObj.renameShip 'C-ROC Cruiser', 'Крейсер C-ROC'
exportObj.renameShip 'Scurrg H-6 Bomber', 'Бомбардировщик Скуррг H-6'
exportObj.renameShip 'M12-L Kimogila Fighter', 'Истребитель M12-L Кимогила'
pilot_translations =
"Wedge Antilles":
name: "Ведж Антиллес"
text: """При атаке сократите параметр маневренности защищающегося на 1 (но не ниже 0)."""
ship: "Икс-Крыл"
"Garven Dreis":
name: "Гарвен Дрейс"
text: """Применив жетон концентрации, вы можете положить его на любой дружественный корабль на расстоянии 1-2 (вместо того, чтобы его сбросить)"""
ship: "Икс-Крыл"
"Red Squadron Pilot":
name: "Пилот Красной эскадрильи"
ship: "Икс-Крыл"
"Rookie Pilot":
name: "Пилот новичок"
ship: "Икс-Крыл"
"Biggs Darklighter":
name: "Биггс Дарклайтер"
text: """Один раз за игру, в начале фазы Боя, вы можете выбрать, чтобы другие дружественные корабли на расстоянии 1 не могли быть выбраны целью атаки, если вместо них атакующий может выбрать вас целью."""
ship: "Икс-Крыл"
"Luke Skywalker":
name: "Люк Скайуокер"
text: """При защите вы можете заменить 1 результат %FOCUS% на результат %EVADE%."""
ship: "Икс-Крыл"
"Gray Squadron Pilot":
name: "Пилот Серой эскадрильи"
ship: "У-Крыл"
'"Dutch" Vander':
name: "Датч Вандер"
text: """После получения захвата цели, выберите другой дружественный корабль на расстоянии 1-2. Выбранный корабль может немедленно получить захват цели."""
ship: "У-Крыл"
"Horton Salm":
name: "Хортон Сальм"
text: """Атакуя на расстоянии 2-3, вы можете перебросить все пустые результаты"""
ship: "У-Крыл"
"Gold Squadron Pilot":
name: "Пилот Золотой эскадрильи"
ship: "У-Крыл"
"Academy Pilot":
name: "Пилот академии"
ship: "TIE истребитель"
"Obsidian Squadron Pilot":
name: "Пилот Обсидиановой эскадрильи"
ship: "TIE истребитель"
"Black Squadron Pilot":
name: "Пилот Черной эскадрильи"
ship: "TIE истребитель"
'"Winged Gundark"':
name: '"Крылатый Гандарк"'
text: """Атакуя на расстоянии 1, вы можете изменить 1 результат %HIT% на результат %CRIT%"""
ship: "TIE истребитель"
'"Night Beast"':
name: '"Ночной Зверь"'
text: """После выполнения зеленого маневра, вы можете выполнить свободное действие Концентрации"""
ship: "TIE истребитель"
'"Backstabber"':
name: '"Ударяющий в спину"'
text: """Атакуя вне арки огня защищающегося, можете бросить 1 дополнительный кубик атаки"""
ship: "TIE истребитель"
'"Dark Curse"':
name: '"Темное проклятье"'
text: """Когда вы защищаетесь в фазу боя, атакующие корабли не могут тратить жетоны Концентрации или перебрасывать кубики атаки"""
ship: "TIE истребитель"
'"Mauler Mithel"':
name: '"Кувалда Мител"'
text: """ Атакуя на расстоянии 1, можете бросить 1 дополнительный кубик атаки."""
ship: "TIE истребитель"
'"Howlrunner"':
name: '"Хоулраннер"'
text: """Когда другой дружественный корабль атакует основным оружием на расстоянии 1, он может перебросить 1 кубик атаки"""
ship: "TIE истребитель"
"Tempest Squadron Pilot":
name: "Пилот эскадрильи Буря"
ship: "TIE улучшенный"
"Storm Squadron Pilot":
name: "Пилот эскадрильи Шторм"
ship: "TIE улучшенный"
"Maarek Stele":
name: "Маарек Стил"
text: """Когда ваша атака наносит противнику карточку повреждения лицом вверх, вместо этого вытяните 3 карты лицом вверх, выберите одну и сбросьте остальные."""
ship: "TIE улучшенный"
"Darth Vader":
name: "Дарт Вейдер"
text: """Во время шага «Выполнение действия» вы можете выполнить 2 действия."""
ship: "TIE улучшенный"
"Alpha Squadron Pilot":
name: "Пилот эскадрильи Альфа"
ship: "TIE перехватчик"
"Avenger Squadron Pilot":
name: "Пилот эскадрильи Мститель"
ship: "TIE перехватчик"
"Saber Squadron Pilot":
name: "Пилот эскадрильи Сабля"
ship: "TIE перехватчик"
"\"Fel's Wrath\"":
name: '"Ярость Фела"'
ship: "TIE перехватчик"
text: """Когда число карт повреждений корабля равно или превышает значение Прочности, корабль не уничтожен до конца фазы Боя."""
"Turr Phennir":
name: "Турр Феннир"
ship: "TIE перехватчик"
text: """После проведения атаки, вы можете выполнить свободное действие Бочка или Ускорение."""
"Soontir Fel":
name: "Сунтир Фел"
ship: "TIE перехватчик"
text: """Когда вы получаете жетон Стресса, вы можете назначить 1 жетон Концентрации на ваш корабль."""
"Tycho Celchu":
name: "Тайко Селчу"
text: """Вы можете выполнять действия даже имея жетоны Стресса."""
ship: "А-Крыл"
"Arvel Crynyd":
name: "Арвел Кринид"
text: """Вы можете назначать корабль противника, которого касаетесь, целью атаки."""
ship: "А-Крыл"
"Green Squadron Pilot":
name: "Пилот Зеленой эскадрильи"
ship: "А-Крыл"
"Prototype Pilot":
name: "Пилот прототипа"
ship: "А-Крыл"
"Outer Rim Smuggler":
name: "Контрабандист Внешнего Кольца"
"Chewbacca":
name: "Чубакка"
text: """Когда вы получаете карту повреждений лицом вверх, немедленно переверните ее лицом вниз (не отрабатывая ее эффект)."""
"Lando Calrissian":
name: "Лэндо Калриссиан"
text: """После выполнения зеленого маневра, выберите 1 другой дружественный корабль на расстоянии 1. Этот корабль может выполнить 1 свободное действие, отображенное в его списке действий."""
"Han Solo":
name: "Хан Соло"
text: """Атакуя, вы можете перебросить все кубики атаки. Делая это, вы должны перебросить столько кубиков, сколько возможно."""
"Bounty Hunter":
name: "Охотник за головами"
"Kath Scarlet":
name: "Кат Скарлет"
text: """При атаке, защищающийся получает 1 жетон Стресса если он отменяет хотя бы 1 результат %CRIT%."""
"Boba Fett":
name: "Боба Фетт"
text: """Когда вы выполняете маневр крена (%BANKLEFT% или %BANKRIGHT%), вы можете повернуть диск маневра на другой маневр крена с той же скоростью."""
"Krassis Trelix":
name: "Крассис Треликс"
text: """Атакуя вспомогательным оружием, вы можете перебросить 1 кубик атаки."""
"Ten Numb":
name: "Тен Намб"
text: """При атаке 1 из ваших результатов %CRIT% не может быть отменен кубиком защиты."""
ship: "Б-Крыл"
"Ibtisam":
name: "Ибитсам"
text: """При атаке или защите, если у вас есть хотя бы 1 жетон Стресса, вы можете перебросить 1 из ваших кубиков."""
ship: "Б-Крыл"
"Dagger Squadron Pilot":
name: "Пилот эскадрильи Кинжал"
ship: "Б-Крыл"
"Blue Squadron Pilot":
name: "Пилот Синей эскадрильи"
ship: "Б-Крыл"
"Rebel Operative":
name: "Повстанец-оперативник"
ship: "HWK-290"
"Roark Garnet":
name: "Роарк Гарнет"
text: """В начале фазы Боя, выберите 1 дружественный корабль на расстоянии 1-3. До конца фазы считайте навык Пилотирования этого корабля равным 12."""
ship: "HWK-290"
"Kyle Katarn":
name: "Кайл Катарн"
text: """В начале фазы боя вы можете назначить 1 из ваших жетонов Концентрации на другой дружественный корабль на расстоянии 1-3."""
ship: "HWK-290"
"Jan Ors":
name: "Джан Орс"
text: """Когда другой дружественный корабль на расстоянии 1-3 выполняет атаку, если у вас нет жетона Стресса, вы можете получить 1 жетон Стресса чтобы позволить дружественному кораблю бросить 1 дополнительный кубик атаки."""
ship: "HWK-290"
"Scimitar Squadron Pilot":
name: "Пилот эскадрильи Ятаган"
ship: "TIE бомбардировщик"
"Gamma Squadron Pilot":
name: "Пилот эскадрильи Гамма"
ship: "TIE бомбардировщик"
"Gamma Squadron Veteran":
name: "Ветеран эскадрильи Гамма"
ship: "TIE бомбардировщик"
"Captain Jonus":
name: "Капитан Джонус"
ship: "TIE бомбардировщик"
text: """Когда другой дружественный корабль на расстоянии 1 атакует вспомогательным оружием, он может перебросить до 2 кубиков атаки."""
"Major Rhymer":
name: "Майор Раймер"
ship: "TIE бомбардировщик"
text: """Атакуя второстепенным оружием, вы можете увеличить или уменьшить дистанцию оружия на 1 (до значения 1 или 3)."""
"Omicron Group Pilot":
name: "Пилот эскадрильи Омикрон"
ship: "Шаттл класса Лямбда"
"Captain Kagi":
name: "Капитан Каги"
text: """Когда вражеский корабль получает захват цели, он должен делать его на ваш корабль (если может)."""
ship: "Шаттл класса Лямбда"
"Colonel Jendon":
name: "Полковник Джендон"
text: """ В начале фазы боя вы можете назначить 1 из ваших синих жетонов захвата цели на союзный корабль на расстоянии 1, если у него еще нет синего жетона захвата цели."""
ship: "Шаттл класса Лямбда"
"Captain Yorr":
name: "Капитан Йорр"
text: """ Когда другой союзный корабль на расстоянии 1-2 получает жетон стресса, если у вас есть 2 жетона стресса или меньше, вы можете получить жетон стресса вместо него."""
ship: "Шаттл класса Лямбда"
"Lieutenant Lorrir":
name: "Лейтенант Лоррир"
ship: "TIE перехватчик"
text: """При выполнении бочки, вы можете получить 1 жетон стресса чтобы использовать (%BANKLEFT% 1) или (%BANKRIGHT% 1) вместо (%STRAIGHT% 1)."""
"Royal Guard Pilot":
name: "Пилот Королевской Стражи"
ship: "TIE перехватчик"
"Tetran Cowall":
name: "Тетран Коуэлл"
ship: "TIE перехватчик"
text: """Когда вы открываете маневр %UTURN%, вы можете считать скорость этого маневра равной 1, 3 или 5."""
"Kir Kanos":
name: "Кир Канос"
ship: "TIE перехватчик"
text: """Атакуя на расстоянии 2-3, можете потратить 1 жетон уклонения чтобы добавить 1 результат %HIT% к броску."""
"Carnor Jax":
name: "Карнор Джакс"
ship: "TIE перехватчик"
text: """Вражеские корабли на расстоянии 1 не могут выполнять действия Концентрации и Уклонения, а также не могут использовать жетоны концентрации и уклонения."""
"GR-75 Medium Transport":
name: "Средний транспорт GR-75"
ship: "Средний транспорт GR-75"
"Bandit Squadron Pilot":
name: "Пилот эскадрильи Бандит"
ship: "Z-95 Охотник за головами"
"Tala Squadron Pilot":
name: "Пилот эскадрильи Тала"
ship: "Z-95 Охотник за головами"
"Lieutenant Blount":
name: "Лейтенант Блант"
text: """При атаке считается, что она попала по противнику, даже если он не понес повреждений."""
ship: "Z-95 Охотник за головами"
"Airen Cracken":
name: "Айрен Кракен"
text: """После выполнения атаки, вы можете выбрать другой дружественный корабль на расстоянии 1. Этот корабль может выполнить 1 свободное действие."""
ship: "Z-95 Охотник за головами"
"Delta Squadron Pilot":
name: "Пилот эскадрильи Дельта"
ship: "TIE защитник"
"Onyx Squadron Pilot":
name: "Пилот эскадрильи Оникс"
ship: "TIE защитник"
"Colonel Vessery":
name: "Полковник Вессери"
text: """ Когда вы атакуете, сразу после броска кубиков атаки, вы можете назначить захват цели на защищающегося, если на нем уже есть красный жетон захвата."""
ship: "TIE защитник"
"Rexler Brath":
name: "Рекслер Брас"
text: """Когда вы выполнили атаку, которая нанесла хотя бы 1 карту повреждений защищающемуся, вы можете потратить 1 жетон концентрации, чтобы перевернуть эти карты лицом вверх."""
ship: "TIE защитник"
"Knave Squadron Pilot":
name: "Пилот эскадрильи Негодяй"
ship: "Е-Крыл"
"Blackmoon Squadron Pilot":
name: "Пилот эскадрильи Черная Луна"
ship: "Е-Крыл"
"Etahn A'baht":
name: "Итан А'Бахт"
text: """Когда вражеский корабль в вашей арке огня и на расстоянии 1-3 защищается, атакующий может заменить 1 результат %HIT% на 1 результат %CRIT%."""
ship: "Е-Крыл"
"Corran Horn":
name: "Корран Хорн"
text: """В начале фазы Окончания вы можете выполнить 1 атаку. Вы не можете атаковать в следующем ходу."""
ship: "Е-Крыл"
"Sigma Squadron Pilot":
name: "Пилот эскадрильи Сигма"
ship: "TIE фантом"
"Shadow Squadron Pilot":
name: "Пилот эскадрильи Тень"
ship: "TIE фантом"
'"Echo"':
name: '"Эхо"'
text: """При снятии маскировки, вы должны использовать (%BANKLEFT% 2) или (%BANKRIGHT% 2) вместо (%STRAIGHT% 2)."""
ship: "TIE фантом"
'"Whisper"':
name: '"Шепот"'
text: """После выполнения атаки, завершившейся попаданием, вы можете назначить 1 жетон концентрации на ваш корабль."""
ship: "TIE фантом"
"CR90 Corvette (Fore)":
name: "Корвет CR90 (Нос)"
ship: "Корвет CR90 (Нос)"
text: """Атакуя основным оружием, вы можете потратить 1 энергии, чтобы бросить 1 дополнительный кубик атаки."""
"CR90 Corvette (Aft)":
name: "Корвет CR90 (Корма)"
ship: "Корвет CR90 (Корма)"
"Wes Janson":
name: "Вес Дженсон"
text: """После выполнения атаки, вы можете снять 1 жетон концентрации, уклонения или синий жетон захвата цели с защищавшегося."""
ship: "Икс-Крыл"
"Jek Porkins":
name: "Джек Поркинс"
text: """При получении жетона Стресса, вы можете убрать его и бросить 1 кубик атаки. При результате %HIT%, получите 1 карту повреждения на этот корабль лицом вниз."""
ship: "Икс-Крыл"
'"Hobbie" Klivian':
name: "Хобби Кливиан"
text: """При получении или использовании захвата цели, вы можете убрать 1 жетон Стресса."""
ship: "Икс-Крыл"
"Tarn Mison":
name: "Тарн Майсон"
text: """ Когда вражеский корабль объявляет вас объектом атаки, вы можете установить захват цели на этот корабль."""
ship: "Икс-Крыл"
"Jake Farrell":
name: "Джек Фаррелл"
text: """ После того, как вы выполните действие Концентрации или вам назначен жетон концентрации, вы можете совершить свободное действие Ускорение или Бочку."""
ship: "А-Крыл"
"Gemmer Sojan":
name: "Геммер Соян"
text: """Когда вы на расстоянии 1 от хотя бы 1 вражеского корабля, увеличьте параметр Уклонения на 1."""
ship: "А-Крыл"
"Keyan Farlander":
name: "Кейан Фарлэндер"
text: """Атакуя, вы можете убрать 1 жетон Стресса, чтобы заменить все результаты %FOCUS% на %HIT%."""
ship: "Б-Крыл"
"Nera Dantels":
name: "Нера Дантелс"
text: """Вы можете выполнять атаки вспомогательным оружием %TORPEDO% против кораблей вне вашей арки огня."""
ship: "Б-Крыл"
# "CR90 Corvette (Crippled Aft)":
# name: "CR90 Corvette (Crippled Aft)"
# ship: "Корвет CR90 (Корма)"
# text: """Вы не можете выбирать и выполнять маневры (%STRAIGHT% 4), (%BANKLEFT% 2), или (%BANKRIGHT% 2)."""
# "CR90 Corvette (Crippled Fore)":
# name: "CR90 Corvette (Crippled Fore)"
# ship: "Корвет CR90 (Нос)"
"Wild Space Fringer":
name: "Пограничник дикого космоса"
ship: "YT-2400"
"Dash Rendar":
name: "Даш Рендар"
text: """Вы можете игнорировать препятствия в фазу Активации и при выполнении дествий."""
'"Leebo"':
name: "Лиибо"
text: """Когда вы получаете карту повреждений лицом вверх, возьмите 1 дополнительную карту лицом вверх, выберите 1 из них и сбросьте вторую."""
"Eaden Vrill":
name: "Иден Врилл"
text: """При атаке основным оружием против корабля, имеющего жетон Стресса, бросьте 1 дополнительный кубик атаки."""
"Patrol Leader":
name: "Лидер патруля"
ship: "VT-49 Дециматор"
"Rear Admiral Chiraneau":
name: "Контр-адмирал Ширано"
text: """Атакуя на расстоянии 1-2, вы можете заменить 1 результат %FOCUS% на результат %CRIT%."""
ship: "VT-49 Дециматор"
"Commander Kenkirk":
ship: "VT-49 Дециматор"
name: "Командор Кенкирк"
text: """Если у вас нет щитов и вы имеете хотя бы 1 карту повреждений, ваше Уклонение повышается на 1."""
"Captain Oicunn":
name: "Капитан Ойкунн"
text: """После выполнения маневра, каждый вражеский корабль, которого вы касаетесь, получает 1 повреждение."""
ship: "VT-49 Дециматор"
"Black Sun Enforcer":
name: "Боевик Черного Солнца"
ship: "Звездная Гадюка"
"Black Sun Vigo":
name: "Силовик Черного Солнца"
ship: "Звездная Гадюка"
"Prince Xizor":
name: "Принц Ксизор"
text: """При защите, союзный корабль на расстоянии 1 может получить 1 неотмененный %HIT% или %CRIT% вместо вас."""
ship: "Звездная Гадюка"
"Guri":
name: "Гури"
text: """В начале фазы Боя, если вы на расстоянии 1 от вражеского корабля, вы можете назначить 1 жетон Концентрации на свой корабль."""
ship: "Звездная Гадюка"
"Cartel Spacer":
name: "Агент картеля"
ship: "Перехватчик M3-A"
"Tansarii Point Veteran":
name: "Ветеран Тансари Поинт"
ship: "Перехватчик M3-A"
"Serissu":
name: "Сериссу"
text: """Когда другой дружественный корабль на расстоянии 1 защищается, он может перебросить 1 кубик защиты."""
ship: "Перехватчик M3-A"
"Laetin A'shera":
name: "Летин А'Шера"
text: """После того, как вы провели защиту от атаки, если атака не попала, вы можете назначить 1 жетон Уклонения на свой корабль."""
ship: "Перехватчик M3-A"
"IG-88A":
text: """После выполнения атаки, уничтожившей корабль противника, вы можете восстановить 1 щит."""
ship: "Агрессор"
"IG-88B":
text: """Раз за ход, проведя атаку, которая не попала, вы можете выполнить атаку вспомогательным оружием %CANNON% ."""
ship: "Агрессор"
"IG-88C":
text: """После выполнения Ускорения, вы можете выполнить свободное действие Уклонения."""
ship: "Агрессор"
"IG-88D":
text: """Вы можете выполнять (%SLOOPLEFT% 3) или (%SLOOPRIGHT% 3) используя соответствующий (%TURNLEFT% 3) или (%TURNRIGHT% 3) шаблон."""
ship: "Агрессор"
"Mandalorian Mercenary":
name: "Мандалорский наемник"
"Boba Fett (Scum)":
name: "Боба Фетт (Пираты)"
text: """Атакуя или защищаясь, вы можете перебросить 1 кубик за каждый вражеский корабль на расстоянии 1."""
"Kath Scarlet (Scum)":
name: "Кат Скарлет (Пираты)"
text: """Атакуя корабль в вашей вторичной арке стрельбы, бросьте 1 дополнительный кубик атаки."""
"Emon Azzameen":
name: "Эмон Аззамин"
text: """Бросая бомбу, вы можете использовать шаблон [%TURNLEFT% 3], [%STRAIGHT% 3] или [%TURNRIGHT% 3] вместо [%STRAIGHT% 1]."""
"Kavil":
name: "Кавил"
ship: "У-Крыл"
text: """Атакуя корабль вне вашей арки огня, бросьте 1 дополнительный кубик."""
"Drea Renthal":
name: "Дреа Рентал"
text: """После того, как вы используете захват цели, вы можете получить 1 жетон Стресса, чтобы получить захват цели."""
ship: "У-Крыл"
"Syndicate Thug":
name: "Головорез синдиката"
ship: "У-Крыл"
"Hired Gun":
name: "Наемник"
ship: "У-Крыл"
"Spice Runner":
name: "Контрабандист"
ship: "HWK-290"
"Dace Bonearm":
name: "Дэйс Боунарм"
text: """Когда вражеский корабль на расстоянии 1-3 получает хотя бы 1 ионный жетон, если вы не под Стрессом, вы можете получить 1 жетон Стресса чтобы тот корабль получил 1 повреждение."""
ship: "HWK-290"
"Palob Godalhi":
name: "Палоб Годалхи"
text: """В начале фазы боя вы можете убрать 1 жетон Концентрации или Уклонения с вражеского корабля на расстоянии 1-2 и назначить этот жетон вашему кораблю."""
"Torkil Mux":
name: "Торкил Мукс"
text: """В конце фазы Активации, выберите 1 вражеский корабль на расстоянии 1-2. До конца фазы Боя считайте умение пилота этого корабля равным 0."""
"Binayre Pirate":
name: "Бинайрский пират"
ship: "Z-95 Охотник за головами"
"Black Sun Soldier":
name: "Солдат Черного Солнца"
ship: "Z-95 Охотник за головами"
"N'Dru Suhlak":
name: "Н'Дру Шулак"
text: """При атаке, если нет других дружественных кораблей на расстоянии 1-2, бросьте 1 дополнительный кубик атаки."""
ship: "Z-95 Охотник за головами"
"Kaa'to Leeachos":
name: "Каа'ту Личос"
text: """В начале фазы Боя, вы можете убрать 1 жетон Концентрации или Уклонения с дружественного корабля на расстоянии 1-2 и назначить его на свой корабль."""
ship: "Z-95 Охотник за головами"
"Commander Alozen":
name: "Командор Алозен"
ship: "TIE улучшенный"
text: """В начале фазы Боя, вы можете назначить захват цели на вражеский корабль на расстоянии 1."""
"Juno Eclipse":
name: "Джуно Эклипс"
ship: "TIE улучшенный"
text: """Когда открываете маневр, вы можете изменить его скорость на 1 (до минимума в 1)."""
"Zertik Strom":
name: "Зертик Штром"
ship: "TIE улучшенный"
text: """Вражеские корабли на расстоянии 1 не получают боевого бонуса за расстояние при атаке."""
"Lieutenant Colzet":
name: "Лейтенант Колзет"
ship: "TIE улучшенный"
text: """В начале фазы Завершения, вы можете потратить захват цели на вражеском корабле, чтобы заставить его перевернуть одну из полученных карт повреждений лицом вверх."""
"Latts Razzi":
name: "Латтс Рацци"
text: """ Когда дружественный корабль объявляет атаку, вы можете потратить захват цели на защищающемся, чтобы уменьшить его Маневренность на 1 для этой атаки."""
"Miranda Doni":
name: "Миранда Дони"
ship: 'К-Крыл'
text: """ Один раз за ход, во время атаки, вы можете потратить 1 щит, чтобы бросить 1 дополнительный кубик атаки, <strong>или</strong> бросить на 1 кубик атаки меньше, чтобы восстановить 1 щит."""
"Esege Tuketu":
name: "Есеге Тукету"
ship: 'К-Крыл'
text: """Когда другой дружественный корабль на расстоянии 1-2 атакует, он может считать ваши жетоны Концентрации как свои собственные."""
"Guardian Squadron Pilot":
name: "Пилот эскадрильи Страж"
ship: 'К-Крыл'
"Warden Squadron Pilot":
name: "Пилот эскадрильи Надзиратель"
ship: 'К-Крыл'
'"Redline"':
name: '"Красная линия"'
ship: 'TIE каратель'
text: """Вы можете поддерживать 2 захвата цели на одном и том же корабле. Когда вы получаете захват цели, вы можете получить второй захват на том же корабле."""
'"Deathrain"':
name: '"Смертельный Дождь"'
ship: 'TIE каратель'
text: """Бросая бомбу, вы можете использовать передние направляющие вашего корабля. После сброса бомбы, вы можете выполнить свободное действие Бочку."""
'Black Eight Squadron Pilot':
name: "Пилот эскадрильи Черная Восьмерка"
ship: 'TIE каратель'
'Cutlass Squadron Pilot':
name: "Пилот эскадрильи Палаш"
ship: 'TIE каратель'
"Moralo Eval":
name: "Морало Эвал"
text: """Вы можете выполнять атаки вспомогательным оружием %CANNON% против кораблей в вашей вторичной арке огня."""
'Gozanti-class Cruiser':
name: "Крейсер класса Гозанти"
text: """После выполнения маневра, вы можете отстыковать до 2 присоединенных кораблей."""
'"Scourge"':
name: "Плеть"
ship: "TIE истребитель"
text: """При атаке, если у защищающегося уже есть 1 или более карт повреждений, бросьте 1 дополнительный кубик атаки."""
"The Inquisitor":
name: "Инквизитор"
ship: "TIE улучшенный прототип"
text: """Атакуя основным оружием на расстоянии 2-3, считайте расстояние атаки как 1."""
"Zuckuss":
name: "Закасс"
ship: "Звездный истребитель G-1A"
text: """Атакуя, вы можете бросить 1 дополнительный кубик атаки. Если вы делаете это, защищающийся бросает 1 дополнительный кубик защиты."""
"Ruthless Freelancer":
name: "Беспощадный наемник"
ship: "Звездный истребитель G-1A"
"Gand Findsman":
name: "Гандский искатель"
ship: "Звездный истребитель G-1A"
"Dengar":
name: "Денгар"
ship: "Джампмастер 5000"
text: """Один раз за ход, после защиты, если атакующий находится в вашей основной арке огня, вы можете провести атаку против этого корабля."""
"Talonbane Cobra":
name: "Кобра Гибельный Коготь"
ship: "Истребитель Кихраксз"
text: """Атакуя или защищаясь, удваивайте эффект бонусов за расстояние."""
"Graz the Hunter":
name: "Грац Охотник"
ship: "Истребитель Кихраксз"
text: """Защищаясь, если атакующий находится в вашей основной арке огня, бросьте 1 дополнительный кубик защиты."""
"Black Sun Ace":
name: "Ас Черного Солнца"
ship: "Истребитель Кихраксз"
"Cartel Marauder":
name: "Мародер картеля"
ship: "Истребитель Кихраксз"
"Trandoshan Slaver":
name: "Трандошанский работорговец"
ship: "YV-666"
"Bossk":
name: "Босск"
ship: "YV-666"
text: """Когда вы выполняете атаку, завершившуюся попаданием, перед нанесением повреждений, вы можете отменить 1 из ваших результатов %CRIT%, чтобы нанести 2 результата %HIT%."""
# T-70
"Poe Dameron":
name: "По Дэмерон"
ship: "Икс-Крыл T-70"
text: """Атакуя или защищаясь, если у вас есть жетон Концентрации, вы можете заменить 1 из ваших результатов %FOCUS% на результат %HIT% или %EVADE%."""
'"Blue Ace"':
name: '"Синий ас"'
ship: "Икс-Крыл T-70"
text: """Выполняя действие Ускорение, вы можете использовать шаблон (%TURNLEFT% 1) или (%TURNRIGHT% 1)."""
"Red Squadron Veteran":
name: "Ветеран Красной эскадрильи"
ship: "Икс-Крыл T-70"
"Blue Squadron Novice":
name: "Новичок Синей эскадрильи"
ship: "Икс-Крыл T-70"
'"Red Ace"':
name: "Красный ас"
ship: "Икс-Крыл T-70"
text: '''В первый раз за ход, когда вы убираете жетон щита с вашего корабля, назначьте 1 жетон Уклонения на ваш корабль.'''
# TIE/fo
'"Omega Ace"':
name: '"Омега ас"'
ship: "Истребитель TIE/пп"
text: """Атакуя, вы можете потратить жетон Концентрации и захват цели на защищающемся, чтобы заменить все ваши результаты на результаты %CRIT%."""
'"Epsilon Leader"':
name: '"Эпсилон лидер"'
ship: "Истребитель TIE/пп"
text: """В начале фазы Боя, уберите 1 жетон Стресса с каждого дружественного корабля на расстоянии 1."""
'"Zeta Ace"':
name: '"Зета ас"'
ship: "Истребитель TIE/пп"
text: """Когда вы выполняете Бочку, вы можете использовать шаблон (%STRAIGHT% 2) вместо шаблона (%STRAIGHT% 1)."""
"Omega Squadron Pilot":
name: "Пилот эскадрильи Омега"
ship: "Истребитель TIE/пп"
"Zeta Squadron Pilot":
name: "Пилот эскадрильи Зета"
ship: "Истребитель TIE/пп"
"Epsilon Squadron Pilot":
name: "Пилот эскадрильи Эпсилон"
ship: "Истребитель TIE/пп"
'"Omega Leader"':
name: "Омега лидер"
ship: "Истребитель TIE/пп"
text: '''Вражеские корабли, находящиеся в вашем захвате цели, не могут модифицировать кубики, атакуя вас или защищаясь от ваших атак.'''
'Hera Syndulla':
name: "Гера Синдулла"
text: '''Когда вы открываете зеленый или красный маневр, вы можете повернуть ваш диск на другой маневр той же сложности.'''
'"Youngster"':
name: "Юнец"
ship: "TIE истребитель"
text: """Дружественные TIE истребители на расстоянии 1-3 могут выполнять действие с вашей экипированной карты улучшений %ELITE%."""
'"Wampa"':
name: "Вампа"
ship: "TIE истребитель"
text: """Атакуя, вы можете отменить все результаты кубиков. Если вы отменяете результат %CRIT%, назначьте 1 карту повреждений лицом вниз на защищающегося."""
'"Chaser"':
name: "Преследователь"
ship: "TIE истребитель"
text: """Когда другой дружественный корабль на расстоянии 1 тратит жетон Концентрации, назначьте жетон Концентрации на ваш корабль."""
'Ezra Bridger':
name: "Эзра Бриджер"
ship: "Атакующий шаттл"
text: """Защищаясь, если у вас есть Стресс, вы можете заменить до 2 ваших результатов %FOCUS% на результаты %EVADE%."""
'"Zeta Leader"':
name: "Зета лидер"
text: '''Атакуя, если у вас нет Стресса, вы можете получить 1 жетон Стресса, чтобы бросить 1 дополнительный кубик атаки.'''
ship: "Истребитель TIE/пп"
'"Epsilon Ace"':
name: "Эпсилон ас"
text: '''Пока у вас нет карт повреждений, считайте ваше умение пилота равным 12.'''
ship: "Истребитель TIE/пп"
"Kanan Jarrus":
name: "Кейнан Джаррус"
text: """Когда вражеский корабль на расстоянии 1-2 атакует, вы можете потратить жетон Концентрации. Если вы делаете это, атакующий бросает на 1 кубик атаки меньше."""
'"Chopper"':
name: "Чоппер"
text: """В начале фазы Боя, каждый вражеский корабль, которого вы касаетесь, получает 1 жетон Стресса."""
'Hera Syndulla (Attack Shuttle)':
name: "Гера Синдулла (Атакующий шаттл)"
ship: "Атакующий шаттл"
text: """Когда вы открываете зеленый или красный маневр, вы можете повернуть ваш диск на другой маневр той же сложности."""
'Sabine Wren':
name: "Сабина Врен"
ship: "Атакующий шаттл"
text: """Сразу перед открытием вашего маневра, вы можете выполнить свободное действие Ускорение или Бочку."""
'"Zeb" Orrelios':
name: "Зеб Ореллиос"
ship: "Атакующий шаттл"
text: '''Защищаясь, вы можете отменять результаты %CRIT% перед результатами %HIT%.'''
"Lothal Rebel":
name: "Повстанец с Лотала"
ship: "VCX-100"
'Tomax Bren':
name: "Томакс Брен"
text: '''Один раз за ход, после того, как вы сбрасываете карту улучшений %ELITE%, переверните эту карту обратно.'''
ship: "TIE бомбардировщик"
'Ello Asty':
name: "Элло Эсти"
text: '''Когда у вас нет жетонов Стресса, можете считать маневры %TROLLLEFT% и %TROLLRIGHT% белыми маневрами.'''
ship: "Икс-Крыл T-70"
"Valen Rudor":
name: "Вален Рудор"
text: """После защиты, вы можете выполнить свободное действие."""
ship: "TIE улучшенный прототип"
"4-LOM":
ship: "Звездный истребитель G-1A"
text: """В начале фазы Завершения, вы можете назначить 1 из ваших жетонов Стресса на другой корабль на расстоянии 1."""
"Tel Trevura":
name: "Тел Тревура"
ship: "Джампмастер 5000"
text: """В первый раз, когда вы должны быть уничтожены, вместо этого отмените все оставшиеся повреждения, сбросьте все карты повреждений, и назначьте 4 карты повреждений лицом вниз этому кораблю."""
"Manaroo":
name: "Манару"
ship: "Джампмастер 5000"
text: """В начале фазы Боя, вы можете назначить все жетоны Концентрации, Уклонения и захвата цели, назначенные вам, на другой дружественный корабль на расстоянии 1."""
"Contracted Scout":
name: "Разведчик-контрактник"
ship: "Джампмастер 5000"
'"Deathfire"':
name: "Смертельное пламя"
text: '''Когда вы открываете ваш диск маневров или после того, как вы выполняете действие, вы можете выполнить действие с карты улучшения %BOMB% как свободное действие.'''
ship: "TIE бомбардировщик"
"Sienar Test Pilot":
name: "Сиенарский летчик-испытатель"
ship: "TIE улучшенный прототип"
"Baron of the Empire":
name: "Барон Империи"
ship: "TIE улучшенный прототип"
"Maarek Stele (TIE Defender)":
name: "Маарек Стил (TIE защитник)"
text: """Когда ваша атака наносит защищающемуся карту повреждений в открытую, вместо этого вытяните 3 карты повреждений, выберите 1 для отработки и сбросьте остальные."""
ship: "TIE защитник"
"Countess Ryad":
name: "Графиня Рияд"
text: """Когда вы открываете маневр %STRAIGHT%, вы можете считать его маневром %KTURN%."""
ship: "TIE защитник"
"Glaive Squadron Pilot":
name: "Пилот эскадрильи Глефа"
ship: "TIE защитник"
"Poe Dameron (PS9)":
name: "По Дэмерон (УП9)"
text: """Атакуя или защищаясь, если у вас есть жетон Концентрации, вы можете заменить 1 из ваших результатов %FOCUS% на результат %HIT% или %EVADE%."""
ship: "Икс-Крыл T-70"
"Resistance Sympathizer":
name: "Сочувствующий повстанцам"
ship: "YT-1300"
"Rey":
name: "Рэй"
text: """Атакуя или защищаясь, если вражеский корабль находится в вашей основной арке огня, вы можете перебросить до 2 пустых результатов."""
'Han Solo (TFA)':
name: "Хан Соло (ПС)"
text: '''Во время расстановки, вы можете быть расположены где угодно на игровом поле на расстоянии не ближе 3 от вражеских кораблей.'''
'Chewbacca (TFA)':
name: "Чубакка (ПС)"
text: '''После того, как другой дружественный корабль на расстоянии 1-3 уничтожен (но не сбежал с поля боя), вы можете выполнить атаку.'''
'Norra Wexley':
name: "Норра Вэксли"
ship: "ARC-170"
text: '''Атакуя или защищаясь, вы можете потратить захват цели на защищающемся, чтобы добавить 1 результат %FOCUS% к вашему броску.'''
'Shara Bey':
name: "Шара Бэй"
ship: "ARC-170"
text: '''Когда другой дружественный корабль на расстоянии 1-2 атакует, он может считать ваши синие жетоны захвата цели как свои собственные.'''
'Thane Kyrell':
name: "Тейн Кирелл"
ship: "ARC-170"
text: '''После того, как вражеский корабль в вашей арке огня на расстоянии 1-3 атакует другой дружественный корабль, вы можете выполнить свободное действие.'''
'Braylen Stramm':
name: "Брайлен Штрамм"
ship: "ARC-170"
text: '''После того, как вы выполните маневр, вы можете бросить кубик атаки. При результате %HIT% или %CRIT%, уберите 1 жетон Стресса с вашего корабля.'''
'"Quickdraw"':
name: "Шустрый"
ship: "Истребитель TIE/сс"
text: '''Один раз за ход, когда вы теряете жетон щита, вы можете выполнить атаку основным оружием.'''
'"Backdraft"':
name: "Бэкдрафт"
ship: "Истребитель TIE/сс"
text: '''Атакуя корабль в вашей вторичной арке огня, вы можете добавить 1 результат %CRIT%.'''
'Omega Specialist':
name: "Омега специалист"
ship: "Истребитель TIE/сс"
'Zeta Specialist':
name: "Зета специалист"
ship: "Истребитель TIE/сс"
'Fenn Rau':
name: "Фенн Рау"
ship: "Звездный истребитель Протектората"
text: '''Атакуя или защищаясь, если вражеский корабль находится на расстоянии 1, вы можете бросить 1 дополнительный кубик.'''
'Old Teroch':
name: "Старый Терох"
ship: "Звездный истребитель Протектората"
text: '''В начале фазы Боя, вы можете выбрать 1 вражеский корабль на расстоянии 1. Если вы находитесь в его арке огня, он должен сбросить все жетоны Концентрации и Уклонения.'''
'Kad Solus':
name: "Кад Солус"
ship: "Звездный истребитель Протектората"
text: '''После выполнения красного маневра, назначьте 2 жетона Концентрации на ваш корабль.'''
'Concord Dawn Ace':
name: "Ас Рассвета Конкорда"
ship: "Звездный истребитель Протектората"
'Concord Dawn Veteran':
name: "Ветеран Рассвета Конкорда"
ship: "Звездный истребитель Протектората"
'Zealous Recruit':
name: "Рьяный рекрут"
ship: "Звездный истребитель Протектората"
'Ketsu Onyo':
name: "Кетсу Онио"
ship: "Корабль-преследователь класса Копьеносец"
text: '''В начале фазы Боя, вы можете выбрать корабль на расстоянии 1. Если он находится в вашей основной <strong>и</strong> мобильной арках огня, назначьте на него 1 жетон Луча Захвата.'''
'Asajj Ventress':
name: "Асажж Вентресс"
ship: "Корабль-преследователь класса Копьеносец"
text: '''В начале фазы Боя, вы можете выбрать корабль на расстоянии 1-2. Если он находится в вашей мобильной арке огня, назначьте ему 1 жетон Стресса.'''
'Sabine Wren (Scum)':
name: "Сабина Врен (Пираты)"
ship: "Корабль-преследователь класса Копьеносец"
text: '''Защищаясь от вражеского корабля в вашей мобильной арке огня на расстоянии 1-2, вы можете добавить 1 результат %FOCUS% к вашему броску.'''
'Shadowport Hunter':
name: "Охотник Шэдоупорта"
ship: "Корабль-преследователь класса Копьеносец"
'Sabine Wren (TIE Fighter)':
name: "Сабина Врен (TIE истребитель)"
ship: "TIE истребитель"
text: '''Сразу перед открытием вашего маневра, вы можете выполнить свободное действие Ускорение или Бочку.'''
'"Zeb" Orrelios (TIE Fighter)':
name: "Зеб Ореллиос (TIE истребитель)"
ship: "TIE истребитель"
text: '''Защищаясь, вы можете отменять результаты %CRIT% перед результатами %HIT%.'''
'Kylo Ren':
name: "Кайло Рен"
ship: "Шаттл класса Ипсилон"
text: '''В первый раз за ход, когда вы получаете попадание, назначьте атакующему карту состояния "Я покажу тебе Темную Сторону".'''
'Unkar Plutt':
name: "Анкар Платт"
ship: "Квадджампер"
text: '''В конце фазы Активации, вы <strong>должны</strong> назначить жетон Луча Захвата каждому кораблю, которого касаетесь.'''
'Cassian Andor':
name: "Кассиан Эндор"
ship: "Ю-Крыл"
text: '''В начале фазы Активации, вы можете убрать 1 жетон Стресса с 1 другого дружественного корабля на расстоянии 1-2.'''
'Bodhi Rook':
name: "Бодхи Рук"
ship: "Ю-Крыл"
text: '''Когда дружественный корабль получает захват цели на противника, этот корабль может захватывать вражеский корабль на расстоянии 1-3 от любого дружественного корабля.'''
'Heff Tobber':
name: "Хефф Тоббер"
ship: "Ю-Крыл"
text: '''После того, как вражеский корабль выполняет маневр, приводящий к наложению на ваш корабль, вы можете выполнить свободное действие.'''
'''"Duchess"''':
ship: "TIE ударник"
name: '"Герцогиня"'
text: '''Когда у вас есть экипированная карта улучшения "Адаптивные элероны", вы можете игнорировать особенность этой карты.'''
'''"Pure Sabacc"''':
ship: "TIE ударник"
name: '"Пьюр Сабакк"'
text: '''Атакуя, если у вас есть 1 или меньше карт повреждений, бросьте 1 дополнительный кубик атаки.'''
'''"Countdown"''':
ship: "TIE ударник"
name: '"Обратный Отсчет"'
text: '''Защищаясь, если у вас нет Стресса, во время шага "Сравнение результатов кубиков" вы можете получить 1 повреждение, чтобы отменить <strong>все</strong> результаты кубиков. Если вы делаете это, получите 1 жетон Стресса.'''
'Nien Nunb':
name: "Ниен Нанб"
ship: "Икс-Крыл T-70"
text: '''Когда вы получаете жетон Стресса, если в вашей арке огня на расстоянии 1 есть вражеский корабль, вы можете сбросить этот жетон стресса.'''
'"Snap" Wexley':
name: "Снэп Вексли"
ship: "Икс-Крыл T-70"
text: '''После того, как вы выполняете маневр со скоростью 2, 3 или 4, если вы не касаетесь другого корабля, вы можете выполнить свободное действие Бочку.'''
'Jess Pava':
name: "Джесс Пава"
ship: "Икс-Крыл T-70"
text: '''Атакуя или защищаясь, вы можете перебросить 1 из ваших кубиков за каждый другой дружественный корабль на расстоянии 1.'''
'Ahsoka Tano':
ship: "TIE истребитель"
name: "Асока Тано"
text: '''В начале фазы Боя, вы можете потратить 1 жетон Концентрации, чтобы выбрать дружественный корабль на расстоянии 1. Он может выполнить 1 свободное действие.'''
'Captain Rex':
ship: "TIE истребитель"
name: "Капитан Рекс"
text: '''После выполнения атаки, назначьте защищающемуся карту состояния "Подавляющий огонь".'''
'Major Stridan':
ship: "Шаттл класса Ипсилон"
name: "Майор Стридан"
text: '''С точки зрения ваший действий и карт улучшений, вы можете считать дружественные корабли на расстоянии 2-3 как находящиеся на расстоянии 1.'''
'Lieutenant Dormitz':
ship: "Шаттл класса Ипсилон"
name: "Лейтенант Дормитц"
text: '''Во время расстановки, дружественные корабли могут располагаться где угодно на игровом поле на расстоянии 1-2 от вас.'''
'Constable Zuvio':
ship: "Квадджампер"
name: "Констебль Зувио"
text: '''Когда вы открываете реверсивный маневр, вы можете сбрасывать бомбу, испольтзуя ваши передние направляющие (в том числе бомбы с указателем "<strong>Действие:</strong>").'''
'Sarco Plank':
name: "Сарко Планк"
ship: "Квадджампер"
text: '''Защищаясь, вместо того, чтобы использовать ваше значение Маневренности, вы можете бросить число кубиков защиты, равное скорости маневра, который вы выполняли на этом ходу.'''
"Blue Squadron Pathfinder":
name: "Следопыт Синей эскадрильи"
ship: "Ю-Крыл"
"Black Squadron Scout":
name: "Скаут Черной эскадрильи"
ship: "TIE ударник"
"Scarif Defender":
name: "Защитник Скарифа"
ship: "TIE ударник"
"Imperial Trainee":
name: "Имперский кадет"
ship: "TIE ударник"
"Starkiller Base Pilot":
ship: "Шаттл класса Ипсилон"
name: "Пилот базы Старкиллер"
"Jakku Gunrunner":
ship: "Квадджампер"
name: "Стрелок с Джакку"
'Genesis Red':
name: "Генезис Рэд"
ship: "Перехватчик M3-A"
text: '''После получения захвата цели, назначьте жетоны Концентрации и Уклонения на ваш корабль, пока у вас не будет такого же количества каждого жетона, как и на корабле в захвате.'''
'Quinn Jast':
name: "Квинн Джаст"
ship: "Перехватчик M3-A"
text: '''В начале фазы Боя, вы можете получить жетон "Орудие выведено из строя", чтобы перевернуть 1 из ваших сброшенных карт улучшений %TORPEDO% или %MISSILE%.'''
'Inaldra':
name: "Инальдра"
ship: "Перехватчик M3-A"
text: '''Атакуя или защищаясь, вы можете потратить 1 щит, чтобы перебросить любое количество ваших кубиков.'''
'Sunny Bounder':
name: "Санни Баундер"
ship: "Перехватчик M3-A"
text: '''Один раз за ход, после того, как вы бросаете или перебрасываете кубик, если у вас выпал тот же результат на каждом кубике, добавьте 1 соответствующий результат.'''
'C-ROC Cruiser':
ship: "Крейсер C-ROC"
name: "Крейсер C-ROC"
'Lieutenant Kestal':
name: "Лейтенант Кестал"
ship: "TIE агрессор"
text: '''Атакуя, вы можете потратить 1 жетон Концентрации, чтобы отменить все пустые и %FOCUS% результаты защищающегося.'''
'"Double Edge"':
ship: "TIE агрессор"
name: "Обоюдоострый"
text: '''Один раз за ход, после того, как вы выполнили атаку вспомогательным оружием, которая не попала, вы можете выполнить атаку другим оружием.'''
'Onyx Squadron Escort':
ship: "TIE агрессор"
name: "Эскорт эскадрильи Оникс"
'Sienar Specialist':
ship: "TIE агрессор"
name: "Сиенарский специалист"
'Viktor Hel':
name: "Виктор Хел"
ship: "Истребитель Кихраксз"
text: '''После защиты, если вы не бросили ровно 2 кубика защиты, атакующий получает 1 жетон Стресса.'''
'Lowhhrick':
name: "Лоуххрик"
ship: "Канонерка Озитук"
text: '''Когда другой дружественный корабль на расстоянии 1 защищается, вы можете потратить 1 жетон Усиления. Если вы делаете это, защищающийся добавляет 1 результат %EVADE%.'''
'Wullffwarro':
name: "Вульфарро"
ship: "Канонерка Озитук"
text: '''Атакуя, если у вас нет щитов и есть хотя бы 1 назначенная карта повреждений, бросьте 1 дополнительный кубик атаки.'''
'Wookiee Liberator':
name: "Вуки-освободитель"
ship: "Канонерка Озитук"
'Kashyyyk Defender':
name: "Защитник Кашиика"
ship: "Канонерка Озитук"
'Captain Nym (Scum)':
name: "Капитан Ним (Пираты)"
ship: "Бомбардировщик Скуррг H-6"
text: '''Вы можете игнорировать дружественные бомбы. Когда дружественный корабль защищается, если атакующий меряет дистанцию через дружественный жетон бомбы, защищающийся может добавить 1 результат %EVADE%.'''
'Captain Nym (Rebel)':
name: "Капитан Ним (Повстанцы)"
ship: "Бомбардировщик Скуррг H-6"
text: '''Один раз за ход, вы можете предотвратить взрыв дружественной бомбы.'''
'Lok Revenant':
name: "Лок Ревенант"
ship: "Бомбардировщик Скуррг H-6"
'Karthakk Pirate':
name: "Пират Картхакка"
ship: "Бомбардировщик Скуррг H-6"
'Sol Sixxa':
name: "Сол Сиккса"
ship: "Бомбардировщик Скуррг H-6"
text: '''Сбрасывая бомбу, вы можете использовать шаблон (%TURNLEFT% 1) или (%TURNRIGHT% 1) вместо шаблона (%STRAIGHT% 1).'''
'Dalan Oberos':
name: "Далан Оберос"
ship: 'Звездная Гадюка'
text: '''Если у вас нет Стресса, когда вы открываете маневр крена, поворота или Петлю Сеньора, вместо этого вы можете считать это красным маневром Коготь того же направления (влево или вправо), используя шаблон изначально открытого маневра.'''
'Thweek':
name: "Твик"
ship: 'Звездная Гадюка'
text: '''Во время расстановки, перед шагом "Расстановка сил", вы можете выбрать 1 вражеский корабль и назначить ему карту состояния "Затененный" или "Мимикрированный".'''
'Captain Jostero':
name: "Капитан Жостеро"
ship: "Истребитель Кихраксз"
text: '''Один раз за ход, после того, как вражеский корабль, не защищающийся от атаки, получает повреждение или критическое повреждение, вы можете выполнить атаку против этого корабля.'''
'Major Vynder':
ship: "Звездное Крыло класса Альфа"
name: "Майор Виндер"
text: '''Защищаясь, если у вас есть жетон Оружие выведено из Строя, бросьте 1 дополнительный кубик защиты.'''
'Nu Squadron Pilot':
name: "Пилот эскадрильи Ню"
ship: "Звездное Крыло класса Альфа"
'Rho Squadron Veteran':
name: "Ветеран эскадрильи Ро"
ship: "Звездное Крыло класса Альфа"
'Lieutenant Karsabi':
ship: "Звездное Крыло класса Альфа"
name: "Лейтенант Карсаби"
text: '''Когда вы получаете жетон Оружие выведено из Строя, если вы не под Стрессом, вы можете получить 1 жетон Стресса, чтобы убрать его.'''
'Cartel Brute':
name: "Вышибала картеля"
ship: "Истребитель M12-L Кимогила"
'Cartel Executioner':
name: "Палач картеля"
ship: "Истребитель M12-L Кимогила"
'Torani Kulda':
name: "Торани Кулда"
ship: "Истребитель M12-L Кимогила"
text: '''После выполнения атаки, каждый вражеский корабль в вашей арке прицельного огня на расстоянии 1-3 должен выбрать: получить 1 повреждение или убрать все жетоны Концентрации и Уклонения.'''
'Dalan Oberos (Kimogila)':
name: "Далан Оберос (Кимогила)"
ship: "Истребитель M12-L Кимогила"
text: '''В начале фазы Боя, вы можете получить захват цели на вражеский корабль в вашей арке прицельного огня на расстоянии 1-3.'''
'Fenn Rau (Sheathipede)':
name: "Фенн Рау (Колчан)"
ship: "Шаттл класса Колчан"
text: '''Когда вражеский корабль в вашей арке огня на расстояниим 1-3 становится активным кораблем во время фазы Боя, если у вас нет Стресса, вы можете получить 1 жетон Стресса. Если вы делаете это, тот корабль не может тратить жетоны для модификации его кубиков во время атаки на этом ходу.'''
'Ezra Bridger (Sheathipede)':
name: "Эзра Бриджер (Колчан)"
ship: "Шаттл класса Колчан"
text: """Защищаясь, если у вас нет Стресса, вы можете заменить до 2 ваших результатов %FOCUS% на результаты %EVADE%."""
'"Zeb" Orrelios (Sheathipede)':
name: "Зеб Ореллиос (Колчан)"
ship: "Шаттл класса Колчан"
text: '''Защищаясь, вы можете отменять результаты %CRIT% перед результатами %HIT%.'''
'AP-5':
ship: "Шаттл класса Колчан"
text: '''Когда вы выполняете действие Координации, после выбора дружественного корабля и перед выполнением им свободного действия, вы можете получить 2 жетона Стресса, чтобы убрать с него 1 жетон Стресса.'''
'Crimson Squadron Pilot':
name: "Пилот Багровой эскадрильи"
ship: "Бомбардировщик B/SF-17"
'"Crimson Leader"':
name: '"Багровый лидер"'
ship: "Бомбардировщик B/SF-17"
text: '''Атакуя, если защищающийся находится в вашей арке огня, вы можете потратить 1 результат %HIT% или %CRIT%, чтобы назначить карту состояния "Разбитый" на защищающегося.'''
'"Crimson Specialist"':
name: '"Багровый специалист"'
ship: "Bombardero B/SF-17"
text: '''Размещая жетон бомбы, которую вы сбросили после открытия диска маневров, вы можете расположить жетон бомбы где угодно в игровой зоне, касаясь вашего корабля.'''
'"Cobalt Leader"':
name: '"Кобальтовый лидер"'
ship: "Бомбардировщик B/SF-17"
text: '''Атакуя, если защищающийся находится на расстоянии 1 от жетона бомбы, защищающийся бросает на 1 кубик защиты меньше.'''
'Sienar-Jaemus Analyst':
name: "Аналитик Сиенар-Джемус"
ship: "TIE глушитель"
'First Order Test Pilot':
name: "Летчик-испытатель Первого Порядка"
ship: "TIE глушитель"
'Kylo Ren (TIE Silencer)':
name: "Кайло Рен (TIE глушитель)"
ship: "TIE глушитель"
text: '''В первый раз за ход, когда вы получаете попадание, назначьте атакующему карту состояния "Я покажу тебе Темную Сторону".'''
'Test Pilot "Blackout"':
name: 'Летчик-испытатель "Затмение"'
ship: "TIE глушитель"
text: '''Атакуя, если атака идет через преграду, защищающийся бросает на 2 кубика защиты меньше.'''
'Kullbee Sperado':
name: "Кулби Сперадо"
ship: "Икс-Крыл"
text: '''After you perform a boost or barrel roll action, you may flip your equipped "Servomotor S-foils" upgrade card.'''
'Major Vermeil':
name: "Майор Вермейл"
text: '''Атакуя, если у защищающегося нет жетонов Концентрации или Уклонения, вы можете заменить 1 из ваших пустых или %FOCUS% результатов на результат %HIT%.'''
'Captain Feroph':
text: '''When defending, if the attacker is jammed, add 1 %EVADE% result to your roll.'''
'"Vizier"':
text: '''After a friendly ship executes a 1-speed maneuver, if it is at Range 1 and did not overlap a ship, you may assign 1 of your focus or evade tokens to it.'''
'Magva Yarro':
text: '''When another friendly ship at Range 1-2 is defending, the attacker cannot reroll more than 1 attack die.'''
'Edrio Two-Tubes':
text: '''When you become the active ship during the Activation phase, if you have 1 or more focus tokens, you may perform a free action.'''
upgrade_translations =
"Ion Cannon Turret":
name: "Ионная турель"
text: """<strong>Атака:</strong> Атакуйте 1 корабль(даже корабль вне вашей арки стрельбы).<br /><br />Если атака попадает по кораблю-цели, корабль получает 1 повреждение и 1 ионный жетон. Затем отмените все результаты кубиков."""
"Proton Torpedoes":
name: "Протонные торпеды"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете заменить 1 результат %FOCUS% на результат %CRIT%."""
"R2 Astromech":
name: "Астромех R2"
text: """Можете считать все маневры со скоростью 1 и 2 зелеными маневрами."""
"R2-D2":
text: """После выполнения зеленого маневра, вы можете восстановить 1 щит (до максимального значения щитов)."""
"R2-F2":
text: """<strong>Действие:</strong> Увеличьте вашу Маневренность на 1 до конца этого хода."""
"R5-D8":
text: """<strong>Действие:</strong> Бросьте 1 кубик защиты.<br /><br />При результате %EVADE% или %FOCUS%, сбросьте 1 из ваших карт повреждений, лежащих лицом вниз."""
"R5-K6":
text: """После того, как вы потратили захват цели, бросьте 1 кубик защиты.<br /><br />При результате %EVADE% немедленно получите захват цели на том же корабле. Вы не можете использовать этот захват цели во время этой атаки."""
"R5 Astromech":
name: "Астромех R5"
text: """Во время фазы Завершения, вы можете выбрать одну из ваших карт повреждений лицом вверх со свойством <strong>Корабль</strong> и перевернуть ее лицом вниз."""
"Determination":
name: "Решительность"
text: """Если вы получили карту повреждений лицом вверх со свойством <strong>Пилот</strong>, сбросьте ее немедленно, не отрабатывая ее эффект."""
"Swarm Tactics":
name: "Тактика стаи"
text: """В начале фазы Боя, вы можете выбрать 1 дружественный корабль на расстоянии 1.<br /><br />До конца этой фазы, считайте умение пилота выбранного корабля равным вашему."""
"Squad Leader":
name: "Лидер отряда"
text: """<strong>Действие:</strong> Выберите 1 корабль на расстоянии 1-2, умение пилота которого ниже вашего.<br /><br />Выбранный корабль может немедленно выполнить 1 свободное действие."""
"Expert Handling":
name: "Мастерское управление"
text: """<strong>Действие:</strong> Выполните свободное действие Бочку. Если у вас нет значка действий %BARRELROLL%, получите 1 жетон Стресса.<br /><br />Затем вы можете убрать 1 вражеский захват цели с вашего корабля."""
"Marksmanship":
name: "Меткость"
text: """<strong>Действие:</strong> Атакуя в этот ход, вы можете сменить 1 из ваших результатов %FOCUS% на результат %CRIT% , и все прочие результаты %FOCUS% на результат %HIT%."""
"Concussion Missiles":
name: "Ударные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете сменить 1 пустой результат на результат %HIT%."""
"Cluster Missiles":
name: "Кластерные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку <strong>дважды</strong>."""
"Daredevil":
name: "Сорвиголова"
text: """<strong>Действие:</strong> Выполните белый (%TURNLEFT% 1) или (%TURNRIGHT% 1) маневр. Затем получите 1 жетон стресса.<br /><br />Затем, если у вас нет значка действия %BOOST%, бросьте 2 кубика атаки. Получите любое выброшенное повреждение(%HIT%) или критическое повреждение(%CRIT%)."""
"Elusiveness":
name: "Уклончивость"
text: """Защищаясь, вы можете получить 1 жетон стресса чтобы выбрать 1 кубик атаки. Атакующий должен перебросить этот кубик.<br /><br />Если у вас есть хотя бы 1 жетон стресса, вы не можете использовать эту способность."""
"Homing Missiles":
name: "Самонаводящиеся ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Защищающийся не может использовать жетоны уклонения во время этой атаки."""
"Push the Limit":
name: "Предел возможностей"
text: """Один раз за ход, после выполнения действия, вы можете выполнить 1 свободное действие, отображенное на вашей полоске действий.<br /><br />Затем получите 1 жетон стресса."""
"Deadeye":
name: "Меткий глаз"
text: """%SMALLSHIPONLY%%LINEBREAK%Вы можете считать <strong>"Атака (захват цели)"</strong> как <strong>"Атака (концентрация)"</strong>.<br /><br />Когда атака обязывает вас использовать захват цели, вместо этого вы можете использовать жетон Концентрации."""
"Expose":
name: "Раскрытие"
text: """<strong>Действие:</strong> До конца хода увеличьте значение основной атаки на 1 и снизьте значение уклонения на 1."""
"Gunner":
name: "Стрелок"
text: """После проведения атаки без попадания, вы можете немедленно выполнить атаку основным оружием. Вы не можете выполнять другую атаку на этом ходу."""
"Ion Cannon":
name: "Ионная пушка"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.<br /><br />Если атака попадает, защищающийся получает 1 повреждение и получает 1 ионный жетон. Затем отмените <b>все</b> результаты кубиков."""
"Heavy Laser Cannon":
name: "Тяжелая лазерная пушка"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.<br /><br />Сразу после броска кубиков атаки, вы должны заменить все результаты %CRIT% на результаты %HIT%."""
"Seismic Charges":
name: "Сейсмические заряды"
text: """Когда вы открываете диск маневров, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон сейсмического заряда.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы Активации.<br /><br /><strong>Жетон сейсмического заряда:</strong> Когда этот жетон бомбы взрывается, каждый корабль на расстоянии 1 от жетона получает 1 повреждение. Затем сбросьте этот жетон."""
"Mercenary Copilot":
name: "Второй пилот-наемник"
text: """Атакуя на расстоянии 3, вы можете сменить 1 результат %HIT% на результат %CRIT%."""
"Assault Missiles":
name: "Штурмовые ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если эта атака попадает, каждый другой корабль на расстоянии 1 от защищающегося получает 1 повреждение."""
"Veteran Instincts":
name: "Инстинкты ветерана"
text: """Повышает умение пилотирования на 2."""
"Proximity Mines":
name: "Мины приближения"
text: """<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>сбросить</strong> 1 жетон мины приближения.<br /><br />Когда подставка корабля или шаблон маневра перекрывает этот жетон, он <strong>взрывается</strong>.<br /><br /><strong>Жетон мины приближения:</strong> Когда этот бомбовый жетон взрывается, корабль, прошедший через него или вставший на нем бросает 3 кубика атаки и получает все выброшенные результаты повреждений(%HIT%) и критических повреждений(%CRIT%). Затем сбросьте этот жетон."""
"Weapons Engineer":
name: "Инженер-оружейник"
text: """Вы можете поддерживать 2 захвата цели(только 1 на каждый вражеский корабль).<br /><br />Когда вы получаете захват цели, вы можете захватывать 2 разных корабля."""
"Draw Their Fire":
name: "Огонь на себя"
text: """Когда дружественный корабль на расстоянии 1 получает попадание от атаки, вы можете получить 1 из неотмененных %CRIT% результатов вместо целевого корабля."""
"Luke Skywalker":
name: "Люк Скайуокер"
text: """После проведения атаки без попадания вы можете немедленно провести атаку основным оружием. Вы можете сменить 1 результат %FOCUS% на результат %HIT%. Вы не можете выполнять другую атаку в этот ход."""
"Nien Nunb":
name: "Ниен Нанб"
text: """Вы можете считать все %STRAIGHT% маневры как зеленые маневры."""
"Chewbacca":
name: "Чубакка"
text: """Когда вы получаете карту повреждений, вы можете немедленно сбросить эту карту и восстановить 1 щит.<br /><br />Затем сбросьте эту карту улучшения."""
"Advanced Proton Torpedoes":
name: "Улучшенные протонные торпеды"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете заменить до 3 ваших пустых результатов на результаты %FOCUS%."""
"Autoblaster":
name: "Автобластер"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.<br /><br />Ваши %HIT% результаты не могут быть отменены кубиками защиты.<br /><br />Защищающийся может отменять результаты %CRIT% до результатов %HIT%."""
"Fire-Control System":
name: "Система контроля огня"
text: """После выполнения атаки, вы можете получить захват цели на защищающемся."""
"Blaster Turret":
name: "Бластерная турель"
text: """<strong>Атака(концентрация):</strong> Потратьте 1 жетон Концентрации чтобы выполнить эту атаку против 1 корабля (даже вне пределов вашей арки огня)."""
"Recon Specialist":
name: "Специалист разведки"
text: """Когда вы выполняете действие Концентрации, назначьте 1 дополнительный жетон Концентрации на ваш корабль."""
"Saboteur":
name: "Саботажник"
text: """<strong>Действие:</strong> Выберите 1 вражеский корабль на расстоянии 1 и бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, выберите 1 случайную карту, лежащую лицом вниз на этом корабле, переверните ее и отработайте ее."""
"Intelligence Agent":
name: "Агент разведки"
text: """В начале фазы Активации выберите 1 вражеский корабль на расстоянии 1-2. Вы можете посмотреть на выбранный маневр этого корабля."""
"Proton Bombs":
name: "Протонные бомбы"
text: """Когда вы открываете ваш диск маневра, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон протонной бомбы.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы активации.<br /><br /><strong>Жетон протонной бомбы:</strong> Когда этот бомбовый жетон взрывается, каждый корабль на расстоянии 1 от жетона получает карту повреждения лицом вверх. Затем сбросьте этот жетон."""
"Adrenaline Rush":
name: "Выброс адреналина"
text: """Когда вы открываете красный маневр, вы можете сбросить эту карту чтобы считать этот маневр как белый маневр до конца фазы Активации."""
"Advanced Sensors":
name: "Продвинутые сенсоры"
text: """Сразу перед объявлением маневра, вы можете выполнить 1 свободное действие.<br /><br />Если вы используете эту способность, вы должны пропустить шаг "Выполнение действия" в этом ходу."""
"Sensor Jammer":
name: "Глушитель сенсоров"
text: """Защищаясь, вы можете сменить 1 результат %HIT% атакующего на результат %FOCUS%.<br /><br />Атакующий не может перебрасывать кубик с измененным результатом."""
"Darth Vader":
name: "Дарт Вейдер"
text: """После того, как вы выполните атаку вражеского корабля, вы можете получить 2 повреждения чтобы заставить тот корабль получить 1 критическое повреждение."""
"Rebel Captive":
name: "Пленный повстанец"
text: """Один раз за ход, первый корабль, заявляющий вас целью атаки, немедленно получает 1 жетон стресса."""
"Flight Instructor":
name: "Полетный инструктор"
text: """Защищаясь, вы можете перебросить 1 из ваших результатов %FOCUS%. Если умение пилота атакующего "2" или ниже, вместо этого вы можете перебросить 1 пустой результат."""
"Navigator":
name: "Навигатор"
text: """Когда вы открываете маневр, вы можете повернуть ваш диск на другой маневр того же типа.<br /><br />Вы не можете выбирать красный маневр если у вас есть жетон(ы) Стресса."""
"Opportunist":
name: "Оппортунист"
text: """При атаке, если защищающийся не имеет жетонов Концентрации или Уклонения, вы можете получить 1 жетон стресса чтобы бросить 1 дополнительный кубик атаки.<br /><br />Вы не можете использовать эту способность если у вас есть жетон(ы) стресса."""
"Comms Booster":
name: "Усилитель связи"
text: """<strong>Энергия:</strong> Потратьте 1 энергии, чтобы убрать все жетоны Стресса с дружественного корабля на расстоянии 1-3. Затем назначьте 1 жетон Концентрации на тот корабль."""
"Slicer Tools":
name: "Электронные боевые системы"
text: """<strong>Действие:</strong> Выберите 1 или более кораблей на расстоянии 1-3, имеющих жетон Стресса. За каждый выбранный корабль, вы можете потратить 1 энергии чтобы заставить этот корабль получить 1 повреждение."""
"Shield Projector":
name: "Проектор щита"
text: """Когда вражеский корабль заявляет маленький или большой корабль целью атаки, вы можете потратить 3 энергии, чтобы заставить этот корабль атаковать вас (при возможности)."""
"Ion Pulse Missiles":
name: "Ионные импульсные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если эта атака попадает, защищающийся получает 1 повреждение и 2 ионных жетона. Затем отмените <strong>все</strong> результаты кубиков."""
"Wingman":
name: "Ведомый"
text: """В начале фазы Боя, уберите 1 жетон стресса с другого дружественного корабля на расстоянии 1."""
"Decoy":
name: "Приманка"
text: """В начале фазы Боя, вы можете выбрать 1 дружественный корабль на расстоянии 1-2. Поменяйтесь умением пилота с умением пилота этого корабля до конца этой фазы."""
"Outmaneuver":
name: "Переманеврирование"
text: """Атакуя корабль в вашей арке огня, если вы не находитесь в арке огня этого корабля, его Маневренность снижается на 1."""
"Predator":
name: "Хищник"
text: """Атакуя, вы можете перебросить 1 кубик атаки. Если умение пилота защищающегося "2" или ниже, вместо этого вы можете перебросить до 2 кубиков атаки."""
"Flechette Torpedoes":
name: "Осколочные торпеды"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />После выполнения этой атаки, защищающийся получает 1 жетон стресса, если его значение корпуса 4 или ниже."""
"R7 Astromech":
name: "Астромех R7"
text: """Один раз за ход, защищаясь, если у вас есть захват цели на атакующего, вы можете потратить этот захват цели чтобы выбрать любой или все кубики атаки. Атакующий должен перебросить выбранные кубики."""
"R7-T1":
name: "R7-T1"
text: """<strong>Действие:</strong> Выберите вражеский корабль на расстоянии 1-2. Если вы находитесь в арке огня этого корабля, вы можете получить захват цели на этот корабль. Затем вы можете выполнить свободное действие Ускорения"""
"Tactician":
name: "Тактик"
text: """%LIMITED%%LINEBREAK%После того, как вы выполните атаку против корабля в вашей арке стрельбы на расстоянии 2, этот корабль получает 1 жетон стресса."""
"R2-D2 (Crew)":
name: "R2-D2 (Экипаж)"
text: """В конце фазы Завершения, если у вас нет щитов, вы можете восстановить 1 щит и бросить 1 кубик атаки. При результате %HIT%, случайным образом выберите и переверните 1 карту повреждений, лежащую лицом вниз, и отработайте ее."""
"C-3PO":
name: "C-3PO"
text: """Один раз за ход, перед тем, как бросить 1 или более кубиков защиты, вы можете заявить вслух количество результатов %EVADE%. Если вы выбросили именно столько (до модификации кубиков), добавьте 1 %EVADE% результат."""
"Single Turbolasers":
name: "Одноствольные турболазеры"
text: """<strong>Атака (Энергия):</strong> Потратьте 2 энергии с этой карты чтобы выполнить эту атаку. Защищающийся удваивает свою Маневренность против этой атаки. Вы можете сменить 1 из ваших результатов %FOCUS% на 1 результат %HIT%."""
"Quad Laser Cannons":
name: "Счетверенные лазерные пушки"
text: """<strong>Атака (Энергия):</strong> Потратьте 1 энергии с этой карты чтобы выполнить эту атаку. Если атака не попала, вы можете немедленно потратить 1 энергии с этой карты чтобы выполнить эту атаку снова."""
"Tibanna Gas Supplies":
name: "Склад тибаннского газа"
text: """<strong>Энергия:</strong> Вы можете сбросить эту карту чтобы получить 3 энергии."""
"Ionization Reactor":
name: "Ионизационный реактор"
text: """<strong>Энергия:</strong> Потратьте 5 энергии с этой карты и сбросьте эту карту чтобы заставить каждый другой корабль на расстоянии 1 получить 1 повреждение и 1 ионный жетон"""
"Engine Booster":
name: "Ускоритель двигателя"
text: """Сразу перед открытием вашего диска маневров, вы можете потратить 1 энергию чтобы выполнить белый (%STRAIGHT% 1)маневр. Вы не можете использовать эту способность если вы перекроете другой корабль."""
"R3-A2":
name: "R3-A2"
text: """Когда вы заявляете цель для атаки, если защищающийся находится в вашей арке огня, вы можете получить 1 жетон Стресса чтобы заставить защищающегося получить 1 жетон стресса."""
"R2-D6":
name: "R2-D6"
text: """Ваша панель улучшений получает значок улучшения %ELITE%.<br /><br />Вы не можете выбрать это улучшение если вы уже имеете значок улучшения %ELITE% или если ваше умение пилота "2" или ниже."""
"Enhanced Scopes":
name: "Улучшенная оптика"
text: """Во время фазы Активации, считайте ваше умение пилота равным "0"."""
"Chardaan Refit":
name: "Чардаанский тюнинг"
ship: "А-Крыл"
text: """<span class="card-restriction">Только для А-Крыла.</span><br /><br />Эта карта имеет отрицательное значение очковой стоимости отряда."""
"Proton Rockets":
name: "Протонные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете бросить дополнительные кубики атаки, равные по количеству вашему значению Маневренности, до максимума в 3 кубика."""
"Kyle Katarn":
name: "Кайл Катарн"
text: """После того, как вы снимаете жетон Стресса с вашего корабля, вы можете назначить жетон Концентрации на ваш корабль."""
"Jan Ors":
name: "Джан Орс"
text: """Один раз за ход, когда дружественный корабль на расстоянии 1-3 выполняет действие Концентрации или получает жетон Концентрации, вы можете назначить ему жетон Уклонения вместо этого."""
"Toryn Farr":
name: "Торин Фарр"
text: """<strong>Действие:</strong> Потратьте любое количество энергии чтобы выбрать это количество кораблей на расстоянии 1-2. Уберите все жетоны Концентрации, Уклонения, и синие жетоны захвата цели с этих кораблей."""
# TODO Check card formatting
"R4-D6":
name: "R4-D6"
text: """Когда вы получаете попадание от атаки и имеете по меньшей мере 3 неотмененных результата %HIT% , вы можете отменить эти результаты пока не останется 2. За каждый результат, отмененный этим способом, получите 1 жетон стресса."""
"R5-P9":
name: "R5-P9"
text: """В конце фазы Боя, вы можете потратить 1 из ваших жетонов Концентрации чтобы восстановить 1 щит (до максимального значения ваших щитов)."""
"WED-15 Repair Droid":
name: "Ремонтный дроид WED-15"
text: """<strong>Действие:</strong> Потратьте 1 энергии чтобы сбросить 1 из ваших карт повреждений, лежащих лицом вниз, или потратьте 3 энергии чтобы сбросить 1 из ваших карт повреждений, лежащих лицом вверх."""
"Carlist Rieekan":
name: "Карлист Риеекан"
text: """В начале фазы Активации, вы можете сбросить эту карту чтобы считать умение пилота каждого дружественного корабля как "12" до конца фазы."""
"Jan Dodonna":
name: "Ян Додонна"
text: """Когда другой дружественный корабль на расстоянии 1 атакует, он может сменить 1 результат %HIT% на 1 результат %CRIT%."""
"Expanded Cargo Hold":
name: "Расширенный грузовой отсек"
text: """<span class="card-restriction">Только для GR-75</span><br /><br />Один раз за ход, когда вы должны получить карту повреждений лицом вверх, вы можете потянуть эту карту из колоды повреждений носовой или кормовой части."""
ship: 'Средний транспорт GR-75'
"Backup Shield Generator":
name: "Вспомогательный генератор щита"
text: """В конце каждого хода вы можете потратить 1 энергии чтобы восстановить 1 щит (до максимального значения щитов)."""
"EM Emitter":
name: "ЭМ эмиттер"
text: """Когда вы перекрываете атаку, защищающийся бросает 3 дополнительных кубика защиты (вместо 1)."""
"Frequency Jammer":
name: "Глушитель частот"
text: """Когда вы выполняете действие Заклинивания, выберите 1 вражеский корабль, не имеющий жетон стресса и находящийся на расстоянии 1 от заклинившего корабля. Выбранный корабль получает 1 жетон стресса."""
"Han Solo":
name: "Хан Соло"
text: """Когда вы атакуете, если у вас есть захват цели на защищающемся, вы можете потратить этот захват цели чтобы сменить все результаты %FOCUS% на результаты %HIT%."""
"Leia Organa":
name: "Лея Органа"
text: """В начале фазы Активации вы можете сбросить эту карту чтобы позволить всем дружественным кораблям, объявляющим красный маневр, считать этот маневр белым до конца фазы."""
"Raymus Antilles":
name: "Раймус Антиллес"
text: """В начале фазы Активации, выберите 1 вражеский корабль на расстоянии 1-3. Вы можете посмотреть на выбранный маневр этого корабля. Если маневр белый, назначьте этому кораблю 1 жетон стресса."""
"Gunnery Team":
name: "Орудийная команда"
text: """Один раз за ход, атакуя вспомогательным оружием, вы можете потратить 1 энергии чтобы сменить 1 пустой результат на результат %HIT%."""
"Sensor Team":
name: "Сенсорная команда"
text: """При получении захвата цели, вы можете захватывать вражеский корабль на расстоянии 1-5 вместо 1-3."""
"Engineering Team":
name: "Инженерная команда"
text: """Во время фазы активации, когда вы открываете %STRAIGHT% маневр, получите дополнительно 1 энергии во время шага "Получение энергии"."""
"Lando Calrissian":
name: "Лэндо Калриссиан"
text: """<strong>Действие:</strong> Бросьте 2 кубика защиты. За каждый результат %FOCUS% назначьте 1 жетон Концентрации на ваш корабль. За каждый результат %EVADE% , назначьте 1 жетон Уклонения на ваш корабль."""
"Mara Jade":
name: "Мара Джейд"
text: """В конце фазы Боя, каждый вражеский корабль на расстоянии 1, не имеющий жетона Стресса, получает 1 жетон Стресса."""
"Fleet Officer":
name: "Офицер флота"
text: """<strong>Действие:</strong> Выберите до двух дружественных кораблей на расстоянии 1-2 и назначьте 1 жетон концентрации каждому из них. Затем получите 1 жетон Стресса."""
"Lone Wolf":
name: "Одинокий волк"
text: """Атакуя или защищаясь, при отсутствии других дружественных кораблей на расстоянии 1-2, вы можете перебросить 1 из ваших пустых результатов."""
"Stay On Target":
name: "Оставайся на цели"
text: """Когда вы открываете маневр, вы можете повернуть ваш диск на другой маневр с той же скоростью.<br /><br />Считайте эот маневр красным маневром."""
"Dash Rendar":
name: "Даш Рендар"
text: """Вы можете проводить атаки, перекрывая подставкой препятствие.<br /><br />Ваши атаки не могут быть перекрыты."""
'"Leebo"':
name: "Лиибо"
text: """<strong>Действие:</strong> Выполните свободное действие Ускорение. Затем получите 1 ионный жетон."""
"Ruthlessness":
name: "Беспощадность"
text: """После того, как вы выполните атаку, которая попала, вы <strong>должны</strong> выбрать 1 корабль на расстоянии 1 от защищающегося (кроме себя). Этот корабль получает 1 повреждение."""
"Intimidation":
name: "Устрашение"
text: """Когда вы касаетесь вражеского корабля, его Маневренность снижается на 1."""
"Ysanne Isard":
name: "Исанн Айсард"
text: """В начале фазы Боя, если у вас нет щитов и на ваш корабль назначена хотя бы 1 карта повреждений, вы можете провести свободное действие Уклонения."""
"Moff Jerjerrod":
name: "Мофф Джерджеррод"
text: """Когда вы получаете карту повреждений лицом вверх, вы можете сбросить эту карту или другую карту улучшений %CREW% типа, чтобы перевернуть эту карту повреждений лицом вниз (не отрабатывая ее эффект)."""
"Ion Torpedoes":
name: "Ионные торпеды"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если эта атака попадет, защищающийся и каждый корабль на расстоянии 1 получает 1 ионный жетон."""
"Bomb Loadout":
name: "Бомбовая загрузка"
text: """<span class="card-restriction">Только для У-Крыла.</span><br /><br />Ваша панель улучшений получает значок %BOMB%."""
ship: "У-Крыл"
"Bodyguard":
name: "Телохранитель"
text: """%SCUMONLY%<br /><br />В начале фазы Боя, вы можете потратить жетон Концентрации, чтобы выбрать дружественный корабль с более высоким умением пилота на расстоянии 1. Увеличьте его значение Маневренности на 1 до конца хода."""
"Calculation":
name: "Счисление"
text: """Атакуя, вы можете потратить жетон Концентрации, чтобы сменить 1 из ваших результатов %FOCUS% на результат %CRIT%."""
"Accuracy Corrector":
name: "Корректировщик огня"
text: """Атакуя, во время шага "Модификация кубиков атаки", вы можете отменить все результаты кубиков. Затем, вы можете добавить 2 результата %HIT% к броску.<br /><br />Ваши кубики не могут быть модифицированы снова во время этой атаки."""
"Inertial Dampeners":
name: "Инерциальные амортизаторы"
text: """Когда вы открываете ваш маневр, вы можете сбросить эту карту чтобы вместо него выполнить белый [0%STOP%] маневр. Затем получите 1 жетон Стресса."""
"Flechette Cannon":
name: "Осколочная пушка"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK% Если эта атака попадает, защищающийся получает 1 повреждение и, если он не имеет жетонов Стресса, также получает 1 жетон Стресса. Затем отмените <strong>все</strong> результаты кубиков."""
'"Mangler" Cannon':
name: 'Пушка "Потрошитель"'
text: """<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK% Атакуя, вы можете заменить 1 результат %HIT% на результат %CRIT%."""
"Dead Man's Switch":
name: "Кнопка мертвеца"
text: """Когда вы уничтожены, каждый корабль на расстоянии 1 получает 1 повреждение."""
"Feedback Array":
name: "Матрица обратной связи"
text: """Во время фазы Боя, вместо выполнения каких-либо атак, вы можете получить 1 ионный жетон и 1 повреждение, чтобы выбрать 1 вражеский корабль на расстоянии 1. Этот корабль получает 1 повреждение."""
'"Hot Shot" Blaster':
name: "Бластер Пробивной"
text: """<strong>Атака:</strong> Сбросьте эту карту, чтобы атаковать 1 корабль (даже корабль вне вашей арки огня)."""
"Greedo":
name: "Гридо"
text: """%SCUMONLY%<br /><br />В первый раз за ход, когда вы атакуете, и в первый раз за ход, когда вы защищаетесь, первая нанесенная карта повреждений отрабатывается в открытую."""
"Outlaw Tech":
name: "Техник вне закона"
text: """%SCUMONLY%<br /><br />После того, как вы выполнили красный маневр, вы можете назначить 1 жетон Концентрации на ваш корабль."""
"K4 Security Droid":
name: "Дроид безопасности K4"
text: """%SCUMONLY%<br /><br />После выполнения зеленого маневра, вы можете получить захват цели."""
"Salvaged Astromech":
name: "Трофейный астромех"
text: """Когда вы получаете карту повреждений лицом вверх с обозначением <strong>Корабль</strong>, вы можете немедленно сбросить эту карту (не отрабатывая ее эффект).<br /><br />Затем сбросьте эту карту."""
'"Genius"':
name: '"Гений"'
text: """После того, как вы откроете и выполните маневр, если вы не перекрываете другой корабль, вы можете сбросить 1 из ваших карт улучшения %BOMB% без указателя <strong>Действие:</strong> чтобы сбросить соответствующий жетон бомбы."""
"Unhinged Astromech":
name: "Неподвешенный астромех"
text: """Вы можете считать маневры со скоростью 3 зелеными маневрами."""
"R4 Agromech":
name: "Агромех R4"
text: """Атакуя, после того, как вы потратили жетон Концентрации, вы можете получить захват цели на защищающегося."""
"R4-B11":
text: """Атакуя, если у вас есть захват цели на защищающегося, вы можете потратить захват цели чтобы выбрать любые кубики защиты. Защищающийся должен перебросить выбранные кубики."""
"Autoblaster Turret":
name: "Автобластерная турель"
text: """<strong>Атака:</strong> Атакуйте 1 корабль (даже если он находится вне вашей арки огня).<br /><br />Ваши %HIT% результаты не могут быть отменены кубиками защиты.<br /><br />Защищающийся может отменять результаты %CRIT% до результатов %HIT%."""
"Advanced Targeting Computer":
ship: "TIE Улучшенный"
name: "Улучшенный компьютер наведения"
text: """<span class="card-restriction">Только для TIE улучшенный.</span>%LINEBREAK%Атакуя основным оружием, если у вас есть захват цели на защищающегося, вы можете добавить 1 результат %CRIT% к вашему броску. Если вы решаете это сделать, вы не можете использовать захваты цели во время этой атаки."""
"Ion Cannon Battery":
name: "Батарея ионных пушек"
text: """<strong>Атака (Энергия):</strong> Потратьте 2 энергии с этой карты чтобы выполнить эту атаку. Если эта атака попадает, защищающийся получает 1 критическое повреждение и 1 ионный жетон. Затем отмените <strong>все</strong> результаты кубиков."""
"Emperor Palpatine":
name: "Император Палпатин"
text: """%IMPERIALONLY%%LINEBREAK%Один раз за ход, до того как дружественный корабль бросает кубики, вы можете назвать результат кубика. После броска вы должны заменить 1 из ваших резултьтатов на кубиках на названный результат. Результат этого кубика не может быть модифицирован снова."""
"Bossk":
name: "Босск"
text: """%SCUMONLY%%LINEBREAK%После того, как вы выполнили атаку, которая не попала, если у вас нет Стресса, вы <strong>должны</strong> получить 1 жетон Стресса. Затем получите 1 жетон Концентрации на ваш корабль, а также получите захват цели на защищающегося."""
"Lightning Reflexes":
name: "Молниеносные рефлексы"
text: """%SMALLSHIPONLY%%LINEBREAK%После выполнения белого или зеленого маневра, вы можете сбросить эту карту чтобы развернуть корабль на 180°. Затем получите 1 жетон стресса <strong>после</strong> шага "Проверка стресса пилота."""
"Twin Laser Turret":
name: "Спаренная лазерная турель"
text: """<strong>Атака:</strong> Выполните эту атаку <strong>дважды</strong> (даже против корабля вне вашей арки огня).<br /><br />Каждый раз, когда эта атака попадает, защищающийся получает 1 повреждение. Затем отмените <strong>все</strong> результаты кубиков."""
"Plasma Torpedoes":
name: "Плазменные торпеды"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если атака попадает, после нанесения повреждений, снимите 1 жетон щита с защищающегося."""
"Ion Bombs":
name: "Ионные бомбы"
text: """Когда вы открываете диск маневров, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон ионной бомбы.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы Активации.<br /><br /><strong>Жетон ионной бомбы:</strong> Когда этот жетон бомбы взрывается, каждый корабль на расстоянии 1 от жетона получает 2 ионных жетона. Затем сбросьте этот жетон."""
"Conner Net":
name: "Сеть Коннер"
text: """<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>бросить</strong> 1 жетон сети Коннер.<br /><br />Когда подставка корабля или шаблон маневра перекрывает этот жетон, он <strong>взрывается</strong>.<br /><br /><strong>Жетон сети Коннер:</strong> Когда этот бомбовый жетон взрывается, корабль, прощедший через него или перекрывший его, получает 1 повреждение, 2 ионных жетона и пропускает шаг "Выполнение действия". Затем сбросьте этот жетон."""
"Bombardier":
name: "Бомбардир"
text: """Сбрасывая бомбу, вы можете использовать шаблон (%STRAIGHT% 2) вместо шаблона (%STRAIGHT% 1)."""
"Cluster Mines":
name: "Кластерные мины"
text: """<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>бросить</strong> комплект кластерных мин (3 жетона).<br /><br />Когда подставка корабля или шаблон маневра перекрывает жетон кластерной мины, он <strong>взрывается</strong>.<br /><br /><strong>Жетоны кластерных мин:</strong> Когда один из этих жетонов бомб взрывается, корабль, прощедший через него или перекрывший его, бросает 2 кубика атаки и получает 1 повреждение за каждый результат %HIT% или %CRIT%. Затем сбросьте этот жетон."""
'Crack Shot':
name: "Точный выстрел"
text: '''Когда вы атакуете корабль в вашей арке огня, в начале шага "Сравнение результатов", вы можете сбросить эту карту чтобы отменить 1 результат %EVADE% защищающегося.'''
"Advanced Homing Missiles":
name: "Улучшенные самонаводящиеся ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадает, назначьте 1 карту повреждений лицом вверх защищающемуся. Затем отмените <strong>все</strong> результаты кубиков."""
'Agent Kallus':
name: "Агент Каллус"
text: '''%IMPERIALONLY%%LINEBREAK%В начале первого хода, выберите 1 маленький или большой корабль врага. Атакуя или защищаясь против этого корабля, вы можете сменить 1 из ваших результатов %FOCUS% на результат %HIT% или %EVADE%.'''
'XX-23 S-Thread Tracers':
name: "Следящие маяки XX-23"
text: """<strong>Атака (Концентрация):</strong> Cбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK% Если эта атака попадает, каждый дружественный корабль на расстоянии 1-2 от вас может получить захват цели на защищающемся. Затем отмените <strong>все</strong> результаты кубиков."""
"Tractor Beam":
name: "Луч захвата"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK%Если эта атака попадает, защищающийся получает 1 жетон Луча Захвата. Затем отмените <strong>все</strong> результаты кубиков."""
"Cloaking Device":
name: "Маскировочное устройство"
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Действие:</strong> Выполните свободное действие Маскировки.%LINEBREAK%В конце каждого хода, если вы замаскированы, бросьте 1 кубик атаки. При результатк %FOCUS%, сбросьте эту карту, затем размаскируйтесь или сбросьте ваш жетон Маскировки."""
"Shield Technician":
name: "Техник щита"
text: """%HUGESHIPONLY%%LINEBREAK%Когда вы выполняете действие Восстановления, вместо того, чтобы потратить всю вашу энергию, вы можете выбрать количество энергии для использования."""
"Grand Moff Tarkin":
name: "Гранд Мофф Таркин"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%В начале фазы Боя, вы можете выбрать другой корабль на расстоянии 1-4. Затем уберите 1 жетон Концентрации с выбранного корабля, или же назначьте 1 жетон концентрации на него."""
"Captain Needa":
name: "Капитан Нида"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%Если вы перекрываете препятствие во время фазы Активации, не получайте 1 карту повреждений лицом вверх. Вместо этого, бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, получите 1 повреждение."""
"Admiral Ozzel":
name: "Адмирал Оззел"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%<strong>Энергия</strong>: Вы можете снять до 3 щитов с вашего корабля. За каждый убранный щит, получите 1 энергии."""
'Glitterstim':
name: "Глиттерстим"
text: """В начале фазы Боя, вы можете сбросить эту карту и получить 1 жетон стресса. Если вы делаете это, до конца хода, защищаясь или атакуя, вы можете сменить все ваши результаты %FOCUS% на результаты %HIT% или %EVADE%."""
'Extra Munitions':
name: "Дополнительные боеприпасы"
text: """Когда вы экипируете эту карту, положите 1 жетон боеприпасов на каждую экипированную карту улучшений %TORPEDO%, %MISSILE% и %BOMB%. Когда вы должны сбросить карту улучшений, вместо этого вы можете сбросить жетон боеприпасов с этой карты."""
"Weapons Guidance":
name: "Система наведения"
text: """Атакуя, вы можете потратить жетон Концентрации, чтобы заменить 1 из ваших пустых результатов на результат %HIT%."""
"BB-8":
text: """Когда вы открываете зеленый маневр, вы можете выполнить свободное действие Бочку."""
"R5-X3":
text: """Перед открытием вашего маневра, вы можете сбросить эту карту, чтобы игнорировать препятствия до конца хода."""
"Wired":
name: "Подключенный"
text: """Атакуя или защищаясь, если у вас есть жетон Стресса, вы можете перебросить 1 или более результатов %FOCUS%."""
'Cool Hand':
name: "Хладнокровный"
text: '''Когда вы получаете жетон стресса, вы можете сбросить эту карту чтобы назначить 1 жетон Концентрации или Уклонения на ваш корабль.'''
'Juke':
name: "Финт"
text: '''%SMALLSHIPONLY%%LINEBREAK%Атакуя, если у вас есть жетон Уклонения, вы можете заменить 1 из результатов %EVADE% защищающегося на результат %FOCUS%.'''
'Comm Relay':
name: "Реле связи"
text: '''Вы не можете иметь больше 1 жетона Уклонения.%LINEBREAK%Во время фазы Завершения, не убирайте неиспользованный жетон Уклонения с вашего корабля.'''
'Twin Laser Turret':
name: "Двойная лазерная турель"
text: '''%GOZANTIONLY%%LINEBREAK%<strong>Атака (Энергия):</strong> Потратьте 1 энергии с этой карты чтобы выполнить эту атаку против 1 корабля (даже если он находится вне вашей арки огня).'''
'Broadcast Array':
name: "Реле вещания"
text: '''%GOZANTIONLY%%LINEBREAK%Ваша панель действий получает значок %JAM%.'''
'Rear Admiral Chiraneau':
name: "Контр-адмирал Ширано"
text: '''%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Действие:</strong> Выполните белый(%STRAIGHT% 1) маневр.'''
'Ordnance Experts':
name: "Ракетные эксперты"
text: '''Один раз за ход, когда дружественный корабль на расстоянии 1-3 атакует вспомогательным оружием %TORPEDO% или %MISSILE%, он может заменить 1 пустой результат на результат %HIT%.'''
'Docking Clamps':
name: "Доковые порты"
text: '''%GOZANTIONLY% %LIMITED%%LINEBREAK%Вы можете пристыковать до 4 TIE истребителей, TIE перехватчиков, TIE улучшенных или TIE бомбардировщиков к этому кораблю. Все пристыкованные корабли должны иметь один и тот же тип корабля.'''
'"Zeb" Orrelios':
name: "Зеб Ореллиос"
text: """%REBELONLY%%LINEBREAK%Вражеские корабли в вашей арке огня, которых вы касаетесь, не считаются касающимися вас, когда они или вы активируетесь во время фазы Боя."""
'Kanan Jarrus':
name: "Кейнан Джаррус"
text: """%REBELONLY%%LINEBREAK%Один раз за ход, после того, как дружественный корабль на расстоянии 1-2 выполняет белый маневр, вы можете снять 1 жетон Стресса с того корабля."""
'Reinforced Deflectors':
name: "Усиленные отражатели"
text: """%LARGESHIPONLY%%LINEBREAK%После защиты, если вы получили 3 или более повреждений или критических повреждений во время атаки, восстановите 1 щит (до максимального значения щитов)."""
'Dorsal Turret':
name: "Палубная турель"
text: """<strong>Атака:</strong> Атакуйте 1 корабль (даже если он находится вне вашей арки огня).%LINEBREAK%Если цель атаки находится на расстоянии 1, бросьте 1 дополнительный кубик атаки."""
'Targeting Astromech':
name: "Астромех наведения"
text: '''После выполнения красного маневра, вы можете получить захват цели.'''
'Hera Syndulla':
name: "Гера Синдулла"
text: """%REBELONLY%%LINEBREAK%Вы можете открывать и выполнять красные маневры, даже находясь под Стрессом."""
'Ezra Bridger':
name: "Эзра Бриджер"
text: """%REBELONLY%%LINEBREAK%Атакуя, если вы под Стрессом, вы можете заменить 1 результат %FOCUS% на результат %CRIT%."""
'Sabine Wren':
name: "Сабина Врен"
text: """%REBELONLY%%LINEBREAK%Ваша панель улучшений получает значок %BOMB%. Один раз за ход, перед тем, как убрать дружественный жетон бомбы, выберите 1 вражеский корабль на расстоянии 1 от этого жетона. Этот корабль получает 1 повреждение."""
'"Chopper"':
name: "Чоппер"
text: """%REBELONLY%%LINEBREAK%Вы можете выполнять действия, находясь под Стрессом.%LINEBREAK%После того, как вы выполнили действие, находясь под Стрессом, получите 1 повреждение."""
'Construction Droid':
name: "Строительный дроид"
text: '''%HUGESHIPONLY% %LIMITED%%LINEBREAK%Когда вы выполняете действие Восстановления, вы можете потратить 1 энергии, чтобы сбросить 1 карту повреждений, лежащую лицом вниз.'''
'Cluster Bombs':
name: "Кластерные бимбы"
text: '''После защиты, вы можете сбросить эту карту. Если вы делаете это, любой другой корабль на расстоянии 1 от защищающейся секции бросает 2 кубика атаки, получая выброшенные повреждения (%HIT%) и критические повреждения (%CRIT%).'''
"Adaptability":
name: "Адаптивность"
text: """<span class="card-restriction">Двойная карта.</span>%LINEBREAK%<strong>Сторона A:</strong> Увеличьте ваше умение пилота на 1.%LINEBREAK%<strong>Сторона Б:</strong> Уменьшите ваше умение пилота на 1."""
"Electronic Baffle":
name: "Электронный экран"
text: """Когда вы получаете жетон стресса или ионный жетон, вы можете получить 1 повреждение чтобы сбросить этот жетон."""
"4-LOM":
text: """%SCUMONLY%%LINEBREAK%Атакуя, во время шага "Модификация кубиков атаки", вы можете получить 1 ионный жетон чтобы выбрать 1 из жетонов Концентрации или Уклонения защищающегося. Этот жетон не может использоваться во время этой атаки."""
"Zuckuss":
name: "Закасс"
text: """%SCUMONLY%%LINEBREAK%Атакуя, если вы не под Стрессом, вы можете получить любое количество жетонов Стресса, чтобы выбрать равное количество кубиков защиты. Защищающийся должен перебросить эти кубики."""
'Rage':
name: "Гнев"
text: """<strong>Действие:</strong> Назначьте 1 жетон Концентрации вашему кораблю и получите 2 жетона Стресса. До конца хода, при атаке, вы можете перебросить до 3 кубиков атаки."""
"Attanni Mindlink":
name: "Мысленная связь Аттанни"
text: """%SCUMONLY%%LINEBREAK%Каждый раз, когда вы получаете жетон Концентрации или Стресса, каждый другой дружественный корабль с Мысленной связью Аттанни также должен получить тот же тип жетона, если его у него нет."""
"Boba Fett":
name: "Боба Фетт"
text: """%SCUMONLY%%LINEBREAK%После выполнения атаки, если защищающийся получил карту повреждений лицом вверх, вы можете сбросить эту карту чтобы выбрать и сбросить 1 карту улучшений защищающегося."""
"Dengar":
name: "Денгар"
text: """%SCUMONLY%%LINEBREAK%Атакуя, вы можете перебросить 1 кубик атаки. Если защищающийся - уникальный пилот, вы можете перебросить до 2 кубиков атаки."""
'"Gonk"':
name: '"Гонк"'
text: """%SCUMONLY%%LINEBREAK%<strong>Действие:</strong> Положите 1 жетон щита на эту карту.%LINEBREAK%<strong>Действие:</strong> Уберите 1 жетон щита с этой карты чтобы восстановить 1 щит (до максимального значения щитов)."""
"R5-P8":
text: """Один раз за ход, после защиты, вы можете бросить 1 кубик атаки. При результате %HIT%, атакующий получает 1 повреждение. При результате %CRIT%, вы и атакующий получаете 1 повреждение каждый."""
'Thermal Detonators':
name: "Термальные детонаторы"
text: """Когда вы открываете диск маневров, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон термального детонатора.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы Активации.<br /><br /><strong>Жетон термального детонатора:</strong> Когда этот жетон бомбы взрывается, каждый корабль на расстоянии 1 от жетона получает 1 повреждение и 1 жетон Стресса. Затем сбросьте этот жетон."""
"Overclocked R4":
name: "Разогнанный R4"
text: """Во время фазы Боя, когда вы тратите жетон Концентрации, вы можете получить 1 жетон Стресса чтобы назначить 1 жетон Концентрации на ваш корабль."""
'Systems Officer':
name: "Системный офицер"
text: '''%IMPERIALONLY%%LINEBREAK%После выполнения зеленого маневра, выберите другой дружественный корабль на расстоянии 1. Этот корабль может получить захват цели.'''
'Tail Gunner':
name: "Кормовой стрелок"
text: '''Атакуя с кормовой вторичной арки огня, снизьте Маневренность защищающегося на 1.'''
'R3 Astromech':
name: "Астромех R3"
text: '''Один раз за ход, атакуя основным оружием, во время шага "Модификация кубиков атаки", вы можете отменить один из ваших результатов %FOCUS%, чтобы назначить 1 жетон Уклонения на ваш корабль.'''
'Collision Detector':
name: "Детектор столкновений"
text: '''Выполняя Ускорение, Бочку или Размаскировывание, ваш корабль и шаблон маневра могут накладываться на преграды.%LINEBREAK%При броске за повреждение от преград, игнорируйте все результаты %CRIT%.'''
'Sensor Cluster':
name: "Сенсорный кластер"
text: '''Защищаясь, вы можете потратить жетон Концентрации, чтобы сменить 1 из ваших пустых результатов на результат %EVADE%.'''
'Fearlessness':
name: "Бесстрашие"
text: '''%SCUMONLY%%LINEBREAK%Атакуя, если вы находитесь в арке огня защищающегося на расстоянии 1 и защищающийся находится в вашей арке огня, вы можете добавить 1 результат %HIT% к вашему броску.'''
'Ketsu Onyo':
name: "Кетсу Онио"
text: '''%SCUMONLY%%LINEBREAK%В начале фазы Завершения, вы можете выбрать 1 корабль в вашей арке огня на расстоянии 1-2. Этот корабль не убирает свои жетоны Луча захвата.'''
'Latts Razzi':
name: "Латтс Рацци"
text: '''%SCUMONLY%%LINEBREAK%Защищаясь, вы можете снять 1 жетон стресса с атакующего и добавить 1 результат %EVADE% к вашему броску.'''
'IG-88D':
text: '''%SCUMONLY%%LINEBREAK%Вы имеете способность пилота каждого другого дружественного корабля с картой улучшения <em>IG-2000</em> (в дополнение к вашей собственной способности пилота).'''
'Rigged Cargo Chute':
name: "Подъёмный грузовой желоб"
text: '''%LARGESHIPONLY%%LINEBREAK%<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>сбросить</strong> 1 жетон Груза.'''
'Seismic Torpedo':
name: "Сейсмическая торпеда"
text: '''<strong>Действие:</strong> Сбросьте эту карту чтобы выбрать препятствие на расстоянии 1-2 и в вашей арке огня. Каждый корабль на расстоянии 1 от препятствия бросает 1 кубик атаки и получает любое выброшенное повреждение (%HIT%) или критическое повреждение (%CRIT%). Затем уберите препятствие.'''
'Black Market Slicer Tools':
name: "Боевые системы с черного рынка"
text: '''<strong>Действие:</strong> Выберите вражеский корабль под Стрессом на расстоянии 1-2 и бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, уберите 1 жетон стресса и нанесите ему 1 повреждение лицом вниз.'''
# Wave X
'Kylo Ren':
name: "Кайло Рен"
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Действие:</strong> Назначьте карту состояния "Я покажу тебе Темную Сторону" на вражеский корабль на расстоянии 1-3.'''
'Unkar Plutt':
name: "Анкар Платт"
text: '''%SCUMONLY%%LINEBREAK%После выполнения маневра, который приводит к наложению на вражеский корабль, вы можете получить 1 повреждение, чтобы выполнить 1 свободное действие.'''
'A Score to Settle':
name: "Личные счеты"
text: '''Во время расстановки, перед шагом "Расстановка сил", выберите 1 вражеский корабль и назначьте ему карту состояния "Счет к оплате"."%LINEBREAK%Атакуя корабль, имеющий карту состояния "Счет к оплате", вы можете заменить 1 результат %FOCUS% на результат %CRIT%.'''
'Jyn Erso':
name: "Джин Эрсо"
text: '''%REBELONLY%%LINEBREAK%<strong>Действие:</strong> Выберите 1 дружественный корабль на расстоянии 1-2. Назначьте 1 жетон Концентрации на этот корабль за каждый вражеский корабль в вашей арке огня на расстоянии 1-3. Вы не можете назначить более 3 жетонов Концентрации этим способом.'''
'Cassian Andor':
name: "Кассиан Эндор"
text: '''%REBELONLY%%LINEBREAK%В конце фазы Планирования, вы можете выбрать вражеский корабль на расстоянии 1-2. Озвучьте скорость и направление маневра этого корабля, затем посмотрите на его диск маневров. Если вы правы, вы можете повернуть ваш диск на другой маневр.'''
'Finn':
name: "Финн"
text: '''%REBELONLY%%LINEBREAK%Атакуя основным оружием или защищаясь, если вражеский корабль находится в вашей арке огня, вы можете добавить 1 пустой результат к вашему броску.'''
'Rey':
name: "Рэй"
text: '''%REBELONLY%%LINEBREAK%В начале фазы Завершения, вы можете положить 1 из жетонов Концентрации вашего корабля на эту карту. В начале фазы Боя, вы можете назначить 1 из этих жетонов на ваш корабль.'''
'Burnout SLAM':
name: "Ускоритель ССДУ"
text: '''%LARGESHIPONLY%%LINEBREAK%Ваша панель действий получает значок действия %SLAM%.%LINEBREAK%После выполнения действия ССДУ (СубСветовой Двигатель Ускорения), сбросьте эту карту.'''
'Primed Thrusters':
name: "Турбоускорители"
text: '''%SMALLSHIPONLY%%LINEBREAK%Вы можете выполнять действия Бочка и Ускорение, имея жетоны стресса, если их три или меньше.'''
'Pattern Analyzer':
name: "Шаблонный анализатор"
text: '''При выполнении маневра, вы можете отрабатывать шаг "Проверка стресса пилота" после шага "Выполнение действий" (вместо того, чтобы отрабатывать его перед этим шагом).'''
'Snap Shot':
name: "Выстрел навскидку"
text: '''После того, как вражеский корабль выполняет маневр, вы можете выполнить эту атаку против него.%LINEBREAK% <strong>Атака:</strong> Атакуйте 1 корабль. Вы не можете модифицировать кубики атаки и не можете атаковать снова в эту фазу.'''
'M9-G8':
text: '''%REBELONLY%%LINEBREAK%Когда корабль, на котором есть ваш жетон захвата, атакует, вы можете выбрать 1 кубик атаки. Атакующий должен перебросить этот кубик.%LINEBREAK%Вы можете заявлять захват цели на другие дружественные корабли.'''
'EMP Device':
name: "Прибор ЭМИ"
text: '''Во время фазы Боя, вместо выполнения любых атак, вы можете сбросить эту карту, чтобы назначить 2 ионных жетона на каждый корабль на расстоянии 1.'''
'Captain Rex':
name: "Капитан Рекс"
text: '''%REBELONLY%%LINEBREAK%После проведения атаки, не завершившейся попаданием, вы можете назначить 1 жетон Концентрации на ваш корабль.'''
'General Hux':
name: "Генерал Хакс"
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Действие:</strong> Выберите до 3 дружественных кораблей на расстоянии 1-2. Назначьте 1 жетон Концентрации на каждый из них, а также назначьте карту состояния "Фанатическая преданность" на 1 из них. Затем получите 1 жетон Стресса.'''
'Operations Specialist':
name: "Операционный специалист"
text: '''%LIMITED%%LINEBREAK%После того, как дружественный корабль на расстоянии 1-2 выполняет атаку, не завершившуюся попаданием, вы можете назначить 1 жетон Концентрации на дружественный корабль на расстоянии 1-3 от атакующего.'''
'Targeting Synchronizer':
name: "Целевой синхронизатор"
text: '''Когда дружественный корабль на расстоянии 1-2 атакует корабль, находящийся в вашем захвате, дружественный корабль считает указатель "<strong>Атака (Захват цели):</strong> как указатель "<strong>Атака:</strong>." Если игровой эффект обязывает этот корабль потратить захват цели, он может потратить ваш захват цели вместо этого.'''
'Hyperwave Comm Scanner':
name: "Гиперволновой сканер связи"
text: '''В начале шага "Расстановка сил", вы можете считать ваше умение пилота равным "0", "6" или "12" до конца этого шага.%LINEBREAK% Во время расстановки, после того, как другой дружественный корабль выставляется на расстоянии 1-2, вы можете назначить ему 1 жетон Концентрации или Уклонения.'''
'Trick Shot':
name: "Ловкий выстрел"
text: '''Атакуя, если вы стреляете через препятствие, вы можете бросить 1 дополнительный кубик атаки.'''
'Hotshot Co-pilot':
name: "Умелый второй пилот"
text: '''Когда вы атакуете основным оружием, защищающийся должен потратить 1 жетон Концентрации при возможности.%LINEBREAK%Когда вы защищаетесь, атакующий должен потратить 1 жетон Концентрации при возможности.'''
'''Scavenger Crane''':
name: "Кран мусорщика"
text: '''После того, как корабль на расстоянии 1-2 уничтожен, вы можете выбрать сброшенную карту %TORPEDO%, %MISSILE%, %BOMB%, %CANNON%, %TURRET%, или Модификационное улучшение, которое было экипировано на ваш корабль, и вернуть его. Затем бросьте 1 кубик атаки. При пустом результате, сбросьте Кран мусорщика.'''
'Bodhi Rook':
name: "Боди Рук"
text: '''%REBELONLY%%LINEBREAK%Когда вы заявляете захват цели, вы можете захватывать корабль врага на расстоянии 1-3 от любого дружественного корабля.'''
'Baze Malbus':
name: "Бэйз Мальбус"
text: '''%REBELONLY%%LINEBREAK%После выполнения атаки, которая не попала, вы можете немедленно выполнить атаку основным оружием против другого корабля. Вы не можете выполнять другую атаку в этот ход.'''
'Inspiring Recruit':
name: "Вдохновляющий рекрут"
text: '''Один раз за ход, когда дружественный корабль на расстоянии 1-2 снимает жетон Стресса, он может снять 1 дополнительный жетон стресса.'''
'Swarm Leader':
name: "Лидер роя"
text: '''Выполняя атаку основным оружием, выберите до 2 других дружественных кораблей, имеющих защищающегося в их арках огня на расстоянии 1-3. Снимите 1 жетон Уклонения с каждого выбранного корабля чтобы бросить 1 дополнительный кубик атаки за каждый убранный жетон Уклонения.'''
'Bistan':
name: "Бистан"
text: '''%REBELONLY%%LINEBREAK%Атакуя на расстоянии 1-2, вы можете сменить 1 из ваших результатов %HIT% на результат %CRIT%.'''
'Expertise':
name: "Опытность"
text: '''Атакуя, если вы не под стрессом, вы можете заменить все ваши результаты %FOCUS% на результаты %HIT%.'''
'BoShek':
name: "БоШек"
text: '''Когда корабль, которого вы касаетесь, активируется, вы можете посмотреть на его выбранный маневр. Если вы это делаете, он должен повернуть диск на противоположный маневр. Корабль может объявлять и выполнять этот маневр, даже находясь под Стрессом.'''
# C-ROC
'Heavy Laser Turret':
ship: "Крейсер C-ROC"
name: "Тяжелая лазерная турель"
text: '''<span class="card-restriction">Только крейсер C-ROC</span>%LINEBREAK%<strong>Атака (Энергия):</strong> Потратьте 2 энергии с этой карты, чтобы выполнить эту атаку против 1 корабля (даже если он находится вне вашей арки огня).'''
'Cikatro Vizago':
name: "Сикатро Визаго"
text: '''%SCUMONLY%%LINEBREAK%В начале фазы Завершения, вы можете сбросить эту карту, чтобы заменить лежащую лицом вверх экипированную карту улучшения %ILLICIT% или %CARGO% на другую карту улучшения того же типа и той же (или меньшей) стоимости в очках отряда.'''
'Azmorigan':
name: "Азмориган"
text: '''%HUGESHIPONLY% %SCUMONLY%%LINEBREAK%В начале фазы Завершения, вы можете потратить 1 энергии, чтобы заменить экипированную лежащую лицом вверх карту улучшений %CREW% или %TEAM% на другую карту улучшения того же типа и той же (или меньшей) стоимости в очках отряда.'''
'Quick-release Cargo Locks':
name: "Замки быстрого сброса груза"
text: '''%LINEBREAK%В конце фазы Активации, вы можете сбросить эту карту, чтобы <strong>положить</strong> 1 жетон Контейнера.'''
'Supercharged Power Cells':
name: "Сверхзаряженные энергоячейки"
text: '''Атакуя, вы можете сбросить эту карту, чтобы бросить 2 дополнительных кубика атаки.'''
'ARC Caster':
name: "Проектор ARC"
text: '''<span class="card-restriction">Только для Повстанцев или Пиратов. Двойная карта.</span>%DUALCARD%%LINEBREAK%<strong>Сторона A:</strong>%LINEBREAK%<strong>Атака:</strong> Атакуйте 1 корабль. Если эта атака попадает, вы должны выбрать 1 другой корабль на расстоянии 1 от защищающегося. Этот корабль получает 1 повреждение.%LINEBREAK%Затем переверните эту карту.%LINEBREAK%<strong>Сторона Б:</strong>%LINEBREAK%(Перезарядка) В начале фазы Боя, вы можете получить жетон Отключения оружия, чтобы перевернуть эту карту.'''
'Wookiee Commandos':
name: "Вуки коммандос"
text: '''Атакуя, вы можете перебросить ваши результаты %FOCUS%.'''
'Synced Turret':
name: "Синхронная турель"
text: '''<strong>Атака (Захват цели):</strong> Атакуйте 1 корабль (даже если он находится вне вашей арки огня).%LINEBREAK%Если защищающийся находится в вашей арке огня, вы можете перебросить количество кубиков атаки, равное значению вашего основного оружия.'''
'Unguided Rockets':
name: "Неуправляемые ракеты"
text: '''<strong>Атака (Концентрация):</strong> Атакуйте 1 корабль.%LINEBREAK%Ваши кубики атаки могут быть модифицированы только с помощью использования жетона Концентрации.'''
'Intensity':
name: "Интенсивность"
text: '''%SMALLSHIPONLY% %DUALCARD%%LINEBREAK%<strong>Сторона A:</strong> После того, как вы выполните действие Ускорения или Бочку, вы можете назначить 1 жетон Концентрации или Уклонения на ваш корабль. Если вы делаете это, переверните эту карту.%LINEBREAK%<strong>Сторона Б:</strong> (Истощение) В конце фазы боя, вы можете потратить 1 жетон Концентрации или Уклонения, чтобы перевернуть эту карту.'''
'Jabba the Hutt':
name: "Джабба Хатт"
text: '''%SCUMONLY%%LINEBREAK%Когда вы экипируете эту карту, положите 1 жетон Внезаконности на каждую карту улучшения %ILLICIT% в вашем отряде. Когда вы должны сбросить карту Улучшения, вместо этого вы можете сбросить 1 жетон Внезаконности с этой карты.'''
'IG-RM Thug Droids':
name: "Дроиды-головорезы IG-RM"
text: '''Атакуя, вы можете заменить 1 из ваших результатов %HIT% на результат %CRIT%.'''
'Selflessness':
name: "Самоотверженность"
text: '''%SMALLSHIPONLY% %REBELONLY%%LINEBREAK%Когда дружественный корабльт на расстоянии 1 получает попадание от атаки, вы можете сбросить эту карту, чтобы получить все неотмененные результаты %HIT% вместо корабля-цели.'''
'Breach Specialist':
name: "Специалист по пробоинам"
text: '''Когда вы получаете карту повреждений лицом вверх, вы можете потратить 1 жетон Усиления, чтобы перевернуть ее лицом вниз (не отрабатывая ее эффект). Если вы делаете это, то до конца хода, когда вы получаете карту .'''
'Bomblet Generator':
name: "Генератор минибомб"
text: '''Когда вы открываете маневр, вы можете <strong>сбросить</strong> 1 жетон Минибомбы.%LINEBREAK%Этот жетон <strong>взрывается</strong> в конце фазы Активации.%LINEBREAK%<strong>Жетон минибомбы:</strong> Когда этот жетон взрывается, каждый корабль на расстоянии 1 бросает 2 кубика атаки и получает все выброшенные повреждения(%HIT%) и критические повреждения (%CRIT%). Затем уберите этот жетон.'''
'Cad Bane':
name: "Кэд Бэйн"
text: '''%SCUMONLY%%LINEBREAK%Ваша панель улучшений получает значок %BOMB%. Один раз за ход, когда вражеский корабль бросает кубики атаки из-за взрыва дружественной бомбы, вы можете выбрать любое количество пустых или %FOCUS% результатов. Он должен перебросить эти результаты.'''
'Minefield Mapper':
name: "Карта минных полей"
text: '''Во время расстановки, после шага "Расстановка сил", вы можете сбросить любое количество карт улучшений %BOMB%. Расположите все соответствующие жетоны бомб на игровом поле на расстоянии 3 и дальше от вражеских кораблей.'''
'R4-E1':
text: '''Вы можете выполнять действия на ваших картах улучшения %TORPEDO% и %BOMB%, даже находясь под Стрессом. После выполнения действия этим способом, вы можете сбросить эту карту, чтобы убрать 1 жетон Стресса с вашего корабля.'''
'Cruise Missiles':
name: "Крейсирующие ракеты"
text: '''<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Вы можете бросить дополнительные кубики атаки, равные по количеству скорости маневра, который вы выполнили в этот ход, до максимума в 4 дополнительных кубика.'''
'Ion Dischargers':
name: "Ионные разрядники"
text: '''После получения ионного жетона, вы можете выбрать вражеский корабль на расстоянии 1. Если вы делаете это, сбросьте ионный жетон. Затем тот корабль может решить получить 1 ионный жетон. Если он делает это - сбросьте эту карту.'''
'Harpoon Missiles':
name: "Гарпунные ракеты"
text: '''<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадает, после отрабатывания атаки, назначьте защищающемуся карту состояния "Загарпунен!".'''
'Ordnance Silos':
name: "Бомболюки"
ship: "Бомбардировщик B/SF-17"
text: '''<span class="card-restriction">Только бомбардировщик B/SF-17.</span>%LINEBREAK%Когда вы экипируете эту карту, положите 3 жетона Боеприпасов на каждую экипированную карту улучшений %BOMB%. Когда вы должны сбросить карту улучшений, вместо этого вы можете сбросить с этой карты жетон Боеприпасов.'''
'Trajectory Simulator':
name: "Симулятор траектории"
text: '''Вы можете запускать бомбы, используя шаблон (%STRAIGHT% 5) вместо того, стобы их сбрасывать. Вы не можете таким способом сбрасывать бомбы с указателем "<strong>Действие:</strong>".'''
'Jamming Beam':
name: "Луч заклинивания"
text: '''<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK%Если эта атака попадает, назначьте защищающемуся 1 жетон Заклинивания. Затем отмените <strong>все</strong> результаты кубиков.'''
'Linked Battery':
name: "Спаренная батарея"
text: '''%SMALLSHIPONLY%%LINEBREAK%Атакуя основным или %CANNON% вспомогательным оружием, вы можете перебросить 1 кубик атаки.'''
'Saturation Salvo':
name: "Плотный залп"
text: '''После того, как вы выполняете атаку вспомогательным оружием %TORPEDO% или %MISSILE%, которая не попала, каждый корабль на расстоянии 1 от защищающегося со значением Маневренности ниже, чем стоимость карты улучшения %TORPEDO% или %MISSILE% в очках отряда, должен бросить 1 кубик атаки и получить любое выброшенное повреждение (%HIT%) или критическое повреждение (%CRIT%).'''
'Contraband Cybernetics':
name: "Контрабандная кибернетика"
text: '''Когда вы становитесь активным кораблем во время фазы Активации, вы можете сбросить эту карту и получить 1 жетон стресса. Если вы делаете это, до конца хода вы можете выполнять действия и красные маневры, даже находясь под Стрессом.'''
'Maul':
name: "Мол"
text: '''%SCUMONLY% <span class="card-restriction">Игнорируйте это ограничение, если ваш отряд содержит Эзру Бриджера."</span>%LINEBREAK%Атакуя, если вы не под Стрессом, вы можете получить любое количество жетонов Стрееса, чтобы перебросить равное количество кубиков атаки.%LINEBREAK% После выполнения атаки, завершившейся попаданием, вы можете убрать 1 из ваших жетонов Стресса.'''
'Courier Droid':
name: "Дроид-курьер"
text: '''В начале шага "Расположение сил", вы можете выбрать считать ваше умение пилота равным "0" или "8" до конца этого шага.'''
'"Chopper" (Astromech)':
text: '''<strong>Действие: </strong>Сбросьте 1 другую экипированную карту улучшений, чтобы восстановить 1 щит.'''
'Flight-Assist Astromech':
name: "Полетный астромех"
text: '''Вы не можете атаковать корабли вне вашей арки огня.%LINEBREAK%После того, как вы выполните маневр, если вы не перекрываете корабль или преграду и не имеете кораблей врага в вашей арке огня на расстоянии 1-3, вы можете выполнить свободное действие Бочку или Ускорение.'''
'Advanced Optics':
name: "Улучшенная оптика"
text: '''Вы не можете иметь более 1 жетона Концентрации.%LINEBREAK%Во время фазы Завершения, не убирайте неиспользованный жетон Концентрации с вашего корабля.'''
'Scrambler Missiles':
name: "Ракеты с помехами"
text: '''<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадает, защищающийся и каждый другой корабль на расстоянии 1 получает 1 жетон Заклинивания. Затем отмените <strong>все</strong> результаты кубиков.'''
'R5-TK':
text: '''Вы можете заявлять захват цели на дружественные корабли.%LINEBREAK%Вы можете атаковать дружественные корабли.'''
'Threat Tracker':
name: "Детектор угроз"
text: '''%SMALLSHIPONLY%%LINEBREAK%Когда вражеский корабль в важей арке огня на расстоянии 1-2 становится активным кораблем во время фазы Боя, вы можете потратить захват цели на этом корабле, чтобы выполнить свободное действие Ускорение или Бочку, если оно есть на вашей панели действий.'''
'Debris Gambit':
name: "Уклонение в астероидах"
text: '''%SMALLSHIPONLY%%LINEBREAK%<strong>Действие:</strong> Назначьте 1 жетон Уклонения на ваш корабль за каждую преграду на расстоянии 1, до максимума в 2 жетона Уклонения.'''
'Targeting Scrambler':
name: "Помехи наведения"
text: '''В начале фазы Планирования, вы можете получить жетон Оружие выведено из строя, чтобы выбрать корабль на расстоянии 1-3 и назначить ему состояние "Помехи".'''
'Death Troopers':
name: "Штурмовики Смерти"
text: '''После того, как другой дружественный корабль на расстоянии 1 становится защищающимся, если вы находитесь в арке огня атакующего на расстоянии 1-3, атакующий получает 1 жетон Стресса.'''
'Saw Gerrera':
name: "Со Геррера"
text: '''%REBELONLY%%LINEBREAK%Атакуя, вы можете получить 1 повреждение, чтобы заменить все ваши результаты %FOCUS% на результаты %CRIT%.'''
'Director Krennic':
name: "Директор Кренник"
text: '''Во время расстановки, перед шагом "Расстановка сил", назначьте состояние "Оптимизированный прототип" на дружественный корабль Галактической Империи с 3 или меньшим количеством щитов.'''
'Tactical Officer':
text: '''%IMPERIALONLY%%LINEBREAK%Your action bar gains %COORDINATE%.'''
'ISB Slicer':
text: '''After you perform a jam action against an enemy ship, you may choose a ship at Range 1 of that ship that is not jammed and assign it 1 jam token.'''
'Thrust Corrector':
text: '''When defending, if you have 3 or fewer stress tokens, you may receive 1 stress token to cancel all of your dice results. If you do, add 1 %EVADE% result to your roll. Your dice cannot be modified again during this attack.%LINEBREAK%You can equip this Upgrade only if your hull value is "4" or lower.'''
modification_translations =
"Stealth Device":
name: "Маскировочное устройство"
text: """Увеличьте вашу Маневренность на 1. Если вы получаете попадание от атаки, сбросьте эту карту."""
"Shield Upgrade":
name: "Улучшенный щит"
text: """Ваше значение Щита увеличивается на 1."""
"Engine Upgrade":
name: "Улучшенный двигатель"
text: """Ваша панель действий получает значок %BOOST%."""
"Anti-Pursuit Lasers":
name: "Оборонительные лазеры"
text: """После того, как вражеский корабль выполняет маневр, приводящий к перекрытию им вашего корабля, бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, вражеский корабль получает 1 повреждение."""
"Targeting Computer":
name: "Компьютер наведения"
text: """Ваша панель действий получает значок %TARGETLOCK%."""
"Hull Upgrade":
name: "Укрепление корпуса"
text: """Ваше значение Корпуса повышается на 1."""
"Munitions Failsafe":
name: "Корректор промаха"
text: """Атакуя вспомогательным оружием, которое обязывает сбросить его для выполнения атаки, не сбрасывайте его, если атака не попала."""
"Stygium Particle Accelerator":
name: "Стигийский ускоритель частиц"
text: """Когда вы размаскировываетесь или выполняете действие Маскировки, вы можете выполнить свободное действие Уклонения."""
"Advanced Cloaking Device":
name: "Улучшеный маскировочный прибор"
text: """<span class="card-restriction">Только для TIE Фантом.</span><br /><br />После выполнения атаки, вы можете выполнить свободное действие Маскировки."""
ship: "TIE Фантом"
"Combat Retrofit":
name: "Боевое оснащение"
text: """<span class="card-restriction">Только для GR-75.</span><br /><br />Увеличьте ваше значение Корпуса на 2 и значение Щита на 1."""
ship: 'Средний транспорт GR-75'
"B-Wing/E2":
text: """<span class="card-restriction">Только для Б-Крыла.</span><br /><br />Ваша панель улучшений получает значок улучшения %CREW%."""
ship: "Б-Крыл"
"Countermeasures":
name: "Контрмеры"
text: """В начале фазы Боя, вы можете сбросить эту карту, чтобы повысить вашу Маневренность на 1 до конца хода. Затем вы можете убрать 1 вражеский захват цели с вашего корабля."""
"Experimental Interface":
name: "Экспериментальный интерфейс"
text: """Один раз за ход, после выполнения вами действия, вы можете выполнить 1 свободное действие с экипированной карты улучшений с указателем "<strong>Действие:</strong>". Затем получите 1 жетон Стресса."""
"Tactical Jammer":
name: "Тактический глушитель"
text: """Ваш корабль может служить преградой для вражеских атак."""
"Autothrusters":
name: "Автоускорители"
text: """Защищаясь, еслим вы далее расстояния 2 или находитесь вне арки огня атакующего, вы можете заменить 1 из ваших пустых результатов на результат %EVADE%. Вы можете экипировать это карту только при наличии значка %BOOST%."""
"Twin Ion Engine Mk. II":
name: "Двойной ионный двигатель Мк.II"
text: """<span class="card-restriction">Только для TIE.</span>%LINEBREAK%Вы можете считать все маневры крена (%BANKLEFT% и %BANKRIGHT%) зелеными маневрами."""
"Maneuvering Fins":
name: "Маневровые кили"
text: """<span class="card-restriction">Только для YV-666.</span>%LINEBREAK%Когда вы открываете маневр поворота (%TURNLEFT% или %TURNRIGHT%), вы можете повернуть ваш диск маневров на соответствующий маневр крена (%BANKLEFT% или %BANKRIGHT%) с той же скоростью."""
"Ion Projector":
name: "Ионный проектор"
text: """%LARGESHIPONLY%%LINEBREAK%После того, как вражеский корабль выполняет маневр, приводящий к перекрытию им вашего корабля, бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, вражеский корабль получает 1 ионный жетон."""
"Advanced SLAM":
name: "Улучшенный ССДУ"
text: """После выполнения действия ССДУ, если вы не перекрываете преграду или другой корабль, вы можете выполнить свободное действие с вашей панели действий."""
'Integrated Astromech':
name: "Интегрированный астромех"
text: '''<span class="card-restriction">Только для Икс-Крыла.</span>%LINEBREAK%Когда вы получаете карту повреждений, вы можете сбросить 1 из ваших карту улучшений %ASTROMECH% чтобы сбросить эту карту повреждений.'''
'Optimized Generators':
name: "Оптимизированные генераторы"
text: '''%HUGESHIPONLY%%LINEBREAK%Один раз за ход, когда вы назначаете энергию на экипированную карту улучшений, получите 2 энергии.'''
'Automated Protocols':
name: "Автоматизированные протоколы"
text: '''%HUGESHIPONLY%%LINEBREAK%Один раз за ход, после выполнения действия, не являющегося действием Восстановления или Усиления, вы можете потратить 1 энергии, чтобы выполнить свободное действие Восстановления или Усиления.'''
'Ordnance Tubes':
name: "Ракетные шахты"
text: '''%HUGESHIPONLY%%LINEBREAK%Вы можете считать каждый из ваших значков улучшений %HARDPOINT% как значок %TORPEDO% или %MISSILE%.%LINEBREAK%Когда вы должны сбросить карту улучшений %TORPEDO% или %MISSILE%, не сбрасывайте ее.'''
'Long-Range Scanners':
name: "Сканеры дальнего действия"
text: '''Вы можете объявлять захват цели на корабли на расстоянии 3 и дальше. Вы не можете объявлять захват цели на корабли на расстоянии 1-2. Вы можете екипировать эту карту только если у вас есть %TORPEDO% и %MISSILE% на вашей панели улучшений.'''
"Guidance Chips":
name: "Чипы наведения"
text: """Один раз за ход, атакуя вспомогательным оружием %TORPEDO% или %MISSILE%, вы можете заменить один результат кубика на %HIT% (или на результат %CRIT% , если значение вашего основного оружия "3" или больше)."""
'Vectored Thrusters':
name: "Векторные ускорители"
text: '''%SMALLSHIPONLY%%LINEBREAK%Ваша панель действий получает значок %BARRELROLL%.'''
'Smuggling Compartment':
name: "Отсек контрабанды"
text: '''<span class="card-restriction">Только для YT-1300 и YT-2400.</span>%LINEBREAK%Ваша панель улучшений получает значок %ILLICIT%.%LINEBREAK%Вы можете экипировать 1 дополнительное Модификационное улучшение, которое стоит 3 или меньше очков отряда.'''
'Gyroscopic Targeting':
name: "Гироскопическое наведение"
ship: "Корабль-преследователь класса Копьеносец"
text: '''<span class="card-restriction">Только для Корабля-преследователя класса Копьеносец.</span>%LINEBREAK%В конце фазы Боя, если в этом ходу вы выполняли маневр со скоростью 3, 4 или 5, вы можете повернуть вашу мобильную арку огня.'''
'Captured TIE':
ship: "TIE истребитель"
name: "TIE захваченный"
text: '''<span class="card-restriction">только для TIE.</span>%REBELONLY%%LINEBREAK%Вражеские корабли с умением пилота ниже вашего не могут объявлять вас целью атаки. После того, как вы выполните атаку или останетесь единственным дружественным кораблем, сбросьте эту карту.'''
'Spacetug Tractor Array':
name: "Матрица космической тяги"
ship: "Квадджампер"
text: '''<span class="card-restriction">Только для Квадджампера.</span>%LINEBREAK%<strong>Действие:</strong> Выберите корабль в вашей арке огня на расстоянии 1 и назначьте ему жетон Луча Захвата. Если это дружественный корабль, отработайте эффект жетона Луча Захвата, как если бы это был вражеский корабль.'''
'Lightweight Frame':
name: "Облегченный каркас"
text: '''<span class="card-restriction">только для TIE.</span>%LINEBREAK%Защищаясь, после броска кубиков защиты, если кубиков атаки больше, чем кубиков защиты, бросьте 1 дополнительный кубик защиты.%LINEBREAK%Вы не можете экипировать эту карту, если ваша Маневренность "3" или выше.'''
'Pulsed Ray Shield':
name: "Импульсный лучевой щит"
text: '''<span class="card-restriction">Только для Повстанцев и Пиратов.</span>%LINEBREAK%Во время фазы Завершения, вы можете получить 1 ионный жетон чтобы восстановить 1 щит (до максимального значения щитов). Вы можете экипировать эту карту только если ваше значение Щитов "1".'''
'Deflective Plating':
name: "Отражающее покрытие"
ship: "Бомбардировщик B/SF-17"
text: '''<span class="card-restriction">Только для бомбардировщика B/SF-17.</span>%LINEBREAK%Когда взрывается дружественный жетон бомбы, вы можете выбрать не получать соответствующий эффект. Если вы делаете это, бросьте кубик атаки. При результате %HIT%, сбросьте эту карту.'''
'Multi-spectral Camouflage':
text: '''%SMALLSHIPONLY%%LINEBREAK%After you receive a red target lock token, if you have only 1 red target lock token, roll 1 defense die. On an %EVADE% result, remove 1 red target lock token.'''
title_translations =
"Slave I":
name: "Раб 1"
text: """<span class="card-restriction">Только для Огнедыщащего-31.</span><br /><br />Ваша панель улучшений получает значок улучшения %TORPEDO%."""
"Millennium Falcon":
name: "Тысячелетний сокол"
text: """<span class="card-restriction">Только для YT-1300.</span><br /><br />Ваша панель действий получает значок %EVADE%."""
"Moldy Crow":
name: "Старый ворон"
text: """<span class="card-restriction">Только для HWK-290.</span><br /><br />Во время фазы Завершения, не убирайте неиспользованные жетоны Концентрации с вашего корабля."""
"ST-321":
text: """<span class="card-restriction">Только для шаттла класса <em>Лямбда</em>.</span><br /><br />При объявлении захвата цели, вы можете захватывать вражеский корабль по всему игровому полю."""
ship: "Шаттл класса Лямбда"
"Royal Guard TIE":
name: "TIE королевской стражи"
ship: "TIE перехватчик"
text: """<span class="card-restriction">Только для TIE перехватчика.</span><br /><br />Вы можете экипировать до двух различных Модификационных улучшений (вместо 1).<br /><br />Вы не можете экипировать эту карту, если ваше умение пилота "4" или ниже."""
"Dodonna's Pride":
name: "Гордость Додонны"
text: """<span class="card-restriction">Только для носовой части CR90.</span><br /><br />Когда вы выполняете действие Координации, вы можете выбрать 2 дружественных корабля (вместо 1). Каждый из этих кораблей может выполнить 1 свободное действие."""
ship: "Корвет CR90 (Нос)"
"A-Wing Test Pilot":
name: "Пилот-испытатель А-Крыла"
text: """<span class="card-restriction">Только для А-Крыла.</span><br /><br />Ваша панель улучшений получает 1 значок %ELITE%.<br /><br />Вы не можете экипировать 2 одинаковых карты улучшений %ELITE%. Вы не можете экипировать эту карту, если ваше умение пилота "1" или ниже."""
ship: "А-Крыл"
"Tantive IV":
name: "Тантив IV"
text: """<span class="card-restriction">Только для носовой части CR90.</span><br /><br />Ваша панель улучшений носовой секции получает 1 дополнительный значок %CREW% и 1 дополнительный значок %TEAM%."""
ship: "Корвет CR90 (Нос)"
"Bright Hope":
name: "Яркая Надежда"
text: """<span class="card-restriction">Только для GR-75.</span><br /><br />Действие усиления, назначенное на вашу носовую часть, добавляет 2 результата %EVADE% вместо 1."""
ship: 'Средний транспорт GR-75'
"Quantum Storm":
name: "Квантовый шторм"
text: """<span class="card-restriction">Только для GR-75.</span><br /><br />В начале фазы Завершения, если у вас 1 или меньше жетонов энергии, получите 1 жетон энергии."""
ship: 'Средний транспорт GR-75'
"Dutyfree":
name: "Дьюти-фри"
text: """<span class="card-restriction">Только для GR-75./span><br /><br />При выполнении действия Заклинивания, вы можете выбрать вражеский корабль на расстоянии 1-3 (вместо 1-2)."""
ship: 'Средний транспорт GR-75'
"Jaina's Light":
name: "Свет Джайны"
text: """<span class="card-restriction">Только для носовой секции CR90.</span><br /><br />Защищаясь, один раз за атаку, если вы получаете карту повреждений лицом вверх, вы можете сбросить ее и вытянуть другую карту повреждений лицом вверх."""
"Outrider":
name: "Наездник"
text: """<span class="card-restriction">Только для YT-2400.</span><br /><br />Когда у вас есть экипированная карта улучшения %CANNON%, вы <strong>не можете</strong> выполнять атаки основным оружием и можете выполнять атаки вспомогательным оружием %CANNON% против кораблей вне вашей арки огня."""
"Andrasta":
name: "Андраста"
text: """<span class="card-restriction">Только для Огнедышащего-31.</span><br /><br />Ваша панель улучшений получает 2 дополнительных значка %BOMB%."""
"TIE/x1":
ship: "TIE улучшенный"
text: """<span class="card-restriction">Только для TIE улучшенного.</span>%LINEBREAK%Ваша панель улучшений получает значок %SYSTEM%.%LINEBREAK%Если вы экипируете улучшение %SYSTEM%, его стоимость в очках отряда снижается на 4 (до минимума в 0)."""
"BTL-A4 Y-Wing":
name: "BTL-A4 У-Крыл"
text: """<span class="card-restriction">Только для У-Крыла.</span><br /><br />Вы не можете атаковать корабли вне вашей арки огня. После выполнения атаки основным оружием, вы можете немедленно выполнить атаку вспомогательным оружием %TURRET%."""
ship: "У-Крыл"
"IG-2000":
name: "IG-2000"
text: """<span class="card-restriction">Только для Агрессора.</span><br /><br />Вы получаете способности пилотов каждого другого дружественного корабля с картой улучшения <em>IG-2000</em> (в дополнение к вашей собственной способности пилота)."""
ship: "Агрессор"
"Virago":
name: "Мегера"
text: """<span class="card-restriction">Только для Звездной Гадюки.</span><br /><br />Ваша панель улучшений получает значки %SYSTEM% и %ILLICIT%.<br /><br />Вы не можете экипировать эту карту, если ваше умение пилота "3" или ниже."""
ship: 'Звездная гадюка'
'"Heavy Scyk" Interceptor (Cannon)':
name: 'Перехватчик "Тяжелый Сцик" (Пушечный)'
text: """<span class="card-restriction">Только для перехватчика M3-A.</span><br /><br />Ваша панель улучшений получает значок %CANNON%. Ваше значение Корпуса повышается на 1."""
ship: 'Перехватчик M3-A'
'"Heavy Scyk" Interceptor (Missile)':
name: 'Перехватчик "Тяжелый Сцик" (Ракетный)'
text: """<span class="card-restriction">Только для перехватчика M3-A.</span><br /><br />Ваша панель улучшений получает значок %MISSILE%. Ваше значение Корпуса повышается на 1."""
ship: 'Перехватчик M3-A'
'"Heavy Scyk" Interceptor (Torpedo)':
name: 'Перехватчик "Тяжелый Сцик" (Торпедный)'
text: """<span class="card-restriction">Только для перехватчика M3-A.</span><br /><br />Ваша панель улучшений получает значок %TORPEDO%. Ваше значение Корпуса повышается на 1."""
ship: 'Перехватчик M3-A'
"Dauntless":
name: "Неустрашимый"
text: """<span class="card-restriction">Только для VT-49 Дециматора.</span><br /><br />После выполнения маневра, который привел к наложению на другой корабль, вы можете выполнить 1 свободное действие. Затем получите 1 жетон Стресса."""
ship: 'VT-49 Дециматор'
"Ghost":
name: "Призрак"
text: """<span class="card-restriction">Только для VCX-100.</span>%LINEBREAK%Екипируйте карту названия <em>Фантом</em> на дружественный Атакующий Шаттл, и пристыкуйте его к этому кораблю.%LINEBREAK%После выполнения маневра, вы можете отстыковать его из ваших задних направляющих."""
"Phantom":
name: "Фантом"
text: """Когда вы пристыкованы, <em>Призрак</em> может выполнять атаки его основным оружием, используя его специальную арку огня, а также, в конце фазы Боя, он может выполнить дополнительную атаку экипированной %TURRET%. Если он не может выполнить эту атаку, он не может атаковать снова в этот ход."""
ship: 'Атакующий шаттл'
"TIE/v1":
text: """<span class="card-restriction">Только для TIE улучшенного прототипа.</span>%LINEBREAK%После того, как вы получаете захват цели на другой корабль, вы можете выполнить свободное действие Уклонения."""
ship: 'TIE улучшенный прототип'
"Mist Hunter":
name: "Туманный охотник"
text: """<span class="card-restriction">Только для Звездного истребителя G-1A.</span>%LINEBREAK%Ваша панель действий получает значок %BARRELROLL%.%LINEBREAK%Вы <strong>должны</strong> экипировать 1 карту улучшений "Луч захвата"(считая ее стоимость в очках отряда как обычно)."""
ship: 'Звездный истребитель G-1A'
"Punishing One":
name: "Карающий Один"
text: """<span class="card-restriction">Только для Джампмастера 5000.</span>%LINEBREAK%Увеличивает значение вашего основного оружия на 1."""
ship: 'Джампмастер 5000'
"Hound's Tooth":
name: "Зуб гончей"
text: """<span class="card-restriction">Только для YV-666.</span>%LINEBREAK%После того, как вы уничтожены, но перед тем, как убрать корабль с игрового поля, вы можете </strong>выставить корабль <span>Щенок Наштаха</span>.%LINEBREAK%El <span>Щенок Наштаха</span> не может атаковать в этот ход."""
"Assailer":
name: "Наступающий"
text: """<span class="card-restriction">Только для кормовой секции корвета класса <em>Рейдер</em>.</span>%LINEBREAK%Защищаясь, если целевая секция имеет жетон Усиления, вы можете заменить 1 результат %FOCUS% на 1 результат %EVADE%."""
"Instigator":
name: "Зачинщик"
text: """<span class="card-restriction">Только для кормовой секции корвета класса <em>Рейдер</em>.</span>%LINEBREAK%После того, как вы выполняете действие Восстановления, восстановите 1 дополнительный щит."""
"Impetuous":
name: "Бушующий"
text: """<span class="card-restriction">Только для кормовой секции корвета класса <em>Рейдер</em>.</span>%LINEBREAK%После того, как вы выполняете атаку, уничтожившую вражеский корабль, вы можете получить захват цели."""
'TIE/x7':
text: '''<span class="card-restriction">Только для TIE защитника.</span>%LINEBREAK%Ваша панель улучшений теряет значки улучшений %CANNON% и %MISSILE%.%LINEBREAK%После выполнения маневра со скоростью 3, 4 или 5, если вы не перекрываете преграду или корабль, вы можете выполнить свободное действие Уклонения.'''
ship: 'TIE защитник'
'TIE/D':
text: '''<span class="card-restriction">Только для TIE защитника.</span>%LINEBREAK%Один раз за ход, после того, как вы выполнили атаку вспомогательным оружием %CANNON%, которое стоит 3 или менее очков отряда, вы можете выполнить атаку основным оружием.'''
ship: 'TIE защитник'
'TIE Shuttle':
name: "TIE шаттл"
text: '''<span class="card-restriction">Только для TIE бомбардировщика.</span>%LINEBREAK%Ваша панель улучшений теряет все значки улучшений %TORPEDO%, %MISSILE% и %BOMB% и получает 2 значка улучшений %CREW%. Вы не можете экипировать карту улучшений %CREW%, которая стоит больше 4 очков отряда.'''
ship: 'TIE бомбардировщик'
'Requiem':
name: "Реквием"
text: '''%GOZANTIONLY%%LINEBREAK%Когда вы выставляете корабль, считайте его навык пилота равным "8" до конца хода.'''
'Vector':
name: "Вектор"
text: '''%GOZANTIONLY%%LINEBREAK%После выполнения маневра, вы можете разместить до 4 присоединенных кораблей (вместо 2).'''
'Suppressor':
name: "Подавитель"
text: '''%GOZANTIONLY%%LINEBREAK%Один раз за ход, после получения захвата цели на врага, вы можете убрать 1 жетон Концентрации, Уклонения или синий жетон захвата цели с этого корабля.'''
'Black One':
name: "Черный Один"
text: '''<span class="card-restriction">Только для Икс-Крыла Т-70.</span>%LINEBREAK%После того, как вы выполнили действие Ускорения или Бочку, вы можете снять 1 вражеский захват цели с дружественного корабля на расстоянии 1. Вы не можете экипировать эту карту, если ваш навык пилота "6" или ниже.'''
ship: "Икс-Крыл T-70"
'Millennium Falcon (TFA)':
name: "Тысячелетний Сокол (ПС)"
text: '''После выполнения маневра крена со скоростью 3 (%BANKLEFT% или %BANKRIGHT%), если вы не касаетесь другого корабля и не находитесь под Стрессом, вы можете получить 1 жетон Стресса, чтобы развернуть ваш корабль на 180°.'''
'Alliance Overhaul':
name: "Обновления Альянса"
text: '''<span class="card-restriction">Только для ARC-170.</span>%LINEBREAK%Атакуя основным оружием в вашей основной арке огня, вы можете бросить 1 дополнительный кубик атаки. Атакуя в вашей дополнительной арке огня, вы можете заменить 1 из ваших результатов %FOCUS% на 1 результат %CRIT%.'''
'Special Ops Training':
ship: "Истребитель TIE/сс"
name: "Специальная оперативная подготовка"
text: '''<span class="card-restriction">Только для TIE/сс.</span>%LINEBREAK%Атакуя основным оружием в вашей основной арке огня, вы можете бросить 1 дополнительный кубик атаки. Если вы не делаете этого, вы можете выполнить дополнительную атаку в вашей вспомогательной арке огня.'''
'Concord Dawn Protector':
name: "Протектор Рассвета Конкорда"
ship: "Истребитель Протектората"
text: '''<span class="card-restriction">Только для истребителя Протектората.</span>%LINEBREAK%Защищаясь, если вы назходитесь в арке огня атакующего на расстоянии 1, и атакующий находится в вашей арке огня, добавьте 1 результат %EVADE%.'''
'Shadow Caster':
name: "Наводящий Тень"
ship: "Корабль-преследователь класса Копьеносец"
text: '''<span class="card-restriction">Только для Корабля-преследователя класса Копьеносец</span>%LINEBREAK%После того, как вы выполнили атаку, которая попала, если защищающийся находится в вашей мобильной арке огня на расстоянии 1-2, вы можете назначить защищающемуся 1 жетон Луча захвата.'''
# Wave X
'''Sabine's Masterpiece''':
ship: "TIE истребитель"
name: "Шедевр Сабины"
text: '''<span class="card-restriction">Только для TIE истребителя.</span>%REBELONLY%%LINEBREAK%Ваша панель улучшений получает значки улучшений %CREW% и %ILLICIT%.'''
'''Kylo Ren's Shuttle''':
ship: "Шаттл класса Ипсилон"
name: "Шаттл Кайло Рена"
text: '''<span class="card-restriction">Только для шаттла класса Ипсилон.</span>%LINEBREAK%В конце фазы Боя, выберите вражеский корабль на расстоянии 1-2, не имеющий стресса. Его владелец должен назначить ему жетон Стресса, или назначить жетон Стресса на другой его корабль на расстоянии 1-2 от вас.'''
'''Pivot Wing''':
name: "Поворотное крыло"
ship: "Ю-Крыл"
text: '''<span class="card-restriction">Только для Ю-Крыла.</span> %DUALCARD%%LINEBREAK%<strong>Сторона A (Боевое положение):</strong> Ваша Маневренность увеличивается на 1.%LINEBREAK%После выполнения маневра, вы можете перевернуть эту карту.%LINEBREAK%<strong>Сторона Б (Положение посадки):</strong> Когда вы открываете маневр (%STOP% 0), вы можете повернуть ваш корабль на 180°.%LINEBREAK%После выполнения маневра, вы можете перевернуть эту карту.'''
'''Adaptive Ailerons''':
name: "Адаптивные элероны"
ship: "TIE ударник"
text: '''<span class="card-restriction">Только для TIE ударника.</span>%LINEBREAK%Сразу перед открытием вашего диска, если у вас нет Стресса, вы <strong>должны</strong> выполнить белый маневр (%BANKLEFT% 1), (%STRAIGHT% 1) или (%BANKRIGHT% 1).'''
# C-ROC
'''Merchant One''':
name: "Торговец"
ship: "Крейсер C-ROC"
text: '''<span class="card-restriction">Только для крейсера C-ROC.</span>%LINEBREAK%Ваша панель улучшений получает 1 дополнительный значок улучшения %CREW% и 1 дополнительный значок улучшения %TEAM%, а также теряет 1 значок улучшения %CARGO%.'''
'''"Light Scyk" Interceptor''':
name: 'Перехватчик "Легкий Сцик"'
ship: "Перехватчик M3-A"
text: '''<span class="card-restriction">Только для Перехватчика M3-A.</span>%LINEBREAK%Все получаемые вами карты повреждений отрабатываются в открытую. Вы можете считать все маневры крена (%BANKLEFT% или %BANKRIGHT%) зелеными маневрами. Вы не можете экипировать Модификационные улучшения.'''
'''Insatiable Worrt''':
name: "Ненасытный Воррт"
ship: "Крейсер C-ROC"
text: '''После выполнения действия Восстановления, получите 3 энергии.'''
'''Broken Horn''':
name: "Сломанный Рог"
ship: "Крейсер C-ROC"
text: '''Защищаясь, если у вас есть жетон Усиления, вы можете добавить дополнительный результат %EVADE%. Если вы делаете это, после защиты, сбросьте ваш жетон Усиления.'''
'Havoc':
name: "Разрушение"
ship: "Бомбардировщик Скуррг H-6"
text: '''<span class="card-restriction">Только для бомбардировщика Скуррг H-6.</span>%LINEBREAK%Ваша панель улучшений получает значки %SYSTEM% и %SALVAGEDASTROMECH% и теряет значок улучшения %CREW%.%LINEBREAK%Вы не можете экипировать неуникальные карты улучшения %SALVAGEDASTROMECH%.'''
'Vaksai':
name: "Ваксай"
ship: "Истребитель Кихраксз"
text: '''<span class="card-restriction">Только для истребителя Кихраксз.</span>%LINEBREAK%Стоимость в очках отряда для каждого из экипированных улучшений снижается на 1 (до минимума в 0).%LINEBREAK%Вы можете экипировать до 3 различных Модификационных улучшений.'''
'StarViper Mk. II':
name: "Звездная Гадюка Мк.II"
ship: "Звездна Гадюка"
text: '''<span class="card-restriction">Только для Звездной Гадюки.</span>%LINEBREAK%Вы можете экипировать до 2 различных улучшений Названий.%LINEBREAK%Выполняя действие Бочку, вы <strong>должны</strong> использовать шаблон (%BANKLEFT% 1) или (%BANKRIGHT% 1) вместо шаблона (%STRAIGHT% 1).'''
'XG-1 Assault Configuration':
ship: "Звездное Крыло класса Альфа"
name: "Штурмовая конфигурация XG-1"
text: '''<span class="card-restriction">Только для Звездного Крыла класса Альфа.</span>%LINEBREAK%Ваша панель улучшений получает 2 значка %CANNON%.%LINEBREAK%Вы можете выполнять атаки вспомогательным оружием %CANNON%, стоящим 2 или менее очков отряда, даже если у вас есть жетон Выведения оружия из строя.'''
'Enforcer':
name: "Инфорсер"
ship: "Истребитель M12-L Кимогила"
text: '''<span class="card-restriction">Только для истребителя M12-L Кимогила.</span>%LINEBREAK%После защиты, если атакующий находится в вашей арки прицельного огня, атакующий получает 1 жетон Стресса.'''
'Ghost (Phantom II)':
name: "Призрак (Фантом II)"
text: '''<span class="card-restriction">Только для VCX-100.</span>%LINEBREAK%Экипируйте карту Названия <em>Фантом II</em> на дружественный шаттл класса <em>Колчан</em> и пристыкуйте его к вашему кораблю.%LINEBREAK%После выполнения маневра, вы можете отстыковать его с ваших задних направляющих.'''
'Phantom II':
name: "Фантом II"
ship: "Шаттл класса Колчан"
text: '''Когда вы пристыкованы, <em>Призрак</em> может выполнять атаки основным оружием в своей специальной арке огня.%LINEBREAK%Пока вы пристыкованы, до конца фазы Активации, <em>Призрак</em> может выполнять свободное действие Координации.'''
'First Order Vanguard':
name: "Авангард Первого Порядка"
ship: "TIE глушитель"
text: '''<span class="card-restriction">Только для TIE глушителя.</span>%LINEBREAK%Атакуя, если ащищающийся - единственный вражеский корабль в вашей арке огня на расстоянии 1-3, вы можете перебросить 1 кубик атаки.%LINEBREAK%Защищаясь, вы можете сбросить эту карту, чтобы перебросить все ваши кубики защиты.'''
'Os-1 Arsenal Loadout':
name: "Загрузка арсенала Os-1"
ship: "Звездное Крыло класса Альфа"
text: '''<span class="card-restriction">Только для Звездного Крыла класса Альфа.</span>%LINEBREAK%Ваша панель улучшений получает значки %TORPEDO% и %MISSILE%.%LINEBREAK%Вы можете выполнять атаки вспомогательным оружием %TORPEDO% и %MISSILE% против кораблей, находящихся в вашем захвате, даже если у вас есть жетон Оружия выведенного из строя.'''
'Crossfire Formation':
name: "Построение перекрестного огня"
ship: "Бомбардировщик B/SF-17"
text: '''<span class="card-restriction">Только для Бомбардировщика B/SF-17.</span>%LINEBREAK%Защищаясь, если есть по меньшей мере 1 дружественный корабль Сопротивления на расстоянии 1-2 от атакующего, вы можете добавить 1 результат %FOCUS% к вашему броску.'''
'Advanced Ailerons':
text: '''<span class="card-restriction">TIE Reaper only.</span>%LINEBREAK%Treat your (%BANKLEFT% 3) and (%BANKRIGHT% 3) maneuvers as white.%LINEBREAK%Immediately before you reveal your dial, if you are not stressed, you must execute a white (%BANKLEFT% 1), (%STRAIGHT% 1), or (%BANKRIGHT% 1) maneuver.'''
condition_translations =
'''I'll Show You the Dark Side''':
name: "Я Покажу Тебе Темную Сторону"
text: '''Когда эта карта назначена, если она уже не находится в игре, игрок, который ее назначил, выбирает из колоды 1 карту повреждений с указателем <strong><em>Пилот</em></strong> и может положить ее на эту карту лицом вверх. Затем перетасуйте колоду карт повреждений.%LINEBREAK% Когда вы получаете критическое повреждение во время атаки, вместо него вы отрабатываете выбранную карту повреждений.%LINEBREAK%Когда на этой карте нет больше карты повреждений, уберите ее.'''
'Suppressive Fire':
name: "Подавляющий огонь"
text: '''Атакуя корабль, не являющийся кораблем "Капитан Рекс", бросьте на 1 кубик атаки меньше.%LINEBREAK% Когда вы объявляете атаку против "Капитана Рекса" или "Капитан Рекс" уничтожен - уберите эту карту.%LINEBREAK%В конце фазы Боя, если "Капитан Рекс" не выполнял атаку в эту фазу, уберите эту карту.'''
'Fanatical Devotion':
name: "Фанатическая преданность"
text: '''Защищаясь, вы не можете использовать жетоны Концентрации.%LINEBREAK%Атакуя, если вы используете жетон Концентрации, чтобы заменить все результаты %FOCUS% на результаты %HIT%, отложите в сторону первый результат %FOCUS%, который вы заменили. Отставленный в сторону результат %HIT% не может быть отменен кубиками защиты, но защищающийся может отменять результаты %CRIT% до него.%LINEBREAK%Во время фазы Завершения, уберите эту карту.'''
'A Debt to Pay':
name: "Счет к оплате"
text: '''Атакуя корабль, имеющий карту улучшения "Личные счеты", вы можете заменить 1 результат %FOCUS% на результат %CRIT%.'''
'Shadowed':
name: "Затененный"
text: '''"Твик" считается имеющим значение умения пилота, которое у вас было после фазы расстановки.%LINEBREAK%Умение пилота "Твика" не меняется, если ваше значение умения пилота изменяется или вы уничтожены.'''
'Mimicked':
name: "Мимикрированный"
text: '''"Твик" считается имеющим вашу способность пилота.%LINEBREAK%"Твик" не может применить карту Состояния, используя вашу способность пилота.%LINEBREAK%"Твик" не теряет вашу способность пилота, если вы уничтожены.'''
'Harpooned!':
name: "Загарпунен!"
text: '''Когда в вас попадает атака, если хотя бы 1 результат %CRIT% не отменен, каждый другой корабль на расстоянии 1 получает 1 повреждение. Затем сбросьте эту карту и получите 1 карту повреждений лицом вниз.%LINEBREAK%Когда вы уничтожены, каждый корабль на расстоянии 1 получает 1 повреждение.%LINEBREAK%<strong>Действие:</strong> Сбросьте эту карту. Затем бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, получите 1 повреждение.'''
'Rattled':
name: "Разбитый"
text: '''Когда вы получаете повреждение или критическое повреждение от бомбы, вы получаете 1 дополнительное критическое повреждение. Затем сбросьте эту карту.%LINEBREAK%<strong>Действие:</strong> Бросьте 1 кубик атакию. При результате %FOCUS% или %HIT%, сбросьте эту карту.'''
'Scrambled':
name: "Помехи"
text: '''Атакуя корабль на расстоянии 1, оснащенный улучшением "Помехи наведения", вы не можете модифицировать кубики атаки.%LINEBREAK%В конце фазы Боя, сбросьте эту карту.'''
'Optimized Prototype':
name: "Оптимизированный прототип"
text: '''Increase your shield value by 1.%LINEBREAK%Once per round, when performing a primary weapon attack, you may spend 1 die result to remove 1 shield from the defender.%LINEBREAK%After you perform a primary weapon attack, a friendly ship at Range 1-2 equipped with the "Director Krennic" Upgrade card may acquire a target lock on the defender.'''
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations, condition_translations | 102562 | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.ru = 'Русский'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations['Русский'] =
action:
"Barrel Roll": "Бочка"
"Boost": "Ускорение"
"Evade": "Уклонение"
"Focus": "Концентрация"
"Target Lock": "Захват цели"
"Recover": "Восстановление"
"Reinforce": "Усиление"
"Jam": "Заклинивание"
"Coordinate": "Координирование"
"Cloak": "Маскировка"
slot:
"Astromech": "Дроид-астромех"
"Bomb": "Бомба"
"Cannon": "Пушка"
"Crew": "Экипаж"
"Elite": "Элитный навык"
"Missile": "Ракета"
"System": "Система"
"Torpedo": "Торпеда"
"Turret": "Турель"
"Cargo": "Груз"
"Hardpoint": "Тяжелая установка"
"Team": "Команда"
"Illicit": "Незаконное"
"Salvaged Astromech": "Трофейный астромех"
"Tech": "Техника"
sources: # needed?
"Core": "Базовый набор"
"A-Wing Expansion Pack": "Дополнение А-Крыл"
"B-Wing Expansion Pack": "Дополнение Б-Крыл"
"X-Wing Expansion Pack": "Дополнение Икс-Крыл"
"Y-Wing Expansion Pack": "Дополнение У-Крыл"
"Millennium Falcon Expansion Pack": "Дополнение Тысячелетний Сокол"
"HWK-290 Expansion Pack": "Дополнение HWK-290"
"TIE Fighter Expansion Pack": "Дополнение TIE-истребитель"
"TIE Interceptor Expansion Pack": "Дополнение TIE-перехватчик"
"TIE Bomber Expansion Pack": "Дополнение TIE-бомбардировщик"
"TIE Advanced Expansion Pack": "Дополнение TIE-улучшенный"
"Lambda-Class Shuttle Expansion Pack": "Дополнение Шаттл класса Лямбда"
"Slave I Expansion Pack": "Дополнение Раб-1"
"Imperial Aces Expansion Pack": "Дополнение Имперские асы"
"Rebel Transport Expansion Pack": "Дополнение Транспорт повстанцев"
"Z-95 Headhunter Expansion Pack": "Дополнение Z-95 Охотник за головами"
"TIE Defender Expansion Pack": "Дополнение TIE-защитник"
"E-Wing Expansion Pack": "Дополнение Е-Крыл"
"TIE Phantom Expansion Pack": "Дополнение TIE-фантом"
"Tantive IV Expansion Pack": "Дополнение Тантив IV"
"Rebel Aces Expansion Pack": "Дополнение Асы повстанцев"
"YT-2400 Freighter Expansion Pack": "Дополнение Грузовоз YT-2400"
"VT-49 Decimator Expansion Pack": "Дополнение VT-49 Дециматор"
"StarViper Expansion Pack": "Дополнение Звездная Гадюка"
"M3-A Interceptor Expansion Pack": "Дополнение Перехватчик M3-A"
"IG-2000 Expansion Pack": "Дополнение IG-2000"
"Most Wanted Expansion Pack": "Дополнение Самые разыскиваемые"
"Imperial Raider Expansion Pack": "Дополнение Имперский рейдер"
"K-Wing Expansion Pack": "Дополнение К-Крыл"
"TIE Punisher Expansion Pack": "Дополнение TIE-каратель"
"Kihraxz Fighter Expansion Pack": "Дополнение Истребитель Кихраксз"
"Hound's Tooth Expansion Pack": "Дополнение Зуб Гончей"
"The Force Awakens Core Set": "Базовый набор Пробуждение Силы"
"T-70 X-Wing Expansion Pack": "Дополнение Икс-Крыл T-70"
"TIE/fo Fighter Expansion Pack": "Дополнение Истребитель TIE/пп"
"Imperial Assault Carrier Expansion Pack": "Дополнение Имперский штурмовой носитель"
"Ghost Expansion Pack": "Дополнение Призрак"
"Inquisitor's TIE Expansion Pack": "Дополнение TIE инквизитора"
"Mist Hunter Expansion Pack": "Дополнение Туманный охотник"
"Punishing One Expansion Pack": "Дополнение Карающий Один"
"Imperial Veterans Expansion Pack": "Дополнение Имперские ветераны"
"Protectorate Starfighter Expansion Pack": "Дополнение Звездный истребитель Протектората"
"Shadow Caster Expansion Pack": "Дополнение Наводящий Тень"
"Special Forces TIE Expansion Pack": "Дополнение TIE специальных сил"
"ARC-170 Expansion Pack": "Дополнение ARC-170"
"U-Wing Expansion Pack": "Дополнение Ю-Крыл"
"TIE Striker Expansion Pack": "Дополнение TIE-ударник"
"Upsilon-class Shuttle Expansion Pack": "Дополнение Шаттл класса Ипсилон"
"Sabine's TIE Fighter Expansion Pack": "Дополнение TIE-истребитель Сабины"
"Quadjumper Expansion Pack": "Дополнение Квадджампер"
"C-ROC Cruiser Expansion Pack": "Дополнение Крейсер C-ROC"
"TIE Aggressor Expansion Pack": "Дополнение TIE-агрессор"
"Scurrg H-6 Bomber Expansion Pack": "Дополнение Бомбардировщик Скуррг H-6"
"Auzituck Gunship Expansion Pack": "Дополнение Канонерка Озитук"
"TIE Silencer Expansion Pack": "Дополнение TIE-глушитель"
"Alpha-class Star Wing Expansion Pack": "Pасширение Звездноое Крыло Альфа-класса"
"Resistance Bomber Expansion Pack": "Дополнение Бомбардировщик сопротивления"
"Phantom II Expansion Pack": "Дополнение Фантом II"
"Kimogila Fighter Expansion Pack": "Дополнение Истребитель Кимогила"
ui:
shipSelectorPlaceholder: "Выбор корабля"
pilotSelectorPlaceholder: "Выбор пилота"
upgradePlaceholder: (translator, language, slot) ->
switch slot
when 'Elite'
"Элитный навык"
when 'Astromech'
"Астромех"
when 'Illicit'
"Незаконное"
when 'Salvaged Astromech'
"Трофейный астромех"
else
"Нет улучшения #{translator language, 'slot', slot}"
modificationPlaceholder: "Модификация"
titlePlaceholder: "Название"
upgradeHeader: (translator, language, slot) ->
switch slot
when 'Elite'
"Элитный навык"
when 'Astromech'
"Дроид-астромех"
when 'Illicit'
"Незаконное"
when 'Salvaged Astromech'
"Трофейный дроид-астромех"
else
"Улучшение #{translator language, 'slot', slot}"
unreleased: "не выпущено"
epic: "эпик"
byCSSSelector:
# Warnings
'.unreleased-content-used .translated': 'Этот отряд использует неизданный контент!'
'.epic-content-used .translated': 'Этот отряд использует эпический контент!'
'.illegal-epic-too-many-small-ships .translated': 'Вы не можете использовать более 12 малых кораблей одного типа!'
'.illegal-epic-too-many-large-ships .translated': 'Вы не можете использовать более 6 больших кораблей одного типа!'
'.collection-invalid .translated': 'Вы не можете использовать этот лист с вашей коллекцией!'
# Type selector
'.game-type-selector option[value="standard"]': 'Стандарт'
'.game-type-selector option[value="custom"]': 'Свой'
'.game-type-selector option[value="epic"]': 'Эпик'
'.game-type-selector option[value="team-epic"]': 'Командный эпик'
'.xwing-card-browser .translate.sort-cards-by': 'Сортировать по'
'.xwing-card-browser option[value="name"]': 'Названию'
'.xwing-card-browser option[value="source"]': 'Источнику'
'.xwing-card-browser option[value="type-by-points"]': 'Типу (по очкам)'
'.xwing-card-browser option[value="type-by-name"]': 'Типу (по названию)'
'.xwing-card-browser .translate.select-a-card': 'Выберите карту из списка слева.'
# Info well
'.info-well .info-ship td.info-header': 'Корабль'
'.info-well .info-skill td.info-header': 'Умение'
'.info-well .info-actions td.info-header': 'Действия'
'.info-well .info-upgrades td.info-header': 'Улучшения'
'.info-well .info-range td.info-header': 'Дистанция'
# Squadron edit buttons
'.clear-squad' : 'Новая эскадрилья'
'.save-list' : 'Сохранить'
'.save-list-as' : 'Сохранить как...'
'.delete-list' : 'Удалить'
'.backend-list-my-squads' : 'Загрузить эскадрилью'
'.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i> Imprimir/Ver como </span>Text'
'.randomize' : 'Случайный'
'.randomize-options' : 'Случайные опции…'
'.notes-container > span' : 'Примечания отряда'
# Print/View modal
'.bbcode-list' : 'Скопируйте BBCode ниже и вставьте его в сообщение своего форума.<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.html-list' : '<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.vertical-space-checkbox' : """Добавить место для письма с ухудшением / улучшением при печати. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Цветная печать. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="fa fa-print"></i> Imprimir'
# Randomizer options
'.do-randomize' : 'Сгенерировать случайным образом'
# Top tab bar
'#empireTab' : 'Галактическая Империя'
'#rebelTab' : 'Альянс повстанцев'
'#scumTab' : 'Пираты'
'#browserTab' : 'Поиск по картам'
'#aboutTab' : 'О нас'
singular:
'pilots': 'Пилоты'
'modifications': 'Модификации'
'titles': 'Названия'
types:
'Pilot': 'Пилот'
'Modification': 'Модификация'
'Title': 'Название'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders['Русский'] = () ->
exportObj.cardLanguage = 'Русский'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
# ship translations
exportObj.renameShip 'Lambda-Class Shuttle', 'Шаттл класса Лямбда'
exportObj.renameShip 'TIE Advanced', 'TIE улучшенный'
exportObj.renameShip 'TIE Bomber', 'TIE бомбардировщик'
exportObj.renameShip 'TIE Fighter', 'TIE истребитель'
exportObj.renameShip 'TIE Interceptor', 'TIE перехватчик'
exportObj.renameShip 'TIE Phantom', 'TIE фантом'
exportObj.renameShip 'TIE Defender', 'TIE защитник'
exportObj.renameShip 'TIE Punisher', 'TIE каратель'
exportObj.renameShip 'TIE Advanced Prototype', 'TIE улучшенный прототип'
exportObj.renameShip 'VT-49 Decimator', 'VT-49 Дециматор'
exportObj.renameShip 'TIE/fo Fighter', 'Истребитель TIE/пп'
exportObj.renameShip 'TIE/sf Fighter', 'Истребитель TIE/сс'
exportObj.renameShip 'TIE Striker', 'TIE ударник'
exportObj.renameShip 'Upsilon-class Shuttle', 'Шаттл класса Ипсилон'
exportObj.renameShip 'TIE Aggressor', 'TIE агрессор'
exportObj.renameShip 'TIE Silencer', 'TIE глушитель'
exportObj.renameShip 'Alpha-class Star Wing', 'Звездное Крыло класса Альфа'
exportObj.renameShip 'A-Wing', 'А-Крыл'
exportObj.renameShip 'B-Wing', 'Б-Крыл'
exportObj.renameShip 'E-Wing', 'Е-Крыл'
exportObj.renameShip 'X-Wing', 'Икс-Крыл'
exportObj.renameShip 'Y-Wing', 'У-Крыл'
exportObj.renameShip 'K-Wing', 'К-Крыл'
exportObj.renameShip 'Z-95 Headhunter', 'Z-95 охотник за головами'
exportObj.renameShip 'Attack Shuttle', 'Атакующий шаттл'
exportObj.renameShip 'CR90 Corvette (Aft)', 'Корвет CR90 (Корма)'
exportObj.renameShip 'CR90 Corvette (Fore)', 'Корвет CR90 (Нос)'
exportObj.renameShip 'GR-75 Medium Transport', 'Средний транспорт GR-75'
exportObj.renameShip 'T-70 X-Wing', 'Икс-Крыл T-70'
exportObj.renameShip 'U-Wing', 'Ю-Крыл'
exportObj.renameShip 'Auzituck Gunship', 'Канонерка Озитук'
exportObj.renameShip 'B/SF-17 Bomber', 'Бомбардировщик B/SF-17'
exportObj.renameShip 'Sheathipede-class Shuttle', 'Шаттл класса Колчан'
exportObj.renameShip 'M3-A Interceptor', 'Перехватчик M3-A'
exportObj.renameShip 'StarViper', 'Звездная Гадюка'
exportObj.renameShip 'Aggressor', 'Агрессор'
exportObj.renameShip 'Kihraxz Fighter', 'Истребитель Кихраксз'
exportObj.renameShip 'G-1A Starfighter', 'Звездный истребитель G-1A'
exportObj.renameShip 'JumpMaster 5000', 'Джампмастер 5000'
exportObj.renameShip 'Protectorate Starfighter', 'Звездный истребитель Протектората'
exportObj.renameShip 'Lancer-class Pursuit Craft', 'Транспорт преследования класса Копьеносец'
exportObj.renameShip 'Quadjumper', 'Квадджампер'
exportObj.renameShip 'C-ROC Cruiser', 'Крейсер C-ROC'
exportObj.renameShip 'Scurrg H-6 Bomber', 'Бомбардировщик Скуррг H-6'
exportObj.renameShip 'M12-L Kimogila Fighter', 'Истребитель M12-L Кимогила'
pilot_translations =
"<NAME>":
name: "<NAME>"
text: """При атаке сократите параметр маневренности защищающегося на 1 (но не ниже 0)."""
ship: "Икс-Крыл"
"<NAME>":
name: "<NAME>"
text: """Применив жетон концентрации, вы можете положить его на любой дружественный корабль на расстоянии 1-2 (вместо того, чтобы его сбросить)"""
ship: "Икс-Крыл"
"Red Squadron Pilot":
name: "<NAME>"
ship: "Икс-Крыл"
"R<NAME> Pilot":
name: "<NAME>"
ship: "Икс-Крыл"
"Big<NAME> Dark<NAME>er":
name: "<NAME>"
text: """Один раз за игру, в начале фазы Б<NAME>, вы можете выбрать, чтобы другие дружественные корабли на расстоянии 1 не могли быть выбраны целью атаки, если вместо них атакующий может выбрать вас целью."""
ship: "Икс-Крыл"
"<NAME>":
name: "<NAME>"
text: """При защите вы можете заменить 1 результат %FOCUS% на результат %EVADE%."""
ship: "Икс-Крыл"
"Gray Squadron Pilot":
name: "<NAME>"
ship: "У-Крыл"
'"D<NAME>" Vander':
name: "<NAME>"
text: """После получения захвата цели, выберите другой дружественный корабль на расстоянии 1-2. Выбранный корабль может немедленно получить захват цели."""
ship: "У-Крыл"
"<NAME>":
name: "<NAME>"
text: """Атакуя на расстоянии 2-3, вы можете перебросить все пустые результаты"""
ship: "У-Крыл"
"Gold Squadron Pilot":
name: "<NAME>от Золотой эскадрильи"
ship: "У-Крыл"
"Academy Pilot":
name: "Пилот академии"
ship: "TIE истребитель"
"Obsidian Squadron Pilot":
name: "<NAME> Обс<NAME>ановой эскадрильи"
ship: "TIE истребитель"
"Black Squadron Pilot":
name: "<NAME> Черной эскадрильи"
ship: "TIE истребитель"
'"W<NAME>ed <NAME>"':
name: '"<NAME>"'
text: """Атакуя на расстоянии 1, вы можете изменить 1 результат %HIT% на результат %CRIT%"""
ship: "TIE истребитель"
'"Night Beast"':
name: '"Ночной Зверь"'
text: """После выполнения зеленого маневра, вы можете выполнить свободное действие Концентрации"""
ship: "TIE истребитель"
'"Backstabber"':
name: '"Ударяющий в спину"'
text: """Атакуя вне арки огня защищающегося, можете бросить 1 дополнительный кубик атаки"""
ship: "TIE истребитель"
'"Dark Curse"':
name: '"Темное проклятье"'
text: """Когда вы защищаетесь в фазу боя, атакующие корабли не могут тратить жетоны Концентрации или перебрасывать кубики атаки"""
ship: "TIE истребитель"
'"Mauler Mit<NAME>"':
name: '"<NAME>"'
text: """ Атакуя на расстоянии 1, можете бросить 1 дополнительный кубик атаки."""
ship: "TIE истребитель"
'"<NAME>"':
name: '"<NAME>"'
text: """Когда другой дружественный корабль атакует основным оружием на расстоянии 1, он может перебросить 1 кубик атаки"""
ship: "TIE истребитель"
"Tempest Squadron Pilot":
name: "<NAME> э<NAME>"
ship: "TIE улучшенный"
"Storm Squadron Pilot":
name: "<NAME> э<NAME>"
ship: "TIE улучшенный"
"<NAME>":
name: "<NAME>"
text: """Когда ваша атака наносит противнику карточку повреждения лицом вверх, вместо этого вытяните 3 карты лицом вверх, выберите одну и сбросьте остальные."""
ship: "TIE улучшенный"
"<NAME>":
name: "<NAME>"
text: """Во время шага «Выполнение действия» вы можете выполнить 2 действия."""
ship: "TIE улучшенный"
"Alpha Squadron Pilot":
name: "<NAME> э<NAME>"
ship: "TIE перехватчик"
"Avenger Squadron Pilot":
name: "<NAME>"
ship: "TIE перехватчик"
"Saber Squadron Pilot":
name: "<NAME>илот эскадрильи С<NAME>ля"
ship: "TIE перехватчик"
"\"<NAME> Wrath\"":
name: '"<NAME>"'
ship: "TIE перехватчик"
text: """Когда число карт повреждений корабля равно или превышает значение Прочности, корабль не уничтожен до конца фазы Боя."""
"<NAME>":
name: "<NAME>"
ship: "TIE перехватчик"
text: """После проведения атаки, вы можете выполнить свободное действие Бочка или Ускорение."""
"<NAME>":
name: "<NAME>"
ship: "TIE перехватчик"
text: """Когда вы получаете жетон Стресса, вы можете назначить 1 жетон Концентрации на ваш корабль."""
"<NAME>":
name: "<NAME>"
text: """Вы можете выполнять действия даже имея жетоны Стресса."""
ship: "А-Крыл"
"<NAME>":
name: "<NAME>"
text: """Вы можете назначать корабль противника, которого касаетесь, целью атаки."""
ship: "А-Крыл"
"Green Squadron Pilot":
name: "Пилот З<NAME>скад<NAME>и"
ship: "А-Крыл"
"Prototype Pilot":
name: "Пилот прототипа"
ship: "А-Крыл"
"Outer Rim Smuggler":
name: "Контрабандист Внешнего Кольца"
"<NAME>":
name: "<NAME>"
text: """Когда вы получаете карту повреждений лицом вверх, немедленно переверните ее лицом вниз (не отрабатывая ее эффект)."""
"<NAME>":
name: "<NAME>"
text: """После выполнения зеленого маневра, выберите 1 другой дружественный корабль на расстоянии 1. Этот корабль может выполнить 1 свободное действие, отображенное в его списке действий."""
"<NAME>":
name: "<NAME>"
text: """Атакуя, вы можете перебросить все кубики атаки. Делая это, вы должны перебросить столько кубиков, сколько возможно."""
"<NAME>":
name: "Охотник за головами"
"<NAME>":
name: "<NAME>"
text: """При атаке, защищающийся получает 1 жетон Стресса если он отменяет хотя бы 1 результат %CRIT%."""
"<NAME>":
name: "<NAME>"
text: """Когда вы выполняете маневр крена (%BANKLEFT% или %BANKRIGHT%), вы можете повернуть диск маневра на другой маневр крена с той же скоростью."""
"<NAME>":
name: "<NAME>"
text: """Атакуя вспомогательным оружием, вы можете перебросить 1 кубик атаки."""
"<NAME>":
name: "<NAME>"
text: """При атаке 1 из ваших результатов %CRIT% не может быть отменен кубиком защиты."""
ship: "Б-Крыл"
"Ibtis<NAME>":
name: "<NAME>"
text: """При атаке или защите, если у вас есть хотя бы 1 жетон Стресса, вы можете перебросить 1 из ваших кубиков."""
ship: "Б-Крыл"
"Dagger Squadron Pilot":
name: "<NAME>"
ship: "Б-Крыл"
"Blue Squadron Pilot":
name: "<NAME>"
ship: "Б-Крыл"
"Rebel Operative":
name: "Повстанец-оперативник"
ship: "HWK-290"
"<NAME>":
name: "<NAME>"
text: """В начале фазы Б<NAME>, выберите 1 дружественный корабль на расстоянии 1-3. До конца фазы считайте навык Пилотирования этого корабля равным 12."""
ship: "HWK-290"
"<NAME>":
name: "<NAME>"
text: """В начале фазы боя вы можете назначить 1 из ваших жетонов Концентрации на другой дружественный корабль на расстоянии 1-3."""
ship: "HWK-290"
"<NAME>":
name: "<NAME>"
text: """Когда другой дружественный корабль на расстоянии 1-3 выполняет атаку, если у вас нет жетона Стресса, вы можете получить 1 жетон Стресса чтобы позволить дружественному кораблю бросить 1 дополнительный кубик атаки."""
ship: "HWK-290"
"Scimitar Squadron Pilot":
name: "<NAME>"
ship: "TIE бомбардировщик"
"Gamma Squadron Pilot":
name: "<NAME>"
ship: "TIE бомбардировщик"
"Gamma Squadron Veteran":
name: "<NAME>"
ship: "TIE бомбардировщик"
"Capt<NAME>":
name: "<NAME>"
ship: "TIE бомбардировщик"
text: """Когда другой дружественный корабль на расстоянии 1 атакует вспомогательным оружием, он может перебросить до 2 кубиков атаки."""
"Major R<NAME>ymer":
name: "<NAME>"
ship: "TIE бомбардировщик"
text: """Атакуя второстепенным оружием, вы можете увеличить или уменьшить дистанцию оружия на 1 (до значения 1 или 3)."""
"Omicron Group Pilot":
name: "<NAME>"
ship: "Шаттл класса Лямбда"
"Captain K<NAME>":
name: "<NAME>"
text: """Когда вражеский корабль получает захват цели, он должен делать его на ваш корабль (если может)."""
ship: "Шаттл класса Лямбда"
"Colonel Jendon":
name: "<NAME>"
text: """ В начале фазы боя вы можете назначить 1 из ваших синих жетонов захвата цели на союзный корабль на расстоянии 1, если у него еще нет синего жетона захвата цели."""
ship: "Шаттл класса Лямбда"
"<NAME>":
name: "<NAME>"
text: """ Когда другой союзный корабль на расстоянии 1-2 получает жетон стресса, если у вас есть 2 жетона стресса или меньше, вы можете получить жетон стресса вместо него."""
ship: "Шаттл класса Лямбда"
"<NAME>":
name: "<NAME>"
ship: "TIE перехватчик"
text: """При выполнении бочки, вы можете получить 1 жетон стресса чтобы использовать (%BANKLEFT% 1) или (%BANKRIGHT% 1) вместо (%STRAIGHT% 1)."""
"<NAME>":
name: "<NAME>"
ship: "TIE перехватчик"
"<NAME>":
name: "<NAME>"
ship: "TIE перехватчик"
text: """Когда вы открываете маневр %UTURN%, вы можете считать скорость этого маневра равной 1, 3 или 5."""
"<NAME>":
name: "<NAME>"
ship: "TIE перехватчик"
text: """Атакуя на расстоянии 2-3, можете потратить 1 жетон уклонения чтобы добавить 1 результат %HIT% к броску."""
"<NAME>":
name: "<NAME>"
ship: "TIE перехватчик"
text: """Вражеские корабли на расстоянии 1 не могут выполнять действия Концентрации и Уклонения, а также не могут использовать жетоны концентрации и уклонения."""
"GR-75 Medium Transport":
name: "Средний транспорт GR-75"
ship: "Средний транспорт GR-75"
"Bandit Squadron Pilot":
name: "<NAME>"
ship: "Z-95 Охотник за головами"
"Tala Squadron Pilot":
name: "<NAME> э<NAME>"
ship: "Z-95 Охотник за головами"
"<NAME>":
name: "<NAME>"
text: """При атаке считается, что она попала по противнику, даже если он не понес повреждений."""
ship: "Z-95 Охотник за головами"
"<NAME>":
name: "<NAME>"
text: """После выполнения атаки, вы можете выбрать другой дружественный корабль на расстоянии 1. Этот корабль может выполнить 1 свободное действие."""
ship: "Z-95 Охотник за головами"
"Delta Squadron Pilot":
name: "<NAME>"
ship: "TIE защитник"
"Onyx Squadron Pilot":
name: "<NAME> э<NAME>"
ship: "TIE защитник"
"<NAME>":
name: "Полковник <NAME>"
text: """ Когда вы атакуете, сразу после броска кубиков атаки, вы можете назначить захват цели на защищающегося, если на нем уже есть красный жетон захвата."""
ship: "TIE защитник"
"<NAME>":
name: "<NAME>"
text: """Когда вы выполнили атаку, которая нанесла хотя бы 1 карту повреждений защищающемуся, вы можете потратить 1 жетон концентрации, чтобы перевернуть эти карты лицом вверх."""
ship: "TIE защитник"
"Knave Squadron Pilot":
name: "<NAME>"
ship: "Е-Крыл"
"Blackmoon Squadron Pilot":
name: "<NAME>"
ship: "Е-Крыл"
"<NAME>":
name: "<NAME>"
text: """Когда вражеский корабль в вашей арке огня и на расстоянии 1-3 защищается, атакующий может заменить 1 результат %HIT% на 1 результат %CRIT%."""
ship: "Е-Крыл"
"<NAME>":
name: "<NAME>"
text: """В начале фазы Окончания вы можете выполнить 1 атаку. Вы не можете атаковать в следующем ходу."""
ship: "Е-Крыл"
"Sigma Squadron Pilot":
name: "<NAME>"
ship: "TIE фантом"
"Shadow Squadron Pilot":
name: "<NAME>"
ship: "TIE фантом"
'"<NAME>"':
name: '"<NAME>"'
text: """При снятии маскировки, вы должны использовать (%BANKLEFT% 2) или (%BANKRIGHT% 2) вместо (%STRAIGHT% 2)."""
ship: "TIE фантом"
'"<NAME>"':
name: '"<NAME>"'
text: """После выполнения атаки, завершившейся попаданием, вы можете назначить 1 жетон концентрации на ваш корабль."""
ship: "TIE фантом"
"CR90 Corvette (Fore)":
name: "К<NAME> CR90 (Нос)"
ship: "Корвет CR90 (Нос)"
text: """Атакуя основным оружием, вы можете потратить 1 энергии, чтобы бросить 1 дополнительный кубик атаки."""
"CR90 Corvette (Aft)":
name: "<NAME> CR90 (Корма)"
ship: "Корвет CR90 (Корма)"
"<NAME>":
name: "<NAME>"
text: """После выполнения атаки, вы можете снять 1 жетон концентрации, уклонения или синий жетон захвата цели с защищавшегося."""
ship: "Икс-Крыл"
"<NAME>":
name: "<NAME>"
text: """При получении жетона Стресса, вы можете убрать его и бросить 1 кубик атаки. При результате %HIT%, получите 1 карту повреждения на этот корабль лицом вниз."""
ship: "Икс-Крыл"
'"<NAME>" <NAME>':
name: "<NAME>"
text: """При получении или использовании захвата цели, вы можете убрать 1 жетон Стресса."""
ship: "Икс-Крыл"
"<NAME>":
name: "<NAME>"
text: """ Когда вражеский корабль объявляет вас объектом атаки, вы можете установить захват цели на этот корабль."""
ship: "Икс-Крыл"
"<NAME>":
name: "<NAME>"
text: """ После того, как вы выполните действие Концентрации или вам назначен жетон концентрации, вы можете совершить свободное действие Ускорение или Бочку."""
ship: "А-Крыл"
"<NAME>":
name: "<NAME>"
text: """Когда вы на расстоянии 1 от хотя бы 1 вражеского корабля, увеличьте параметр Уклонения на 1."""
ship: "А-Крыл"
"<NAME>":
name: "<NAME>"
text: """Атакуя, вы можете убрать 1 жетон Стресса, чтобы заменить все результаты %FOCUS% на %HIT%."""
ship: "Б-Крыл"
"<NAME>":
name: "<NAME>"
text: """Вы можете выполнять атаки вспомогательным оружием %TORPEDO% против кораблей вне вашей арки огня."""
ship: "Б-Крыл"
# "CR90 Corvette (Crippled Aft)":
# name: "CR90 Corvette (Crippled Aft)"
# ship: "Корвет CR90 (Корма)"
# text: """Вы не можете выбирать и выполнять маневры (%STRAIGHT% 4), (%BANKLEFT% 2), или (%BANKRIGHT% 2)."""
# "CR90 Corvette (Crippled Fore)":
# name: "CR90 Corvette (Crippled Fore)"
# ship: "Корвет CR90 (Нос)"
"Wild Space Fringer":
name: "Пограничник дикого космоса"
ship: "YT-2400"
"Dash Rendar":
name: "<NAME>"
text: """Вы можете игнорировать препятствия в фазу Активации и при выполнении дествий."""
'"L<NAME>"':
name: "<NAME>"
text: """Когда вы получаете карту повреждений лицом вверх, возьмите 1 дополнительную карту лицом вверх, выберите 1 из них и сбросьте вторую."""
"E<NAME>ill":
name: "<NAME>"
text: """При атаке основным оружием против корабля, имеющего жетон С<NAME>, бросьте 1 дополнительный кубик атаки."""
"Patrol Leader":
name: "<NAME>"
ship: "VT-49 Дециматор"
"Rear Admiral Ch<NAME>au":
name: "<NAME>"
text: """Атакуя на расстоянии 1-2, вы можете заменить 1 результат %FOCUS% на результат %CRIT%."""
ship: "VT-49 Дециматор"
"Command<NAME>":
ship: "VT-49 Дециматор"
name: "<NAME>"
text: """Если у вас нет щитов и вы имеете хотя бы 1 карту повреждений, ваше Уклонение повышается на 1."""
"<NAME>":
name: "<NAME>"
text: """После выполнения маневра, каждый вражеский корабль, которого вы касаетесь, получает 1 повреждение."""
ship: "VT-49 Дециматор"
"Black <NAME>":
name: "<NAME>"
ship: "Звездная Гадюка"
"<NAME>":
name: "<NAME>"
ship: "Звездная Гадюка"
"<NAME>":
name: "<NAME>"
text: """При защите, союзный корабль на расстоянии 1 может получить 1 неотмененный %HIT% или %CRIT% вместо вас."""
ship: "Звездная Гадюка"
"<NAME>":
name: "<NAME>"
text: """В начале фазы Боя, если вы на расстоянии 1 от вражеского корабля, вы можете назначить 1 жетон Концентрации на свой корабль."""
ship: "Звездная Гадюка"
"Cart<NAME>":
name: "<NAME>"
ship: "Перехватчик M3-A"
"Tansarii Point Veteran":
name: "<NAME>"
ship: "Перехватчик M3-A"
"<NAME>":
name: "<NAME>у"
text: """Когда другой дружественный корабль на расстоянии 1 защищается, он может перебросить 1 кубик защиты."""
ship: "Перехватчик M3-A"
"<NAME>":
name: "<NAME>"
text: """После того, как вы провели защиту от атаки, если атака не попала, вы можете назначить 1 жетон Уклонения на свой корабль."""
ship: "Перехватчик M3-A"
"IG-88A":
text: """После выполнения атаки, уничтожившей корабль противника, вы можете восстановить 1 щит."""
ship: "Агрессор"
"IG-88B":
text: """Раз за ход, проведя атаку, которая не попала, вы можете выполнить атаку вспомогательным оружием %CANNON% ."""
ship: "Агрессор"
"IG-88C":
text: """После выполнения Ускорения, вы можете выполнить свободное действие Уклонения."""
ship: "Агрессор"
"IG-88D":
text: """Вы можете выполнять (%SLOOPLEFT% 3) или (%SLOOPRIGHT% 3) используя соответствующий (%TURNLEFT% 3) или (%TURNRIGHT% 3) шаблон."""
ship: "Агрессор"
"<NAME>":
name: "<NAME>андалорский наемник"
"<NAME> (Scum)":
name: "<NAME> (Пираты)"
text: """Атакуя или защищаясь, вы можете перебросить 1 кубик за каждый вражеский корабль на расстоянии 1."""
"<NAME> (Sc<NAME>)":
name: "<NAME> (<NAME>)"
text: """Атакуя корабль в вашей вторичной арке стрельбы, бросьте 1 дополнительный кубик атаки."""
"<NAME>":
name: "<NAME>"
text: """Бросая бомбу, вы можете использовать шаблон [%TURNLEFT% 3], [%STRAIGHT% 3] или [%TURNRIGHT% 3] вместо [%STRAIGHT% 1]."""
"<NAME>":
name: "<NAME>"
ship: "У-Крыл"
text: """Атакуя корабль вне вашей арки огня, бросьте 1 дополнительный кубик."""
"<NAME>":
name: "<NAME>"
text: """После того, как вы используете захват цели, вы можете получить 1 жетон Стресса, чтобы получить захват цели."""
ship: "У-Крыл"
"<NAME>":
name: "<NAME>"
ship: "У-Крыл"
"<NAME>":
name: "<NAME>"
ship: "У-Крыл"
"<NAME>":
name: "<NAME>"
ship: "HWK-290"
"<NAME>":
name: "<NAME>"
text: """Когда вражеский корабль на расстоянии 1-3 получает хотя бы 1 ионный жетон, если вы не под Стрессом, вы можете получить 1 жетон Стресса чтобы тот корабль получил 1 повреждение."""
ship: "HWK-290"
"<NAME>":
name: "<NAME>"
text: """В начале фазы боя вы можете убрать 1 жетон Концентрации или Уклонения с вражеского корабля на расстоянии 1-2 и назначить этот жетон вашему кораблю."""
"<NAME>":
name: "<NAME>"
text: """В конце фазы Активации, выберите 1 вражеский корабль на расстоянии 1-2. До конца фазы Боя считайте умение пилота этого корабля равным 0."""
"<NAME>":
name: "<NAME>"
ship: "Z-95 Охотник за головами"
"<NAME>":
name: "<NAME>"
ship: "Z-95 Охотник за головами"
"<NAME>":
name: "<NAME>"
text: """При атаке, если нет других дружественных кораблей на расстоянии 1-2, бросьте 1 дополнительный кубик атаки."""
ship: "Z-95 Охотник за головами"
"<NAME>":
name: "<NAME>"
text: """В начале фазы Б<NAME>, вы можете убрать 1 жетон Концентрации или Уклонения с дружественного корабля на расстоянии 1-2 и назначить его на свой корабль."""
ship: "Z-95 Охотник за головами"
"<NAME>":
name: "<NAME>оманд<NAME>"
ship: "TIE улучшенный"
text: """В начале фазы Боя, вы можете назначить захват цели на вражеский корабль на расстоянии 1."""
"<NAME>":
name: "<NAME>"
ship: "TIE улучшенный"
text: """Когда открываете маневр, вы можете изменить его скорость на 1 (до минимума в 1)."""
"<NAME>":
name: "<NAME>"
ship: "TIE улучшенный"
text: """Вражеские корабли на расстоянии 1 не получают боевого бонуса за расстояние при атаке."""
"<NAME>":
name: "<NAME>"
ship: "TIE улучшенный"
text: """В начале фазы Завершения, вы можете потратить захват цели на вражеском корабле, чтобы заставить его перевернуть одну из полученных карт повреждений лицом вверх."""
"<NAME>":
name: "<NAME>"
text: """ Когда дружественный корабль объявляет атаку, вы можете потратить захват цели на защищающемся, чтобы уменьшить его Маневренность на 1 для этой атаки."""
"<NAME>":
name: "<NAME>"
ship: 'К-Крыл'
text: """ Один раз за ход, во время атаки, вы можете потратить 1 щит, чтобы бросить 1 дополнительный кубик атаки, <strong>или</strong> бросить на 1 кубик атаки меньше, чтобы восстановить 1 щит."""
"<NAME>":
name: "<NAME>"
ship: 'К-Крыл'
text: """Когда другой дружественный корабль на расстоянии 1-2 атакует, он может считать ваши жетоны Концентрации как свои собственные."""
"Guardian Squadron Pilot":
name: "<NAME>"
ship: 'К-Крыл'
"Warden Squadron Pilot":
name: "<NAME>"
ship: 'К-Крыл'
'"Red<NAME>"':
name: '"<NAME>"'
ship: 'TIE каратель'
text: """Вы можете поддерживать 2 захвата цели на одном и том же корабле. Когда вы получаете захват цели, вы можете получить второй захват на том же корабле."""
'"Death<NAME>"':
name: '"<NAME>"'
ship: 'TIE каратель'
text: """Бросая бомбу, вы можете использовать передние направляющие вашего корабля. После сброса бомбы, вы можете выполнить свободное действие Бочку."""
'Black Eight Squadron Pilot':
name: "<NAME>"
ship: 'TIE каратель'
'Cutlass Squadron Pilot':
name: "<NAME>"
ship: 'TIE каратель'
"Moralo Eval":
name: "<NAME>"
text: """Вы можете выполнять атаки вспомогательным оружием %CANNON% против кораблей в вашей вторичной арке огня."""
'Gozanti-class Cruiser':
name: "<NAME>"
text: """После выполнения маневра, вы можете отстыковать до 2 присоединенных кораблей."""
'"<NAME>"':
name: "<NAME>"
ship: "TIE истребитель"
text: """При атаке, если у защищающегося уже есть 1 или более карт повреждений, бросьте 1 дополнительный кубик атаки."""
"The <NAME>":
name: "<NAME>"
ship: "TIE улучшенный прототип"
text: """Атакуя основным оружием на расстоянии 2-3, считайте расстояние атаки как 1."""
"<NAME>":
name: "<NAME>"
ship: "Звездный истребитель G-1A"
text: """Атакуя, вы можете бросить 1 дополнительный кубик атаки. Если вы делаете это, защищающийся бросает 1 дополнительный кубик защиты."""
"Ruthless Freelancer":
name: "Беспощадный наемник"
ship: "Звездный истребитель G-1A"
"<NAME>":
name: "<NAME>"
ship: "Звездный истребитель G-1A"
"<NAME>":
name: "<NAME>"
ship: "Джампмастер 5000"
text: """Один раз за ход, после защиты, если атакующий находится в вашей основной арке огня, вы можете провести атаку против этого корабля."""
"<NAME>":
name: "<NAME>"
ship: "Истребитель Кихраксз"
text: """Атакуя или защищаясь, удваивайте эффект бонусов за расстояние."""
"<NAME>":
name: "<NAME>"
ship: "Истребитель Кихраксз"
text: """Защищаясь, если атакующий находится в вашей основной арке огня, бросьте 1 дополнительный кубик защиты."""
"<NAME>":
name: "<NAME>"
ship: "Истребитель Кихраксз"
"<NAME>":
name: "<NAME>"
ship: "Истребитель Кихраксз"
"<NAME>":
name: "<NAME>ский работорговец"
ship: "YV-666"
"<NAME>":
name: "<NAME>"
ship: "YV-666"
text: """Когда вы выполняете атаку, завершившуюся попаданием, перед нанесением повреждений, вы можете отменить 1 из ваших результатов %CRIT%, чтобы нанести 2 результата %HIT%."""
# T-70
"<NAME>":
name: "<NAME>"
ship: "Икс-Крыл T-70"
text: """Атакуя или защищаясь, если у вас есть жетон Концентрации, вы можете заменить 1 из ваших результатов %FOCUS% на результат %HIT% или %EVADE%."""
'"Blue Ace"':
name: '"<NAME>"'
ship: "Икс-Крыл T-70"
text: """Выполняя действие Ускорение, вы можете использовать шаблон (%TURNLEFT% 1) или (%TURNRIGHT% 1)."""
"Red Squadron Veteran":
name: "<NAME>"
ship: "Икс-Крыл T-70"
"Blue Squadron Novice":
name: "<NAME>"
ship: "Икс-Крыл T-70"
'"Red Ace"':
name: "<NAME>"
ship: "Икс-Крыл T-70"
text: '''В первый раз за ход, когда вы убираете жетон щита с вашего корабля, назначьте 1 жетон Уклонения на ваш корабль.'''
# TIE/fo
'"Omega Ace"':
name: '"<NAME>"'
ship: "Истребитель TIE/пп"
text: """Атакуя, вы можете потратить жетон Концентрации и захват цели на защищающемся, чтобы заменить все ваши результаты на результаты %CRIT%."""
'"Epsilon Leader"':
name: '"<NAME>"'
ship: "Истребитель TIE/пп"
text: """В начале фазы <NAME>, уберите 1 жетон Стресса с каждого дружественного корабля на расстоянии 1."""
'"Zeta Ace"':
name: '"<NAME>"'
ship: "Истребитель TIE/пп"
text: """Когда вы выполняете Бочку, вы можете использовать шаблон (%STRAIGHT% 2) вместо шаблона (%STRAIGHT% 1)."""
"Omega Squadron Pilot":
name: "Пилот э<NAME>ад<NAME>"
ship: "Истребитель TIE/пп"
"Zeta Squadron Pilot":
name: "Пилот эскадр<NAME>"
ship: "Истребитель TIE/пп"
"Epsilon Squadron Pilot":
name: "Пилот эскадр<NAME>"
ship: "Истребитель TIE/пп"
'"Omega Leader"':
name: "<NAME>"
ship: "Истребитель TIE/пп"
text: '''Вражеские корабли, находящиеся в вашем захвате цели, не могут модифицировать кубики, атакуя вас или защищаясь от ваших атак.'''
'H<NAME>':
name: "<NAME>"
text: '''Когда вы открываете зеленый или красный маневр, вы можете повернуть ваш диск на другой маневр той же сложности.'''
'"Yo<NAME>"':
name: "<NAME>"
ship: "TIE истребитель"
text: """Дружественные TIE истребители на расстоянии 1-3 могут выполнять действие с вашей экипированной карты улучшений %ELITE%."""
'"<NAME>"':
name: "<NAME>"
ship: "TIE истребитель"
text: """Атакуя, вы можете отменить все результаты кубиков. Если вы отменяете результат %CRIT%, назначьте 1 карту повреждений лицом вниз на защищающегося."""
'"<NAME>"':
name: "<NAME>"
ship: "TIE истребитель"
text: """Когда другой дружественный корабль на расстоянии 1 тратит жетон Концентрации, назначьте жетон Концентрации на ваш корабль."""
'<NAME>':
name: "<NAME>"
ship: "Атакующий шаттл"
text: """Защищаясь, если у вас есть Стресс, вы можете заменить до 2 ваших результатов %FOCUS% на результаты %EVADE%."""
'"<NAME>"':
name: "<NAME>"
text: '''Атакуя, если у вас нет Стресса, вы можете получить 1 жетон Стресса, чтобы бросить 1 дополнительный кубик атаки.'''
ship: "Истребитель TIE/пп"
'"<NAME>"':
name: "<NAME>"
text: '''Пока у вас нет карт повреждений, считайте ваше умение пилота равным 12.'''
ship: "Истребитель TIE/пп"
"<NAME>":
name: "<NAME>"
text: """Когда вражеский корабль на расстоянии 1-2 атакует, вы можете потратить жетон Концентрации. Если вы делаете это, атакующий бросает на 1 кубик атаки меньше."""
'"<NAME>"':
name: "<NAME>"
text: """В начале фазы <NAME>, каждый вражеский корабль, которого вы касаетесь, получает 1 жетон Стресса."""
'<NAME> (Attack Shuttle)':
name: "<NAME> (Атакующий шаттл)"
ship: "Атакующий шаттл"
text: """Когда вы открываете зеленый или красный маневр, вы можете повернуть ваш диск на другой маневр той же сложности."""
'<NAME>':
name: "<NAME>"
ship: "Атакующий шаттл"
text: """Сразу перед открытием вашего маневра, вы можете выполнить свободное действие Ускорение или Бочку."""
'"<NAME>" Or<NAME>':
name: "<NAME>"
ship: "Атакующий шаттл"
text: '''Защищаясь, вы можете отменять результаты %CRIT% перед результатами %HIT%.'''
"<NAME>":
name: "<NAME>"
ship: "VCX-100"
'<NAME>':
name: "<NAME>"
text: '''Один раз за ход, после того, как вы сбрасываете карту улучшений %ELITE%, переверните эту карту обратно.'''
ship: "TIE бомбардировщик"
'<NAME>':
name: "<NAME>"
text: '''Когда у вас нет жетонов Стресса, можете считать маневры %TROLLLEFT% и %TROLLRIGHT% белыми маневрами.'''
ship: "Икс-Крыл T-70"
"<NAME>":
name: "<NAME>"
text: """После защиты, вы можете выполнить свободное действие."""
ship: "TIE улучшенный прототип"
"4-LOM":
ship: "Звездный истребитель G-1A"
text: """В начале фазы Завершения, вы можете назначить 1 из ваших жетонов Стресса на другой корабль на расстоянии 1."""
"Tel <NAME>":
name: "<NAME>"
ship: "Джампмастер 5000"
text: """В первый раз, когда вы должны быть уничтожены, вместо этого отмените все оставшиеся повреждения, сбросьте все карты повреждений, и назначьте 4 карты повреждений лицом вниз этому кораблю."""
"Man<NAME>":
name: "<NAME>"
ship: "Джампмастер 5000"
text: """В начале фазы Боя, вы можете назначить все жетоны Концентрации, Уклонения и захвата цели, назначенные вам, на другой дружественный корабль на расстоянии 1."""
"Contracted Scout":
name: "Разведчик-контрактник"
ship: "Джампмастер 5000"
'"Deathfire"':
name: "Смертельное пламя"
text: '''Когда вы открываете ваш диск маневров или после того, как вы выполняете действие, вы можете выполнить действие с карты улучшения %BOMB% как свободное действие.'''
ship: "TIE бомбардировщик"
"Sienar Test Pilot":
name: "С<NAME>енарский летчик-испытатель"
ship: "TIE улучшенный прототип"
"Baron of the Empire":
name: "<NAME>"
ship: "TIE улучшенный прототип"
"<NAME> (TIE Defender)":
name: "<NAME> (TIE защитник)"
text: """Когда ваша атака наносит защищающемуся карту повреждений в открытую, вместо этого вытяните 3 карты повреждений, выберите 1 для отработки и сбросьте остальные."""
ship: "TIE защитник"
"<NAME>":
name: "<NAME>"
text: """Когда вы открываете маневр %STRAIGHT%, вы можете считать его маневром %KTURN%."""
ship: "TIE защитник"
"Glaive Squadron Pilot":
name: "<NAME>"
ship: "TIE защитник"
"Po<NAME> (PS9)":
name: "<NAME> (УП9)"
text: """Атакуя или защищаясь, если у вас есть жетон Концентрации, вы можете заменить 1 из ваших результатов %FOCUS% на результат %HIT% или %EVADE%."""
ship: "Икс-Крыл T-70"
"Resistance Sympathizer":
name: "Сочувствующий повстанцам"
ship: "YT-1300"
"Rey":
name: "<NAME>"
text: """Атакуя или защищаясь, если вражеский корабль находится в вашей основной арке огня, вы можете перебросить до 2 пустых результатов."""
'<NAME> (TFA)':
name: "<NAME> (ПС)"
text: '''Во время расстановки, вы можете быть расположены где угодно на игровом поле на расстоянии не ближе 3 от вражеских кораблей.'''
'<NAME> (TFA)':
name: "<NAME> (ПС)"
text: '''После того, как другой дружественный корабль на расстоянии 1-3 уничтожен (но не сбежал с поля боя), вы можете выполнить атаку.'''
'<NAME>':
name: "<NAME>"
ship: "ARC-170"
text: '''Атакуя или защищаясь, вы можете потратить захват цели на защищающемся, чтобы добавить 1 результат %FOCUS% к вашему броску.'''
'<NAME>':
name: "<NAME>"
ship: "ARC-170"
text: '''Когда другой дружественный корабль на расстоянии 1-2 атакует, он может считать ваши синие жетоны захвата цели как свои собственные.'''
'<NAME>':
name: "<NAME>"
ship: "ARC-170"
text: '''После того, как вражеский корабль в вашей арке огня на расстоянии 1-3 атакует другой дружественный корабль, вы можете выполнить свободное действие.'''
'<NAME>':
name: "<NAME>"
ship: "ARC-170"
text: '''После того, как вы выполните маневр, вы можете бросить кубик атаки. При результате %HIT% или %CRIT%, уберите 1 жетон Стресса с вашего корабля.'''
'"Quickdraw"':
name: "<NAME>"
ship: "Истребитель TIE/сс"
text: '''Один раз за ход, когда вы теряете жетон щита, вы можете выполнить атаку основным оружием.'''
'"Backdraft"':
name: "<NAME>"
ship: "Истребитель TIE/сс"
text: '''Атакуя корабль в вашей вторичной арке огня, вы можете добавить 1 результат %CRIT%.'''
'Omega Specialist':
name: "О<NAME> сп<NAME>"
ship: "Истребитель TIE/сс"
'Zeta Specialist':
name: "З<NAME>"
ship: "Истребитель TIE/сс"
'<NAME>':
name: "<NAME>"
ship: "Звездный истребитель Протектората"
text: '''Атакуя или защищаясь, если вражеский корабль находится на расстоянии 1, вы можете бросить 1 дополнительный кубик.'''
'<NAME>':
name: "<NAME>"
ship: "Звездный истребитель Протектората"
text: '''В начале фазы Б<NAME>, вы можете выбрать 1 вражеский корабль на расстоянии 1. Если вы находитесь в его арке огня, он должен сбросить все жетоны Концентрации и Уклонения.'''
'<NAME>':
name: "<NAME>"
ship: "Звездный истребитель Протектората"
text: '''После выполнения красного маневра, назначьте 2 жетона Концентрации на ваш корабль.'''
'Con<NAME>':
name: "<NAME>"
ship: "Звездный истребитель Протектората"
'Con<NAME> D<NAME> V<NAME>an':
name: "<NAME>"
ship: "Звездный истребитель Протектората"
'Ze<NAME>ous Recruit':
name: "<NAME>"
ship: "Звездный истребитель Протектората"
'<NAME>':
name: "<NAME>"
ship: "Корабль-преследователь класса Копьеносец"
text: '''В начале фазы Боя, вы можете выбрать корабль на расстоянии 1. Если он находится в вашей основной <strong>и</strong> мобильной арках огня, назначьте на него 1 жетон Луча Захвата.'''
'<NAME>':
name: "<NAME>"
ship: "Корабль-преследователь класса Копьеносец"
text: '''В начале фазы Боя, вы можете выбрать корабль на расстоянии 1-2. Если он находится в вашей мобильной арке огня, назначьте ему 1 жетон Стресса.'''
'<NAME> (Scum)':
name: "<NAME> (<NAME>)"
ship: "Корабль-преследователь класса Копьеносец"
text: '''Защищаясь от вражеского корабля в вашей мобильной арке огня на расстоянии 1-2, вы можете добавить 1 результат %FOCUS% к вашему броску.'''
'<NAME>':
name: "<NAME>"
ship: "Корабль-преследователь класса Копьеносец"
'<NAME> (TIE Fighter)':
name: "<NAME> (TIE истребитель)"
ship: "TIE истребитель"
text: '''Сразу перед открытием вашего маневра, вы можете выполнить свободное действие Ускорение или Бочку.'''
'"<NAME>" Orreli<NAME> (TIE Fighter)':
name: "<NAME> (TIE истребитель)"
ship: "TIE истребитель"
text: '''Защищаясь, вы можете отменять результаты %CRIT% перед результатами %HIT%.'''
'<NAME>':
name: "<NAME>"
ship: "Шаттл класса Ипсилон"
text: '''В первый раз за ход, когда вы получаете попадание, назначьте атакующему карту состояния "Я покажу тебе Темную Сторону".'''
'<NAME>':
name: "<NAME>"
ship: "Квадджампер"
text: '''В конце фазы Активации, вы <strong>должны</strong> назначить жетон Луча Захвата каждому кораблю, которого касаетесь.'''
'<NAME>':
name: "<NAME>"
ship: "Ю-Крыл"
text: '''В начале фазы Активации, вы можете убрать 1 жетон Стресса с 1 другого дружественного корабля на расстоянии 1-2.'''
'<NAME>':
name: "<NAME>"
ship: "Ю-Крыл"
text: '''Когда дружественный корабль получает захват цели на противника, этот корабль может захватывать вражеский корабль на расстоянии 1-3 от любого дружественного корабля.'''
'<NAME>':
name: "<NAME>"
ship: "Ю-Крыл"
text: '''После того, как вражеский корабль выполняет маневр, приводящий к наложению на ваш корабль, вы можете выполнить свободное действие.'''
'''"<NAME>"''':
ship: "TIE ударник"
name: '"<NAME>"'
text: '''Когда у вас есть экипированная карта улучшения "Адаптивные элероны", вы можете игнорировать особенность этой карты.'''
'''"<NAME>"''':
ship: "TIE ударник"
name: '"<NAME>"'
text: '''Атакуя, если у вас есть 1 или меньше карт повреждений, бросьте 1 дополнительный кубик атаки.'''
'''"Countdown"''':
ship: "TIE ударник"
name: '"Обратный Отсчет"'
text: '''Защищаясь, если у вас нет Стресса, во время шага "Сравнение результатов кубиков" вы можете получить 1 повреждение, чтобы отменить <strong>все</strong> результаты кубиков. Если вы делаете это, получите 1 жетон Стресса.'''
'<NAME>':
name: "<NAME>"
ship: "Икс-Крыл T-70"
text: '''Когда вы получаете жетон Стресса, если в вашей арке огня на расстоянии 1 есть вражеский корабль, вы можете сбросить этот жетон стресса.'''
'"<NAME>" <NAME>':
name: "<NAME>"
ship: "Икс-Крыл T-70"
text: '''После того, как вы выполняете маневр со скоростью 2, 3 или 4, если вы не касаетесь другого корабля, вы можете выполнить свободное действие Бочку.'''
'<NAME>':
name: "<NAME>"
ship: "Икс-Крыл T-70"
text: '''Атакуя или защищаясь, вы можете перебросить 1 из ваших кубиков за каждый другой дружественный корабль на расстоянии 1.'''
'<NAME>':
ship: "TIE истребитель"
name: "<NAME>"
text: '''В начале фазы Боя, вы можете потратить 1 жетон Концентрации, чтобы выбрать дружественный корабль на расстоянии 1. Он может выполнить 1 свободное действие.'''
'<NAME>':
ship: "TIE истребитель"
name: "<NAME>"
text: '''После выполнения атаки, назначьте защищающемуся карту состояния "Подавляющий огонь".'''
'<NAME>':
ship: "Шаттл класса Ипсилон"
name: "<NAME>"
text: '''С точки зрения ваший действий и карт улучшений, вы можете считать дружественные корабли на расстоянии 2-3 как находящиеся на расстоянии 1.'''
'<NAME>':
ship: "Шаттл класса Ипсилон"
name: "<NAME>"
text: '''Во время расстановки, дружественные корабли могут располагаться где угодно на игровом поле на расстоянии 1-2 от вас.'''
'<NAME>':
ship: "Квадджампер"
name: "<NAME>"
text: '''Когда вы открываете реверсивный маневр, вы можете сбрасывать бомбу, испольтзуя ваши передние направляющие (в том числе бомбы с указателем "<strong>Действие:</strong>").'''
'<NAME>':
name: "<NAME>"
ship: "Квадджампер"
text: '''Защищаясь, вместо того, чтобы использовать ваше значение Маневренности, вы можете бросить число кубиков защиты, равное скорости маневра, который вы выполняли на этом ходу.'''
"Blue Squadron <NAME>finder":
name: "<NAME> <NAME>"
ship: "Ю-Крыл"
"Black Squadron Scout":
name: "<NAME>"
ship: "TIE ударник"
"Scarif Defender":
name: "<NAME>ащ<NAME>"
ship: "TIE ударник"
"Imperial Trainee":
name: "Имперский кадет"
ship: "TIE ударник"
"Starkiller Base Pilot":
ship: "Шаттл класса Ипсилон"
name: "Пилот базы Старкиллер"
"J<NAME>":
ship: "Квадджампер"
name: "Стрелок с Джакку"
'<NAME>':
name: "<NAME>"
ship: "Перехватчик M3-A"
text: '''После получения захвата цели, назначьте жетоны Концентрации и Уклонения на ваш корабль, пока у вас не будет такого же количества каждого жетона, как и на корабле в захвате.'''
'<NAME>':
name: "<NAME>"
ship: "Перехватчик M3-A"
text: '''В начале фазы Боя, вы можете получить жетон "Орудие выведено из строя", чтобы перевернуть 1 из ваших сброшенных карт улучшений %TORPEDO% или %MISSILE%.'''
'<NAME>':
name: "<NAME>"
ship: "Перехватчик M3-A"
text: '''Атакуя или защищаясь, вы можете потратить 1 щит, чтобы перебросить любое количество ваших кубиков.'''
'Sunny Bounder':
name: "<NAME>"
ship: "Перехватчик M3-A"
text: '''Один раз за ход, после того, как вы бросаете или перебрасываете кубик, если у вас выпал тот же результат на каждом кубике, добавьте 1 соответствующий результат.'''
'C-ROC Cruiser':
ship: "Крейсер C-ROC"
name: "Крейс<NAME> C-ROC"
'<NAME>':
name: "<NAME>"
ship: "TIE агрессор"
text: '''Атакуя, вы можете потратить 1 жетон Концентрации, чтобы отменить все пустые и %FOCUS% результаты защищающегося.'''
'"Double Edge"':
ship: "TIE агрессор"
name: "<NAME>"
text: '''Один раз за ход, после того, как вы выполнили атаку вспомогательным оружием, которая не попала, вы можете выполнить атаку другим оружием.'''
'Onyx Squadron Escort':
ship: "TIE агрессор"
name: "<NAME>"
'Sienar Specialist':
ship: "TIE агрессор"
name: "<NAME>арский специалист"
'<NAME>':
name: "<NAME>"
ship: "Истребитель Кихраксз"
text: '''После защиты, если вы не бросили ровно 2 кубика защиты, атакующий получает 1 жетон Стресса.'''
'<NAME>':
name: "<NAME>"
ship: "Канонерка Озитук"
text: '''Когда другой дружественный корабль на расстоянии 1 защищается, вы можете потратить 1 жетон Усиления. Если вы делаете это, защищающийся добавляет 1 результат %EVADE%.'''
'W<NAME>':
name: "<NAME>"
ship: "Канонерка Озитук"
text: '''Атакуя, если у вас нет щитов и есть хотя бы 1 назначенная карта повреждений, бросьте 1 дополнительный кубик атаки.'''
'W<NAME> Li<NAME>ator':
name: "<NAME>"
ship: "Канонерка Озитук"
'<NAME>yyyk Defender':
name: "<NAME>"
ship: "Канонерка Озитук"
'Captain Nym (Scum)':
name: "<NAME> (Пираты)"
ship: "Бомбардировщик Скуррг H-6"
text: '''Вы можете игнорировать дружественные бомбы. Когда дружественный корабль защищается, если атакующий меряет дистанцию через дружественный жетон бомбы, защищающийся может добавить 1 результат %EVADE%.'''
'Captain Nym (Rebel)':
name: "<NAME> (Повстанцы)"
ship: "Бомбардировщик Скуррг H-6"
text: '''Один раз за ход, вы можете предотвратить взрыв дружественной бомбы.'''
'Lok Revenant':
name: "<NAME>"
ship: "Бомбардировщик Скуррг H-6"
'<NAME>':
name: "<NAME>"
ship: "Бомбардировщик Скуррг H-6"
'<NAME>':
name: "<NAME>"
ship: "Бомбардировщик Скуррг H-6"
text: '''Сбрасывая бомбу, вы можете использовать шаблон (%TURNLEFT% 1) или (%TURNRIGHT% 1) вместо шаблона (%STRAIGHT% 1).'''
'<NAME>':
name: "<NAME>"
ship: 'Звездная Гадюка'
text: '''Если у вас нет Стресса, когда вы открываете маневр крена, поворота или Петлю Сеньора, вместо этого вы можете считать это красным маневром Коготь того же направления (влево или вправо), используя шаблон изначально открытого маневра.'''
'<NAME>':
name: "<NAME>"
ship: 'Звездная Гадюка'
text: '''Во время расстановки, перед шагом "Расстановка сил", вы можете выбрать 1 вражеский корабль и назначить ему карту состояния "Затененный" или "Мимикрированный".'''
'<NAME>':
name: "<NAME>"
ship: "Истребитель Кихраксз"
text: '''Один раз за ход, после того, как вражеский корабль, не защищающийся от атаки, получает повреждение или критическое повреждение, вы можете выполнить атаку против этого корабля.'''
'<NAME>':
ship: "Звездное Крыло класса Альфа"
name: "<NAME>"
text: '''Защищаясь, если у вас есть жетон Оружие выведено из Строя, бросьте 1 дополнительный кубик защиты.'''
'Nu Squadron Pilot':
name: "<NAME>"
ship: "Звездное Крыло класса Альфа"
'Rho Squadron Veteran':
name: "<NAME>"
ship: "Звездное Крыло класса Альфа"
'<NAME>':
ship: "Звездное Крыло класса Альфа"
name: "<NAME>"
text: '''Когда вы получаете жетон Оружие выведено из Строя, если вы не под Стрессом, вы можете получить 1 жетон Стресса, чтобы убрать его.'''
'<NAME>':
name: "<NAME>"
ship: "Истребитель M12-L Кимогила"
'<NAME>':
name: "<NAME>"
ship: "Истребитель M12-L Кимогила"
'<NAME>':
name: "<NAME>"
ship: "Истребитель M12-L Кимогила"
text: '''После выполнения атаки, каждый вражеский корабль в вашей арке прицельного огня на расстоянии 1-3 должен выбрать: получить 1 повреждение или убрать все жетоны Концентрации и Уклонения.'''
'<NAME> (Kimogila)':
name: "<NAME> (Кимогила)"
ship: "Истребитель M12-L Кимогила"
text: '''В начале фазы Боя, вы можете получить захват цели на вражеский корабль в вашей арке прицельного огня на расстоянии 1-3.'''
'<NAME> (Sheathipede)':
name: "<NAME> (Колчан)"
ship: "Шаттл класса Колчан"
text: '''Когда вражеский корабль в вашей арке огня на расстояниим 1-3 становится активным кораблем во время фазы Боя, если у вас нет Стресса, вы можете получить 1 жетон Стресса. Если вы делаете это, тот корабль не может тратить жетоны для модификации его кубиков во время атаки на этом ходу.'''
'<NAME> (Sheathipede)':
name: "<NAME> (Колчан)"
ship: "Шаттл класса Колчан"
text: """Защищаясь, если у вас нет Стресса, вы можете заменить до 2 ваших результатов %FOCUS% на результаты %EVADE%."""
'"Zeb" Orrelios (Sheathipede)':
name: "<NAME> (Колчан)"
ship: "Шаттл класса Колчан"
text: '''Защищаясь, вы можете отменять результаты %CRIT% перед результатами %HIT%.'''
'AP-5':
ship: "Шаттл класса Колчан"
text: '''Когда вы выполняете действие Координации, после выбора дружественного корабля и перед выполнением им свободного действия, вы можете получить 2 жетона Стресса, чтобы убрать с него 1 жетон Стресса.'''
'Crimson Squadron Pilot':
name: "<NAME>"
ship: "Бомбардировщик B/SF-17"
'"Crimson Leader"':
name: '"<NAME>"'
ship: "Бомбардировщик B/SF-17"
text: '''Атакуя, если защищающийся находится в вашей арке огня, вы можете потратить 1 результат %HIT% или %CRIT%, чтобы назначить карту состояния "Разбитый" на защищающегося.'''
'"Crimson Specialist"':
name: '"<NAME>"'
ship: "Bombardero B/SF-17"
text: '''Размещая жетон бомбы, которую вы сбросили после открытия диска маневров, вы можете расположить жетон бомбы где угодно в игровой зоне, касаясь вашего корабля.'''
'"Cobalt Leader"':
name: '"<NAME>"'
ship: "Бомбардировщик B/SF-17"
text: '''Атакуя, если защищающийся находится на расстоянии 1 от жетона бомбы, защищающийся бросает на 1 кубик защиты меньше.'''
'Sienar-Jaemus Analyst':
name: "<NAME>"
ship: "TIE глушитель"
'First Order Test Pilot':
name: "<NAME>етчик-испытатель <NAME>"
ship: "TIE глушитель"
'<NAME> (TIE Silencer)':
name: "<NAME> (TIE глушитель)"
ship: "TIE глушитель"
text: '''В первый раз за ход, когда вы получаете попадание, назначьте атакующему карту состояния "Я покажу тебе Темную Сторону".'''
'Test Pilot "Blackout"':
name: 'Летчик-испытатель "<NAME>"'
ship: "TIE глушитель"
text: '''Атакуя, если атака идет через преграду, защищающийся бросает на 2 кубика защиты меньше.'''
'<NAME>':
name: "<NAME>"
ship: "Икс-Крыл"
text: '''After you perform a boost or barrel roll action, you may flip your equipped "Servomotor S-foils" upgrade card.'''
'Major Vermeil':
name: "<NAME>"
text: '''Атакуя, если у защищающегося нет жетонов Концентрации или Уклонения, вы можете заменить 1 из ваших пустых или %FOCUS% результатов на результат %HIT%.'''
'Capt<NAME>':
text: '''When defending, if the attacker is jammed, add 1 %EVADE% result to your roll.'''
'"Viz<NAME>"':
text: '''After a friendly ship executes a 1-speed maneuver, if it is at Range 1 and did not overlap a ship, you may assign 1 of your focus or evade tokens to it.'''
'<NAME>':
text: '''When another friendly ship at Range 1-2 is defending, the attacker cannot reroll more than 1 attack die.'''
'Edrio Two-Tubes':
text: '''When you become the active ship during the Activation phase, if you have 1 or more focus tokens, you may perform a free action.'''
upgrade_translations =
"Ion Cannon Turret":
name: "<NAME>"
text: """<strong>Атака:</strong> Атакуйте 1 корабль(даже корабль вне вашей арки стрельбы).<br /><br />Если атака попадает по кораблю-цели, корабль получает 1 повреждение и 1 ионный жетон. Затем отмените все результаты кубиков."""
"Proton Tor<NAME>":
name: "<NAME>онные т<NAME>еды"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете заменить 1 результат %FOCUS% на результат %CRIT%."""
"R2 Astromech":
name: "<NAME>стромех R2"
text: """Можете считать все маневры со скоростью 1 и 2 зелеными маневрами."""
"R2-D2":
text: """После выполнения зеленого маневра, вы можете восстановить 1 щит (до максимального значения щитов)."""
"R2-F2":
text: """<strong>Действие:</strong> Увеличьте вашу Маневренность на 1 до конца этого хода."""
"R5-D8":
text: """<strong>Действие:</strong> Бросьте 1 кубик защиты.<br /><br />При результате %EVADE% или %FOCUS%, сбросьте 1 из ваших карт повреждений, лежащих лицом вниз."""
"R5-K6":
text: """После того, как вы потратили захват цели, бросьте 1 кубик защиты.<br /><br />При результате %EVADE% немедленно получите захват цели на том же корабле. Вы не можете использовать этот захват цели во время этой атаки."""
"R5 Astromech":
name: "Астромех R5"
text: """Во время фазы Завершения, вы можете выбрать одну из ваших карт повреждений лицом вверх со свойством <strong>Корабль</strong> и перевернуть ее лицом вниз."""
"Determination":
name: "Решительность"
text: """Если вы получили карту повреждений лицом вверх со свойством <strong>Пилот</strong>, сбросьте ее немедленно, не отрабатывая ее эффект."""
"Swarm Tactics":
name: "<NAME>"
text: """В начале фазы Боя, вы можете выбрать 1 дружественный корабль на расстоянии 1.<br /><br />До конца этой фазы, считайте умение пилота выбранного корабля равным вашему."""
"Squad Leader":
name: "<NAME>"
text: """<strong>Действие:</strong> Выберите 1 корабль на расстоянии 1-2, умение пилота которого ниже вашего.<br /><br />Выбранный корабль может немедленно выполнить 1 свободное действие."""
"Expert Handling":
name: "Мастерское управление"
text: """<strong>Действие:</strong> Выполните свободное действие Бочку. Если у вас нет значка действий %BARRELROLL%, получите 1 жетон Стресса.<br /><br />Затем вы можете убрать 1 вражеский захват цели с вашего корабля."""
"Marksmanship":
name: "<NAME>"
text: """<strong>Действие:</strong> Атакуя в этот ход, вы можете сменить 1 из ваших результатов %FOCUS% на результат %CRIT% , и все прочие результаты %FOCUS% на результат %HIT%."""
"Concussion Missiles":
name: "Ударные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете сменить 1 пустой результат на результат %HIT%."""
"Cluster Missiles":
name: "Кластерные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку <strong>дважды</strong>."""
"Daredevil":
name: "<NAME>"
text: """<strong>Действие:</strong> Выполните белый (%TURNLEFT% 1) или (%TURNRIGHT% 1) маневр. Затем получите 1 жетон стресса.<br /><br />Затем, если у вас нет значка действия %BOOST%, бросьте 2 кубика атаки. Получите любое выброшенное повреждение(%HIT%) или критическое повреждение(%CRIT%)."""
"Elusiveness":
name: "Уклончивость"
text: """Защищаясь, вы можете получить 1 жетон стресса чтобы выбрать 1 кубик атаки. Атакующий должен перебросить этот кубик.<br /><br />Если у вас есть хотя бы 1 жетон стресса, вы не можете использовать эту способность."""
"Homing Missiles":
name: "Самонаводящиеся ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Защищающийся не может использовать жетоны уклонения во время этой атаки."""
"Push the Limit":
name: "Предел возможностей"
text: """Один раз за ход, после выполнения действия, вы можете выполнить 1 свободное действие, отображенное на вашей полоске действий.<br /><br />Затем получите 1 жетон стресса."""
"Deadeye":
name: "М<NAME>"
text: """%SMALLSHIPONLY%%LINEBREAK%Вы можете считать <strong>"Атака (захват цели)"</strong> как <strong>"Атака (концентрация)"</strong>.<br /><br />Когда атака обязывает вас использовать захват цели, вместо этого вы можете использовать жетон Концентрации."""
"Expose":
name: "<NAME>"
text: """<strong>Действие:</strong> До конца хода увеличьте значение основной атаки на 1 и снизьте значение уклонения на 1."""
"Gun<NAME>":
name: "<NAME>"
text: """После проведения атаки без попадания, вы можете немедленно выполнить атаку основным оружием. Вы не можете выполнять другую атаку на этом ходу."""
"Ion Cannon":
name: "Ионная пушка"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.<br /><br />Если атака попадает, защищающийся получает 1 повреждение и получает 1 ионный жетон. Затем отмените <b>все</b> результаты кубиков."""
"Heavy Laser Cannon":
name: "Тяжелая лазерная пушка"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.<br /><br />Сразу после броска кубиков атаки, вы должны заменить все результаты %CRIT% на результаты %HIT%."""
"Seismic Charges":
name: "Сейсмические заряды"
text: """Когда вы открываете диск маневров, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон сейсмического заряда.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы Активации.<br /><br /><strong>Жетон сейсмического заряда:</strong> Когда этот жетон бомбы взрывается, каждый корабль на расстоянии 1 от жетона получает 1 повреждение. Затем сбросьте этот жетон."""
"Mercenary Copilot":
name: "Второй пилот-наемник"
text: """Атакуя на расстоянии 3, вы можете сменить 1 результат %HIT% на результат %CRIT%."""
"Assault Missiles":
name: "Штурмовые ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если эта атака попадает, каждый другой корабль на расстоянии 1 от защищающегося получает 1 повреждение."""
"Veteran Instincts":
name: "Инстинкт<NAME> ветер<NAME>"
text: """Повышает умение пилотирования на 2."""
"Proximity Mines":
name: "Мины приближения"
text: """<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>сбросить</strong> 1 жетон мины приближения.<br /><br />Когда подставка корабля или шаблон маневра перекрывает этот жетон, он <strong>взрывается</strong>.<br /><br /><strong>Жетон мины приближения:</strong> Когда этот бомбовый жетон взрывается, корабль, прошедший через него или вставший на нем бросает 3 кубика атаки и получает все выброшенные результаты повреждений(%HIT%) и критических повреждений(%CRIT%). Затем сбросьте этот жетон."""
"Weapons Engineer":
name: "Инженер-оружейник"
text: """Вы можете поддерживать 2 захвата цели(только 1 на каждый вражеский корабль).<br /><br />Когда вы получаете захват цели, вы можете захватывать 2 разных корабля."""
"Draw Their Fire":
name: "Огонь на себя"
text: """Когда дружественный корабль на расстоянии 1 получает попадание от атаки, вы можете получить 1 из неотмененных %CRIT% результатов вместо целевого корабля."""
"<NAME>":
name: "<NAME>"
text: """После проведения атаки без попадания вы можете немедленно провести атаку основным оружием. Вы можете сменить 1 результат %FOCUS% на результат %HIT%. Вы не можете выполнять другую атаку в этот ход."""
"<NAME>":
name: "<NAME>"
text: """Вы можете считать все %STRAIGHT% маневры как зеленые маневры."""
"<NAME>":
name: "<NAME>"
text: """Когда вы получаете карту повреждений, вы можете немедленно сбросить эту карту и восстановить 1 щит.<br /><br />Затем сбросьте эту карту улучшения."""
"Advanced Proton Torpedoes":
name: "Улучшенные протонные торпеды"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете заменить до 3 ваших пустых результатов на результаты %FOCUS%."""
"Autoblaster":
name: "Автобластер"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.<br /><br />Ваши %HIT% результаты не могут быть отменены кубиками защиты.<br /><br />Защищающийся может отменять результаты %CRIT% до результатов %HIT%."""
"Fire-Control System":
name: "Система контроля огня"
text: """После выполнения атаки, вы можете получить захват цели на защищающемся."""
"Blaster Turret":
name: "Бластерная турель"
text: """<strong>Атака(концентрация):</strong> Потратьте 1 жетон Концентрации чтобы выполнить эту атаку против 1 корабля (даже вне пределов вашей арки огня)."""
"Recon Specialist":
name: "Специалист разведки"
text: """Когда вы выполняете действие Концентрации, назначьте 1 дополнительный жетон Концентрации на ваш корабль."""
"Saboteur":
name: "Саботажник"
text: """<strong>Действие:</strong> Выберите 1 вражеский корабль на расстоянии 1 и бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, выберите 1 случайную карту, лежащую лицом вниз на этом корабле, переверните ее и отработайте ее."""
"Intelligence Agent":
name: "<NAME>"
text: """В начале фазы Активации выберите 1 вражеский корабль на расстоянии 1-2. Вы можете посмотреть на выбранный маневр этого корабля."""
"<NAME>":
name: "<NAME>ы"
text: """Когда вы открываете ваш диск маневра, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон протонной бомбы.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы активации.<br /><br /><strong>Жетон протонной бомбы:</strong> Когда этот бомбовый жетон взрывается, каждый корабль на расстоянии 1 от жетона получает карту повреждения лицом вверх. Затем сбросьте этот жетон."""
"<NAME>":
name: "<NAME>"
text: """Когда вы открываете красный маневр, вы можете сбросить эту карту чтобы считать этот маневр как белый маневр до конца фазы Активации."""
"Advanced Sensors":
name: "Продвинутые сенсоры"
text: """Сразу перед объявлением маневра, вы можете выполнить 1 свободное действие.<br /><br />Если вы используете эту способность, вы должны пропустить шаг "Выполнение действия" в этом ходу."""
"<NAME>":
name: "<NAME>"
text: """Защищаясь, вы можете сменить 1 результат %HIT% атакующего на результат %FOCUS%.<br /><br />Атакующий не может перебрасывать кубик с измененным результатом."""
"<NAME>":
name: "<NAME>"
text: """После того, как вы выполните атаку вражеского корабля, вы можете получить 2 повреждения чтобы заставить тот корабль получить 1 критическое повреждение."""
"Rebel Captive":
name: "<NAME>"
text: """Один раз за ход, первый корабль, заявляющий вас целью атаки, немедленно получает 1 жетон стресса."""
"Flight Instructor":
name: "<NAME>"
text: """Защищаясь, вы можете перебросить 1 из ваших результатов %FOCUS%. Если умение пилота атакующего "2" или ниже, вместо этого вы можете перебросить 1 пустой результат."""
"Navigator":
name: "<NAME>"
text: """Когда вы открываете маневр, вы можете повернуть ваш диск на другой маневр того же типа.<br /><br />Вы не можете выбирать красный маневр если у вас есть жетон(ы) Стресса."""
"Opportunist":
name: "Оппортунист"
text: """При атаке, если защищающийся не имеет жетонов Концентрации или Уклонения, вы можете получить 1 жетон стресса чтобы бросить 1 дополнительный кубик атаки.<br /><br />Вы не можете использовать эту способность если у вас есть жетон(ы) стресса."""
"Comms Booster":
name: "Усилитель связи"
text: """<strong>Энергия:</strong> Потратьте 1 энергии, чтобы убрать все жетоны Стресса с дружественного корабля на расстоянии 1-3. Затем назначьте 1 жетон Концентрации на тот корабль."""
"Slicer Tools":
name: "Электронные боевые системы"
text: """<strong>Действие:</strong> Выберите 1 или более кораблей на расстоянии 1-3, имеющих жетон Стресса. За каждый выбранный корабль, вы можете потратить 1 энергии чтобы заставить этот корабль получить 1 повреждение."""
"Shield Projector":
name: "Проект<NAME>"
text: """Когда вражеский корабль заявляет маленький или большой корабль целью атаки, вы можете потратить 3 энергии, чтобы заставить этот корабль атаковать вас (при возможности)."""
"Ion Pulse Missiles":
name: "Ионные импульсные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если эта атака попадает, защищающийся получает 1 повреждение и 2 ионных жетона. Затем отмените <strong>все</strong> результаты кубиков."""
"<NAME>":
name: "<NAME>"
text: """В начале фазы <NAME>, уберите 1 жетон стресса с другого дружественного корабля на расстоянии 1."""
"<NAME>":
name: "<NAME>"
text: """В начале фазы <NAME>, вы можете выбрать 1 дружественный корабль на расстоянии 1-2. Поменяйтесь умением пилота с умением пилота этого корабля до конца этой фазы."""
"<NAME>":
name: "<NAME>"
text: """Атакуя корабль в вашей арке огня, если вы не находитесь в арке огня этого корабля, его Маневренность снижается на 1."""
"<NAME>":
name: "<NAME>"
text: """Атакуя, вы можете перебросить 1 кубик атаки. Если умение пилота защищающегося "2" или ниже, вместо этого вы можете перебросить до 2 кубиков атаки."""
"<NAME>":
name: "<NAME>"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />После выполнения этой атаки, защищающийся получает 1 жетон стресса, если его значение корпуса 4 или ниже."""
"R7 Astromech":
name: "Астромех R7"
text: """Один раз за ход, защищаясь, если у вас есть захват цели на атакующего, вы можете потратить этот захват цели чтобы выбрать любой или все кубики атаки. Атакующий должен перебросить выбранные кубики."""
"R7-T1":
name: "R7-T1"
text: """<strong>Действие:</strong> Выберите вражеский корабль на расстоянии 1-2. Если вы находитесь в арке огня этого корабля, вы можете получить захват цели на этот корабль. Затем вы можете выполнить свободное действие Ускорения"""
"Tactician":
name: "<NAME>"
text: """%LIMITED%%LINEBREAK%После того, как вы выполните атаку против корабля в вашей арке стрельбы на расстоянии 2, этот корабль получает 1 жетон стресса."""
"R2-D2 (Crew)":
name: "R2-D2 (Экипаж)"
text: """В конце фазы Завершения, если у вас нет щитов, вы можете восстановить 1 щит и бросить 1 кубик атаки. При результате %HIT%, случайным образом выберите и переверните 1 карту повреждений, лежащую лицом вниз, и отработайте ее."""
"C-3PO":
name: "C-3PO"
text: """Один раз за ход, перед тем, как бросить 1 или более кубиков защиты, вы можете заявить вслух количество результатов %EVADE%. Если вы выбросили именно столько (до модификации кубиков), добавьте 1 %EVADE% результат."""
"Single Turbolasers":
name: "Одноствольные турболазеры"
text: """<strong>Атака (Энергия):</strong> Потратьте 2 энергии с этой карты чтобы выполнить эту атаку. Защищающийся удваивает свою Маневренность против этой атаки. Вы можете сменить 1 из ваших результатов %FOCUS% на 1 результат %HIT%."""
"Quad Laser Cannons":
name: "Счетверенные лазерные пушки"
text: """<strong>Атака (Энергия):</strong> Потратьте 1 энергии с этой карты чтобы выполнить эту атаку. Если атака не попала, вы можете немедленно потратить 1 энергии с этой карты чтобы выполнить эту атаку снова."""
"Tibanna Gas Supplies":
name: "Склад тибаннского газа"
text: """<strong>Энергия:</strong> Вы можете сбросить эту карту чтобы получить 3 энергии."""
"Ionization Reactor":
name: "Ионизационный реактор"
text: """<strong>Энергия:</strong> Потратьте 5 энергии с этой карты и сбросьте эту карту чтобы заставить каждый другой корабль на расстоянии 1 получить 1 повреждение и 1 ионный жетон"""
"Engine Booster":
name: "Ускоритель двигателя"
text: """Сразу перед открытием вашего диска маневров, вы можете потратить 1 энергию чтобы выполнить белый (%STRAIGHT% 1)маневр. Вы не можете использовать эту способность если вы перекроете другой корабль."""
"R3-A2":
name: "R3-A2"
text: """Когда вы заявляете цель для атаки, если защищающийся находится в вашей арке огня, вы можете получить 1 жетон Стресса чтобы заставить защищающегося получить 1 жетон стресса."""
"R2-D6":
name: "R2-D6"
text: """Ваша панель улучшений получает значок улучшения %ELITE%.<br /><br />Вы не можете выбрать это улучшение если вы уже имеете значок улучшения %ELITE% или если ваше умение пилота "2" или ниже."""
"Enhanced Scopes":
name: "Улучшенная оптика"
text: """Во время фазы Активации, считайте ваше умение пилота равным "0"."""
"Chardaan Refit":
name: "Чардаанский тюнинг"
ship: "А-Крыл"
text: """<span class="card-restriction">Только для А-Крыла.</span><br /><br />Эта карта имеет отрицательное значение очковой стоимости отряда."""
"Proton Rockets":
name: "Протонные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете бросить дополнительные кубики атаки, равные по количеству вашему значению Маневренности, до максимума в 3 кубика."""
"<NAME>":
name: "<NAME>"
text: """После того, как вы снимаете жетон Стресса с вашего корабля, вы можете назначить жетон Концентрации на ваш корабль."""
"<NAME>":
name: "<NAME>"
text: """Один раз за ход, когда дружественный корабль на расстоянии 1-3 выполняет действие Концентрации или получает жетон Концентрации, вы можете назначить ему жетон Уклонения вместо этого."""
"<NAME>":
name: "<NAME>"
text: """<strong>Действие:</strong> Потратьте любое количество энергии чтобы выбрать это количество кораблей на расстоянии 1-2. Уберите все жетоны Концентрации, Уклонения, и синие жетоны захвата цели с этих кораблей."""
# TODO Check card formatting
"R4-D6":
name: "R4-D6"
text: """Когда вы получаете попадание от атаки и имеете по меньшей мере 3 неотмененных результата %HIT% , вы можете отменить эти результаты пока не останется 2. За каждый результат, отмененный этим способом, получите 1 жетон стресса."""
"R5-P9":
name: "R5-P9"
text: """В конце фазы Боя, вы можете потратить 1 из ваших жетонов Концентрации чтобы восстановить 1 щит (до максимального значения ваших щитов)."""
"WED-15 Repair Droid":
name: "Ремонтный дроид WED-15"
text: """<strong>Действие:</strong> Потратьте 1 энергии чтобы сбросить 1 из ваших карт повреждений, лежащих лицом вниз, или потратьте 3 энергии чтобы сбросить 1 из ваших карт повреждений, лежащих лицом вверх."""
"<NAME>":
name: "<NAME>"
text: """В начале фазы Активации, вы можете сбросить эту карту чтобы считать умение пилота каждого дружественного корабля как "12" до конца фазы."""
"<NAME>":
name: "<NAME>"
text: """Когда другой дружественный корабль на расстоянии 1 атакует, он может сменить 1 результат %HIT% на 1 результат %CRIT%."""
"Expanded Cargo Hold":
name: "Расширенный грузовой отсек"
text: """<span class="card-restriction">Только для GR-75</span><br /><br />Один раз за ход, когда вы должны получить карту повреждений лицом вверх, вы можете потянуть эту карту из колоды повреждений носовой или кормовой части."""
ship: 'Средний транспорт GR-75'
"Backup Shield Generator":
name: "Вспомогательный генератор щита"
text: """В конце каждого хода вы можете потратить 1 энергии чтобы восстановить 1 щит (до максимального значения щитов)."""
"EM Emitter":
name: "ЭМ эмиттер"
text: """Когда вы перекрываете атаку, защищающийся бросает 3 дополнительных кубика защиты (вместо 1)."""
"Frequency Jammer":
name: "Г<NAME>"
text: """Когда вы выполняете действие Заклинивания, выберите 1 вражеский корабль, не имеющий жетон стресса и находящийся на расстоянии 1 от заклинившего корабля. Выбранный корабль получает 1 жетон стресса."""
"<NAME>":
name: "<NAME>"
text: """Когда вы атакуете, если у вас есть захват цели на защищающемся, вы можете потратить этот захват цели чтобы сменить все результаты %FOCUS% на результаты %HIT%."""
"<NAME>":
name: "<NAME>"
text: """В начале фазы Активации вы можете сбросить эту карту чтобы позволить всем дружественным кораблям, объявляющим красный маневр, считать этот маневр белым до конца фазы."""
"<NAME>":
name: "<NAME>"
text: """В начале фазы Активации, выберите 1 вражеский корабль на расстоянии 1-3. Вы можете посмотреть на выбранный маневр этого корабля. Если маневр белый, назначьте этому кораблю 1 жетон стресса."""
"Gunnery Team":
name: "О<NAME>дий<NAME>"
text: """Один раз за ход, атакуя вспомогательным оружием, вы можете потратить 1 энергии чтобы сменить 1 пустой результат на результат %HIT%."""
"Sensor Team":
name: "Сенсорная <NAME>"
text: """При получении захвата цели, вы можете захватывать вражеский корабль на расстоянии 1-5 вместо 1-3."""
"Engineering Team":
name: "И<NAME>ж<NAME>"
text: """Во время фазы активации, когда вы открываете %STRAIGHT% маневр, получите дополнительно 1 энергии во время шага "Получение энергии"."""
"<NAME>":
name: "<NAME>"
text: """<strong>Действие:</strong> Бросьте 2 кубика защиты. За каждый результат %FOCUS% назначьте 1 жетон Концентрации на ваш корабль. За каждый результат %EVADE% , назначьте 1 жетон Уклонения на ваш корабль."""
"<NAME>":
name: "<NAME>"
text: """В конце фазы Боя, каждый вражеский корабль на расстоянии 1, не имеющий жетона Стресса, получает 1 жетон Стресса."""
"Fleet Officer":
name: "<NAME>"
text: """<strong>Действие:</strong> Выберите до двух дружественных кораблей на расстоянии 1-2 и назначьте 1 жетон концентрации каждому из них. Затем получите 1 жетон Стресса."""
"Lone Wolf":
name: "<NAME>"
text: """Атакуя или защищаясь, при отсутствии других дружественных кораблей на расстоянии 1-2, вы можете перебросить 1 из ваших пустых результатов."""
"Stay On Target":
name: "Оставайся на цели"
text: """Когда вы открываете маневр, вы можете повернуть ваш диск на другой маневр с той же скоростью.<br /><br />Считайте эот маневр красным маневром."""
"Dash Rendar":
name: "<NAME>"
text: """Вы можете проводить атаки, перекрывая подставкой препятствие.<br /><br />Ваши атаки не могут быть перекрыты."""
'"L<NAME>"':
name: "<NAME>"
text: """<strong>Действие:</strong> Выполните свободное действие Ускорение. Затем получите 1 ионный жетон."""
"Ruthlessness":
name: "Беспощадность"
text: """После того, как вы выполните атаку, которая попала, вы <strong>должны</strong> выбрать 1 корабль на расстоянии 1 от защищающегося (кроме себя). Этот корабль получает 1 повреждение."""
"<NAME>":
name: "<NAME>"
text: """Когда вы касаетесь вражеского корабля, его Маневренность снижается на 1."""
"<NAME>":
name: "<NAME>"
text: """В начале фазы Боя, если у вас нет щитов и на ваш корабль назначена хотя бы 1 карта повреждений, вы можете провести свободное действие Уклонения."""
"<NAME>":
name: "<NAME>"
text: """Когда вы получаете карту повреждений лицом вверх, вы можете сбросить эту карту или другую карту улучшений %CREW% типа, чтобы перевернуть эту карту повреждений лицом вниз (не отрабатывая ее эффект)."""
"Ion Torpedoes":
name: "Ионные т<NAME>ы"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если эта атака попадет, защищающийся и каждый корабль на расстоянии 1 получает 1 ионный жетон."""
"Bomb Loadout":
name: "Бомбовая загрузка"
text: """<span class="card-restriction">Только для У-Крыла.</span><br /><br />Ваша панель улучшений получает значок %BOMB%."""
ship: "У-Крыл"
"Bodyguard":
name: "Телохранитель"
text: """%SCUMONLY%<br /><br />В начале фазы Боя, вы можете потратить жетон Концентрации, чтобы выбрать дружественный корабль с более высоким умением пилота на расстоянии 1. Увеличьте его значение Маневренности на 1 до конца хода."""
"Calculation":
name: "Счисление"
text: """Атакуя, вы можете потратить жетон Концентрации, чтобы сменить 1 из ваших результатов %FOCUS% на результат %CRIT%."""
"Accuracy Corrector":
name: "Корректировщик огня"
text: """Атакуя, во время шага "Модификация кубиков атаки", вы можете отменить все результаты кубиков. Затем, вы можете добавить 2 результата %HIT% к броску.<br /><br />Ваши кубики не могут быть модифицированы снова во время этой атаки."""
"Inertial Dampeners":
name: "Инерциальные амортизаторы"
text: """Когда вы открываете ваш маневр, вы можете сбросить эту карту чтобы вместо него выполнить белый [0%STOP%] маневр. Затем получите 1 жетон Стресса."""
"Flechette Cannon":
name: "Осколочная пушка"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK% Если эта атака попадает, защищающийся получает 1 повреждение и, если он не имеет жетонов Стресса, также получает 1 жетон Стресса. Затем отмените <strong>все</strong> результаты кубиков."""
'"M<NAME>" Cannon':
name: '<NAME> "<NAME>"'
text: """<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK% Атакуя, вы можете заменить 1 результат %HIT% на результат %CRIT%."""
"Dead Man's Switch":
name: "Кнопка мертвеца"
text: """Когда вы уничтожены, каждый корабль на расстоянии 1 получает 1 повреждение."""
"Feedback Array":
name: "Матрица обратной связи"
text: """Во время фазы Боя, вместо выполнения каких-либо атак, вы можете получить 1 ионный жетон и 1 повреждение, чтобы выбрать 1 вражеский корабль на расстоянии 1. Этот корабль получает 1 повреждение."""
'"Hot Shot" Blaster':
name: "<NAME>"
text: """<strong>Атака:</strong> Сбросьте эту карту, чтобы атаковать 1 корабль (даже корабль вне вашей арки огня)."""
"Greedo":
name: "<NAME>"
text: """%SCUMONLY%<br /><br />В первый раз за ход, когда вы атакуете, и в первый раз за ход, когда вы защищаетесь, первая нанесенная карта повреждений отрабатывается в открытую."""
"Outlaw Tech":
name: "Техник вне закона"
text: """%SCUMONLY%<br /><br />После того, как вы выполнили красный маневр, вы можете назначить 1 жетон Концентрации на ваш корабль."""
"K4 Security Droid":
name: "Дроид безопасности K4"
text: """%SCUMONLY%<br /><br />После выполнения зеленого маневра, вы можете получить захват цели."""
"Salvaged Astromech":
name: "Трофейный астромех"
text: """Когда вы получаете карту повреждений лицом вверх с обозначением <strong>Корабль</strong>, вы можете немедленно сбросить эту карту (не отрабатывая ее эффект).<br /><br />Затем сбросьте эту карту."""
'"Genius"':
name: '"Г<NAME>"'
text: """После того, как вы откроете и выполните маневр, если вы не перекрываете другой корабль, вы можете сбросить 1 из ваших карт улучшения %BOMB% без указателя <strong>Действие:</strong> чтобы сбросить соответствующий жетон бомбы."""
"Unhinged Astromech":
name: "Неподвешенный астромех"
text: """Вы можете считать маневры со скоростью 3 зелеными маневрами."""
"R4 Agromech":
name: "Агромех R4"
text: """Атакуя, после того, как вы потратили жетон Концентрации, вы можете получить захват цели на защищающегося."""
"R4-B11":
text: """Атакуя, если у вас есть захват цели на защищающегося, вы можете потратить захват цели чтобы выбрать любые кубики защиты. Защищающийся должен перебросить выбранные кубики."""
"Autoblaster Turret":
name: "Автобластерная турель"
text: """<strong>Атака:</strong> Атакуйте 1 корабль (даже если он находится вне вашей арки огня).<br /><br />Ваши %HIT% результаты не могут быть отменены кубиками защиты.<br /><br />Защищающийся может отменять результаты %CRIT% до результатов %HIT%."""
"Advanced Targeting Computer":
ship: "TIE Улучшенный"
name: "Улучшенный компьютер наведения"
text: """<span class="card-restriction">Только для TIE улучшенный.</span>%LINEBREAK%Атакуя основным оружием, если у вас есть захват цели на защищающегося, вы можете добавить 1 результат %CRIT% к вашему броску. Если вы решаете это сделать, вы не можете использовать захваты цели во время этой атаки."""
"Ion Cannon Battery":
name: "Батарея ионных пушек"
text: """<strong>Атака (Энергия):</strong> Потратьте 2 энергии с этой карты чтобы выполнить эту атаку. Если эта атака попадает, защищающийся получает 1 критическое повреждение и 1 ионный жетон. Затем отмените <strong>все</strong> результаты кубиков."""
"Emperor Palpatine":
name: "<NAME>"
text: """%IMPERIALONLY%%LINEBREAK%Один раз за ход, до того как дружественный корабль бросает кубики, вы можете назвать результат кубика. После броска вы должны заменить 1 из ваших резултьтатов на кубиках на названный результат. Результат этого кубика не может быть модифицирован снова."""
"Bossk":
name: "Босск"
text: """%SCUMONLY%%LINEBREAK%После того, как вы выполнили атаку, которая не попала, если у вас нет Стресса, вы <strong>должны</strong> получить 1 жетон Стресса. Затем получите 1 жетон Концентрации на ваш корабль, а также получите захват цели на защищающегося."""
"Lightning Reflexes":
name: "Молниеносные рефлексы"
text: """%SMALLSHIPONLY%%LINEBREAK%После выполнения белого или зеленого маневра, вы можете сбросить эту карту чтобы развернуть корабль на 180°. Затем получите 1 жетон стресса <strong>после</strong> шага "Проверка стресса пилота."""
"Twin Laser Turret":
name: "Спаренная лазерная турель"
text: """<strong>Атака:</strong> Выполните эту атаку <strong>дважды</strong> (даже против корабля вне вашей арки огня).<br /><br />Каждый раз, когда эта атака попадает, защищающийся получает 1 повреждение. Затем отмените <strong>все</strong> результаты кубиков."""
"Plasma Torpedoes":
name: "Плазменные торпеды"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если атака попадает, после нанесения повреждений, снимите 1 жетон щита с защищающегося."""
"Ion Bombs":
name: "Ионные бомбы"
text: """Когда вы открываете диск маневров, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон ионной бомбы.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы Активации.<br /><br /><strong>Жетон ионной бомбы:</strong> Когда этот жетон бомбы взрывается, каждый корабль на расстоянии 1 от жетона получает 2 ионных жетона. Затем сбросьте этот жетон."""
"Conner Net":
name: "<NAME>"
text: """<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>бросить</strong> 1 жетон сети Коннер.<br /><br />Когда подставка корабля или шаблон маневра перекрывает этот жетон, он <strong>взрывается</strong>.<br /><br /><strong>Жетон сети Коннер:</strong> Когда этот бомбовый жетон взрывается, корабль, прощедший через него или перекрывший его, получает 1 повреждение, 2 ионных жетона и пропускает шаг "Выполнение действия". Затем сбросьте этот жетон."""
"<NAME>":
name: "<NAME>"
text: """Сбрасывая бомбу, вы можете использовать шаблон (%STRAIGHT% 2) вместо шаблона (%STRAIGHT% 1)."""
"Cluster Mines":
name: "Кластерные мины"
text: """<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>бросить</strong> комплект кластерных мин (3 жетона).<br /><br />Когда подставка корабля или шаблон маневра перекрывает жетон кластерной мины, он <strong>взрывается</strong>.<br /><br /><strong>Жетоны кластерных мин:</strong> Когда один из этих жетонов бомб взрывается, корабль, прощедший через него или перекрывший его, бросает 2 кубика атаки и получает 1 повреждение за каждый результат %HIT% или %CRIT%. Затем сбросьте этот жетон."""
'Crack Shot':
name: "Точный выстрел"
text: '''Когда вы атакуете корабль в вашей арке огня, в начале шага "Сравнение результатов", вы можете сбросить эту карту чтобы отменить 1 результат %EVADE% защищающегося.'''
"Advanced Homing Missiles":
name: "Улучшенные самонаводящиеся ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадает, назначьте 1 карту повреждений лицом вверх защищающемуся. Затем отмените <strong>все</strong> результаты кубиков."""
'Agent Kallus':
name: "<NAME>"
text: '''%IMPERIALONLY%%LINEBREAK%В начале первого хода, выберите 1 маленький или большой корабль врага. Атакуя или защищаясь против этого корабля, вы можете сменить 1 из ваших результатов %FOCUS% на результат %HIT% или %EVADE%.'''
'XX-23 S-Thread Tracers':
name: "Следящие маяки XX-23"
text: """<strong>Атака (Концентрация):</strong> Cбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK% Если эта атака попадает, каждый дружественный корабль на расстоянии 1-2 от вас может получить захват цели на защищающемся. Затем отмените <strong>все</strong> результаты кубиков."""
"Tractor Beam":
name: "<NAME>"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK%Если эта атака попадает, защищающийся получает 1 жетон <NAME>. Затем отмените <strong>все</strong> результаты кубиков."""
"Cloaking Device":
name: "Маскировочное устройство"
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Действие:</strong> Выполните свободное действие Маскировки.%LINEBREAK%В конце каждого хода, если вы замаскированы, бросьте 1 кубик атаки. При результатк %FOCUS%, сбросьте эту карту, затем размаскируйтесь или сбросьте ваш жетон Маскировки."""
"Shield Technician":
name: "Техник щита"
text: """%HUGESHIPONLY%%LINEBREAK%Когда вы выполняете действие Восстановления, вместо того, чтобы потратить всю вашу энергию, вы можете выбрать количество энергии для использования."""
"<NAME>":
name: "<NAME>"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%В начале фазы Боя, вы можете выбрать другой корабль на расстоянии 1-4. Затем уберите 1 жетон Концентрации с выбранного корабля, или же назначьте 1 жетон концентрации на него."""
"Captain Needa":
name: "<NAME>"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%Если вы перекрываете препятствие во время фазы Активации, не получайте 1 карту повреждений лицом вверх. Вместо этого, бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, получите 1 повреждение."""
"Admir<NAME> O<NAME>el":
name: "<NAME>"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%<strong>Энергия</strong>: Вы можете снять до 3 щитов с вашего корабля. За каждый убранный щит, получите 1 энергии."""
'Glitterstim':
name: "<NAME>"
text: """В начале фазы Боя, вы можете сбросить эту карту и получить 1 жетон стресса. Если вы делаете это, до конца хода, защищаясь или атакуя, вы можете сменить все ваши результаты %FOCUS% на результаты %HIT% или %EVADE%."""
'Extra Munitions':
name: "Дополнительные боеприпасы"
text: """Когда вы экипируете эту карту, положите 1 жетон боеприпасов на каждую экипированную карту улучшений %TORPEDO%, %MISSILE% и %BOMB%. Когда вы должны сбросить карту улучшений, вместо этого вы можете сбросить жетон боеприпасов с этой карты."""
"Weapons Guidance":
name: "Система наведения"
text: """Атакуя, вы можете потратить жетон Концентрации, чтобы заменить 1 из ваших пустых результатов на результат %HIT%."""
"BB-8":
text: """Когда вы открываете зеленый маневр, вы можете выполнить свободное действие Бочку."""
"R5-X3":
text: """Перед открытием вашего маневра, вы можете сбросить эту карту, чтобы игнорировать препятствия до конца хода."""
"Wired":
name: "Подключенный"
text: """Атакуя или защищаясь, если у вас есть жетон Стресса, вы можете перебросить 1 или более результатов %FOCUS%."""
'Cool Hand':
name: "Хладнокровный"
text: '''Когда вы получаете жетон стресса, вы можете сбросить эту карту чтобы назначить 1 жетон Концентрации или Уклонения на ваш корабль.'''
'Juke':
name: "Финт"
text: '''%SMALLSHIPONLY%%LINEBREAK%Атакуя, если у вас есть жетон Уклонения, вы можете заменить 1 из результатов %EVADE% защищающегося на результат %FOCUS%.'''
'Comm Relay':
name: "Реле связи"
text: '''Вы не можете иметь больше 1 жетона Уклонения.%LINEBREAK%Во время фазы Завершения, не убирайте неиспользованный жетон Уклонения с вашего корабля.'''
'Twin Laser Turret':
name: "Двойная лазерная турель"
text: '''%GOZANTIONLY%%LINEBREAK%<strong>Атака (Энергия):</strong> Потратьте 1 энергии с этой карты чтобы выполнить эту атаку против 1 корабля (даже если он находится вне вашей арки огня).'''
'Broadcast Array':
name: "Реле вещания"
text: '''%GOZANTIONLY%%LINEBREAK%Ваша панель действий получает значок %JAM%.'''
'<NAME>':
name: "<NAME>"
text: '''%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Действие:</strong> Выполните белый(%STRAIGHT% 1) маневр.'''
'Ordnance Experts':
name: "Ракетные эксперты"
text: '''Один раз за ход, когда дружественный корабль на расстоянии 1-3 атакует вспомогательным оружием %TORPEDO% или %MISSILE%, он может заменить 1 пустой результат на результат %HIT%.'''
'Docking Clamps':
name: "Доковые порты"
text: '''%GOZANTIONLY% %LIMITED%%LINEBREAK%Вы можете пристыковать до 4 TIE истребителей, TIE перехватчиков, TIE улучшенных или TIE бомбардировщиков к этому кораблю. Все пристыкованные корабли должны иметь один и тот же тип корабля.'''
'"Zeb" Orrelios':
name: "<NAME>"
text: """%REBELONLY%%LINEBREAK%Вражеские корабли в вашей арке огня, которых вы касаетесь, не считаются касающимися вас, когда они или вы активируетесь во время фазы Боя."""
'Kanan Jarrus':
name: "<NAME>"
text: """%REBELONLY%%LINEBREAK%Один раз за ход, после того, как дружественный корабль на расстоянии 1-2 выполняет белый маневр, вы можете снять 1 жетон Стресса с того корабля."""
'Reinforced Deflectors':
name: "Усиленные отражатели"
text: """%LARGESHIPONLY%%LINEBREAK%После защиты, если вы получили 3 или более повреждений или критических повреждений во время атаки, восстановите 1 щит (до максимального значения щитов)."""
'Dorsal Turret':
name: "Палубная турель"
text: """<strong>Атака:</strong> Атакуйте 1 корабль (даже если он находится вне вашей арки огня).%LINEBREAK%Если цель атаки находится на расстоянии 1, бросьте 1 дополнительный кубик атаки."""
'Targeting Astromech':
name: "Астром<NAME> н<NAME>ения"
text: '''После выполнения красного маневра, вы можете получить захват цели.'''
'<NAME>':
name: "<NAME>"
text: """%REBELONLY%%LINEBREAK%Вы можете открывать и выполнять красные маневры, даже находясь под Стрессом."""
'<NAME>':
name: "<NAME>"
text: """%REBELONLY%%LINEBREAK%Атакуя, если вы под Стрессом, вы можете заменить 1 результат %FOCUS% на результат %CRIT%."""
'S<NAME>':
name: "<NAME>"
text: """%REBELONLY%%LINEBREAK%Ваша панель улучшений получает значок %BOMB%. Один раз за ход, перед тем, как убрать дружественный жетон бомбы, выберите 1 вражеский корабль на расстоянии 1 от этого жетона. Этот корабль получает 1 повреждение."""
'"Chopper"':
name: "<NAME>"
text: """%REBELONLY%%LINEBREAK%Вы можете выполнять действия, находясь под Стрессом.%LINEBREAK%После того, как вы выполнили действие, находясь под Стрессом, получите 1 повреждение."""
'Construction Droid':
name: "Строительный дроид"
text: '''%HUGESHIPONLY% %LIMITED%%LINEBREAK%Когда вы выполняете действие Восстановления, вы можете потратить 1 энергии, чтобы сбросить 1 карту повреждений, лежащую лицом вниз.'''
'Cluster Bombs':
name: "Кластерные бимбы"
text: '''После защиты, вы можете сбросить эту карту. Если вы делаете это, любой другой корабль на расстоянии 1 от защищающейся секции бросает 2 кубика атаки, получая выброшенные повреждения (%HIT%) и критические повреждения (%CRIT%).'''
"Adaptability":
name: "Адаптивность"
text: """<span class="card-restriction">Двойная карта.</span>%LINEBREAK%<strong>Сторона A:</strong> Увеличьте ваше умение пилота на 1.%LINEBREAK%<strong>Сторона Б:</strong> Уменьшите ваше умение пилота на 1."""
"Electronic Baffle":
name: "Электронный экран"
text: """Когда вы получаете жетон стресса или ионный жетон, вы можете получить 1 повреждение чтобы сбросить этот жетон."""
"4-LOM":
text: """%SCUMONLY%%LINEBREAK%Атакуя, во время шага "Модификация кубиков атаки", вы можете получить 1 ионный жетон чтобы выбрать 1 из жетонов Концентрации или Уклонения защищающегося. Этот жетон не может использоваться во время этой атаки."""
"<NAME>":
name: "<NAME>"
text: """%SCUMONLY%%LINEBREAK%Атакуя, если вы не под Стрессом, вы можете получить любое количество жетонов Стресса, чтобы выбрать равное количество кубиков защиты. Защищающийся должен перебросить эти кубики."""
'<NAME>':
name: "<NAME>"
text: """<strong>Действие:</strong> Назначьте 1 жетон Концентрации вашему кораблю и получите 2 жетона Стресса. До конца хода, при атаке, вы можете перебросить до 3 кубиков атаки."""
"<NAME>":
name: "<NAME>"
text: """%SCUMONLY%%LINEBREAK%Каждый раз, когда вы получаете жетон Концентрации или Стресса, каждый другой дружественный корабль с Мысленной связью Аттанни также должен получить тот же тип жетона, если его у него нет."""
"<NAME>":
name: "<NAME>"
text: """%SCUMONLY%%LINEBREAK%После выполнения атаки, если защищающийся получил карту повреждений лицом вверх, вы можете сбросить эту карту чтобы выбрать и сбросить 1 карту улучшений защищающегося."""
"<NAME>":
name: "<NAME>"
text: """%SCUMONLY%%LINEBREAK%Атакуя, вы можете перебросить 1 кубик атаки. Если защищающийся - уникальный пилот, вы можете перебросить до 2 кубиков атаки."""
'"<NAME>"':
name: '"<NAME>"'
text: """%SCUMONLY%%LINEBREAK%<strong>Действие:</strong> Положите 1 жетон щита на эту карту.%LINEBREAK%<strong>Действие:</strong> Уберите 1 жетон щита с этой карты чтобы восстановить 1 щит (до максимального значения щитов)."""
"R5-P8":
text: """Один раз за ход, после защиты, вы можете бросить 1 кубик атаки. При результате %HIT%, атакующий получает 1 повреждение. При результате %CRIT%, вы и атакующий получаете 1 повреждение каждый."""
'Thermal Detonators':
name: "Термальные детонаторы"
text: """Когда вы открываете диск маневров, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон термального детонатора.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы Активации.<br /><br /><strong>Жетон термального детонатора:</strong> Когда этот жетон бомбы взрывается, каждый корабль на расстоянии 1 от жетона получает 1 повреждение и 1 жетон Стресса. Затем сбросьте этот жетон."""
"Overclocked R4":
name: "Разогнанный R4"
text: """Во время фазы Боя, когда вы тратите жетон Концентрации, вы можете получить 1 жетон Стресса чтобы назначить 1 жетон Концентрации на ваш корабль."""
'Systems Officer':
name: "Системный офицер"
text: '''%IMPERIALONLY%%LINEBREAK%После выполнения зеленого маневра, выберите другой дружественный корабль на расстоянии 1. Этот корабль может получить захват цели.'''
'Tail Gunner':
name: "Кормовой стрелок"
text: '''Атакуя с кормовой вторичной арки огня, снизьте Маневренность защищающегося на 1.'''
'R3 Astromech':
name: "Астромех R3"
text: '''Один раз за ход, атакуя основным оружием, во время шага "Модификация кубиков атаки", вы можете отменить один из ваших результатов %FOCUS%, чтобы назначить 1 жетон Уклонения на ваш корабль.'''
'Collision Detector':
name: "Детектор столкновений"
text: '''Выполняя Ускорение, Бочку или Размаскировывание, ваш корабль и шаблон маневра могут накладываться на преграды.%LINEBREAK%При броске за повреждение от преград, игнорируйте все результаты %CRIT%.'''
'Sensor Cluster':
name: "Сенсорный кластер"
text: '''Защищаясь, вы можете потратить жетон Концентрации, чтобы сменить 1 из ваших пустых результатов на результат %EVADE%.'''
'Fearlessness':
name: "Бес<NAME>рашие"
text: '''%SCUMONLY%%LINEBREAK%Атакуя, если вы находитесь в арке огня защищающегося на расстоянии 1 и защищающийся находится в вашей арке огня, вы можете добавить 1 результат %HIT% к вашему броску.'''
'<NAME>':
name: "<NAME>"
text: '''%SCUMONLY%%LINEBREAK%В начале фазы Завершения, вы можете выбрать 1 корабль в вашей арке огня на расстоянии 1-2. Этот корабль не убирает свои жетоны Луча захвата.'''
'<NAME>':
name: "<NAME>"
text: '''%SCUMONLY%%LINEBREAK%Защищаясь, вы можете снять 1 жетон стресса с атакующего и добавить 1 результат %EVADE% к вашему броску.'''
'IG-88D':
text: '''%SCUMONLY%%LINEBREAK%Вы имеете способность пилота каждого другого дружественного корабля с картой улучшения <em>IG-2000</em> (в дополнение к вашей собственной способности пилота).'''
'Rigged Cargo Chute':
name: "Подъёмный грузовой желоб"
text: '''%LARGESHIPONLY%%LINEBREAK%<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>сбросить</strong> 1 жетон Груза.'''
'Seismic Torpedo':
name: "Сейсмическая торпеда"
text: '''<strong>Действие:</strong> Сбросьте эту карту чтобы выбрать препятствие на расстоянии 1-2 и в вашей арке огня. Каждый корабль на расстоянии 1 от препятствия бросает 1 кубик атаки и получает любое выброшенное повреждение (%HIT%) или критическое повреждение (%CRIT%). Затем уберите препятствие.'''
'Black Market Slicer Tools':
name: "Боевые системы с черного рынка"
text: '''<strong>Действие:</strong> Выберите вражеский корабль под Стрессом на расстоянии 1-2 и бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, уберите 1 жетон стресса и нанесите ему 1 повреждение лицом вниз.'''
# Wave X
'Kylo Ren':
name: "<NAME>"
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Действие:</strong> Назначьте карту состояния "Я покажу тебе Темную Сторону" на вражеский корабль на расстоянии 1-3.'''
'Unkar Plutt':
name: "<NAME>"
text: '''%SCUMONLY%%LINEBREAK%После выполнения маневра, который приводит к наложению на вражеский корабль, вы можете получить 1 повреждение, чтобы выполнить 1 свободное действие.'''
'A Score to Settle':
name: "<NAME>"
text: '''Во время расстановки, перед шагом "Расстановка сил", выберите 1 вражеский корабль и назначьте ему карту состояния "Счет к оплате"."%LINEBREAK%Атакуя корабль, имеющий карту состояния "Счет к оплате", вы можете заменить 1 результат %FOCUS% на результат %CRIT%.'''
'<NAME>':
name: "<NAME>"
text: '''%REBELONLY%%LINEBREAK%<strong>Действие:</strong> Выберите 1 дружественный корабль на расстоянии 1-2. Назначьте 1 жетон Концентрации на этот корабль за каждый вражеский корабль в вашей арке огня на расстоянии 1-3. Вы не можете назначить более 3 жетонов Концентрации этим способом.'''
'<NAME>':
name: "<NAME>"
text: '''%REBELONLY%%LINEBREAK%В конце фазы Планирования, вы можете выбрать вражеский корабль на расстоянии 1-2. Озвучьте скорость и направление маневра этого корабля, затем посмотрите на его диск маневров. Если вы правы, вы можете повернуть ваш диск на другой маневр.'''
'<NAME>':
name: "<NAME>"
text: '''%REBELONLY%%LINEBREAK%Атакуя основным оружием или защищаясь, если вражеский корабль находится в вашей арке огня, вы можете добавить 1 пустой результат к вашему броску.'''
'Re<NAME>':
name: "<NAME>"
text: '''%REBELONLY%%LINEBREAK%В начале фазы Завершения, вы можете положить 1 из жетонов Концентрации вашего корабля на эту карту. В начале фазы Боя, вы можете назначить 1 из этих жетонов на ваш корабль.'''
'Burnout SLAM':
name: "Ускоритель ССДУ"
text: '''%LARGESHIPONLY%%LINEBREAK%Ваша панель действий получает значок действия %SLAM%.%LINEBREAK%После выполнения действия ССДУ (СубСветовой Двигатель Ускорения), сбросьте эту карту.'''
'Primed Thrusters':
name: "<NAME>"
text: '''%SMALLSHIPONLY%%LINEBREAK%Вы можете выполнять действия Бочка и Ускорение, имея жетоны стресса, если их три или меньше.'''
'Pattern Analyzer':
name: "Шаблонный анализатор"
text: '''При выполнении маневра, вы можете отрабатывать шаг "Проверка стресса пилота" после шага "Выполнение действий" (вместо того, чтобы отрабатывать его перед этим шагом).'''
'Snap Shot':
name: "Выстрел навскидку"
text: '''После того, как вражеский корабль выполняет маневр, вы можете выполнить эту атаку против него.%LINEBREAK% <strong>Атака:</strong> Атакуйте 1 корабль. Вы не можете модифицировать кубики атаки и не можете атаковать снова в эту фазу.'''
'M9-G8':
text: '''%REBELONLY%%LINEBREAK%Когда корабль, на котором есть ваш жетон захвата, атакует, вы можете выбрать 1 кубик атаки. Атакующий должен перебросить этот кубик.%LINEBREAK%Вы можете заявлять захват цели на другие дружественные корабли.'''
'EMP Device':
name: "<NAME>рибор ЭМИ"
text: '''Во время фазы Боя, вместо выполнения любых атак, вы можете сбросить эту карту, чтобы назначить 2 ионных жетона на каждый корабль на расстоянии 1.'''
'Captain Rex':
name: "<NAME>"
text: '''%REBELONLY%%LINEBREAK%После проведения атаки, не завершившейся попаданием, вы можете назначить 1 жетон Концентрации на ваш корабль.'''
'General Hux':
name: "<NAME>"
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Действие:</strong> Выберите до 3 дружественных кораблей на расстоянии 1-2. Назначьте 1 жетон Концентрации на каждый из них, а также назначьте карту состояния "Фанатическая преданность" на 1 из них. Затем получите 1 жетон Стресса.'''
'Operations Specialist':
name: "Операционный специалист"
text: '''%LIMITED%%LINEBREAK%После того, как дружественный корабль на расстоянии 1-2 выполняет атаку, не завершившуюся попаданием, вы можете назначить 1 жетон Концентрации на дружественный корабль на расстоянии 1-3 от атакующего.'''
'Targeting Synchronizer':
name: "Целевой синхронизатор"
text: '''Когда дружественный корабль на расстоянии 1-2 атакует корабль, находящийся в вашем захвате, дружественный корабль считает указатель "<strong>Атака (Захват цели):</strong> как указатель "<strong>Атака:</strong>." Если игровой эффект обязывает этот корабль потратить захват цели, он может потратить ваш захват цели вместо этого.'''
'Hyperwave Comm Scanner':
name: "Гиперволновой сканер связи"
text: '''В начале шага "Расстановка сил", вы можете считать ваше умение пилота равным "0", "6" или "12" до конца этого шага.%LINEBREAK% Во время расстановки, после того, как другой дружественный корабль выставляется на расстоянии 1-2, вы можете назначить ему 1 жетон Концентрации или Уклонения.'''
'Trick Shot':
name: "Ловкий выстрел"
text: '''Атакуя, если вы стреляете через препятствие, вы можете бросить 1 дополнительный кубик атаки.'''
'Hotshot Co-pilot':
name: "Умелый второй пилот"
text: '''Когда вы атакуете основным оружием, защищающийся должен потратить 1 жетон Концентрации при возможности.%LINEBREAK%Когда вы защищаетесь, атакующий должен потратить 1 жетон Концентрации при возможности.'''
'''Scavenger Crane''':
name: "<NAME>"
text: '''После того, как корабль на расстоянии 1-2 уничтожен, вы можете выбрать сброшенную карту %TORPEDO%, %MISSILE%, %BOMB%, %CANNON%, %TURRET%, или Модификационное улучшение, которое было экипировано на ваш корабль, и вернуть его. Затем бросьте 1 кубик атаки. При пустом результате, сбросьте Кран мусорщика.'''
'B<NAME>':
name: "<NAME>"
text: '''%REBELONLY%%LINEBREAK%Когда вы заявляете захват цели, вы можете захватывать корабль врага на расстоянии 1-3 от любого дружественного корабля.'''
'Baze Malbus':
name: "<NAME>"
text: '''%REBELONLY%%LINEBREAK%После выполнения атаки, которая не попала, вы можете немедленно выполнить атаку основным оружием против другого корабля. Вы не можете выполнять другую атаку в этот ход.'''
'Inspiring Recruit':
name: "Вдохновляющий рекрут"
text: '''Один раз за ход, когда дружественный корабль на расстоянии 1-2 снимает жетон Стресса, он может снять 1 дополнительный жетон стресса.'''
'Swarm Leader':
name: "<NAME>"
text: '''Выполняя атаку основным оружием, выберите до 2 других дружественных кораблей, имеющих защищающегося в их арках огня на расстоянии 1-3. Снимите 1 жетон Уклонения с каждого выбранного корабля чтобы бросить 1 дополнительный кубик атаки за каждый убранный жетон Уклонения.'''
'Bistan':
name: "<NAME>"
text: '''%REBELONLY%%LINEBREAK%Атакуя на расстоянии 1-2, вы можете сменить 1 из ваших результатов %HIT% на результат %CRIT%.'''
'Expertise':
name: "Опытность"
text: '''Атакуя, если вы не под стрессом, вы можете заменить все ваши результаты %FOCUS% на результаты %HIT%.'''
'BoShek':
name: "<NAME>"
text: '''Когда корабль, которого вы касаетесь, активируется, вы можете посмотреть на его выбранный маневр. Если вы это делаете, он должен повернуть диск на противоположный маневр. Корабль может объявлять и выполнять этот маневр, даже находясь под Стрессом.'''
# C-ROC
'Heavy Laser Turret':
ship: "Крейсер C-ROC"
name: "<NAME>ерная <NAME>ель"
text: '''<span class="card-restriction">Только крейсер C-ROC</span>%LINEBREAK%<strong>Атака (Энергия):</strong> Потратьте 2 энергии с этой карты, чтобы выполнить эту атаку против 1 корабля (даже если он находится вне вашей арки огня).'''
'<NAME>':
name: "<NAME>"
text: '''%SCUMONLY%%LINEBREAK%В начале фазы Завершения, вы можете сбросить эту карту, чтобы заменить лежащую лицом вверх экипированную карту улучшения %ILLICIT% или %CARGO% на другую карту улучшения того же типа и той же (или меньшей) стоимости в очках отряда.'''
'<NAME>':
name: "<NAME>"
text: '''%HUGESHIPONLY% %SCUMONLY%%LINEBREAK%В начале фазы Завершения, вы можете потратить 1 энергии, чтобы заменить экипированную лежащую лицом вверх карту улучшений %CREW% или %TEAM% на другую карту улучшения того же типа и той же (или меньшей) стоимости в очках отряда.'''
'Quick-release Cargo Locks':
name: "Замки быстрого сброса груза"
text: '''%LINEBREAK%В конце фазы Активации, вы можете сбросить эту карту, чтобы <strong>положить</strong> 1 жетон Контейнера.'''
'Supercharged Power Cells':
name: "Сверхзаряженные энергоячейки"
text: '''Атакуя, вы можете сбросить эту карту, чтобы бросить 2 дополнительных кубика атаки.'''
'ARC Caster':
name: "Проектор ARC"
text: '''<span class="card-restriction">Только для Повстанцев или Пиратов. Двойная карта.</span>%DUALCARD%%LINEBREAK%<strong>Сторона A:</strong>%LINEBREAK%<strong>Атака:</strong> Атакуйте 1 корабль. Если эта атака попадает, вы должны выбрать 1 другой корабль на расстоянии 1 от защищающегося. Этот корабль получает 1 повреждение.%LINEBREAK%Затем переверните эту карту.%LINEBREAK%<strong>Сторона Б:</strong>%LINEBREAK%(Перезарядка) В начале фазы Боя, вы можете получить жетон Отключения оружия, чтобы перевернуть эту карту.'''
'Wookiee Commandos':
name: "Вуки ком<NAME>андос"
text: '''Атакуя, вы можете перебросить ваши результаты %FOCUS%.'''
'Synced Turret':
name: "Синхронная турель"
text: '''<strong>Атака (Захват цели):</strong> Атакуйте 1 корабль (даже если он находится вне вашей арки огня).%LINEBREAK%Если защищающийся находится в вашей арке огня, вы можете перебросить количество кубиков атаки, равное значению вашего основного оружия.'''
'Unguided Rockets':
name: "Неуправляемые ракеты"
text: '''<strong>Атака (Концентрация):</strong> Атакуйте 1 корабль.%LINEBREAK%Ваши кубики атаки могут быть модифицированы только с помощью использования жетона Концентрации.'''
'Intensity':
name: "Интенсивность"
text: '''%SMALLSHIPONLY% %DUALCARD%%LINEBREAK%<strong>Сторона A:</strong> После того, как вы выполните действие Ускорения или Бочку, вы можете назначить 1 жетон Концентрации или Уклонения на ваш корабль. Если вы делаете это, переверните эту карту.%LINEBREAK%<strong>Сторона Б:</strong> (Истощение) В конце фазы боя, вы можете потратить 1 жетон Концентрации или Уклонения, чтобы перевернуть эту карту.'''
'Jabba the Hutt':
name: "<NAME>"
text: '''%SCUMONLY%%LINEBREAK%Когда вы экипируете эту карту, положите 1 жетон Внезаконности на каждую карту улучшения %ILLICIT% в вашем отряде. Когда вы должны сбросить карту Улучшения, вместо этого вы можете сбросить 1 жетон Внезаконности с этой карты.'''
'IG-RM Thug Droids':
name: "Дроиды-головорезы IG-RM"
text: '''Атакуя, вы можете заменить 1 из ваших результатов %HIT% на результат %CRIT%.'''
'Selflessness':
name: "Самоотверженность"
text: '''%SMALLSHIPONLY% %REBELONLY%%LINEBREAK%Когда дружественный корабльт на расстоянии 1 получает попадание от атаки, вы можете сбросить эту карту, чтобы получить все неотмененные результаты %HIT% вместо корабля-цели.'''
'Breach Specialist':
name: "Специалист по пробоинам"
text: '''Когда вы получаете карту повреждений лицом вверх, вы можете потратить 1 жетон Усиления, чтобы перевернуть ее лицом вниз (не отрабатывая ее эффект). Если вы делаете это, то до конца хода, когда вы получаете карту .'''
'Bomblet Generator':
name: "<NAME>"
text: '''Когда вы открываете маневр, вы можете <strong>сбросить</strong> 1 жетон Минибомбы.%LINEBREAK%Этот жетон <strong>взрывается</strong> в конце фазы Активации.%LINEBREAK%<strong>Жетон минибомбы:</strong> Когда этот жетон взрывается, каждый корабль на расстоянии 1 бросает 2 кубика атаки и получает все выброшенные повреждения(%HIT%) и критические повреждения (%CRIT%). Затем уберите этот жетон.'''
'Cad Bane':
name: "<NAME>"
text: '''%SCUMONLY%%LINEBREAK%Ваша панель улучшений получает значок %BOMB%. Один раз за ход, когда вражеский корабль бросает кубики атаки из-за взрыва дружественной бомбы, вы можете выбрать любое количество пустых или %FOCUS% результатов. Он должен перебросить эти результаты.'''
'Minefield Mapper':
name: "Карта минных полей"
text: '''Во время расстановки, после шага "Расстановка сил", вы можете сбросить любое количество карт улучшений %BOMB%. Расположите все соответствующие жетоны бомб на игровом поле на расстоянии 3 и дальше от вражеских кораблей.'''
'R4-E1':
text: '''Вы можете выполнять действия на ваших картах улучшения %TORPEDO% и %BOMB%, даже находясь под Стрессом. После выполнения действия этим способом, вы можете сбросить эту карту, чтобы убрать 1 жетон Стресса с вашего корабля.'''
'Cruise Missiles':
name: "Крейсирующие ракеты"
text: '''<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Вы можете бросить дополнительные кубики атаки, равные по количеству скорости маневра, который вы выполнили в этот ход, до максимума в 4 дополнительных кубика.'''
'Ion Dischargers':
name: "Ионные разрядники"
text: '''После получения ионного жетона, вы можете выбрать вражеский корабль на расстоянии 1. Если вы делаете это, сбросьте ионный жетон. Затем тот корабль может решить получить 1 ионный жетон. Если он делает это - сбросьте эту карту.'''
'Har<NAME> M<NAME>':
name: "<NAME>"
text: '''<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадает, после отрабатывания атаки, назначьте защищающемуся карту состояния "Загарпунен!".'''
'Ordnance Silos':
name: "<NAME>"
ship: "Бомбардировщик B/SF-17"
text: '''<span class="card-restriction">Только бомбардировщик B/SF-17.</span>%LINEBREAK%Когда вы экипируете эту карту, положите 3 жетона Боеприпасов на каждую экипированную карту улучшений %BOMB%. Когда вы должны сбросить карту улучшений, вместо этого вы можете сбросить с этой карты жетон Боеприпасов.'''
'Trajectory Simulator':
name: "Симулятор траектории"
text: '''Вы можете запускать бомбы, используя шаблон (%STRAIGHT% 5) вместо того, стобы их сбрасывать. Вы не можете таким способом сбрасывать бомбы с указателем "<strong>Действие:</strong>".'''
'Jamming Beam':
name: "Луч заклинивания"
text: '''<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK%Если эта атака попадает, назначьте защищающемуся 1 жетон Заклинивания. Затем отмените <strong>все</strong> результаты кубиков.'''
'Linked Battery':
name: "Спаренная батарея"
text: '''%SMALLSHIPONLY%%LINEBREAK%Атакуя основным или %CANNON% вспомогательным оружием, вы можете перебросить 1 кубик атаки.'''
'Saturation Salvo':
name: "Плотный залп"
text: '''После того, как вы выполняете атаку вспомогательным оружием %TORPEDO% или %MISSILE%, которая не попала, каждый корабль на расстоянии 1 от защищающегося со значением Маневренности ниже, чем стоимость карты улучшения %TORPEDO% или %MISSILE% в очках отряда, должен бросить 1 кубик атаки и получить любое выброшенное повреждение (%HIT%) или критическое повреждение (%CRIT%).'''
'Contraband Cybernetics':
name: "Контрабандная кибернетика"
text: '''Когда вы становитесь активным кораблем во время фазы Активации, вы можете сбросить эту карту и получить 1 жетон стресса. Если вы делаете это, до конца хода вы можете выполнять действия и красные маневры, даже находясь под Стрессом.'''
'Maul':
name: "<NAME>ол"
text: '''%SCUMONLY% <span class="card-restriction">Игнорируйте это ограничение, если ваш отряд содержит Эзру Бриджера."</span>%LINEBREAK%Атакуя, если вы не под Стрессом, вы можете получить любое количество жетонов Стрееса, чтобы перебросить равное количество кубиков атаки.%LINEBREAK% После выполнения атаки, завершившейся попаданием, вы можете убрать 1 из ваших жетонов Стресса.'''
'Courier Droid':
name: "Дроид-курьер"
text: '''В начале шага "Расположение сил", вы можете выбрать считать ваше умение пилота равным "0" или "8" до конца этого шага.'''
'"Chopper" (Astromech)':
text: '''<strong>Действие: </strong>Сбросьте 1 другую экипированную карту улучшений, чтобы восстановить 1 щит.'''
'Flight-Assist Astromech':
name: "Полетный астромех"
text: '''Вы не можете атаковать корабли вне вашей арки огня.%LINEBREAK%После того, как вы выполните маневр, если вы не перекрываете корабль или преграду и не имеете кораблей врага в вашей арке огня на расстоянии 1-3, вы можете выполнить свободное действие Бочку или Ускорение.'''
'Advanced Optics':
name: "Улучшенная оптика"
text: '''Вы не можете иметь более 1 жетона Концентрации.%LINEBREAK%Во время фазы Завершения, не убирайте неиспользованный жетон Концентрации с вашего корабля.'''
'Scrambler Missiles':
name: "Ракеты с помехами"
text: '''<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадает, защищающийся и каждый другой корабль на расстоянии 1 получает 1 жетон Заклинивания. Затем отмените <strong>все</strong> результаты кубиков.'''
'R5-TK':
text: '''Вы можете заявлять захват цели на дружественные корабли.%LINEBREAK%Вы можете атаковать дружественные корабли.'''
'Threat Tracker':
name: "Детектор угроз"
text: '''%SMALLSHIPONLY%%LINEBREAK%Когда вражеский корабль в важей арке огня на расстоянии 1-2 становится активным кораблем во время фазы Боя, вы можете потратить захват цели на этом корабле, чтобы выполнить свободное действие Ускорение или Бочку, если оно есть на вашей панели действий.'''
'Debris Gambit':
name: "Уклонение в астероидах"
text: '''%SMALLSHIPONLY%%LINEBREAK%<strong>Действие:</strong> Назначьте 1 жетон Уклонения на ваш корабль за каждую преграду на расстоянии 1, до максимума в 2 жетона Уклонения.'''
'Targeting Scrambler':
name: "Помехи наведения"
text: '''В начале фазы Планирования, вы можете получить жетон Оружие выведено из строя, чтобы выбрать корабль на расстоянии 1-3 и назначить ему состояние "Помехи".'''
'<NAME>':
name: "<NAME>"
text: '''После того, как другой дружественный корабль на расстоянии 1 становится защищающимся, если вы находитесь в арке огня атакующего на расстоянии 1-3, атакующий получает 1 жетон Стресса.'''
'<NAME>':
name: "<NAME>"
text: '''%REBELONLY%%LINEBREAK%Атакуя, вы можете получить 1 повреждение, чтобы заменить все ваши результаты %FOCUS% на результаты %CRIT%.'''
'<NAME> <NAME>':
name: "<NAME>"
text: '''Во время расстановки, перед шагом "Расстановка сил", назначьте состояние "Оптимизированный прототип" на дружественный корабль Галактической Империи с 3 или меньшим количеством щитов.'''
'Tactical Officer':
text: '''%IMPERIALONLY%%LINEBREAK%Your action bar gains %COORDINATE%.'''
'ISB Slicer':
text: '''After you perform a jam action against an enemy ship, you may choose a ship at Range 1 of that ship that is not jammed and assign it 1 jam token.'''
'Thrust Corrector':
text: '''When defending, if you have 3 or fewer stress tokens, you may receive 1 stress token to cancel all of your dice results. If you do, add 1 %EVADE% result to your roll. Your dice cannot be modified again during this attack.%LINEBREAK%You can equip this Upgrade only if your hull value is "4" or lower.'''
modification_translations =
"Stealth Device":
name: "Маскировочное устройство"
text: """Увеличьте вашу Маневренность на 1. Если вы получаете попадание от атаки, сбросьте эту карту."""
"Shield Upgrade":
name: "Улучшенный щит"
text: """Ваше значение Щита увеличивается на 1."""
"Engine Upgrade":
name: "Улучшенный двигатель"
text: """Ваша панель действий получает значок %BOOST%."""
"Anti-Pursuit Lasers":
name: "Оборонительные лазеры"
text: """После того, как вражеский корабль выполняет маневр, приводящий к перекрытию им вашего корабля, бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, вражеский корабль получает 1 повреждение."""
"Targeting Computer":
name: "Компьютер наведения"
text: """Ваша панель действий получает значок %TARGETLOCK%."""
"Hull Upgrade":
name: "Укрепление корпуса"
text: """Ваше значение Корпуса повышается на 1."""
"Munitions Failsafe":
name: "Корректор промаха"
text: """Атакуя вспомогательным оружием, которое обязывает сбросить его для выполнения атаки, не сбрасывайте его, если атака не попала."""
"Stygium Particle Accelerator":
name: "Стигийский ускоритель частиц"
text: """Когда вы размаскировываетесь или выполняете действие Маскировки, вы можете выполнить свободное действие Уклонения."""
"Advanced Cloaking Device":
name: "Улучшеный маскировочный прибор"
text: """<span class="card-restriction">Только для TIE Фантом.</span><br /><br />После выполнения атаки, вы можете выполнить свободное действие Маскировки."""
ship: "TIE Фантом"
"Combat Retrofit":
name: "Боевое оснащение"
text: """<span class="card-restriction">Только для GR-75.</span><br /><br />Увеличьте ваше значение Корпуса на 2 и значение Щита на 1."""
ship: 'Средний транспорт GR-75'
"B-Wing/E2":
text: """<span class="card-restriction">Только для Б-Крыла.</span><br /><br />Ваша панель улучшений получает значок улучшения %CREW%."""
ship: "Б-Крыл"
"Countermeasures":
name: "Контрмеры"
text: """В начале фазы Боя, вы можете сбросить эту карту, чтобы повысить вашу Маневренность на 1 до конца хода. Затем вы можете убрать 1 вражеский захват цели с вашего корабля."""
"Experimental Interface":
name: "Экспериментальный интерфейс"
text: """Один раз за ход, после выполнения вами действия, вы можете выполнить 1 свободное действие с экипированной карты улучшений с указателем "<strong>Действие:</strong>". Затем получите 1 жетон Стресса."""
"Tactical Jammer":
name: "Тактический глушитель"
text: """Ваш корабль может служить преградой для вражеских атак."""
"Autothrusters":
name: "Автоускорители"
text: """Защищаясь, еслим вы далее расстояния 2 или находитесь вне арки огня атакующего, вы можете заменить 1 из ваших пустых результатов на результат %EVADE%. Вы можете экипировать это карту только при наличии значка %BOOST%."""
"Twin Ion Engine Mk. II":
name: "Двойной ионный двигатель Мк.II"
text: """<span class="card-restriction">Только для TIE.</span>%LINEBREAK%Вы можете считать все маневры крена (%BANKLEFT% и %BANKRIGHT%) зелеными маневрами."""
"Maneuvering Fins":
name: "Маневровые кили"
text: """<span class="card-restriction">Только для YV-666.</span>%LINEBREAK%Когда вы открываете маневр поворота (%TURNLEFT% или %TURNRIGHT%), вы можете повернуть ваш диск маневров на соответствующий маневр крена (%BANKLEFT% или %BANKRIGHT%) с той же скоростью."""
"Ion Projector":
name: "Ионный проектор"
text: """%LARGESHIPONLY%%LINEBREAK%После того, как вражеский корабль выполняет маневр, приводящий к перекрытию им вашего корабля, бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, вражеский корабль получает 1 ионный жетон."""
"Advanced SLAM":
name: "Улучшенный ССДУ"
text: """После выполнения действия ССДУ, если вы не перекрываете преграду или другой корабль, вы можете выполнить свободное действие с вашей панели действий."""
'Integrated Astromech':
name: "Интегрированный астромех"
text: '''<span class="card-restriction">Только для Икс-Крыла.</span>%LINEBREAK%Когда вы получаете карту повреждений, вы можете сбросить 1 из ваших карту улучшений %ASTROMECH% чтобы сбросить эту карту повреждений.'''
'Optimized Generators':
name: "Оптимизированные генераторы"
text: '''%HUGESHIPONLY%%LINEBREAK%Один раз за ход, когда вы назначаете энергию на экипированную карту улучшений, получите 2 энергии.'''
'Automated Protocols':
name: "Автоматизированные протоколы"
text: '''%HUGESHIPONLY%%LINEBREAK%Один раз за ход, после выполнения действия, не являющегося действием Восстановления или Усиления, вы можете потратить 1 энергии, чтобы выполнить свободное действие Восстановления или Усиления.'''
'Ordnance Tubes':
name: "Ракетные шахты"
text: '''%HUGESHIPONLY%%LINEBREAK%Вы можете считать каждый из ваших значков улучшений %HARDPOINT% как значок %TORPEDO% или %MISSILE%.%LINEBREAK%Когда вы должны сбросить карту улучшений %TORPEDO% или %MISSILE%, не сбрасывайте ее.'''
'Long-Range Scanners':
name: "Сканеры дальнего действия"
text: '''Вы можете объявлять захват цели на корабли на расстоянии 3 и дальше. Вы не можете объявлять захват цели на корабли на расстоянии 1-2. Вы можете екипировать эту карту только если у вас есть %TORPEDO% и %MISSILE% на вашей панели улучшений.'''
"Guidance Chips":
name: "Чипы наведения"
text: """Один раз за ход, атакуя вспомогательным оружием %TORPEDO% или %MISSILE%, вы можете заменить один результат кубика на %HIT% (или на результат %CRIT% , если значение вашего основного оружия "3" или больше)."""
'Vectored Thrusters':
name: "Векторные ускорители"
text: '''%SMALLSHIPONLY%%LINEBREAK%Ваша панель действий получает значок %BARRELROLL%.'''
'Smuggling Compartment':
name: "Отсек контрабанды"
text: '''<span class="card-restriction">Только для YT-1300 и YT-2400.</span>%LINEBREAK%Ваша панель улучшений получает значок %ILLICIT%.%LINEBREAK%Вы можете экипировать 1 дополнительное Модификационное улучшение, которое стоит 3 или меньше очков отряда.'''
'Gyroscopic Targeting':
name: "Гироскопическое наведение"
ship: "Корабль-преследователь класса Копьеносец"
text: '''<span class="card-restriction">Только для Корабля-преследователя класса Копьеносец.</span>%LINEBREAK%В конце фазы Боя, если в этом ходу вы выполняли маневр со скоростью 3, 4 или 5, вы можете повернуть вашу мобильную арку огня.'''
'Captured TIE':
ship: "TIE истребитель"
name: "TIE захваченный"
text: '''<span class="card-restriction">только для TIE.</span>%REBELONLY%%LINEBREAK%Вражеские корабли с умением пилота ниже вашего не могут объявлять вас целью атаки. После того, как вы выполните атаку или останетесь единственным дружественным кораблем, сбросьте эту карту.'''
'Spacetug Tractor Array':
name: "Матрица космической тяги"
ship: "Квадджампер"
text: '''<span class="card-restriction">Только для Квадджампера.</span>%LINEBREAK%<strong>Действие:</strong> Выберите корабль в вашей арке огня на расстоянии 1 и назначьте ему жетон Л<NAME> З<NAME>. Если это дружественный корабль, отработайте эффект жетона Луч<NAME> З<NAME>ата, как если бы это был вражеский корабль.'''
'Lightweight Frame':
name: "Облегченный каркас"
text: '''<span class="card-restriction">только для TIE.</span>%LINEBREAK%Защищаясь, после броска кубиков защиты, если кубиков атаки больше, чем кубиков защиты, бросьте 1 дополнительный кубик защиты.%LINEBREAK%Вы не можете экипировать эту карту, если ваша Маневренность "3" или выше.'''
'Pulsed Ray Shield':
name: "Импульсный лучевой щит"
text: '''<span class="card-restriction">Только для Повстанцев и Пиратов.</span>%LINEBREAK%Во время фазы Завершения, вы можете получить 1 ионный жетон чтобы восстановить 1 щит (до максимального значения щитов). Вы можете экипировать эту карту только если ваше значение Щитов "1".'''
'Deflective Plating':
name: "Отражающее покрытие"
ship: "Бомбардировщик B/SF-17"
text: '''<span class="card-restriction">Только для бомбардировщика B/SF-17.</span>%LINEBREAK%Когда взрывается дружественный жетон бомбы, вы можете выбрать не получать соответствующий эффект. Если вы делаете это, бросьте кубик атаки. При результате %HIT%, сбросьте эту карту.'''
'Multi-spectral Camouflage':
text: '''%SMALLSHIPONLY%%LINEBREAK%After you receive a red target lock token, if you have only 1 red target lock token, roll 1 defense die. On an %EVADE% result, remove 1 red target lock token.'''
title_translations =
"Slave I":
name: "Раб 1"
text: """<span class="card-restriction">Только для Огнедыщащего-31.</span><br /><br />Ваша панель улучшений получает значок улучшения %TORPEDO%."""
"Millennium Falcon":
name: "Тысячелетний сокол"
text: """<span class="card-restriction">Только для YT-1300.</span><br /><br />Ваша панель действий получает значок %EVADE%."""
"<NAME>":
name: "<NAME>"
text: """<span class="card-restriction">Только для HWK-290.</span><br /><br />Во время фазы Завершения, не убирайте неиспользованные жетоны Концентрации с вашего корабля."""
"ST-321":
text: """<span class="card-restriction">Только для шаттла класса <em>Лямбда</em>.</span><br /><br />При объявлении захвата цели, вы можете захватывать вражеский корабль по всему игровому полю."""
ship: "Шаттл класса Лямбда"
"Royal Guard TIE":
name: "TIE королевской <NAME>и"
ship: "TIE перехватчик"
text: """<span class="card-restriction">Только для TIE перехватчика.</span><br /><br />Вы можете экипировать до двух различных Модификационных улучшений (вместо 1).<br /><br />Вы не можете экипировать эту карту, если ваше умение пилота "4" или ниже."""
"<NAME>ride":
name: "<NAME>"
text: """<span class="card-restriction">Только для носовой части CR90.</span><br /><br />Когда вы выполняете действие Координации, вы можете выбрать 2 дружественных корабля (вместо 1). Каждый из этих кораблей может выполнить 1 свободное действие."""
ship: "Корвет CR90 (Нос)"
"A-Wing Test Pilot":
name: "<NAME>-ис<NAME> <NAME>"
text: """<span class="card-restriction">Только для А-Крыла.</span><br /><br />Ваша панель улучшений получает 1 значок %ELITE%.<br /><br />Вы не можете экипировать 2 одинаковых карты улучшений %ELITE%. Вы не можете экипировать эту карту, если ваше умение пилота "1" или ниже."""
ship: "А-Крыл"
"Tantive IV":
name: "<NAME>"
text: """<span class="card-restriction">Только для носовой части CR90.</span><br /><br />Ваша панель улучшений носовой секции получает 1 дополнительный значок %CREW% и 1 дополнительный значок %TEAM%."""
ship: "Корвет CR90 (Нос)"
"Bright Hope":
name: "<NAME>"
text: """<span class="card-restriction">Только для GR-75.</span><br /><br />Действие усиления, назначенное на вашу носовую часть, добавляет 2 результата %EVADE% вместо 1."""
ship: 'Средний транспорт GR-75'
"Quantum Storm":
name: "<NAME>"
text: """<span class="card-restriction">Только для GR-75.</span><br /><br />В начале фазы Завершения, если у вас 1 или меньше жетонов энергии, получите 1 жетон энергии."""
ship: 'Средний транспорт GR-75'
"Duty<NAME>":
name: "<NAME>"
text: """<span class="card-restriction">Только для GR-75./span><br /><br />При выполнении действия Заклинивания, вы можете выбрать вражеский корабль на расстоянии 1-3 (вместо 1-2)."""
ship: 'Средний транспорт GR-75'
"<NAME> Light":
name: "<NAME>"
text: """<span class="card-restriction">Только для носовой секции CR90.</span><br /><br />Защищаясь, один раз за атаку, если вы получаете карту повреждений лицом вверх, вы можете сбросить ее и вытянуть другую карту повреждений лицом вверх."""
"Outrider":
name: "<NAME>"
text: """<span class="card-restriction">Только для YT-2400.</span><br /><br />Когда у вас есть экипированная карта улучшения %CANNON%, вы <strong>не можете</strong> выполнять атаки основным оружием и можете выполнять атаки вспомогательным оружием %CANNON% против кораблей вне вашей арки огня."""
"Andrasta":
name: "<NAME>"
text: """<span class="card-restriction">Только для Огнедышащего-31.</span><br /><br />Ваша панель улучшений получает 2 дополнительных значка %BOMB%."""
"TIE/x1":
ship: "TIE улучшенный"
text: """<span class="card-restriction">Только для TIE улучшенного.</span>%LINEBREAK%Ваша панель улучшений получает значок %SYSTEM%.%LINEBREAK%Если вы экипируете улучшение %SYSTEM%, его стоимость в очках отряда снижается на 4 (до минимума в 0)."""
"BTL-A4 Y-Wing":
name: "BTL-A4 У-Крыл"
text: """<span class="card-restriction">Только для У-Крыла.</span><br /><br />Вы не можете атаковать корабли вне вашей арки огня. После выполнения атаки основным оружием, вы можете немедленно выполнить атаку вспомогательным оружием %TURRET%."""
ship: "У-Крыл"
"IG-2000":
name: "IG-2000"
text: """<span class="card-restriction">Только для Агрессора.</span><br /><br />Вы получаете способности пилотов каждого другого дружественного корабля с картой улучшения <em>IG-2000</em> (в дополнение к вашей собственной способности пилота)."""
ship: "Агрессор"
"Virago":
name: "<NAME>"
text: """<span class="card-restriction">Только для Звездной Гадюки.</span><br /><br />Ваша панель улучшений получает значки %SYSTEM% и %ILLICIT%.<br /><br />Вы не можете экипировать эту карту, если ваше умение пилота "3" или ниже."""
ship: 'Звездная гадюка'
'"Heavy Scyk" Interceptor (Cannon)':
name: 'Перехватчик "Тяжелый С<NAME>к" (Пушечный)'
text: """<span class="card-restriction">Только для перехватчика M3-A.</span><br /><br />Ваша панель улучшений получает значок %CANNON%. Ваше значение Корпуса повышается на 1."""
ship: 'Перехватчик M3-A'
'"Heavy Scyk" Interceptor (Missile)':
name: 'Перехватчик "Тяжелый Сцик" (Ракетный)'
text: """<span class="card-restriction">Только для перехватчика M3-A.</span><br /><br />Ваша панель улучшений получает значок %MISSILE%. Ваше значение Корпуса повышается на 1."""
ship: 'Перехватчик M3-A'
'"Heavy Scyk" Interceptor (Torpedo)':
name: 'Перехватчик "Тяжелый Сцик" (Торпедный)'
text: """<span class="card-restriction">Только для перехватчика M3-A.</span><br /><br />Ваша панель улучшений получает значок %TORPEDO%. Ваше значение Корпуса повышается на 1."""
ship: 'Перехватчик M3-A'
"Dauntless":
name: "Неустрашимый"
text: """<span class="card-restriction">Только для VT-49 Дециматора.</span><br /><br />После выполнения маневра, который привел к наложению на другой корабль, вы можете выполнить 1 свободное действие. Затем получите 1 жетон Стресса."""
ship: 'VT-49 Дециматор'
"Ghost":
name: "Призрак"
text: """<span class="card-restriction">Только для VCX-100.</span>%LINEBREAK%Екипируйте карту названия <em><NAME>ом</em> на дружественный Атакующий Шаттл, и пристыкуйте его к этому кораблю.%LINEBREAK%После выполнения маневра, вы можете отстыковать его из ваших задних направляющих."""
"<NAME>":
name: "<NAME>"
text: """Когда вы пристыкованы, <em>Призрак</em> может выполнять атаки его основным оружием, используя его специальную арку огня, а также, в конце фазы Боя, он может выполнить дополнительную атаку экипированной %TURRET%. Если он не может выполнить эту атаку, он не может атаковать снова в этот ход."""
ship: 'Атакующий шаттл'
"TIE/v1":
text: """<span class="card-restriction">Только для TIE улучшенного прототипа.</span>%LINEBREAK%После того, как вы получаете захват цели на другой корабль, вы можете выполнить свободное действие Уклонения."""
ship: 'TIE улучшенный прототип'
"<NAME>":
name: "<NAME>"
text: """<span class="card-restriction">Только для Звездного истребителя G-1A.</span>%LINEBREAK%Ваша панель действий получает значок %BARRELROLL%.%LINEBREAK%Вы <strong>должны</strong> экипировать 1 карту улучшений "Луч захвата"(считая ее стоимость в очках отряда как обычно)."""
ship: 'Звездный истребитель G-1A'
"Punishing One":
name: "<NAME>"
text: """<span class="card-restriction">Только для Джампмастера 5000.</span>%LINEBREAK%Увеличивает значение вашего основного оружия на 1."""
ship: 'Джампмастер 5000'
"H<NAME>'s Tooth":
name: "<NAME>"
text: """<span class="card-restriction">Только для YV-666.</span>%LINEBREAK%После того, как вы уничтожены, но перед тем, как убрать корабль с игрового поля, вы можете </strong>выставить корабль <span>Щенок Наштаха</span>.%LINEBREAK%El <span>Щенок Наштаха</span> не может атаковать в этот ход."""
"Ass<NAME>":
name: "<NAME>"
text: """<span class="card-restriction">Только для кормовой секции корвета класса <em>Рейдер</em>.</span>%LINEBREAK%Защищаясь, если целевая секция имеет жетон Усиления, вы можете заменить 1 результат %FOCUS% на 1 результат %EVADE%."""
"Instigator":
name: "<NAME>"
text: """<span class="card-restriction">Только для кормовой секции корвета класса <em>Рейдер</em>.</span>%LINEBREAK%После того, как вы выполняете действие Восстановления, восстановите 1 дополнительный щит."""
"Impetuous":
name: "<NAME>"
text: """<span class="card-restriction">Только для кормовой секции корвета класса <em>Рейдер</em>.</span>%LINEBREAK%После того, как вы выполняете атаку, уничтожившую вражеский корабль, вы можете получить захват цели."""
'TIE/x7':
text: '''<span class="card-restriction">Только для TIE защитника.</span>%LINEBREAK%Ваша панель улучшений теряет значки улучшений %CANNON% и %MISSILE%.%LINEBREAK%После выполнения маневра со скоростью 3, 4 или 5, если вы не перекрываете преграду или корабль, вы можете выполнить свободное действие Уклонения.'''
ship: 'TIE защитник'
'TIE/D':
text: '''<span class="card-restriction">Только для TIE защитника.</span>%LINEBREAK%Один раз за ход, после того, как вы выполнили атаку вспомогательным оружием %CANNON%, которое стоит 3 или менее очков отряда, вы можете выполнить атаку основным оружием.'''
ship: 'TIE защитник'
'TIE Shuttle':
name: "<NAME>"
text: '''<span class="card-restriction">Только для TIE бомбардировщика.</span>%LINEBREAK%Ваша панель улучшений теряет все значки улучшений %TORPEDO%, %MISSILE% и %BOMB% и получает 2 значка улучшений %CREW%. Вы не можете экипировать карту улучшений %CREW%, которая стоит больше 4 очков отряда.'''
ship: 'TIE бомбардировщик'
'Requiem':
name: "<NAME>"
text: '''%GOZANTIONLY%%LINEBREAK%Когда вы выставляете корабль, считайте его навык пилота равным "8" до конца хода.'''
'Vector':
name: "Вектор"
text: '''%GOZANTIONLY%%LINEBREAK%После выполнения маневра, вы можете разместить до 4 присоединенных кораблей (вместо 2).'''
'Suppressor':
name: "Подавитель"
text: '''%GOZANTIONLY%%LINEBREAK%Один раз за ход, после получения захвата цели на врага, вы можете убрать 1 жетон Концентрации, Уклонения или синий жетон захвата цели с этого корабля.'''
'Black One':
name: "<NAME>"
text: '''<span class="card-restriction">Только для Икс-Крыла Т-70.</span>%LINEBREAK%После того, как вы выполнили действие Ускорения или Бочку, вы можете снять 1 вражеский захват цели с дружественного корабля на расстоянии 1. Вы не можете экипировать эту карту, если ваш навык пилота "6" или ниже.'''
ship: "Икс-Крыл T-70"
'Millennium Falcon (TFA)':
name: "Тысячелетний Сокол (ПС)"
text: '''После выполнения маневра крена со скоростью 3 (%BANKLEFT% или %BANKRIGHT%), если вы не касаетесь другого корабля и не находитесь под Стрессом, вы можете получить 1 жетон Стресса, чтобы развернуть ваш корабль на 180°.'''
'Alliance Overhaul':
name: "Обновления Альянса"
text: '''<span class="card-restriction">Только для ARC-170.</span>%LINEBREAK%Атакуя основным оружием в вашей основной арке огня, вы можете бросить 1 дополнительный кубик атаки. Атакуя в вашей дополнительной арке огня, вы можете заменить 1 из ваших результатов %FOCUS% на 1 результат %CRIT%.'''
'Special Ops Training':
ship: "Истребитель TIE/сс"
name: "Специальная оперативная подготовка"
text: '''<span class="card-restriction">Только для TIE/сс.</span>%LINEBREAK%Атакуя основным оружием в вашей основной арке огня, вы можете бросить 1 дополнительный кубик атаки. Если вы не делаете этого, вы можете выполнить дополнительную атаку в вашей вспомогательной арке огня.'''
'Concord Dawn Protector':
name: "<NAME>"
ship: "Истребитель Протектората"
text: '''<span class="card-restriction">Только для истребителя Протектората.</span>%LINEBREAK%Защищаясь, если вы назходитесь в арке огня атакующего на расстоянии 1, и атакующий находится в вашей арке огня, добавьте 1 результат %EVADE%.'''
'Shadow Caster':
name: "Наводящий Тень"
ship: "Корабль-преследователь класса Копьеносец"
text: '''<span class="card-restriction">Только для Корабля-преследователя класса Копьеносец</span>%LINEBREAK%После того, как вы выполнили атаку, которая попала, если защищающийся находится в вашей мобильной арке огня на расстоянии 1-2, вы можете назначить защищающемуся 1 жетон Луча захвата.'''
# Wave X
'''Sabine's Masterpiece''':
ship: "TIE истребитель"
name: "<NAME>"
text: '''<span class="card-restriction">Только для TIE истребителя.</span>%REBELONLY%%LINEBREAK%Ваша панель улучшений получает значки улучшений %CREW% и %ILLICIT%.'''
'''Kylo Ren's Shuttle''':
ship: "Шаттл класса Ипсилон"
name: "<NAME>"
text: '''<span class="card-restriction">Только для шаттла класса Ипсилон.</span>%LINEBREAK%В конце фазы Боя, выберите вражеский корабль на расстоянии 1-2, не имеющий стресса. Его владелец должен назначить ему жетон Стресса, или назначить жетон Стресса на другой его корабль на расстоянии 1-2 от вас.'''
'''Pivot Wing''':
name: "<NAME>"
ship: "Ю-Крыл"
text: '''<span class="card-restriction">Только для Ю-Крыла.</span> %DUALCARD%%LINEBREAK%<strong>Сторона A (Боевое положение):</strong> Ваша Маневренность увеличивается на 1.%LINEBREAK%После выполнения маневра, вы можете перевернуть эту карту.%LINEBREAK%<strong>Сторона Б (Положение посадки):</strong> Когда вы открываете маневр (%STOP% 0), вы можете повернуть ваш корабль на 180°.%LINEBREAK%После выполнения маневра, вы можете перевернуть эту карту.'''
'''Adaptive Ailerons''':
name: "<NAME>"
ship: "TIE ударник"
text: '''<span class="card-restriction">Только для TIE ударника.</span>%LINEBREAK%Сразу перед открытием вашего диска, если у вас нет Стресса, вы <strong>должны</strong> выполнить белый маневр (%BANKLEFT% 1), (%STRAIGHT% 1) или (%BANKRIGHT% 1).'''
# C-ROC
'''Merchant One''':
name: "<NAME>"
ship: "Крейсер C-ROC"
text: '''<span class="card-restriction">Только для крейсера C-ROC.</span>%LINEBREAK%Ваша панель улучшений получает 1 дополнительный значок улучшения %CREW% и 1 дополнительный значок улучшения %TEAM%, а также теряет 1 значок улучшения %CARGO%.'''
'''"Light Scyk" Interceptor''':
name: '<NAME> "<NAME>"'
ship: "Перехватчик M3-A"
text: '''<span class="card-restriction">Только для Перехватчика M3-A.</span>%LINEBREAK%Все получаемые вами карты повреждений отрабатываются в открытую. Вы можете считать все маневры крена (%BANKLEFT% или %BANKRIGHT%) зелеными маневрами. Вы не можете экипировать Модификационные улучшения.'''
'''Insatiable Worrt''':
name: "<NAME>"
ship: "Крейсер C-ROC"
text: '''После выполнения действия Восстановления, получите 3 энергии.'''
'''Broken Horn''':
name: "<NAME>"
ship: "Крейсер C-ROC"
text: '''Защищаясь, если у вас есть жетон Усиления, вы можете добавить дополнительный результат %EVADE%. Если вы делаете это, после защиты, сбросьте ваш жетон Усиления.'''
'H<NAME>':
name: "<NAME>"
ship: "Бомбардировщик Скуррг H-6"
text: '''<span class="card-restriction">Только для бомбардировщика Скуррг H-6.</span>%LINEBREAK%Ваша панель улучшений получает значки %SYSTEM% и %SALVAGEDASTROMECH% и теряет значок улучшения %CREW%.%LINEBREAK%Вы не можете экипировать неуникальные карты улучшения %SALVAGEDASTROMECH%.'''
'<NAME>sai':
name: "<NAME>"
ship: "Истребитель Кихраксз"
text: '''<span class="card-restriction">Только для истребителя Кихраксз.</span>%LINEBREAK%Стоимость в очках отряда для каждого из экипированных улучшений снижается на 1 (до минимума в 0).%LINEBREAK%Вы можете экипировать до 3 различных Модификационных улучшений.'''
'StarViper Mk. II':
name: "<NAME>"
ship: "Звездна Гадю<NAME>"
text: '''<span class="card-restriction">Только для Звездной Гадюки.</span>%LINEBREAK%Вы можете экипировать до 2 различных улучшений Названий.%LINEBREAK%Выполняя действие Бочку, вы <strong>должны</strong> использовать шаблон (%BANKLEFT% 1) или (%BANKRIGHT% 1) вместо шаблона (%STRAIGHT% 1).'''
'XG-1 Assault Configuration':
ship: "Звездное Крыло класса Альфа"
name: "Штурмовая конфигурация XG-1"
text: '''<span class="card-restriction">Только для Звездного Крыла класса Альфа.</span>%LINEBREAK%Ваша панель улучшений получает 2 значка %CANNON%.%LINEBREAK%Вы можете выполнять атаки вспомогательным оружием %CANNON%, стоящим 2 или менее очков отряда, даже если у вас есть жетон Выведения оружия из строя.'''
'Enforcer':
name: "<NAME>"
ship: "Истребитель M12-L Кимогила"
text: '''<span class="card-restriction">Только для истребителя M12-L Кимогила.</span>%LINEBREAK%После защиты, если атакующий находится в вашей арки прицельного огня, атакующий получает 1 жетон Стресса.'''
'Ghost (Phantom II)':
name: "Призрак (Фантом II)"
text: '''<span class="card-restriction">Только для VCX-100.</span>%LINEBREAK%Экипируйте карту Названия <em>Фантом II</em> на дружественный шаттл класса <em>Колчан</em> и пристыкуйте его к вашему кораблю.%LINEBREAK%После выполнения маневра, вы можете отстыковать его с ваших задних направляющих.'''
'Ph<NAME> II':
name: "<NAME>"
ship: "Шаттл класса Колчан"
text: '''Когда вы пристыкованы, <em>Призрак</em> может выполнять атаки основным оружием в своей специальной арке огня.%LINEBREAK%Пока вы пристыкованы, до конца фазы Активации, <em>Призрак</em> может выполнять свободное действие Координации.'''
'First Order Vanguard':
name: "<NAME> <NAME>"
ship: "TIE глушитель"
text: '''<span class="card-restriction">Только для TIE глушителя.</span>%LINEBREAK%Атакуя, если ащищающийся - единственный вражеский корабль в вашей арке огня на расстоянии 1-3, вы можете перебросить 1 кубик атаки.%LINEBREAK%Защищаясь, вы можете сбросить эту карту, чтобы перебросить все ваши кубики защиты.'''
'Os-1 Arsenal Loadout':
name: "Загрузка арсенала Os-1"
ship: "Звездное Крыло класса Альфа"
text: '''<span class="card-restriction">Только для Звездного Крыла класса Альфа.</span>%LINEBREAK%Ваша панель улучшений получает значки %TORPEDO% и %MISSILE%.%LINEBREAK%Вы можете выполнять атаки вспомогательным оружием %TORPEDO% и %MISSILE% против кораблей, находящихся в вашем захвате, даже если у вас есть жетон Оружия выведенного из строя.'''
'Crossfire Formation':
name: "Построение перекрестного огня"
ship: "Бомбардировщик B/SF-17"
text: '''<span class="card-restriction">Только для Бомбардировщика B/SF-17.</span>%LINEBREAK%Защищаясь, если есть по меньшей мере 1 дружественный корабль Сопротивления на расстоянии 1-2 от атакующего, вы можете добавить 1 результат %FOCUS% к вашему броску.'''
'Advanced Ailerons':
text: '''<span class="card-restriction">TIE Reaper only.</span>%LINEBREAK%Treat your (%BANKLEFT% 3) and (%BANKRIGHT% 3) maneuvers as white.%LINEBREAK%Immediately before you reveal your dial, if you are not stressed, you must execute a white (%BANKLEFT% 1), (%STRAIGHT% 1), or (%BANKRIGHT% 1) maneuver.'''
condition_translations =
'''I'll Show You the Dark Side''':
name: "Я Покажу Тебе Темную Сторону"
text: '''Когда эта карта назначена, если она уже не находится в игре, игрок, который ее назначил, выбирает из колоды 1 карту повреждений с указателем <strong><em>Пилот</em></strong> и может положить ее на эту карту лицом вверх. Затем перетасуйте колоду карт повреждений.%LINEBREAK% Когда вы получаете критическое повреждение во время атаки, вместо него вы отрабатываете выбранную карту повреждений.%LINEBREAK%Когда на этой карте нет больше карты повреждений, уберите ее.'''
'Suppressive Fire':
name: "Подавляющий огонь"
text: '''Атакуя корабль, не являющийся кораблем "Капитан Рекс", бросьте на 1 кубик атаки меньше.%LINEBREAK% Когда вы объявляете атаку против "Капитана Рекса" или "Капитан Рекс" уничтожен - уберите эту карту.%LINEBREAK%В конце фазы Боя, если "Капитан Рекс" не выполнял атаку в эту фазу, уберите эту карту.'''
'Fanatical Devotion':
name: "Фанатическая преданность"
text: '''Защищаясь, вы не можете использовать жетоны Концентрации.%LINEBREAK%Атакуя, если вы используете жетон Концентрации, чтобы заменить все результаты %FOCUS% на результаты %HIT%, отложите в сторону первый результат %FOCUS%, который вы заменили. Отставленный в сторону результат %HIT% не может быть отменен кубиками защиты, но защищающийся может отменять результаты %CRIT% до него.%LINEBREAK%Во время фазы Завершения, уберите эту карту.'''
'A Debt to Pay':
name: "Счет к оплате"
text: '''Атакуя корабль, имеющий карту улучшения "Личные счеты", вы можете заменить 1 результат %FOCUS% на результат %CRIT%.'''
'Shadowed':
name: "Затененный"
text: '''"Т<NAME>" считается имеющим значение умения пилота, которое у вас было после фазы расстановки.%LINEBREAK%Умение пилота "Твика" не меняется, если ваше значение умения пилота изменяется или вы уничтожены.'''
'Mimicked':
name: "Мимикрированный"
text: '''"<NAME>ик" считается имеющим вашу способность пилота.%LINEBREAK%"Твик" не может применить карту Состояния, используя вашу способность пилота.%LINEBREAK%"Твик" не теряет вашу способность пилота, если вы уничтожены.'''
'Harpooned!':
name: "Загарпунен!"
text: '''Когда в вас попадает атака, если хотя бы 1 результат %CRIT% не отменен, каждый другой корабль на расстоянии 1 получает 1 повреждение. Затем сбросьте эту карту и получите 1 карту повреждений лицом вниз.%LINEBREAK%Когда вы уничтожены, каждый корабль на расстоянии 1 получает 1 повреждение.%LINEBREAK%<strong>Действие:</strong> Сбросьте эту карту. Затем бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, получите 1 повреждение.'''
'Rattled':
name: "Разбитый"
text: '''Когда вы получаете повреждение или критическое повреждение от бомбы, вы получаете 1 дополнительное критическое повреждение. Затем сбросьте эту карту.%LINEBREAK%<strong>Действие:</strong> Бросьте 1 кубик атакию. При результате %FOCUS% или %HIT%, сбросьте эту карту.'''
'Scrambled':
name: "Помехи"
text: '''Атакуя корабль на расстоянии 1, оснащенный улучшением "Помехи наведения", вы не можете модифицировать кубики атаки.%LINEBREAK%В конце фазы Боя, сбросьте эту карту.'''
'Optimized Prototype':
name: "Оптимизированный прототип"
text: '''Increase your shield value by 1.%LINEBREAK%Once per round, when performing a primary weapon attack, you may spend 1 die result to remove 1 shield from the defender.%LINEBREAK%After you perform a primary weapon attack, a friendly ship at Range 1-2 equipped with the "Director Krennic" Upgrade card may acquire a target lock on the defender.'''
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations, condition_translations | true | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.ru = 'Русский'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations['Русский'] =
action:
"Barrel Roll": "Бочка"
"Boost": "Ускорение"
"Evade": "Уклонение"
"Focus": "Концентрация"
"Target Lock": "Захват цели"
"Recover": "Восстановление"
"Reinforce": "Усиление"
"Jam": "Заклинивание"
"Coordinate": "Координирование"
"Cloak": "Маскировка"
slot:
"Astromech": "Дроид-астромех"
"Bomb": "Бомба"
"Cannon": "Пушка"
"Crew": "Экипаж"
"Elite": "Элитный навык"
"Missile": "Ракета"
"System": "Система"
"Torpedo": "Торпеда"
"Turret": "Турель"
"Cargo": "Груз"
"Hardpoint": "Тяжелая установка"
"Team": "Команда"
"Illicit": "Незаконное"
"Salvaged Astromech": "Трофейный астромех"
"Tech": "Техника"
sources: # needed?
"Core": "Базовый набор"
"A-Wing Expansion Pack": "Дополнение А-Крыл"
"B-Wing Expansion Pack": "Дополнение Б-Крыл"
"X-Wing Expansion Pack": "Дополнение Икс-Крыл"
"Y-Wing Expansion Pack": "Дополнение У-Крыл"
"Millennium Falcon Expansion Pack": "Дополнение Тысячелетний Сокол"
"HWK-290 Expansion Pack": "Дополнение HWK-290"
"TIE Fighter Expansion Pack": "Дополнение TIE-истребитель"
"TIE Interceptor Expansion Pack": "Дополнение TIE-перехватчик"
"TIE Bomber Expansion Pack": "Дополнение TIE-бомбардировщик"
"TIE Advanced Expansion Pack": "Дополнение TIE-улучшенный"
"Lambda-Class Shuttle Expansion Pack": "Дополнение Шаттл класса Лямбда"
"Slave I Expansion Pack": "Дополнение Раб-1"
"Imperial Aces Expansion Pack": "Дополнение Имперские асы"
"Rebel Transport Expansion Pack": "Дополнение Транспорт повстанцев"
"Z-95 Headhunter Expansion Pack": "Дополнение Z-95 Охотник за головами"
"TIE Defender Expansion Pack": "Дополнение TIE-защитник"
"E-Wing Expansion Pack": "Дополнение Е-Крыл"
"TIE Phantom Expansion Pack": "Дополнение TIE-фантом"
"Tantive IV Expansion Pack": "Дополнение Тантив IV"
"Rebel Aces Expansion Pack": "Дополнение Асы повстанцев"
"YT-2400 Freighter Expansion Pack": "Дополнение Грузовоз YT-2400"
"VT-49 Decimator Expansion Pack": "Дополнение VT-49 Дециматор"
"StarViper Expansion Pack": "Дополнение Звездная Гадюка"
"M3-A Interceptor Expansion Pack": "Дополнение Перехватчик M3-A"
"IG-2000 Expansion Pack": "Дополнение IG-2000"
"Most Wanted Expansion Pack": "Дополнение Самые разыскиваемые"
"Imperial Raider Expansion Pack": "Дополнение Имперский рейдер"
"K-Wing Expansion Pack": "Дополнение К-Крыл"
"TIE Punisher Expansion Pack": "Дополнение TIE-каратель"
"Kihraxz Fighter Expansion Pack": "Дополнение Истребитель Кихраксз"
"Hound's Tooth Expansion Pack": "Дополнение Зуб Гончей"
"The Force Awakens Core Set": "Базовый набор Пробуждение Силы"
"T-70 X-Wing Expansion Pack": "Дополнение Икс-Крыл T-70"
"TIE/fo Fighter Expansion Pack": "Дополнение Истребитель TIE/пп"
"Imperial Assault Carrier Expansion Pack": "Дополнение Имперский штурмовой носитель"
"Ghost Expansion Pack": "Дополнение Призрак"
"Inquisitor's TIE Expansion Pack": "Дополнение TIE инквизитора"
"Mist Hunter Expansion Pack": "Дополнение Туманный охотник"
"Punishing One Expansion Pack": "Дополнение Карающий Один"
"Imperial Veterans Expansion Pack": "Дополнение Имперские ветераны"
"Protectorate Starfighter Expansion Pack": "Дополнение Звездный истребитель Протектората"
"Shadow Caster Expansion Pack": "Дополнение Наводящий Тень"
"Special Forces TIE Expansion Pack": "Дополнение TIE специальных сил"
"ARC-170 Expansion Pack": "Дополнение ARC-170"
"U-Wing Expansion Pack": "Дополнение Ю-Крыл"
"TIE Striker Expansion Pack": "Дополнение TIE-ударник"
"Upsilon-class Shuttle Expansion Pack": "Дополнение Шаттл класса Ипсилон"
"Sabine's TIE Fighter Expansion Pack": "Дополнение TIE-истребитель Сабины"
"Quadjumper Expansion Pack": "Дополнение Квадджампер"
"C-ROC Cruiser Expansion Pack": "Дополнение Крейсер C-ROC"
"TIE Aggressor Expansion Pack": "Дополнение TIE-агрессор"
"Scurrg H-6 Bomber Expansion Pack": "Дополнение Бомбардировщик Скуррг H-6"
"Auzituck Gunship Expansion Pack": "Дополнение Канонерка Озитук"
"TIE Silencer Expansion Pack": "Дополнение TIE-глушитель"
"Alpha-class Star Wing Expansion Pack": "Pасширение Звездноое Крыло Альфа-класса"
"Resistance Bomber Expansion Pack": "Дополнение Бомбардировщик сопротивления"
"Phantom II Expansion Pack": "Дополнение Фантом II"
"Kimogila Fighter Expansion Pack": "Дополнение Истребитель Кимогила"
ui:
shipSelectorPlaceholder: "Выбор корабля"
pilotSelectorPlaceholder: "Выбор пилота"
upgradePlaceholder: (translator, language, slot) ->
switch slot
when 'Elite'
"Элитный навык"
when 'Astromech'
"Астромех"
when 'Illicit'
"Незаконное"
when 'Salvaged Astromech'
"Трофейный астромех"
else
"Нет улучшения #{translator language, 'slot', slot}"
modificationPlaceholder: "Модификация"
titlePlaceholder: "Название"
upgradeHeader: (translator, language, slot) ->
switch slot
when 'Elite'
"Элитный навык"
when 'Astromech'
"Дроид-астромех"
when 'Illicit'
"Незаконное"
when 'Salvaged Astromech'
"Трофейный дроид-астромех"
else
"Улучшение #{translator language, 'slot', slot}"
unreleased: "не выпущено"
epic: "эпик"
byCSSSelector:
# Warnings
'.unreleased-content-used .translated': 'Этот отряд использует неизданный контент!'
'.epic-content-used .translated': 'Этот отряд использует эпический контент!'
'.illegal-epic-too-many-small-ships .translated': 'Вы не можете использовать более 12 малых кораблей одного типа!'
'.illegal-epic-too-many-large-ships .translated': 'Вы не можете использовать более 6 больших кораблей одного типа!'
'.collection-invalid .translated': 'Вы не можете использовать этот лист с вашей коллекцией!'
# Type selector
'.game-type-selector option[value="standard"]': 'Стандарт'
'.game-type-selector option[value="custom"]': 'Свой'
'.game-type-selector option[value="epic"]': 'Эпик'
'.game-type-selector option[value="team-epic"]': 'Командный эпик'
'.xwing-card-browser .translate.sort-cards-by': 'Сортировать по'
'.xwing-card-browser option[value="name"]': 'Названию'
'.xwing-card-browser option[value="source"]': 'Источнику'
'.xwing-card-browser option[value="type-by-points"]': 'Типу (по очкам)'
'.xwing-card-browser option[value="type-by-name"]': 'Типу (по названию)'
'.xwing-card-browser .translate.select-a-card': 'Выберите карту из списка слева.'
# Info well
'.info-well .info-ship td.info-header': 'Корабль'
'.info-well .info-skill td.info-header': 'Умение'
'.info-well .info-actions td.info-header': 'Действия'
'.info-well .info-upgrades td.info-header': 'Улучшения'
'.info-well .info-range td.info-header': 'Дистанция'
# Squadron edit buttons
'.clear-squad' : 'Новая эскадрилья'
'.save-list' : 'Сохранить'
'.save-list-as' : 'Сохранить как...'
'.delete-list' : 'Удалить'
'.backend-list-my-squads' : 'Загрузить эскадрилью'
'.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i> Imprimir/Ver como </span>Text'
'.randomize' : 'Случайный'
'.randomize-options' : 'Случайные опции…'
'.notes-container > span' : 'Примечания отряда'
# Print/View modal
'.bbcode-list' : 'Скопируйте BBCode ниже и вставьте его в сообщение своего форума.<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.html-list' : '<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.vertical-space-checkbox' : """Добавить место для письма с ухудшением / улучшением при печати. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Цветная печать. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="fa fa-print"></i> Imprimir'
# Randomizer options
'.do-randomize' : 'Сгенерировать случайным образом'
# Top tab bar
'#empireTab' : 'Галактическая Империя'
'#rebelTab' : 'Альянс повстанцев'
'#scumTab' : 'Пираты'
'#browserTab' : 'Поиск по картам'
'#aboutTab' : 'О нас'
singular:
'pilots': 'Пилоты'
'modifications': 'Модификации'
'titles': 'Названия'
types:
'Pilot': 'Пилот'
'Modification': 'Модификация'
'Title': 'Название'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders['Русский'] = () ->
exportObj.cardLanguage = 'Русский'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
# ship translations
exportObj.renameShip 'Lambda-Class Shuttle', 'Шаттл класса Лямбда'
exportObj.renameShip 'TIE Advanced', 'TIE улучшенный'
exportObj.renameShip 'TIE Bomber', 'TIE бомбардировщик'
exportObj.renameShip 'TIE Fighter', 'TIE истребитель'
exportObj.renameShip 'TIE Interceptor', 'TIE перехватчик'
exportObj.renameShip 'TIE Phantom', 'TIE фантом'
exportObj.renameShip 'TIE Defender', 'TIE защитник'
exportObj.renameShip 'TIE Punisher', 'TIE каратель'
exportObj.renameShip 'TIE Advanced Prototype', 'TIE улучшенный прототип'
exportObj.renameShip 'VT-49 Decimator', 'VT-49 Дециматор'
exportObj.renameShip 'TIE/fo Fighter', 'Истребитель TIE/пп'
exportObj.renameShip 'TIE/sf Fighter', 'Истребитель TIE/сс'
exportObj.renameShip 'TIE Striker', 'TIE ударник'
exportObj.renameShip 'Upsilon-class Shuttle', 'Шаттл класса Ипсилон'
exportObj.renameShip 'TIE Aggressor', 'TIE агрессор'
exportObj.renameShip 'TIE Silencer', 'TIE глушитель'
exportObj.renameShip 'Alpha-class Star Wing', 'Звездное Крыло класса Альфа'
exportObj.renameShip 'A-Wing', 'А-Крыл'
exportObj.renameShip 'B-Wing', 'Б-Крыл'
exportObj.renameShip 'E-Wing', 'Е-Крыл'
exportObj.renameShip 'X-Wing', 'Икс-Крыл'
exportObj.renameShip 'Y-Wing', 'У-Крыл'
exportObj.renameShip 'K-Wing', 'К-Крыл'
exportObj.renameShip 'Z-95 Headhunter', 'Z-95 охотник за головами'
exportObj.renameShip 'Attack Shuttle', 'Атакующий шаттл'
exportObj.renameShip 'CR90 Corvette (Aft)', 'Корвет CR90 (Корма)'
exportObj.renameShip 'CR90 Corvette (Fore)', 'Корвет CR90 (Нос)'
exportObj.renameShip 'GR-75 Medium Transport', 'Средний транспорт GR-75'
exportObj.renameShip 'T-70 X-Wing', 'Икс-Крыл T-70'
exportObj.renameShip 'U-Wing', 'Ю-Крыл'
exportObj.renameShip 'Auzituck Gunship', 'Канонерка Озитук'
exportObj.renameShip 'B/SF-17 Bomber', 'Бомбардировщик B/SF-17'
exportObj.renameShip 'Sheathipede-class Shuttle', 'Шаттл класса Колчан'
exportObj.renameShip 'M3-A Interceptor', 'Перехватчик M3-A'
exportObj.renameShip 'StarViper', 'Звездная Гадюка'
exportObj.renameShip 'Aggressor', 'Агрессор'
exportObj.renameShip 'Kihraxz Fighter', 'Истребитель Кихраксз'
exportObj.renameShip 'G-1A Starfighter', 'Звездный истребитель G-1A'
exportObj.renameShip 'JumpMaster 5000', 'Джампмастер 5000'
exportObj.renameShip 'Protectorate Starfighter', 'Звездный истребитель Протектората'
exportObj.renameShip 'Lancer-class Pursuit Craft', 'Транспорт преследования класса Копьеносец'
exportObj.renameShip 'Quadjumper', 'Квадджампер'
exportObj.renameShip 'C-ROC Cruiser', 'Крейсер C-ROC'
exportObj.renameShip 'Scurrg H-6 Bomber', 'Бомбардировщик Скуррг H-6'
exportObj.renameShip 'M12-L Kimogila Fighter', 'Истребитель M12-L Кимогила'
pilot_translations =
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """При атаке сократите параметр маневренности защищающегося на 1 (но не ниже 0)."""
ship: "Икс-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Применив жетон концентрации, вы можете положить его на любой дружественный корабль на расстоянии 1-2 (вместо того, чтобы его сбросить)"""
ship: "Икс-Крыл"
"Red Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "Икс-Крыл"
"RPI:NAME:<NAME>END_PI Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "Икс-Крыл"
"BigPI:NAME:<NAME>END_PI DarkPI:NAME:<NAME>END_PIer":
name: "PI:NAME:<NAME>END_PI"
text: """Один раз за игру, в начале фазы БPI:NAME:<NAME>END_PI, вы можете выбрать, чтобы другие дружественные корабли на расстоянии 1 не могли быть выбраны целью атаки, если вместо них атакующий может выбрать вас целью."""
ship: "Икс-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """При защите вы можете заменить 1 результат %FOCUS% на результат %EVADE%."""
ship: "Икс-Крыл"
"Gray Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "У-Крыл"
'"DPI:NAME:<NAME>END_PI" Vander':
name: "PI:NAME:<NAME>END_PI"
text: """После получения захвата цели, выберите другой дружественный корабль на расстоянии 1-2. Выбранный корабль может немедленно получить захват цели."""
ship: "У-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Атакуя на расстоянии 2-3, вы можете перебросить все пустые результаты"""
ship: "У-Крыл"
"Gold Squadron Pilot":
name: "PI:NAME:<NAME>END_PIот Золотой эскадрильи"
ship: "У-Крыл"
"Academy Pilot":
name: "Пилот академии"
ship: "TIE истребитель"
"Obsidian Squadron Pilot":
name: "PI:NAME:<NAME>END_PI ОбсPI:NAME:<NAME>END_PIановой эскадрильи"
ship: "TIE истребитель"
"Black Squadron Pilot":
name: "PI:NAME:<NAME>END_PI Черной эскадрильи"
ship: "TIE истребитель"
'"WPI:NAME:<NAME>END_PIed PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Атакуя на расстоянии 1, вы можете изменить 1 результат %HIT% на результат %CRIT%"""
ship: "TIE истребитель"
'"Night Beast"':
name: '"Ночной Зверь"'
text: """После выполнения зеленого маневра, вы можете выполнить свободное действие Концентрации"""
ship: "TIE истребитель"
'"Backstabber"':
name: '"Ударяющий в спину"'
text: """Атакуя вне арки огня защищающегося, можете бросить 1 дополнительный кубик атаки"""
ship: "TIE истребитель"
'"Dark Curse"':
name: '"Темное проклятье"'
text: """Когда вы защищаетесь в фазу боя, атакующие корабли не могут тратить жетоны Концентрации или перебрасывать кубики атаки"""
ship: "TIE истребитель"
'"Mauler MitPI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """ Атакуя на расстоянии 1, можете бросить 1 дополнительный кубик атаки."""
ship: "TIE истребитель"
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Когда другой дружественный корабль атакует основным оружием на расстоянии 1, он может перебросить 1 кубик атаки"""
ship: "TIE истребитель"
"Tempest Squadron Pilot":
name: "PI:NAME:<NAME>END_PI эPI:NAME:<NAME>END_PI"
ship: "TIE улучшенный"
"Storm Squadron Pilot":
name: "PI:NAME:<NAME>END_PI эPI:NAME:<NAME>END_PI"
ship: "TIE улучшенный"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда ваша атака наносит противнику карточку повреждения лицом вверх, вместо этого вытяните 3 карты лицом вверх, выберите одну и сбросьте остальные."""
ship: "TIE улучшенный"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Во время шага «Выполнение действия» вы можете выполнить 2 действия."""
ship: "TIE улучшенный"
"Alpha Squadron Pilot":
name: "PI:NAME:<NAME>END_PI эPI:NAME:<NAME>END_PI"
ship: "TIE перехватчик"
"Avenger Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE перехватчик"
"Saber Squadron Pilot":
name: "PI:NAME:<NAME>END_PIилот эскадрильи СPI:NAME:<NAME>END_PIля"
ship: "TIE перехватчик"
"\"PI:NAME:<NAME>END_PI Wrath\"":
name: '"PI:NAME:<NAME>END_PI"'
ship: "TIE перехватчик"
text: """Когда число карт повреждений корабля равно или превышает значение Прочности, корабль не уничтожен до конца фазы Боя."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE перехватчик"
text: """После проведения атаки, вы можете выполнить свободное действие Бочка или Ускорение."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE перехватчик"
text: """Когда вы получаете жетон Стресса, вы можете назначить 1 жетон Концентрации на ваш корабль."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Вы можете выполнять действия даже имея жетоны Стресса."""
ship: "А-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Вы можете назначать корабль противника, которого касаетесь, целью атаки."""
ship: "А-Крыл"
"Green Squadron Pilot":
name: "Пилот ЗPI:NAME:<NAME>END_PIскадPI:NAME:<NAME>END_PIи"
ship: "А-Крыл"
"Prototype Pilot":
name: "Пилот прототипа"
ship: "А-Крыл"
"Outer Rim Smuggler":
name: "Контрабандист Внешнего Кольца"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы получаете карту повреждений лицом вверх, немедленно переверните ее лицом вниз (не отрабатывая ее эффект)."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """После выполнения зеленого маневра, выберите 1 другой дружественный корабль на расстоянии 1. Этот корабль может выполнить 1 свободное действие, отображенное в его списке действий."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Атакуя, вы можете перебросить все кубики атаки. Делая это, вы должны перебросить столько кубиков, сколько возможно."""
"PI:NAME:<NAME>END_PI":
name: "Охотник за головами"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """При атаке, защищающийся получает 1 жетон Стресса если он отменяет хотя бы 1 результат %CRIT%."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы выполняете маневр крена (%BANKLEFT% или %BANKRIGHT%), вы можете повернуть диск маневра на другой маневр крена с той же скоростью."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Атакуя вспомогательным оружием, вы можете перебросить 1 кубик атаки."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """При атаке 1 из ваших результатов %CRIT% не может быть отменен кубиком защиты."""
ship: "Б-Крыл"
"IbtisPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """При атаке или защите, если у вас есть хотя бы 1 жетон Стресса, вы можете перебросить 1 из ваших кубиков."""
ship: "Б-Крыл"
"Dagger Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "Б-Крыл"
"Blue Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "Б-Крыл"
"Rebel Operative":
name: "Повстанец-оперативник"
ship: "HWK-290"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы БPI:NAME:<NAME>END_PI, выберите 1 дружественный корабль на расстоянии 1-3. До конца фазы считайте навык Пилотирования этого корабля равным 12."""
ship: "HWK-290"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы боя вы можете назначить 1 из ваших жетонов Концентрации на другой дружественный корабль на расстоянии 1-3."""
ship: "HWK-290"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда другой дружественный корабль на расстоянии 1-3 выполняет атаку, если у вас нет жетона Стресса, вы можете получить 1 жетон Стресса чтобы позволить дружественному кораблю бросить 1 дополнительный кубик атаки."""
ship: "HWK-290"
"Scimitar Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE бомбардировщик"
"Gamma Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE бомбардировщик"
"Gamma Squadron Veteran":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE бомбардировщик"
"CaptPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE бомбардировщик"
text: """Когда другой дружественный корабль на расстоянии 1 атакует вспомогательным оружием, он может перебросить до 2 кубиков атаки."""
"Major RPI:NAME:<NAME>END_PIymer":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE бомбардировщик"
text: """Атакуя второстепенным оружием, вы можете увеличить или уменьшить дистанцию оружия на 1 (до значения 1 или 3)."""
"Omicron Group Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "Шаттл класса Лямбда"
"Captain KPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вражеский корабль получает захват цели, он должен делать его на ваш корабль (если может)."""
ship: "Шаттл класса Лямбда"
"Colonel Jendon":
name: "PI:NAME:<NAME>END_PI"
text: """ В начале фазы боя вы можете назначить 1 из ваших синих жетонов захвата цели на союзный корабль на расстоянии 1, если у него еще нет синего жетона захвата цели."""
ship: "Шаттл класса Лямбда"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """ Когда другой союзный корабль на расстоянии 1-2 получает жетон стресса, если у вас есть 2 жетона стресса или меньше, вы можете получить жетон стресса вместо него."""
ship: "Шаттл класса Лямбда"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE перехватчик"
text: """При выполнении бочки, вы можете получить 1 жетон стресса чтобы использовать (%BANKLEFT% 1) или (%BANKRIGHT% 1) вместо (%STRAIGHT% 1)."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE перехватчик"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE перехватчик"
text: """Когда вы открываете маневр %UTURN%, вы можете считать скорость этого маневра равной 1, 3 или 5."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE перехватчик"
text: """Атакуя на расстоянии 2-3, можете потратить 1 жетон уклонения чтобы добавить 1 результат %HIT% к броску."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE перехватчик"
text: """Вражеские корабли на расстоянии 1 не могут выполнять действия Концентрации и Уклонения, а также не могут использовать жетоны концентрации и уклонения."""
"GR-75 Medium Transport":
name: "Средний транспорт GR-75"
ship: "Средний транспорт GR-75"
"Bandit Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "Z-95 Охотник за головами"
"Tala Squadron Pilot":
name: "PI:NAME:<NAME>END_PI эPI:NAME:<NAME>END_PI"
ship: "Z-95 Охотник за головами"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """При атаке считается, что она попала по противнику, даже если он не понес повреждений."""
ship: "Z-95 Охотник за головами"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """После выполнения атаки, вы можете выбрать другой дружественный корабль на расстоянии 1. Этот корабль может выполнить 1 свободное действие."""
ship: "Z-95 Охотник за головами"
"Delta Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE защитник"
"Onyx Squadron Pilot":
name: "PI:NAME:<NAME>END_PI эPI:NAME:<NAME>END_PI"
ship: "TIE защитник"
"PI:NAME:<NAME>END_PI":
name: "Полковник PI:NAME:<NAME>END_PI"
text: """ Когда вы атакуете, сразу после броска кубиков атаки, вы можете назначить захват цели на защищающегося, если на нем уже есть красный жетон захвата."""
ship: "TIE защитник"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы выполнили атаку, которая нанесла хотя бы 1 карту повреждений защищающемуся, вы можете потратить 1 жетон концентрации, чтобы перевернуть эти карты лицом вверх."""
ship: "TIE защитник"
"Knave Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "Е-Крыл"
"Blackmoon Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "Е-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вражеский корабль в вашей арке огня и на расстоянии 1-3 защищается, атакующий может заменить 1 результат %HIT% на 1 результат %CRIT%."""
ship: "Е-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы Окончания вы можете выполнить 1 атаку. Вы не можете атаковать в следующем ходу."""
ship: "Е-Крыл"
"Sigma Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE фантом"
"Shadow Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE фантом"
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """При снятии маскировки, вы должны использовать (%BANKLEFT% 2) или (%BANKRIGHT% 2) вместо (%STRAIGHT% 2)."""
ship: "TIE фантом"
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """После выполнения атаки, завершившейся попаданием, вы можете назначить 1 жетон концентрации на ваш корабль."""
ship: "TIE фантом"
"CR90 Corvette (Fore)":
name: "КPI:NAME:<NAME>END_PI CR90 (Нос)"
ship: "Корвет CR90 (Нос)"
text: """Атакуя основным оружием, вы можете потратить 1 энергии, чтобы бросить 1 дополнительный кубик атаки."""
"CR90 Corvette (Aft)":
name: "PI:NAME:<NAME>END_PI CR90 (Корма)"
ship: "Корвет CR90 (Корма)"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """После выполнения атаки, вы можете снять 1 жетон концентрации, уклонения или синий жетон захвата цели с защищавшегося."""
ship: "Икс-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """При получении жетона Стресса, вы можете убрать его и бросить 1 кубик атаки. При результате %HIT%, получите 1 карту повреждения на этот корабль лицом вниз."""
ship: "Икс-Крыл"
'"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: """При получении или использовании захвата цели, вы можете убрать 1 жетон Стресса."""
ship: "Икс-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """ Когда вражеский корабль объявляет вас объектом атаки, вы можете установить захват цели на этот корабль."""
ship: "Икс-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """ После того, как вы выполните действие Концентрации или вам назначен жетон концентрации, вы можете совершить свободное действие Ускорение или Бочку."""
ship: "А-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы на расстоянии 1 от хотя бы 1 вражеского корабля, увеличьте параметр Уклонения на 1."""
ship: "А-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Атакуя, вы можете убрать 1 жетон Стресса, чтобы заменить все результаты %FOCUS% на %HIT%."""
ship: "Б-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Вы можете выполнять атаки вспомогательным оружием %TORPEDO% против кораблей вне вашей арки огня."""
ship: "Б-Крыл"
# "CR90 Corvette (Crippled Aft)":
# name: "CR90 Corvette (Crippled Aft)"
# ship: "Корвет CR90 (Корма)"
# text: """Вы не можете выбирать и выполнять маневры (%STRAIGHT% 4), (%BANKLEFT% 2), или (%BANKRIGHT% 2)."""
# "CR90 Corvette (Crippled Fore)":
# name: "CR90 Corvette (Crippled Fore)"
# ship: "Корвет CR90 (Нос)"
"Wild Space Fringer":
name: "Пограничник дикого космоса"
ship: "YT-2400"
"Dash Rendar":
name: "PI:NAME:<NAME>END_PI"
text: """Вы можете игнорировать препятствия в фазу Активации и при выполнении дествий."""
'"LPI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы получаете карту повреждений лицом вверх, возьмите 1 дополнительную карту лицом вверх, выберите 1 из них и сбросьте вторую."""
"EPI:NAME:<NAME>END_PIill":
name: "PI:NAME:<NAME>END_PI"
text: """При атаке основным оружием против корабля, имеющего жетон СPI:NAME:<NAME>END_PI, бросьте 1 дополнительный кубик атаки."""
"Patrol Leader":
name: "PI:NAME:<NAME>END_PI"
ship: "VT-49 Дециматор"
"Rear Admiral ChPI:NAME:<NAME>END_PIau":
name: "PI:NAME:<NAME>END_PI"
text: """Атакуя на расстоянии 1-2, вы можете заменить 1 результат %FOCUS% на результат %CRIT%."""
ship: "VT-49 Дециматор"
"CommandPI:NAME:<NAME>END_PI":
ship: "VT-49 Дециматор"
name: "PI:NAME:<NAME>END_PI"
text: """Если у вас нет щитов и вы имеете хотя бы 1 карту повреждений, ваше Уклонение повышается на 1."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """После выполнения маневра, каждый вражеский корабль, которого вы касаетесь, получает 1 повреждение."""
ship: "VT-49 Дециматор"
"Black PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Звездная Гадюка"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Звездная Гадюка"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """При защите, союзный корабль на расстоянии 1 может получить 1 неотмененный %HIT% или %CRIT% вместо вас."""
ship: "Звездная Гадюка"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы Боя, если вы на расстоянии 1 от вражеского корабля, вы можете назначить 1 жетон Концентрации на свой корабль."""
ship: "Звездная Гадюка"
"CartPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Перехватчик M3-A"
"Tansarii Point Veteran":
name: "PI:NAME:<NAME>END_PI"
ship: "Перехватчик M3-A"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PIу"
text: """Когда другой дружественный корабль на расстоянии 1 защищается, он может перебросить 1 кубик защиты."""
ship: "Перехватчик M3-A"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """После того, как вы провели защиту от атаки, если атака не попала, вы можете назначить 1 жетон Уклонения на свой корабль."""
ship: "Перехватчик M3-A"
"IG-88A":
text: """После выполнения атаки, уничтожившей корабль противника, вы можете восстановить 1 щит."""
ship: "Агрессор"
"IG-88B":
text: """Раз за ход, проведя атаку, которая не попала, вы можете выполнить атаку вспомогательным оружием %CANNON% ."""
ship: "Агрессор"
"IG-88C":
text: """После выполнения Ускорения, вы можете выполнить свободное действие Уклонения."""
ship: "Агрессор"
"IG-88D":
text: """Вы можете выполнять (%SLOOPLEFT% 3) или (%SLOOPRIGHT% 3) используя соответствующий (%TURNLEFT% 3) или (%TURNRIGHT% 3) шаблон."""
ship: "Агрессор"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PIандалорский наемник"
"PI:NAME:<NAME>END_PI (Scum)":
name: "PI:NAME:<NAME>END_PI (Пираты)"
text: """Атакуя или защищаясь, вы можете перебросить 1 кубик за каждый вражеский корабль на расстоянии 1."""
"PI:NAME:<NAME>END_PI (ScPI:NAME:<NAME>END_PI)":
name: "PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)"
text: """Атакуя корабль в вашей вторичной арке стрельбы, бросьте 1 дополнительный кубик атаки."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Бросая бомбу, вы можете использовать шаблон [%TURNLEFT% 3], [%STRAIGHT% 3] или [%TURNRIGHT% 3] вместо [%STRAIGHT% 1]."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "У-Крыл"
text: """Атакуя корабль вне вашей арки огня, бросьте 1 дополнительный кубик."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """После того, как вы используете захват цели, вы можете получить 1 жетон Стресса, чтобы получить захват цели."""
ship: "У-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "У-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "У-Крыл"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "HWK-290"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вражеский корабль на расстоянии 1-3 получает хотя бы 1 ионный жетон, если вы не под Стрессом, вы можете получить 1 жетон Стресса чтобы тот корабль получил 1 повреждение."""
ship: "HWK-290"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы боя вы можете убрать 1 жетон Концентрации или Уклонения с вражеского корабля на расстоянии 1-2 и назначить этот жетон вашему кораблю."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В конце фазы Активации, выберите 1 вражеский корабль на расстоянии 1-2. До конца фазы Боя считайте умение пилота этого корабля равным 0."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Z-95 Охотник за головами"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Z-95 Охотник за головами"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """При атаке, если нет других дружественных кораблей на расстоянии 1-2, бросьте 1 дополнительный кубик атаки."""
ship: "Z-95 Охотник за головами"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы БPI:NAME:<NAME>END_PI, вы можете убрать 1 жетон Концентрации или Уклонения с дружественного корабля на расстоянии 1-2 и назначить его на свой корабль."""
ship: "Z-95 Охотник за головами"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PIомандPI:NAME:<NAME>END_PI"
ship: "TIE улучшенный"
text: """В начале фазы Боя, вы можете назначить захват цели на вражеский корабль на расстоянии 1."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE улучшенный"
text: """Когда открываете маневр, вы можете изменить его скорость на 1 (до минимума в 1)."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE улучшенный"
text: """Вражеские корабли на расстоянии 1 не получают боевого бонуса за расстояние при атаке."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE улучшенный"
text: """В начале фазы Завершения, вы можете потратить захват цели на вражеском корабле, чтобы заставить его перевернуть одну из полученных карт повреждений лицом вверх."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """ Когда дружественный корабль объявляет атаку, вы можете потратить захват цели на защищающемся, чтобы уменьшить его Маневренность на 1 для этой атаки."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: 'К-Крыл'
text: """ Один раз за ход, во время атаки, вы можете потратить 1 щит, чтобы бросить 1 дополнительный кубик атаки, <strong>или</strong> бросить на 1 кубик атаки меньше, чтобы восстановить 1 щит."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: 'К-Крыл'
text: """Когда другой дружественный корабль на расстоянии 1-2 атакует, он может считать ваши жетоны Концентрации как свои собственные."""
"Guardian Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: 'К-Крыл'
"Warden Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: 'К-Крыл'
'"RedPI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
ship: 'TIE каратель'
text: """Вы можете поддерживать 2 захвата цели на одном и том же корабле. Когда вы получаете захват цели, вы можете получить второй захват на том же корабле."""
'"DeathPI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
ship: 'TIE каратель'
text: """Бросая бомбу, вы можете использовать передние направляющие вашего корабля. После сброса бомбы, вы можете выполнить свободное действие Бочку."""
'Black Eight Squadron Pilot':
name: "PI:NAME:<NAME>END_PI"
ship: 'TIE каратель'
'Cutlass Squadron Pilot':
name: "PI:NAME:<NAME>END_PI"
ship: 'TIE каратель'
"Moralo Eval":
name: "PI:NAME:<NAME>END_PI"
text: """Вы можете выполнять атаки вспомогательным оружием %CANNON% против кораблей в вашей вторичной арке огня."""
'Gozanti-class Cruiser':
name: "PI:NAME:<NAME>END_PI"
text: """После выполнения маневра, вы можете отстыковать до 2 присоединенных кораблей."""
'"PI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
ship: "TIE истребитель"
text: """При атаке, если у защищающегося уже есть 1 или более карт повреждений, бросьте 1 дополнительный кубик атаки."""
"The PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE улучшенный прототип"
text: """Атакуя основным оружием на расстоянии 2-3, считайте расстояние атаки как 1."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Звездный истребитель G-1A"
text: """Атакуя, вы можете бросить 1 дополнительный кубик атаки. Если вы делаете это, защищающийся бросает 1 дополнительный кубик защиты."""
"Ruthless Freelancer":
name: "Беспощадный наемник"
ship: "Звездный истребитель G-1A"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Звездный истребитель G-1A"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Джампмастер 5000"
text: """Один раз за ход, после защиты, если атакующий находится в вашей основной арке огня, вы можете провести атаку против этого корабля."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель Кихраксз"
text: """Атакуя или защищаясь, удваивайте эффект бонусов за расстояние."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель Кихраксз"
text: """Защищаясь, если атакующий находится в вашей основной арке огня, бросьте 1 дополнительный кубик защиты."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель Кихраксз"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель Кихраксз"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PIский работорговец"
ship: "YV-666"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "YV-666"
text: """Когда вы выполняете атаку, завершившуюся попаданием, перед нанесением повреждений, вы можете отменить 1 из ваших результатов %CRIT%, чтобы нанести 2 результата %HIT%."""
# T-70
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Икс-Крыл T-70"
text: """Атакуя или защищаясь, если у вас есть жетон Концентрации, вы можете заменить 1 из ваших результатов %FOCUS% на результат %HIT% или %EVADE%."""
'"Blue Ace"':
name: '"PI:NAME:<NAME>END_PI"'
ship: "Икс-Крыл T-70"
text: """Выполняя действие Ускорение, вы можете использовать шаблон (%TURNLEFT% 1) или (%TURNRIGHT% 1)."""
"Red Squadron Veteran":
name: "PI:NAME:<NAME>END_PI"
ship: "Икс-Крыл T-70"
"Blue Squadron Novice":
name: "PI:NAME:<NAME>END_PI"
ship: "Икс-Крыл T-70"
'"Red Ace"':
name: "PI:NAME:<NAME>END_PI"
ship: "Икс-Крыл T-70"
text: '''В первый раз за ход, когда вы убираете жетон щита с вашего корабля, назначьте 1 жетон Уклонения на ваш корабль.'''
# TIE/fo
'"Omega Ace"':
name: '"PI:NAME:<NAME>END_PI"'
ship: "Истребитель TIE/пп"
text: """Атакуя, вы можете потратить жетон Концентрации и захват цели на защищающемся, чтобы заменить все ваши результаты на результаты %CRIT%."""
'"Epsilon Leader"':
name: '"PI:NAME:<NAME>END_PI"'
ship: "Истребитель TIE/пп"
text: """В начале фазы PI:NAME:<NAME>END_PI, уберите 1 жетон Стресса с каждого дружественного корабля на расстоянии 1."""
'"Zeta Ace"':
name: '"PI:NAME:<NAME>END_PI"'
ship: "Истребитель TIE/пп"
text: """Когда вы выполняете Бочку, вы можете использовать шаблон (%STRAIGHT% 2) вместо шаблона (%STRAIGHT% 1)."""
"Omega Squadron Pilot":
name: "Пилот эPI:NAME:<NAME>END_PIадPI:NAME:<NAME>END_PI"
ship: "Истребитель TIE/пп"
"Zeta Squadron Pilot":
name: "Пилот эскадрPI:NAME:<NAME>END_PI"
ship: "Истребитель TIE/пп"
"Epsilon Squadron Pilot":
name: "Пилот эскадрPI:NAME:<NAME>END_PI"
ship: "Истребитель TIE/пп"
'"Omega Leader"':
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель TIE/пп"
text: '''Вражеские корабли, находящиеся в вашем захвате цели, не могут модифицировать кубики, атакуя вас или защищаясь от ваших атак.'''
'HPI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''Когда вы открываете зеленый или красный маневр, вы можете повернуть ваш диск на другой маневр той же сложности.'''
'"YoPI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
ship: "TIE истребитель"
text: """Дружественные TIE истребители на расстоянии 1-3 могут выполнять действие с вашей экипированной карты улучшений %ELITE%."""
'"PI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
ship: "TIE истребитель"
text: """Атакуя, вы можете отменить все результаты кубиков. Если вы отменяете результат %CRIT%, назначьте 1 карту повреждений лицом вниз на защищающегося."""
'"PI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
ship: "TIE истребитель"
text: """Когда другой дружественный корабль на расстоянии 1 тратит жетон Концентрации, назначьте жетон Концентрации на ваш корабль."""
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Атакующий шаттл"
text: """Защищаясь, если у вас есть Стресс, вы можете заменить до 2 ваших результатов %FOCUS% на результаты %EVADE%."""
'"PI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
text: '''Атакуя, если у вас нет Стресса, вы можете получить 1 жетон Стресса, чтобы бросить 1 дополнительный кубик атаки.'''
ship: "Истребитель TIE/пп"
'"PI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
text: '''Пока у вас нет карт повреждений, считайте ваше умение пилота равным 12.'''
ship: "Истребитель TIE/пп"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вражеский корабль на расстоянии 1-2 атакует, вы можете потратить жетон Концентрации. Если вы делаете это, атакующий бросает на 1 кубик атаки меньше."""
'"PI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы PI:NAME:<NAME>END_PI, каждый вражеский корабль, которого вы касаетесь, получает 1 жетон Стресса."""
'PI:NAME:<NAME>END_PI (Attack Shuttle)':
name: "PI:NAME:<NAME>END_PI (Атакующий шаттл)"
ship: "Атакующий шаттл"
text: """Когда вы открываете зеленый или красный маневр, вы можете повернуть ваш диск на другой маневр той же сложности."""
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Атакующий шаттл"
text: """Сразу перед открытием вашего маневра, вы можете выполнить свободное действие Ускорение или Бочку."""
'"PI:NAME:<NAME>END_PI" OrPI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Атакующий шаттл"
text: '''Защищаясь, вы можете отменять результаты %CRIT% перед результатами %HIT%.'''
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "VCX-100"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''Один раз за ход, после того, как вы сбрасываете карту улучшений %ELITE%, переверните эту карту обратно.'''
ship: "TIE бомбардировщик"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''Когда у вас нет жетонов Стресса, можете считать маневры %TROLLLEFT% и %TROLLRIGHT% белыми маневрами.'''
ship: "Икс-Крыл T-70"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """После защиты, вы можете выполнить свободное действие."""
ship: "TIE улучшенный прототип"
"4-LOM":
ship: "Звездный истребитель G-1A"
text: """В начале фазы Завершения, вы можете назначить 1 из ваших жетонов Стресса на другой корабль на расстоянии 1."""
"Tel PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Джампмастер 5000"
text: """В первый раз, когда вы должны быть уничтожены, вместо этого отмените все оставшиеся повреждения, сбросьте все карты повреждений, и назначьте 4 карты повреждений лицом вниз этому кораблю."""
"ManPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Джампмастер 5000"
text: """В начале фазы Боя, вы можете назначить все жетоны Концентрации, Уклонения и захвата цели, назначенные вам, на другой дружественный корабль на расстоянии 1."""
"Contracted Scout":
name: "Разведчик-контрактник"
ship: "Джампмастер 5000"
'"Deathfire"':
name: "Смертельное пламя"
text: '''Когда вы открываете ваш диск маневров или после того, как вы выполняете действие, вы можете выполнить действие с карты улучшения %BOMB% как свободное действие.'''
ship: "TIE бомбардировщик"
"Sienar Test Pilot":
name: "СPI:NAME:<NAME>END_PIенарский летчик-испытатель"
ship: "TIE улучшенный прототип"
"Baron of the Empire":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE улучшенный прототип"
"PI:NAME:<NAME>END_PI (TIE Defender)":
name: "PI:NAME:<NAME>END_PI (TIE защитник)"
text: """Когда ваша атака наносит защищающемуся карту повреждений в открытую, вместо этого вытяните 3 карты повреждений, выберите 1 для отработки и сбросьте остальные."""
ship: "TIE защитник"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы открываете маневр %STRAIGHT%, вы можете считать его маневром %KTURN%."""
ship: "TIE защитник"
"Glaive Squadron Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE защитник"
"PoPI:NAME:<NAME>END_PI (PS9)":
name: "PI:NAME:<NAME>END_PI (УП9)"
text: """Атакуя или защищаясь, если у вас есть жетон Концентрации, вы можете заменить 1 из ваших результатов %FOCUS% на результат %HIT% или %EVADE%."""
ship: "Икс-Крыл T-70"
"Resistance Sympathizer":
name: "Сочувствующий повстанцам"
ship: "YT-1300"
"Rey":
name: "PI:NAME:<NAME>END_PI"
text: """Атакуя или защищаясь, если вражеский корабль находится в вашей основной арке огня, вы можете перебросить до 2 пустых результатов."""
'PI:NAME:<NAME>END_PI (TFA)':
name: "PI:NAME:<NAME>END_PI (ПС)"
text: '''Во время расстановки, вы можете быть расположены где угодно на игровом поле на расстоянии не ближе 3 от вражеских кораблей.'''
'PI:NAME:<NAME>END_PI (TFA)':
name: "PI:NAME:<NAME>END_PI (ПС)"
text: '''После того, как другой дружественный корабль на расстоянии 1-3 уничтожен (но не сбежал с поля боя), вы можете выполнить атаку.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "ARC-170"
text: '''Атакуя или защищаясь, вы можете потратить захват цели на защищающемся, чтобы добавить 1 результат %FOCUS% к вашему броску.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "ARC-170"
text: '''Когда другой дружественный корабль на расстоянии 1-2 атакует, он может считать ваши синие жетоны захвата цели как свои собственные.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "ARC-170"
text: '''После того, как вражеский корабль в вашей арке огня на расстоянии 1-3 атакует другой дружественный корабль, вы можете выполнить свободное действие.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "ARC-170"
text: '''После того, как вы выполните маневр, вы можете бросить кубик атаки. При результате %HIT% или %CRIT%, уберите 1 жетон Стресса с вашего корабля.'''
'"Quickdraw"':
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель TIE/сс"
text: '''Один раз за ход, когда вы теряете жетон щита, вы можете выполнить атаку основным оружием.'''
'"Backdraft"':
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель TIE/сс"
text: '''Атакуя корабль в вашей вторичной арке огня, вы можете добавить 1 результат %CRIT%.'''
'Omega Specialist':
name: "ОPI:NAME:<NAME>END_PI спPI:NAME:<NAME>END_PI"
ship: "Истребитель TIE/сс"
'Zeta Specialist':
name: "ЗPI:NAME:<NAME>END_PI"
ship: "Истребитель TIE/сс"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Звездный истребитель Протектората"
text: '''Атакуя или защищаясь, если вражеский корабль находится на расстоянии 1, вы можете бросить 1 дополнительный кубик.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Звездный истребитель Протектората"
text: '''В начале фазы БPI:NAME:<NAME>END_PI, вы можете выбрать 1 вражеский корабль на расстоянии 1. Если вы находитесь в его арке огня, он должен сбросить все жетоны Концентрации и Уклонения.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Звездный истребитель Протектората"
text: '''После выполнения красного маневра, назначьте 2 жетона Концентрации на ваш корабль.'''
'ConPI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Звездный истребитель Протектората"
'ConPI:NAME:<NAME>END_PI DPI:NAME:<NAME>END_PI VPI:NAME:<NAME>END_PIan':
name: "PI:NAME:<NAME>END_PI"
ship: "Звездный истребитель Протектората"
'ZePI:NAME:<NAME>END_PIous Recruit':
name: "PI:NAME:<NAME>END_PI"
ship: "Звездный истребитель Протектората"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Корабль-преследователь класса Копьеносец"
text: '''В начале фазы Боя, вы можете выбрать корабль на расстоянии 1. Если он находится в вашей основной <strong>и</strong> мобильной арках огня, назначьте на него 1 жетон Луча Захвата.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Корабль-преследователь класса Копьеносец"
text: '''В начале фазы Боя, вы можете выбрать корабль на расстоянии 1-2. Если он находится в вашей мобильной арке огня, назначьте ему 1 жетон Стресса.'''
'PI:NAME:<NAME>END_PI (Scum)':
name: "PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)"
ship: "Корабль-преследователь класса Копьеносец"
text: '''Защищаясь от вражеского корабля в вашей мобильной арке огня на расстоянии 1-2, вы можете добавить 1 результат %FOCUS% к вашему броску.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Корабль-преследователь класса Копьеносец"
'PI:NAME:<NAME>END_PI (TIE Fighter)':
name: "PI:NAME:<NAME>END_PI (TIE истребитель)"
ship: "TIE истребитель"
text: '''Сразу перед открытием вашего маневра, вы можете выполнить свободное действие Ускорение или Бочку.'''
'"PI:NAME:<NAME>END_PI" OrreliPI:NAME:<NAME>END_PI (TIE Fighter)':
name: "PI:NAME:<NAME>END_PI (TIE истребитель)"
ship: "TIE истребитель"
text: '''Защищаясь, вы можете отменять результаты %CRIT% перед результатами %HIT%.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Шаттл класса Ипсилон"
text: '''В первый раз за ход, когда вы получаете попадание, назначьте атакующему карту состояния "Я покажу тебе Темную Сторону".'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Квадджампер"
text: '''В конце фазы Активации, вы <strong>должны</strong> назначить жетон Луча Захвата каждому кораблю, которого касаетесь.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Ю-Крыл"
text: '''В начале фазы Активации, вы можете убрать 1 жетон Стресса с 1 другого дружественного корабля на расстоянии 1-2.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Ю-Крыл"
text: '''Когда дружественный корабль получает захват цели на противника, этот корабль может захватывать вражеский корабль на расстоянии 1-3 от любого дружественного корабля.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Ю-Крыл"
text: '''После того, как вражеский корабль выполняет маневр, приводящий к наложению на ваш корабль, вы можете выполнить свободное действие.'''
'''"PI:NAME:<NAME>END_PI"''':
ship: "TIE ударник"
name: '"PI:NAME:<NAME>END_PI"'
text: '''Когда у вас есть экипированная карта улучшения "Адаптивные элероны", вы можете игнорировать особенность этой карты.'''
'''"PI:NAME:<NAME>END_PI"''':
ship: "TIE ударник"
name: '"PI:NAME:<NAME>END_PI"'
text: '''Атакуя, если у вас есть 1 или меньше карт повреждений, бросьте 1 дополнительный кубик атаки.'''
'''"Countdown"''':
ship: "TIE ударник"
name: '"Обратный Отсчет"'
text: '''Защищаясь, если у вас нет Стресса, во время шага "Сравнение результатов кубиков" вы можете получить 1 повреждение, чтобы отменить <strong>все</strong> результаты кубиков. Если вы делаете это, получите 1 жетон Стресса.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Икс-Крыл T-70"
text: '''Когда вы получаете жетон Стресса, если в вашей арке огня на расстоянии 1 есть вражеский корабль, вы можете сбросить этот жетон стресса.'''
'"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Икс-Крыл T-70"
text: '''После того, как вы выполняете маневр со скоростью 2, 3 или 4, если вы не касаетесь другого корабля, вы можете выполнить свободное действие Бочку.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Икс-Крыл T-70"
text: '''Атакуя или защищаясь, вы можете перебросить 1 из ваших кубиков за каждый другой дружественный корабль на расстоянии 1.'''
'PI:NAME:<NAME>END_PI':
ship: "TIE истребитель"
name: "PI:NAME:<NAME>END_PI"
text: '''В начале фазы Боя, вы можете потратить 1 жетон Концентрации, чтобы выбрать дружественный корабль на расстоянии 1. Он может выполнить 1 свободное действие.'''
'PI:NAME:<NAME>END_PI':
ship: "TIE истребитель"
name: "PI:NAME:<NAME>END_PI"
text: '''После выполнения атаки, назначьте защищающемуся карту состояния "Подавляющий огонь".'''
'PI:NAME:<NAME>END_PI':
ship: "Шаттл класса Ипсилон"
name: "PI:NAME:<NAME>END_PI"
text: '''С точки зрения ваший действий и карт улучшений, вы можете считать дружественные корабли на расстоянии 2-3 как находящиеся на расстоянии 1.'''
'PI:NAME:<NAME>END_PI':
ship: "Шаттл класса Ипсилон"
name: "PI:NAME:<NAME>END_PI"
text: '''Во время расстановки, дружественные корабли могут располагаться где угодно на игровом поле на расстоянии 1-2 от вас.'''
'PI:NAME:<NAME>END_PI':
ship: "Квадджампер"
name: "PI:NAME:<NAME>END_PI"
text: '''Когда вы открываете реверсивный маневр, вы можете сбрасывать бомбу, испольтзуя ваши передние направляющие (в том числе бомбы с указателем "<strong>Действие:</strong>").'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Квадджампер"
text: '''Защищаясь, вместо того, чтобы использовать ваше значение Маневренности, вы можете бросить число кубиков защиты, равное скорости маневра, который вы выполняли на этом ходу.'''
"Blue Squadron PI:NAME:<NAME>END_PIfinder":
name: "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
ship: "Ю-Крыл"
"Black Squadron Scout":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE ударник"
"Scarif Defender":
name: "PI:NAME:<NAME>END_PIащPI:NAME:<NAME>END_PI"
ship: "TIE ударник"
"Imperial Trainee":
name: "Имперский кадет"
ship: "TIE ударник"
"Starkiller Base Pilot":
ship: "Шаттл класса Ипсилон"
name: "Пилот базы Старкиллер"
"JPI:NAME:<NAME>END_PI":
ship: "Квадджампер"
name: "Стрелок с Джакку"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Перехватчик M3-A"
text: '''После получения захвата цели, назначьте жетоны Концентрации и Уклонения на ваш корабль, пока у вас не будет такого же количества каждого жетона, как и на корабле в захвате.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Перехватчик M3-A"
text: '''В начале фазы Боя, вы можете получить жетон "Орудие выведено из строя", чтобы перевернуть 1 из ваших сброшенных карт улучшений %TORPEDO% или %MISSILE%.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Перехватчик M3-A"
text: '''Атакуя или защищаясь, вы можете потратить 1 щит, чтобы перебросить любое количество ваших кубиков.'''
'Sunny Bounder':
name: "PI:NAME:<NAME>END_PI"
ship: "Перехватчик M3-A"
text: '''Один раз за ход, после того, как вы бросаете или перебрасываете кубик, если у вас выпал тот же результат на каждом кубике, добавьте 1 соответствующий результат.'''
'C-ROC Cruiser':
ship: "Крейсер C-ROC"
name: "КрейсPI:NAME:<NAME>END_PI C-ROC"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "TIE агрессор"
text: '''Атакуя, вы можете потратить 1 жетон Концентрации, чтобы отменить все пустые и %FOCUS% результаты защищающегося.'''
'"Double Edge"':
ship: "TIE агрессор"
name: "PI:NAME:<NAME>END_PI"
text: '''Один раз за ход, после того, как вы выполнили атаку вспомогательным оружием, которая не попала, вы можете выполнить атаку другим оружием.'''
'Onyx Squadron Escort':
ship: "TIE агрессор"
name: "PI:NAME:<NAME>END_PI"
'Sienar Specialist':
ship: "TIE агрессор"
name: "PI:NAME:<NAME>END_PIарский специалист"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель Кихраксз"
text: '''После защиты, если вы не бросили ровно 2 кубика защиты, атакующий получает 1 жетон Стресса.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Канонерка Озитук"
text: '''Когда другой дружественный корабль на расстоянии 1 защищается, вы можете потратить 1 жетон Усиления. Если вы делаете это, защищающийся добавляет 1 результат %EVADE%.'''
'WPI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Канонерка Озитук"
text: '''Атакуя, если у вас нет щитов и есть хотя бы 1 назначенная карта повреждений, бросьте 1 дополнительный кубик атаки.'''
'WPI:NAME:<NAME>END_PI LiPI:NAME:<NAME>END_PIator':
name: "PI:NAME:<NAME>END_PI"
ship: "Канонерка Озитук"
'PI:NAME:<NAME>END_PIyyyk Defender':
name: "PI:NAME:<NAME>END_PI"
ship: "Канонерка Озитук"
'Captain Nym (Scum)':
name: "PI:NAME:<NAME>END_PI (Пираты)"
ship: "Бомбардировщик Скуррг H-6"
text: '''Вы можете игнорировать дружественные бомбы. Когда дружественный корабль защищается, если атакующий меряет дистанцию через дружественный жетон бомбы, защищающийся может добавить 1 результат %EVADE%.'''
'Captain Nym (Rebel)':
name: "PI:NAME:<NAME>END_PI (Повстанцы)"
ship: "Бомбардировщик Скуррг H-6"
text: '''Один раз за ход, вы можете предотвратить взрыв дружественной бомбы.'''
'Lok Revenant':
name: "PI:NAME:<NAME>END_PI"
ship: "Бомбардировщик Скуррг H-6"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Бомбардировщик Скуррг H-6"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Бомбардировщик Скуррг H-6"
text: '''Сбрасывая бомбу, вы можете использовать шаблон (%TURNLEFT% 1) или (%TURNRIGHT% 1) вместо шаблона (%STRAIGHT% 1).'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: 'Звездная Гадюка'
text: '''Если у вас нет Стресса, когда вы открываете маневр крена, поворота или Петлю Сеньора, вместо этого вы можете считать это красным маневром Коготь того же направления (влево или вправо), используя шаблон изначально открытого маневра.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: 'Звездная Гадюка'
text: '''Во время расстановки, перед шагом "Расстановка сил", вы можете выбрать 1 вражеский корабль и назначить ему карту состояния "Затененный" или "Мимикрированный".'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель Кихраксз"
text: '''Один раз за ход, после того, как вражеский корабль, не защищающийся от атаки, получает повреждение или критическое повреждение, вы можете выполнить атаку против этого корабля.'''
'PI:NAME:<NAME>END_PI':
ship: "Звездное Крыло класса Альфа"
name: "PI:NAME:<NAME>END_PI"
text: '''Защищаясь, если у вас есть жетон Оружие выведено из Строя, бросьте 1 дополнительный кубик защиты.'''
'Nu Squadron Pilot':
name: "PI:NAME:<NAME>END_PI"
ship: "Звездное Крыло класса Альфа"
'Rho Squadron Veteran':
name: "PI:NAME:<NAME>END_PI"
ship: "Звездное Крыло класса Альфа"
'PI:NAME:<NAME>END_PI':
ship: "Звездное Крыло класса Альфа"
name: "PI:NAME:<NAME>END_PI"
text: '''Когда вы получаете жетон Оружие выведено из Строя, если вы не под Стрессом, вы можете получить 1 жетон Стресса, чтобы убрать его.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель M12-L Кимогила"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель M12-L Кимогила"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель M12-L Кимогила"
text: '''После выполнения атаки, каждый вражеский корабль в вашей арке прицельного огня на расстоянии 1-3 должен выбрать: получить 1 повреждение или убрать все жетоны Концентрации и Уклонения.'''
'PI:NAME:<NAME>END_PI (Kimogila)':
name: "PI:NAME:<NAME>END_PI (Кимогила)"
ship: "Истребитель M12-L Кимогила"
text: '''В начале фазы Боя, вы можете получить захват цели на вражеский корабль в вашей арке прицельного огня на расстоянии 1-3.'''
'PI:NAME:<NAME>END_PI (Sheathipede)':
name: "PI:NAME:<NAME>END_PI (Колчан)"
ship: "Шаттл класса Колчан"
text: '''Когда вражеский корабль в вашей арке огня на расстояниим 1-3 становится активным кораблем во время фазы Боя, если у вас нет Стресса, вы можете получить 1 жетон Стресса. Если вы делаете это, тот корабль не может тратить жетоны для модификации его кубиков во время атаки на этом ходу.'''
'PI:NAME:<NAME>END_PI (Sheathipede)':
name: "PI:NAME:<NAME>END_PI (Колчан)"
ship: "Шаттл класса Колчан"
text: """Защищаясь, если у вас нет Стресса, вы можете заменить до 2 ваших результатов %FOCUS% на результаты %EVADE%."""
'"Zeb" Orrelios (Sheathipede)':
name: "PI:NAME:<NAME>END_PI (Колчан)"
ship: "Шаттл класса Колчан"
text: '''Защищаясь, вы можете отменять результаты %CRIT% перед результатами %HIT%.'''
'AP-5':
ship: "Шаттл класса Колчан"
text: '''Когда вы выполняете действие Координации, после выбора дружественного корабля и перед выполнением им свободного действия, вы можете получить 2 жетона Стресса, чтобы убрать с него 1 жетон Стресса.'''
'Crimson Squadron Pilot':
name: "PI:NAME:<NAME>END_PI"
ship: "Бомбардировщик B/SF-17"
'"Crimson Leader"':
name: '"PI:NAME:<NAME>END_PI"'
ship: "Бомбардировщик B/SF-17"
text: '''Атакуя, если защищающийся находится в вашей арке огня, вы можете потратить 1 результат %HIT% или %CRIT%, чтобы назначить карту состояния "Разбитый" на защищающегося.'''
'"Crimson Specialist"':
name: '"PI:NAME:<NAME>END_PI"'
ship: "Bombardero B/SF-17"
text: '''Размещая жетон бомбы, которую вы сбросили после открытия диска маневров, вы можете расположить жетон бомбы где угодно в игровой зоне, касаясь вашего корабля.'''
'"Cobalt Leader"':
name: '"PI:NAME:<NAME>END_PI"'
ship: "Бомбардировщик B/SF-17"
text: '''Атакуя, если защищающийся находится на расстоянии 1 от жетона бомбы, защищающийся бросает на 1 кубик защиты меньше.'''
'Sienar-Jaemus Analyst':
name: "PI:NAME:<NAME>END_PI"
ship: "TIE глушитель"
'First Order Test Pilot':
name: "PI:NAME:<NAME>END_PIетчик-испытатель PI:NAME:<NAME>END_PI"
ship: "TIE глушитель"
'PI:NAME:<NAME>END_PI (TIE Silencer)':
name: "PI:NAME:<NAME>END_PI (TIE глушитель)"
ship: "TIE глушитель"
text: '''В первый раз за ход, когда вы получаете попадание, назначьте атакующему карту состояния "Я покажу тебе Темную Сторону".'''
'Test Pilot "Blackout"':
name: 'Летчик-испытатель "PI:NAME:<NAME>END_PI"'
ship: "TIE глушитель"
text: '''Атакуя, если атака идет через преграду, защищающийся бросает на 2 кубика защиты меньше.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Икс-Крыл"
text: '''After you perform a boost or barrel roll action, you may flip your equipped "Servomotor S-foils" upgrade card.'''
'Major Vermeil':
name: "PI:NAME:<NAME>END_PI"
text: '''Атакуя, если у защищающегося нет жетонов Концентрации или Уклонения, вы можете заменить 1 из ваших пустых или %FOCUS% результатов на результат %HIT%.'''
'CaptPI:NAME:<NAME>END_PI':
text: '''When defending, if the attacker is jammed, add 1 %EVADE% result to your roll.'''
'"VizPI:NAME:<NAME>END_PI"':
text: '''After a friendly ship executes a 1-speed maneuver, if it is at Range 1 and did not overlap a ship, you may assign 1 of your focus or evade tokens to it.'''
'PI:NAME:<NAME>END_PI':
text: '''When another friendly ship at Range 1-2 is defending, the attacker cannot reroll more than 1 attack die.'''
'Edrio Two-Tubes':
text: '''When you become the active ship during the Activation phase, if you have 1 or more focus tokens, you may perform a free action.'''
upgrade_translations =
"Ion Cannon Turret":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Атака:</strong> Атакуйте 1 корабль(даже корабль вне вашей арки стрельбы).<br /><br />Если атака попадает по кораблю-цели, корабль получает 1 повреждение и 1 ионный жетон. Затем отмените все результаты кубиков."""
"Proton TorPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PIонные тPI:NAME:<NAME>END_PIеды"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете заменить 1 результат %FOCUS% на результат %CRIT%."""
"R2 Astromech":
name: "PI:NAME:<NAME>END_PIстромех R2"
text: """Можете считать все маневры со скоростью 1 и 2 зелеными маневрами."""
"R2-D2":
text: """После выполнения зеленого маневра, вы можете восстановить 1 щит (до максимального значения щитов)."""
"R2-F2":
text: """<strong>Действие:</strong> Увеличьте вашу Маневренность на 1 до конца этого хода."""
"R5-D8":
text: """<strong>Действие:</strong> Бросьте 1 кубик защиты.<br /><br />При результате %EVADE% или %FOCUS%, сбросьте 1 из ваших карт повреждений, лежащих лицом вниз."""
"R5-K6":
text: """После того, как вы потратили захват цели, бросьте 1 кубик защиты.<br /><br />При результате %EVADE% немедленно получите захват цели на том же корабле. Вы не можете использовать этот захват цели во время этой атаки."""
"R5 Astromech":
name: "Астромех R5"
text: """Во время фазы Завершения, вы можете выбрать одну из ваших карт повреждений лицом вверх со свойством <strong>Корабль</strong> и перевернуть ее лицом вниз."""
"Determination":
name: "Решительность"
text: """Если вы получили карту повреждений лицом вверх со свойством <strong>Пилот</strong>, сбросьте ее немедленно, не отрабатывая ее эффект."""
"Swarm Tactics":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы Боя, вы можете выбрать 1 дружественный корабль на расстоянии 1.<br /><br />До конца этой фазы, считайте умение пилота выбранного корабля равным вашему."""
"Squad Leader":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Действие:</strong> Выберите 1 корабль на расстоянии 1-2, умение пилота которого ниже вашего.<br /><br />Выбранный корабль может немедленно выполнить 1 свободное действие."""
"Expert Handling":
name: "Мастерское управление"
text: """<strong>Действие:</strong> Выполните свободное действие Бочку. Если у вас нет значка действий %BARRELROLL%, получите 1 жетон Стресса.<br /><br />Затем вы можете убрать 1 вражеский захват цели с вашего корабля."""
"Marksmanship":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Действие:</strong> Атакуя в этот ход, вы можете сменить 1 из ваших результатов %FOCUS% на результат %CRIT% , и все прочие результаты %FOCUS% на результат %HIT%."""
"Concussion Missiles":
name: "Ударные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете сменить 1 пустой результат на результат %HIT%."""
"Cluster Missiles":
name: "Кластерные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку <strong>дважды</strong>."""
"Daredevil":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Действие:</strong> Выполните белый (%TURNLEFT% 1) или (%TURNRIGHT% 1) маневр. Затем получите 1 жетон стресса.<br /><br />Затем, если у вас нет значка действия %BOOST%, бросьте 2 кубика атаки. Получите любое выброшенное повреждение(%HIT%) или критическое повреждение(%CRIT%)."""
"Elusiveness":
name: "Уклончивость"
text: """Защищаясь, вы можете получить 1 жетон стресса чтобы выбрать 1 кубик атаки. Атакующий должен перебросить этот кубик.<br /><br />Если у вас есть хотя бы 1 жетон стресса, вы не можете использовать эту способность."""
"Homing Missiles":
name: "Самонаводящиеся ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Защищающийся не может использовать жетоны уклонения во время этой атаки."""
"Push the Limit":
name: "Предел возможностей"
text: """Один раз за ход, после выполнения действия, вы можете выполнить 1 свободное действие, отображенное на вашей полоске действий.<br /><br />Затем получите 1 жетон стресса."""
"Deadeye":
name: "МPI:NAME:<NAME>END_PI"
text: """%SMALLSHIPONLY%%LINEBREAK%Вы можете считать <strong>"Атака (захват цели)"</strong> как <strong>"Атака (концентрация)"</strong>.<br /><br />Когда атака обязывает вас использовать захват цели, вместо этого вы можете использовать жетон Концентрации."""
"Expose":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Действие:</strong> До конца хода увеличьте значение основной атаки на 1 и снизьте значение уклонения на 1."""
"GunPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """После проведения атаки без попадания, вы можете немедленно выполнить атаку основным оружием. Вы не можете выполнять другую атаку на этом ходу."""
"Ion Cannon":
name: "Ионная пушка"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.<br /><br />Если атака попадает, защищающийся получает 1 повреждение и получает 1 ионный жетон. Затем отмените <b>все</b> результаты кубиков."""
"Heavy Laser Cannon":
name: "Тяжелая лазерная пушка"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.<br /><br />Сразу после броска кубиков атаки, вы должны заменить все результаты %CRIT% на результаты %HIT%."""
"Seismic Charges":
name: "Сейсмические заряды"
text: """Когда вы открываете диск маневров, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон сейсмического заряда.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы Активации.<br /><br /><strong>Жетон сейсмического заряда:</strong> Когда этот жетон бомбы взрывается, каждый корабль на расстоянии 1 от жетона получает 1 повреждение. Затем сбросьте этот жетон."""
"Mercenary Copilot":
name: "Второй пилот-наемник"
text: """Атакуя на расстоянии 3, вы можете сменить 1 результат %HIT% на результат %CRIT%."""
"Assault Missiles":
name: "Штурмовые ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если эта атака попадает, каждый другой корабль на расстоянии 1 от защищающегося получает 1 повреждение."""
"Veteran Instincts":
name: "ИнстинктPI:NAME:<NAME>END_PI ветерPI:NAME:<NAME>END_PI"
text: """Повышает умение пилотирования на 2."""
"Proximity Mines":
name: "Мины приближения"
text: """<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>сбросить</strong> 1 жетон мины приближения.<br /><br />Когда подставка корабля или шаблон маневра перекрывает этот жетон, он <strong>взрывается</strong>.<br /><br /><strong>Жетон мины приближения:</strong> Когда этот бомбовый жетон взрывается, корабль, прошедший через него или вставший на нем бросает 3 кубика атаки и получает все выброшенные результаты повреждений(%HIT%) и критических повреждений(%CRIT%). Затем сбросьте этот жетон."""
"Weapons Engineer":
name: "Инженер-оружейник"
text: """Вы можете поддерживать 2 захвата цели(только 1 на каждый вражеский корабль).<br /><br />Когда вы получаете захват цели, вы можете захватывать 2 разных корабля."""
"Draw Their Fire":
name: "Огонь на себя"
text: """Когда дружественный корабль на расстоянии 1 получает попадание от атаки, вы можете получить 1 из неотмененных %CRIT% результатов вместо целевого корабля."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """После проведения атаки без попадания вы можете немедленно провести атаку основным оружием. Вы можете сменить 1 результат %FOCUS% на результат %HIT%. Вы не можете выполнять другую атаку в этот ход."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Вы можете считать все %STRAIGHT% маневры как зеленые маневры."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы получаете карту повреждений, вы можете немедленно сбросить эту карту и восстановить 1 щит.<br /><br />Затем сбросьте эту карту улучшения."""
"Advanced Proton Torpedoes":
name: "Улучшенные протонные торпеды"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете заменить до 3 ваших пустых результатов на результаты %FOCUS%."""
"Autoblaster":
name: "Автобластер"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.<br /><br />Ваши %HIT% результаты не могут быть отменены кубиками защиты.<br /><br />Защищающийся может отменять результаты %CRIT% до результатов %HIT%."""
"Fire-Control System":
name: "Система контроля огня"
text: """После выполнения атаки, вы можете получить захват цели на защищающемся."""
"Blaster Turret":
name: "Бластерная турель"
text: """<strong>Атака(концентрация):</strong> Потратьте 1 жетон Концентрации чтобы выполнить эту атаку против 1 корабля (даже вне пределов вашей арки огня)."""
"Recon Specialist":
name: "Специалист разведки"
text: """Когда вы выполняете действие Концентрации, назначьте 1 дополнительный жетон Концентрации на ваш корабль."""
"Saboteur":
name: "Саботажник"
text: """<strong>Действие:</strong> Выберите 1 вражеский корабль на расстоянии 1 и бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, выберите 1 случайную карту, лежащую лицом вниз на этом корабле, переверните ее и отработайте ее."""
"Intelligence Agent":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы Активации выберите 1 вражеский корабль на расстоянии 1-2. Вы можете посмотреть на выбранный маневр этого корабля."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PIы"
text: """Когда вы открываете ваш диск маневра, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон протонной бомбы.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы активации.<br /><br /><strong>Жетон протонной бомбы:</strong> Когда этот бомбовый жетон взрывается, каждый корабль на расстоянии 1 от жетона получает карту повреждения лицом вверх. Затем сбросьте этот жетон."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы открываете красный маневр, вы можете сбросить эту карту чтобы считать этот маневр как белый маневр до конца фазы Активации."""
"Advanced Sensors":
name: "Продвинутые сенсоры"
text: """Сразу перед объявлением маневра, вы можете выполнить 1 свободное действие.<br /><br />Если вы используете эту способность, вы должны пропустить шаг "Выполнение действия" в этом ходу."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Защищаясь, вы можете сменить 1 результат %HIT% атакующего на результат %FOCUS%.<br /><br />Атакующий не может перебрасывать кубик с измененным результатом."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """После того, как вы выполните атаку вражеского корабля, вы можете получить 2 повреждения чтобы заставить тот корабль получить 1 критическое повреждение."""
"Rebel Captive":
name: "PI:NAME:<NAME>END_PI"
text: """Один раз за ход, первый корабль, заявляющий вас целью атаки, немедленно получает 1 жетон стресса."""
"Flight Instructor":
name: "PI:NAME:<NAME>END_PI"
text: """Защищаясь, вы можете перебросить 1 из ваших результатов %FOCUS%. Если умение пилота атакующего "2" или ниже, вместо этого вы можете перебросить 1 пустой результат."""
"Navigator":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы открываете маневр, вы можете повернуть ваш диск на другой маневр того же типа.<br /><br />Вы не можете выбирать красный маневр если у вас есть жетон(ы) Стресса."""
"Opportunist":
name: "Оппортунист"
text: """При атаке, если защищающийся не имеет жетонов Концентрации или Уклонения, вы можете получить 1 жетон стресса чтобы бросить 1 дополнительный кубик атаки.<br /><br />Вы не можете использовать эту способность если у вас есть жетон(ы) стресса."""
"Comms Booster":
name: "Усилитель связи"
text: """<strong>Энергия:</strong> Потратьте 1 энергии, чтобы убрать все жетоны Стресса с дружественного корабля на расстоянии 1-3. Затем назначьте 1 жетон Концентрации на тот корабль."""
"Slicer Tools":
name: "Электронные боевые системы"
text: """<strong>Действие:</strong> Выберите 1 или более кораблей на расстоянии 1-3, имеющих жетон Стресса. За каждый выбранный корабль, вы можете потратить 1 энергии чтобы заставить этот корабль получить 1 повреждение."""
"Shield Projector":
name: "ПроектPI:NAME:<NAME>END_PI"
text: """Когда вражеский корабль заявляет маленький или большой корабль целью атаки, вы можете потратить 3 энергии, чтобы заставить этот корабль атаковать вас (при возможности)."""
"Ion Pulse Missiles":
name: "Ионные импульсные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если эта атака попадает, защищающийся получает 1 повреждение и 2 ионных жетона. Затем отмените <strong>все</strong> результаты кубиков."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы PI:NAME:<NAME>END_PI, уберите 1 жетон стресса с другого дружественного корабля на расстоянии 1."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы PI:NAME:<NAME>END_PI, вы можете выбрать 1 дружественный корабль на расстоянии 1-2. Поменяйтесь умением пилота с умением пилота этого корабля до конца этой фазы."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Атакуя корабль в вашей арке огня, если вы не находитесь в арке огня этого корабля, его Маневренность снижается на 1."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Атакуя, вы можете перебросить 1 кубик атаки. Если умение пилота защищающегося "2" или ниже, вместо этого вы можете перебросить до 2 кубиков атаки."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />После выполнения этой атаки, защищающийся получает 1 жетон стресса, если его значение корпуса 4 или ниже."""
"R7 Astromech":
name: "Астромех R7"
text: """Один раз за ход, защищаясь, если у вас есть захват цели на атакующего, вы можете потратить этот захват цели чтобы выбрать любой или все кубики атаки. Атакующий должен перебросить выбранные кубики."""
"R7-T1":
name: "R7-T1"
text: """<strong>Действие:</strong> Выберите вражеский корабль на расстоянии 1-2. Если вы находитесь в арке огня этого корабля, вы можете получить захват цели на этот корабль. Затем вы можете выполнить свободное действие Ускорения"""
"Tactician":
name: "PI:NAME:<NAME>END_PI"
text: """%LIMITED%%LINEBREAK%После того, как вы выполните атаку против корабля в вашей арке стрельбы на расстоянии 2, этот корабль получает 1 жетон стресса."""
"R2-D2 (Crew)":
name: "R2-D2 (Экипаж)"
text: """В конце фазы Завершения, если у вас нет щитов, вы можете восстановить 1 щит и бросить 1 кубик атаки. При результате %HIT%, случайным образом выберите и переверните 1 карту повреждений, лежащую лицом вниз, и отработайте ее."""
"C-3PO":
name: "C-3PO"
text: """Один раз за ход, перед тем, как бросить 1 или более кубиков защиты, вы можете заявить вслух количество результатов %EVADE%. Если вы выбросили именно столько (до модификации кубиков), добавьте 1 %EVADE% результат."""
"Single Turbolasers":
name: "Одноствольные турболазеры"
text: """<strong>Атака (Энергия):</strong> Потратьте 2 энергии с этой карты чтобы выполнить эту атаку. Защищающийся удваивает свою Маневренность против этой атаки. Вы можете сменить 1 из ваших результатов %FOCUS% на 1 результат %HIT%."""
"Quad Laser Cannons":
name: "Счетверенные лазерные пушки"
text: """<strong>Атака (Энергия):</strong> Потратьте 1 энергии с этой карты чтобы выполнить эту атаку. Если атака не попала, вы можете немедленно потратить 1 энергии с этой карты чтобы выполнить эту атаку снова."""
"Tibanna Gas Supplies":
name: "Склад тибаннского газа"
text: """<strong>Энергия:</strong> Вы можете сбросить эту карту чтобы получить 3 энергии."""
"Ionization Reactor":
name: "Ионизационный реактор"
text: """<strong>Энергия:</strong> Потратьте 5 энергии с этой карты и сбросьте эту карту чтобы заставить каждый другой корабль на расстоянии 1 получить 1 повреждение и 1 ионный жетон"""
"Engine Booster":
name: "Ускоритель двигателя"
text: """Сразу перед открытием вашего диска маневров, вы можете потратить 1 энергию чтобы выполнить белый (%STRAIGHT% 1)маневр. Вы не можете использовать эту способность если вы перекроете другой корабль."""
"R3-A2":
name: "R3-A2"
text: """Когда вы заявляете цель для атаки, если защищающийся находится в вашей арке огня, вы можете получить 1 жетон Стресса чтобы заставить защищающегося получить 1 жетон стресса."""
"R2-D6":
name: "R2-D6"
text: """Ваша панель улучшений получает значок улучшения %ELITE%.<br /><br />Вы не можете выбрать это улучшение если вы уже имеете значок улучшения %ELITE% или если ваше умение пилота "2" или ниже."""
"Enhanced Scopes":
name: "Улучшенная оптика"
text: """Во время фазы Активации, считайте ваше умение пилота равным "0"."""
"Chardaan Refit":
name: "Чардаанский тюнинг"
ship: "А-Крыл"
text: """<span class="card-restriction">Только для А-Крыла.</span><br /><br />Эта карта имеет отрицательное значение очковой стоимости отряда."""
"Proton Rockets":
name: "Протонные ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Вы можете бросить дополнительные кубики атаки, равные по количеству вашему значению Маневренности, до максимума в 3 кубика."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """После того, как вы снимаете жетон Стресса с вашего корабля, вы можете назначить жетон Концентрации на ваш корабль."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Один раз за ход, когда дружественный корабль на расстоянии 1-3 выполняет действие Концентрации или получает жетон Концентрации, вы можете назначить ему жетон Уклонения вместо этого."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Действие:</strong> Потратьте любое количество энергии чтобы выбрать это количество кораблей на расстоянии 1-2. Уберите все жетоны Концентрации, Уклонения, и синие жетоны захвата цели с этих кораблей."""
# TODO Check card formatting
"R4-D6":
name: "R4-D6"
text: """Когда вы получаете попадание от атаки и имеете по меньшей мере 3 неотмененных результата %HIT% , вы можете отменить эти результаты пока не останется 2. За каждый результат, отмененный этим способом, получите 1 жетон стресса."""
"R5-P9":
name: "R5-P9"
text: """В конце фазы Боя, вы можете потратить 1 из ваших жетонов Концентрации чтобы восстановить 1 щит (до максимального значения ваших щитов)."""
"WED-15 Repair Droid":
name: "Ремонтный дроид WED-15"
text: """<strong>Действие:</strong> Потратьте 1 энергии чтобы сбросить 1 из ваших карт повреждений, лежащих лицом вниз, или потратьте 3 энергии чтобы сбросить 1 из ваших карт повреждений, лежащих лицом вверх."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы Активации, вы можете сбросить эту карту чтобы считать умение пилота каждого дружественного корабля как "12" до конца фазы."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда другой дружественный корабль на расстоянии 1 атакует, он может сменить 1 результат %HIT% на 1 результат %CRIT%."""
"Expanded Cargo Hold":
name: "Расширенный грузовой отсек"
text: """<span class="card-restriction">Только для GR-75</span><br /><br />Один раз за ход, когда вы должны получить карту повреждений лицом вверх, вы можете потянуть эту карту из колоды повреждений носовой или кормовой части."""
ship: 'Средний транспорт GR-75'
"Backup Shield Generator":
name: "Вспомогательный генератор щита"
text: """В конце каждого хода вы можете потратить 1 энергии чтобы восстановить 1 щит (до максимального значения щитов)."""
"EM Emitter":
name: "ЭМ эмиттер"
text: """Когда вы перекрываете атаку, защищающийся бросает 3 дополнительных кубика защиты (вместо 1)."""
"Frequency Jammer":
name: "ГPI:NAME:<NAME>END_PI"
text: """Когда вы выполняете действие Заклинивания, выберите 1 вражеский корабль, не имеющий жетон стресса и находящийся на расстоянии 1 от заклинившего корабля. Выбранный корабль получает 1 жетон стресса."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы атакуете, если у вас есть захват цели на защищающемся, вы можете потратить этот захват цели чтобы сменить все результаты %FOCUS% на результаты %HIT%."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы Активации вы можете сбросить эту карту чтобы позволить всем дружественным кораблям, объявляющим красный маневр, считать этот маневр белым до конца фазы."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы Активации, выберите 1 вражеский корабль на расстоянии 1-3. Вы можете посмотреть на выбранный маневр этого корабля. Если маневр белый, назначьте этому кораблю 1 жетон стресса."""
"Gunnery Team":
name: "ОPI:NAME:<NAME>END_PIдийPI:NAME:<NAME>END_PI"
text: """Один раз за ход, атакуя вспомогательным оружием, вы можете потратить 1 энергии чтобы сменить 1 пустой результат на результат %HIT%."""
"Sensor Team":
name: "Сенсорная PI:NAME:<NAME>END_PI"
text: """При получении захвата цели, вы можете захватывать вражеский корабль на расстоянии 1-5 вместо 1-3."""
"Engineering Team":
name: "ИPI:NAME:<NAME>END_PIжPI:NAME:<NAME>END_PI"
text: """Во время фазы активации, когда вы открываете %STRAIGHT% маневр, получите дополнительно 1 энергии во время шага "Получение энергии"."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Действие:</strong> Бросьте 2 кубика защиты. За каждый результат %FOCUS% назначьте 1 жетон Концентрации на ваш корабль. За каждый результат %EVADE% , назначьте 1 жетон Уклонения на ваш корабль."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В конце фазы Боя, каждый вражеский корабль на расстоянии 1, не имеющий жетона Стресса, получает 1 жетон Стресса."""
"Fleet Officer":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Действие:</strong> Выберите до двух дружественных кораблей на расстоянии 1-2 и назначьте 1 жетон концентрации каждому из них. Затем получите 1 жетон Стресса."""
"Lone Wolf":
name: "PI:NAME:<NAME>END_PI"
text: """Атакуя или защищаясь, при отсутствии других дружественных кораблей на расстоянии 1-2, вы можете перебросить 1 из ваших пустых результатов."""
"Stay On Target":
name: "Оставайся на цели"
text: """Когда вы открываете маневр, вы можете повернуть ваш диск на другой маневр с той же скоростью.<br /><br />Считайте эот маневр красным маневром."""
"Dash Rendar":
name: "PI:NAME:<NAME>END_PI"
text: """Вы можете проводить атаки, перекрывая подставкой препятствие.<br /><br />Ваши атаки не могут быть перекрыты."""
'"LPI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Действие:</strong> Выполните свободное действие Ускорение. Затем получите 1 ионный жетон."""
"Ruthlessness":
name: "Беспощадность"
text: """После того, как вы выполните атаку, которая попала, вы <strong>должны</strong> выбрать 1 корабль на расстоянии 1 от защищающегося (кроме себя). Этот корабль получает 1 повреждение."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы касаетесь вражеского корабля, его Маневренность снижается на 1."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы Боя, если у вас нет щитов и на ваш корабль назначена хотя бы 1 карта повреждений, вы можете провести свободное действие Уклонения."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы получаете карту повреждений лицом вверх, вы можете сбросить эту карту или другую карту улучшений %CREW% типа, чтобы перевернуть эту карту повреждений лицом вниз (не отрабатывая ее эффект)."""
"Ion Torpedoes":
name: "Ионные тPI:NAME:<NAME>END_PIы"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если эта атака попадет, защищающийся и каждый корабль на расстоянии 1 получает 1 ионный жетон."""
"Bomb Loadout":
name: "Бомбовая загрузка"
text: """<span class="card-restriction">Только для У-Крыла.</span><br /><br />Ваша панель улучшений получает значок %BOMB%."""
ship: "У-Крыл"
"Bodyguard":
name: "Телохранитель"
text: """%SCUMONLY%<br /><br />В начале фазы Боя, вы можете потратить жетон Концентрации, чтобы выбрать дружественный корабль с более высоким умением пилота на расстоянии 1. Увеличьте его значение Маневренности на 1 до конца хода."""
"Calculation":
name: "Счисление"
text: """Атакуя, вы можете потратить жетон Концентрации, чтобы сменить 1 из ваших результатов %FOCUS% на результат %CRIT%."""
"Accuracy Corrector":
name: "Корректировщик огня"
text: """Атакуя, во время шага "Модификация кубиков атаки", вы можете отменить все результаты кубиков. Затем, вы можете добавить 2 результата %HIT% к броску.<br /><br />Ваши кубики не могут быть модифицированы снова во время этой атаки."""
"Inertial Dampeners":
name: "Инерциальные амортизаторы"
text: """Когда вы открываете ваш маневр, вы можете сбросить эту карту чтобы вместо него выполнить белый [0%STOP%] маневр. Затем получите 1 жетон Стресса."""
"Flechette Cannon":
name: "Осколочная пушка"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK% Если эта атака попадает, защищающийся получает 1 повреждение и, если он не имеет жетонов Стресса, также получает 1 жетон Стресса. Затем отмените <strong>все</strong> результаты кубиков."""
'"MPI:NAME:<NAME>END_PI" Cannon':
name: 'PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI"'
text: """<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK% Атакуя, вы можете заменить 1 результат %HIT% на результат %CRIT%."""
"Dead Man's Switch":
name: "Кнопка мертвеца"
text: """Когда вы уничтожены, каждый корабль на расстоянии 1 получает 1 повреждение."""
"Feedback Array":
name: "Матрица обратной связи"
text: """Во время фазы Боя, вместо выполнения каких-либо атак, вы можете получить 1 ионный жетон и 1 повреждение, чтобы выбрать 1 вражеский корабль на расстоянии 1. Этот корабль получает 1 повреждение."""
'"Hot Shot" Blaster':
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Атака:</strong> Сбросьте эту карту, чтобы атаковать 1 корабль (даже корабль вне вашей арки огня)."""
"Greedo":
name: "PI:NAME:<NAME>END_PI"
text: """%SCUMONLY%<br /><br />В первый раз за ход, когда вы атакуете, и в первый раз за ход, когда вы защищаетесь, первая нанесенная карта повреждений отрабатывается в открытую."""
"Outlaw Tech":
name: "Техник вне закона"
text: """%SCUMONLY%<br /><br />После того, как вы выполнили красный маневр, вы можете назначить 1 жетон Концентрации на ваш корабль."""
"K4 Security Droid":
name: "Дроид безопасности K4"
text: """%SCUMONLY%<br /><br />После выполнения зеленого маневра, вы можете получить захват цели."""
"Salvaged Astromech":
name: "Трофейный астромех"
text: """Когда вы получаете карту повреждений лицом вверх с обозначением <strong>Корабль</strong>, вы можете немедленно сбросить эту карту (не отрабатывая ее эффект).<br /><br />Затем сбросьте эту карту."""
'"Genius"':
name: '"ГPI:NAME:<NAME>END_PI"'
text: """После того, как вы откроете и выполните маневр, если вы не перекрываете другой корабль, вы можете сбросить 1 из ваших карт улучшения %BOMB% без указателя <strong>Действие:</strong> чтобы сбросить соответствующий жетон бомбы."""
"Unhinged Astromech":
name: "Неподвешенный астромех"
text: """Вы можете считать маневры со скоростью 3 зелеными маневрами."""
"R4 Agromech":
name: "Агромех R4"
text: """Атакуя, после того, как вы потратили жетон Концентрации, вы можете получить захват цели на защищающегося."""
"R4-B11":
text: """Атакуя, если у вас есть захват цели на защищающегося, вы можете потратить захват цели чтобы выбрать любые кубики защиты. Защищающийся должен перебросить выбранные кубики."""
"Autoblaster Turret":
name: "Автобластерная турель"
text: """<strong>Атака:</strong> Атакуйте 1 корабль (даже если он находится вне вашей арки огня).<br /><br />Ваши %HIT% результаты не могут быть отменены кубиками защиты.<br /><br />Защищающийся может отменять результаты %CRIT% до результатов %HIT%."""
"Advanced Targeting Computer":
ship: "TIE Улучшенный"
name: "Улучшенный компьютер наведения"
text: """<span class="card-restriction">Только для TIE улучшенный.</span>%LINEBREAK%Атакуя основным оружием, если у вас есть захват цели на защищающегося, вы можете добавить 1 результат %CRIT% к вашему броску. Если вы решаете это сделать, вы не можете использовать захваты цели во время этой атаки."""
"Ion Cannon Battery":
name: "Батарея ионных пушек"
text: """<strong>Атака (Энергия):</strong> Потратьте 2 энергии с этой карты чтобы выполнить эту атаку. Если эта атака попадает, защищающийся получает 1 критическое повреждение и 1 ионный жетон. Затем отмените <strong>все</strong> результаты кубиков."""
"Emperor Palpatine":
name: "PI:NAME:<NAME>END_PI"
text: """%IMPERIALONLY%%LINEBREAK%Один раз за ход, до того как дружественный корабль бросает кубики, вы можете назвать результат кубика. После броска вы должны заменить 1 из ваших резултьтатов на кубиках на названный результат. Результат этого кубика не может быть модифицирован снова."""
"Bossk":
name: "Босск"
text: """%SCUMONLY%%LINEBREAK%После того, как вы выполнили атаку, которая не попала, если у вас нет Стресса, вы <strong>должны</strong> получить 1 жетон Стресса. Затем получите 1 жетон Концентрации на ваш корабль, а также получите захват цели на защищающегося."""
"Lightning Reflexes":
name: "Молниеносные рефлексы"
text: """%SMALLSHIPONLY%%LINEBREAK%После выполнения белого или зеленого маневра, вы можете сбросить эту карту чтобы развернуть корабль на 180°. Затем получите 1 жетон стресса <strong>после</strong> шага "Проверка стресса пилота."""
"Twin Laser Turret":
name: "Спаренная лазерная турель"
text: """<strong>Атака:</strong> Выполните эту атаку <strong>дважды</strong> (даже против корабля вне вашей арки огня).<br /><br />Каждый раз, когда эта атака попадает, защищающийся получает 1 повреждение. Затем отмените <strong>все</strong> результаты кубиков."""
"Plasma Torpedoes":
name: "Плазменные торпеды"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.<br /><br />Если атака попадает, после нанесения повреждений, снимите 1 жетон щита с защищающегося."""
"Ion Bombs":
name: "Ионные бомбы"
text: """Когда вы открываете диск маневров, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон ионной бомбы.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы Активации.<br /><br /><strong>Жетон ионной бомбы:</strong> Когда этот жетон бомбы взрывается, каждый корабль на расстоянии 1 от жетона получает 2 ионных жетона. Затем сбросьте этот жетон."""
"Conner Net":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>бросить</strong> 1 жетон сети Коннер.<br /><br />Когда подставка корабля или шаблон маневра перекрывает этот жетон, он <strong>взрывается</strong>.<br /><br /><strong>Жетон сети Коннер:</strong> Когда этот бомбовый жетон взрывается, корабль, прощедший через него или перекрывший его, получает 1 повреждение, 2 ионных жетона и пропускает шаг "Выполнение действия". Затем сбросьте этот жетон."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Сбрасывая бомбу, вы можете использовать шаблон (%STRAIGHT% 2) вместо шаблона (%STRAIGHT% 1)."""
"Cluster Mines":
name: "Кластерные мины"
text: """<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>бросить</strong> комплект кластерных мин (3 жетона).<br /><br />Когда подставка корабля или шаблон маневра перекрывает жетон кластерной мины, он <strong>взрывается</strong>.<br /><br /><strong>Жетоны кластерных мин:</strong> Когда один из этих жетонов бомб взрывается, корабль, прощедший через него или перекрывший его, бросает 2 кубика атаки и получает 1 повреждение за каждый результат %HIT% или %CRIT%. Затем сбросьте этот жетон."""
'Crack Shot':
name: "Точный выстрел"
text: '''Когда вы атакуете корабль в вашей арке огня, в начале шага "Сравнение результатов", вы можете сбросить эту карту чтобы отменить 1 результат %EVADE% защищающегося.'''
"Advanced Homing Missiles":
name: "Улучшенные самонаводящиеся ракеты"
text: """<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадает, назначьте 1 карту повреждений лицом вверх защищающемуся. Затем отмените <strong>все</strong> результаты кубиков."""
'Agent Kallus':
name: "PI:NAME:<NAME>END_PI"
text: '''%IMPERIALONLY%%LINEBREAK%В начале первого хода, выберите 1 маленький или большой корабль врага. Атакуя или защищаясь против этого корабля, вы можете сменить 1 из ваших результатов %FOCUS% на результат %HIT% или %EVADE%.'''
'XX-23 S-Thread Tracers':
name: "Следящие маяки XX-23"
text: """<strong>Атака (Концентрация):</strong> Cбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK% Если эта атака попадает, каждый дружественный корабль на расстоянии 1-2 от вас может получить захват цели на защищающемся. Затем отмените <strong>все</strong> результаты кубиков."""
"Tractor Beam":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK%Если эта атака попадает, защищающийся получает 1 жетон PI:NAME:<NAME>END_PI. Затем отмените <strong>все</strong> результаты кубиков."""
"Cloaking Device":
name: "Маскировочное устройство"
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Действие:</strong> Выполните свободное действие Маскировки.%LINEBREAK%В конце каждого хода, если вы замаскированы, бросьте 1 кубик атаки. При результатк %FOCUS%, сбросьте эту карту, затем размаскируйтесь или сбросьте ваш жетон Маскировки."""
"Shield Technician":
name: "Техник щита"
text: """%HUGESHIPONLY%%LINEBREAK%Когда вы выполняете действие Восстановления, вместо того, чтобы потратить всю вашу энергию, вы можете выбрать количество энергии для использования."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%В начале фазы Боя, вы можете выбрать другой корабль на расстоянии 1-4. Затем уберите 1 жетон Концентрации с выбранного корабля, или же назначьте 1 жетон концентрации на него."""
"Captain Needa":
name: "PI:NAME:<NAME>END_PI"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%Если вы перекрываете препятствие во время фазы Активации, не получайте 1 карту повреждений лицом вверх. Вместо этого, бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, получите 1 повреждение."""
"AdmirPI:NAME:<NAME>END_PI OPI:NAME:<NAME>END_PIel":
name: "PI:NAME:<NAME>END_PI"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%<strong>Энергия</strong>: Вы можете снять до 3 щитов с вашего корабля. За каждый убранный щит, получите 1 энергии."""
'Glitterstim':
name: "PI:NAME:<NAME>END_PI"
text: """В начале фазы Боя, вы можете сбросить эту карту и получить 1 жетон стресса. Если вы делаете это, до конца хода, защищаясь или атакуя, вы можете сменить все ваши результаты %FOCUS% на результаты %HIT% или %EVADE%."""
'Extra Munitions':
name: "Дополнительные боеприпасы"
text: """Когда вы экипируете эту карту, положите 1 жетон боеприпасов на каждую экипированную карту улучшений %TORPEDO%, %MISSILE% и %BOMB%. Когда вы должны сбросить карту улучшений, вместо этого вы можете сбросить жетон боеприпасов с этой карты."""
"Weapons Guidance":
name: "Система наведения"
text: """Атакуя, вы можете потратить жетон Концентрации, чтобы заменить 1 из ваших пустых результатов на результат %HIT%."""
"BB-8":
text: """Когда вы открываете зеленый маневр, вы можете выполнить свободное действие Бочку."""
"R5-X3":
text: """Перед открытием вашего маневра, вы можете сбросить эту карту, чтобы игнорировать препятствия до конца хода."""
"Wired":
name: "Подключенный"
text: """Атакуя или защищаясь, если у вас есть жетон Стресса, вы можете перебросить 1 или более результатов %FOCUS%."""
'Cool Hand':
name: "Хладнокровный"
text: '''Когда вы получаете жетон стресса, вы можете сбросить эту карту чтобы назначить 1 жетон Концентрации или Уклонения на ваш корабль.'''
'Juke':
name: "Финт"
text: '''%SMALLSHIPONLY%%LINEBREAK%Атакуя, если у вас есть жетон Уклонения, вы можете заменить 1 из результатов %EVADE% защищающегося на результат %FOCUS%.'''
'Comm Relay':
name: "Реле связи"
text: '''Вы не можете иметь больше 1 жетона Уклонения.%LINEBREAK%Во время фазы Завершения, не убирайте неиспользованный жетон Уклонения с вашего корабля.'''
'Twin Laser Turret':
name: "Двойная лазерная турель"
text: '''%GOZANTIONLY%%LINEBREAK%<strong>Атака (Энергия):</strong> Потратьте 1 энергии с этой карты чтобы выполнить эту атаку против 1 корабля (даже если он находится вне вашей арки огня).'''
'Broadcast Array':
name: "Реле вещания"
text: '''%GOZANTIONLY%%LINEBREAK%Ваша панель действий получает значок %JAM%.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Действие:</strong> Выполните белый(%STRAIGHT% 1) маневр.'''
'Ordnance Experts':
name: "Ракетные эксперты"
text: '''Один раз за ход, когда дружественный корабль на расстоянии 1-3 атакует вспомогательным оружием %TORPEDO% или %MISSILE%, он может заменить 1 пустой результат на результат %HIT%.'''
'Docking Clamps':
name: "Доковые порты"
text: '''%GOZANTIONLY% %LIMITED%%LINEBREAK%Вы можете пристыковать до 4 TIE истребителей, TIE перехватчиков, TIE улучшенных или TIE бомбардировщиков к этому кораблю. Все пристыкованные корабли должны иметь один и тот же тип корабля.'''
'"Zeb" Orrelios':
name: "PI:NAME:<NAME>END_PI"
text: """%REBELONLY%%LINEBREAK%Вражеские корабли в вашей арке огня, которых вы касаетесь, не считаются касающимися вас, когда они или вы активируетесь во время фазы Боя."""
'Kanan Jarrus':
name: "PI:NAME:<NAME>END_PI"
text: """%REBELONLY%%LINEBREAK%Один раз за ход, после того, как дружественный корабль на расстоянии 1-2 выполняет белый маневр, вы можете снять 1 жетон Стресса с того корабля."""
'Reinforced Deflectors':
name: "Усиленные отражатели"
text: """%LARGESHIPONLY%%LINEBREAK%После защиты, если вы получили 3 или более повреждений или критических повреждений во время атаки, восстановите 1 щит (до максимального значения щитов)."""
'Dorsal Turret':
name: "Палубная турель"
text: """<strong>Атака:</strong> Атакуйте 1 корабль (даже если он находится вне вашей арки огня).%LINEBREAK%Если цель атаки находится на расстоянии 1, бросьте 1 дополнительный кубик атаки."""
'Targeting Astromech':
name: "АстромPI:NAME:<NAME>END_PI нPI:NAME:<NAME>END_PIения"
text: '''После выполнения красного маневра, вы можете получить захват цели.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: """%REBELONLY%%LINEBREAK%Вы можете открывать и выполнять красные маневры, даже находясь под Стрессом."""
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: """%REBELONLY%%LINEBREAK%Атакуя, если вы под Стрессом, вы можете заменить 1 результат %FOCUS% на результат %CRIT%."""
'SPI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: """%REBELONLY%%LINEBREAK%Ваша панель улучшений получает значок %BOMB%. Один раз за ход, перед тем, как убрать дружественный жетон бомбы, выберите 1 вражеский корабль на расстоянии 1 от этого жетона. Этот корабль получает 1 повреждение."""
'"Chopper"':
name: "PI:NAME:<NAME>END_PI"
text: """%REBELONLY%%LINEBREAK%Вы можете выполнять действия, находясь под Стрессом.%LINEBREAK%После того, как вы выполнили действие, находясь под Стрессом, получите 1 повреждение."""
'Construction Droid':
name: "Строительный дроид"
text: '''%HUGESHIPONLY% %LIMITED%%LINEBREAK%Когда вы выполняете действие Восстановления, вы можете потратить 1 энергии, чтобы сбросить 1 карту повреждений, лежащую лицом вниз.'''
'Cluster Bombs':
name: "Кластерные бимбы"
text: '''После защиты, вы можете сбросить эту карту. Если вы делаете это, любой другой корабль на расстоянии 1 от защищающейся секции бросает 2 кубика атаки, получая выброшенные повреждения (%HIT%) и критические повреждения (%CRIT%).'''
"Adaptability":
name: "Адаптивность"
text: """<span class="card-restriction">Двойная карта.</span>%LINEBREAK%<strong>Сторона A:</strong> Увеличьте ваше умение пилота на 1.%LINEBREAK%<strong>Сторона Б:</strong> Уменьшите ваше умение пилота на 1."""
"Electronic Baffle":
name: "Электронный экран"
text: """Когда вы получаете жетон стресса или ионный жетон, вы можете получить 1 повреждение чтобы сбросить этот жетон."""
"4-LOM":
text: """%SCUMONLY%%LINEBREAK%Атакуя, во время шага "Модификация кубиков атаки", вы можете получить 1 ионный жетон чтобы выбрать 1 из жетонов Концентрации или Уклонения защищающегося. Этот жетон не может использоваться во время этой атаки."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """%SCUMONLY%%LINEBREAK%Атакуя, если вы не под Стрессом, вы можете получить любое количество жетонов Стресса, чтобы выбрать равное количество кубиков защиты. Защищающийся должен перебросить эти кубики."""
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Действие:</strong> Назначьте 1 жетон Концентрации вашему кораблю и получите 2 жетона Стресса. До конца хода, при атаке, вы можете перебросить до 3 кубиков атаки."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """%SCUMONLY%%LINEBREAK%Каждый раз, когда вы получаете жетон Концентрации или Стресса, каждый другой дружественный корабль с Мысленной связью Аттанни также должен получить тот же тип жетона, если его у него нет."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """%SCUMONLY%%LINEBREAK%После выполнения атаки, если защищающийся получил карту повреждений лицом вверх, вы можете сбросить эту карту чтобы выбрать и сбросить 1 карту улучшений защищающегося."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """%SCUMONLY%%LINEBREAK%Атакуя, вы можете перебросить 1 кубик атаки. Если защищающийся - уникальный пилот, вы можете перебросить до 2 кубиков атаки."""
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """%SCUMONLY%%LINEBREAK%<strong>Действие:</strong> Положите 1 жетон щита на эту карту.%LINEBREAK%<strong>Действие:</strong> Уберите 1 жетон щита с этой карты чтобы восстановить 1 щит (до максимального значения щитов)."""
"R5-P8":
text: """Один раз за ход, после защиты, вы можете бросить 1 кубик атаки. При результате %HIT%, атакующий получает 1 повреждение. При результате %CRIT%, вы и атакующий получаете 1 повреждение каждый."""
'Thermal Detonators':
name: "Термальные детонаторы"
text: """Когда вы открываете диск маневров, вы можете сбросить эту карту чтобы <strong>сбросить</strong> 1 жетон термального детонатора.<br /><br />Этот жетон <strong>взрывается</strong> в конце фазы Активации.<br /><br /><strong>Жетон термального детонатора:</strong> Когда этот жетон бомбы взрывается, каждый корабль на расстоянии 1 от жетона получает 1 повреждение и 1 жетон Стресса. Затем сбросьте этот жетон."""
"Overclocked R4":
name: "Разогнанный R4"
text: """Во время фазы Боя, когда вы тратите жетон Концентрации, вы можете получить 1 жетон Стресса чтобы назначить 1 жетон Концентрации на ваш корабль."""
'Systems Officer':
name: "Системный офицер"
text: '''%IMPERIALONLY%%LINEBREAK%После выполнения зеленого маневра, выберите другой дружественный корабль на расстоянии 1. Этот корабль может получить захват цели.'''
'Tail Gunner':
name: "Кормовой стрелок"
text: '''Атакуя с кормовой вторичной арки огня, снизьте Маневренность защищающегося на 1.'''
'R3 Astromech':
name: "Астромех R3"
text: '''Один раз за ход, атакуя основным оружием, во время шага "Модификация кубиков атаки", вы можете отменить один из ваших результатов %FOCUS%, чтобы назначить 1 жетон Уклонения на ваш корабль.'''
'Collision Detector':
name: "Детектор столкновений"
text: '''Выполняя Ускорение, Бочку или Размаскировывание, ваш корабль и шаблон маневра могут накладываться на преграды.%LINEBREAK%При броске за повреждение от преград, игнорируйте все результаты %CRIT%.'''
'Sensor Cluster':
name: "Сенсорный кластер"
text: '''Защищаясь, вы можете потратить жетон Концентрации, чтобы сменить 1 из ваших пустых результатов на результат %EVADE%.'''
'Fearlessness':
name: "БесPI:NAME:<NAME>END_PIрашие"
text: '''%SCUMONLY%%LINEBREAK%Атакуя, если вы находитесь в арке огня защищающегося на расстоянии 1 и защищающийся находится в вашей арке огня, вы можете добавить 1 результат %HIT% к вашему броску.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%SCUMONLY%%LINEBREAK%В начале фазы Завершения, вы можете выбрать 1 корабль в вашей арке огня на расстоянии 1-2. Этот корабль не убирает свои жетоны Луча захвата.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%SCUMONLY%%LINEBREAK%Защищаясь, вы можете снять 1 жетон стресса с атакующего и добавить 1 результат %EVADE% к вашему броску.'''
'IG-88D':
text: '''%SCUMONLY%%LINEBREAK%Вы имеете способность пилота каждого другого дружественного корабля с картой улучшения <em>IG-2000</em> (в дополнение к вашей собственной способности пилота).'''
'Rigged Cargo Chute':
name: "Подъёмный грузовой желоб"
text: '''%LARGESHIPONLY%%LINEBREAK%<strong>Действие:</strong> Сбросьте эту карту чтобы <strong>сбросить</strong> 1 жетон Груза.'''
'Seismic Torpedo':
name: "Сейсмическая торпеда"
text: '''<strong>Действие:</strong> Сбросьте эту карту чтобы выбрать препятствие на расстоянии 1-2 и в вашей арке огня. Каждый корабль на расстоянии 1 от препятствия бросает 1 кубик атаки и получает любое выброшенное повреждение (%HIT%) или критическое повреждение (%CRIT%). Затем уберите препятствие.'''
'Black Market Slicer Tools':
name: "Боевые системы с черного рынка"
text: '''<strong>Действие:</strong> Выберите вражеский корабль под Стрессом на расстоянии 1-2 и бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, уберите 1 жетон стресса и нанесите ему 1 повреждение лицом вниз.'''
# Wave X
'Kylo Ren':
name: "PI:NAME:<NAME>END_PI"
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Действие:</strong> Назначьте карту состояния "Я покажу тебе Темную Сторону" на вражеский корабль на расстоянии 1-3.'''
'Unkar Plutt':
name: "PI:NAME:<NAME>END_PI"
text: '''%SCUMONLY%%LINEBREAK%После выполнения маневра, который приводит к наложению на вражеский корабль, вы можете получить 1 повреждение, чтобы выполнить 1 свободное действие.'''
'A Score to Settle':
name: "PI:NAME:<NAME>END_PI"
text: '''Во время расстановки, перед шагом "Расстановка сил", выберите 1 вражеский корабль и назначьте ему карту состояния "Счет к оплате"."%LINEBREAK%Атакуя корабль, имеющий карту состояния "Счет к оплате", вы можете заменить 1 результат %FOCUS% на результат %CRIT%.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%REBELONLY%%LINEBREAK%<strong>Действие:</strong> Выберите 1 дружественный корабль на расстоянии 1-2. Назначьте 1 жетон Концентрации на этот корабль за каждый вражеский корабль в вашей арке огня на расстоянии 1-3. Вы не можете назначить более 3 жетонов Концентрации этим способом.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%REBELONLY%%LINEBREAK%В конце фазы Планирования, вы можете выбрать вражеский корабль на расстоянии 1-2. Озвучьте скорость и направление маневра этого корабля, затем посмотрите на его диск маневров. Если вы правы, вы можете повернуть ваш диск на другой маневр.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%REBELONLY%%LINEBREAK%Атакуя основным оружием или защищаясь, если вражеский корабль находится в вашей арке огня, вы можете добавить 1 пустой результат к вашему броску.'''
'RePI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%REBELONLY%%LINEBREAK%В начале фазы Завершения, вы можете положить 1 из жетонов Концентрации вашего корабля на эту карту. В начале фазы Боя, вы можете назначить 1 из этих жетонов на ваш корабль.'''
'Burnout SLAM':
name: "Ускоритель ССДУ"
text: '''%LARGESHIPONLY%%LINEBREAK%Ваша панель действий получает значок действия %SLAM%.%LINEBREAK%После выполнения действия ССДУ (СубСветовой Двигатель Ускорения), сбросьте эту карту.'''
'Primed Thrusters':
name: "PI:NAME:<NAME>END_PI"
text: '''%SMALLSHIPONLY%%LINEBREAK%Вы можете выполнять действия Бочка и Ускорение, имея жетоны стресса, если их три или меньше.'''
'Pattern Analyzer':
name: "Шаблонный анализатор"
text: '''При выполнении маневра, вы можете отрабатывать шаг "Проверка стресса пилота" после шага "Выполнение действий" (вместо того, чтобы отрабатывать его перед этим шагом).'''
'Snap Shot':
name: "Выстрел навскидку"
text: '''После того, как вражеский корабль выполняет маневр, вы можете выполнить эту атаку против него.%LINEBREAK% <strong>Атака:</strong> Атакуйте 1 корабль. Вы не можете модифицировать кубики атаки и не можете атаковать снова в эту фазу.'''
'M9-G8':
text: '''%REBELONLY%%LINEBREAK%Когда корабль, на котором есть ваш жетон захвата, атакует, вы можете выбрать 1 кубик атаки. Атакующий должен перебросить этот кубик.%LINEBREAK%Вы можете заявлять захват цели на другие дружественные корабли.'''
'EMP Device':
name: "PI:NAME:<NAME>END_PIрибор ЭМИ"
text: '''Во время фазы Боя, вместо выполнения любых атак, вы можете сбросить эту карту, чтобы назначить 2 ионных жетона на каждый корабль на расстоянии 1.'''
'Captain Rex':
name: "PI:NAME:<NAME>END_PI"
text: '''%REBELONLY%%LINEBREAK%После проведения атаки, не завершившейся попаданием, вы можете назначить 1 жетон Концентрации на ваш корабль.'''
'General Hux':
name: "PI:NAME:<NAME>END_PI"
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Действие:</strong> Выберите до 3 дружественных кораблей на расстоянии 1-2. Назначьте 1 жетон Концентрации на каждый из них, а также назначьте карту состояния "Фанатическая преданность" на 1 из них. Затем получите 1 жетон Стресса.'''
'Operations Specialist':
name: "Операционный специалист"
text: '''%LIMITED%%LINEBREAK%После того, как дружественный корабль на расстоянии 1-2 выполняет атаку, не завершившуюся попаданием, вы можете назначить 1 жетон Концентрации на дружественный корабль на расстоянии 1-3 от атакующего.'''
'Targeting Synchronizer':
name: "Целевой синхронизатор"
text: '''Когда дружественный корабль на расстоянии 1-2 атакует корабль, находящийся в вашем захвате, дружественный корабль считает указатель "<strong>Атака (Захват цели):</strong> как указатель "<strong>Атака:</strong>." Если игровой эффект обязывает этот корабль потратить захват цели, он может потратить ваш захват цели вместо этого.'''
'Hyperwave Comm Scanner':
name: "Гиперволновой сканер связи"
text: '''В начале шага "Расстановка сил", вы можете считать ваше умение пилота равным "0", "6" или "12" до конца этого шага.%LINEBREAK% Во время расстановки, после того, как другой дружественный корабль выставляется на расстоянии 1-2, вы можете назначить ему 1 жетон Концентрации или Уклонения.'''
'Trick Shot':
name: "Ловкий выстрел"
text: '''Атакуя, если вы стреляете через препятствие, вы можете бросить 1 дополнительный кубик атаки.'''
'Hotshot Co-pilot':
name: "Умелый второй пилот"
text: '''Когда вы атакуете основным оружием, защищающийся должен потратить 1 жетон Концентрации при возможности.%LINEBREAK%Когда вы защищаетесь, атакующий должен потратить 1 жетон Концентрации при возможности.'''
'''Scavenger Crane''':
name: "PI:NAME:<NAME>END_PI"
text: '''После того, как корабль на расстоянии 1-2 уничтожен, вы можете выбрать сброшенную карту %TORPEDO%, %MISSILE%, %BOMB%, %CANNON%, %TURRET%, или Модификационное улучшение, которое было экипировано на ваш корабль, и вернуть его. Затем бросьте 1 кубик атаки. При пустом результате, сбросьте Кран мусорщика.'''
'BPI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%REBELONLY%%LINEBREAK%Когда вы заявляете захват цели, вы можете захватывать корабль врага на расстоянии 1-3 от любого дружественного корабля.'''
'Baze Malbus':
name: "PI:NAME:<NAME>END_PI"
text: '''%REBELONLY%%LINEBREAK%После выполнения атаки, которая не попала, вы можете немедленно выполнить атаку основным оружием против другого корабля. Вы не можете выполнять другую атаку в этот ход.'''
'Inspiring Recruit':
name: "Вдохновляющий рекрут"
text: '''Один раз за ход, когда дружественный корабль на расстоянии 1-2 снимает жетон Стресса, он может снять 1 дополнительный жетон стресса.'''
'Swarm Leader':
name: "PI:NAME:<NAME>END_PI"
text: '''Выполняя атаку основным оружием, выберите до 2 других дружественных кораблей, имеющих защищающегося в их арках огня на расстоянии 1-3. Снимите 1 жетон Уклонения с каждого выбранного корабля чтобы бросить 1 дополнительный кубик атаки за каждый убранный жетон Уклонения.'''
'Bistan':
name: "PI:NAME:<NAME>END_PI"
text: '''%REBELONLY%%LINEBREAK%Атакуя на расстоянии 1-2, вы можете сменить 1 из ваших результатов %HIT% на результат %CRIT%.'''
'Expertise':
name: "Опытность"
text: '''Атакуя, если вы не под стрессом, вы можете заменить все ваши результаты %FOCUS% на результаты %HIT%.'''
'BoShek':
name: "PI:NAME:<NAME>END_PI"
text: '''Когда корабль, которого вы касаетесь, активируется, вы можете посмотреть на его выбранный маневр. Если вы это делаете, он должен повернуть диск на противоположный маневр. Корабль может объявлять и выполнять этот маневр, даже находясь под Стрессом.'''
# C-ROC
'Heavy Laser Turret':
ship: "Крейсер C-ROC"
name: "PI:NAME:<NAME>END_PIерная PI:NAME:<NAME>END_PIель"
text: '''<span class="card-restriction">Только крейсер C-ROC</span>%LINEBREAK%<strong>Атака (Энергия):</strong> Потратьте 2 энергии с этой карты, чтобы выполнить эту атаку против 1 корабля (даже если он находится вне вашей арки огня).'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%SCUMONLY%%LINEBREAK%В начале фазы Завершения, вы можете сбросить эту карту, чтобы заменить лежащую лицом вверх экипированную карту улучшения %ILLICIT% или %CARGO% на другую карту улучшения того же типа и той же (или меньшей) стоимости в очках отряда.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%HUGESHIPONLY% %SCUMONLY%%LINEBREAK%В начале фазы Завершения, вы можете потратить 1 энергии, чтобы заменить экипированную лежащую лицом вверх карту улучшений %CREW% или %TEAM% на другую карту улучшения того же типа и той же (или меньшей) стоимости в очках отряда.'''
'Quick-release Cargo Locks':
name: "Замки быстрого сброса груза"
text: '''%LINEBREAK%В конце фазы Активации, вы можете сбросить эту карту, чтобы <strong>положить</strong> 1 жетон Контейнера.'''
'Supercharged Power Cells':
name: "Сверхзаряженные энергоячейки"
text: '''Атакуя, вы можете сбросить эту карту, чтобы бросить 2 дополнительных кубика атаки.'''
'ARC Caster':
name: "Проектор ARC"
text: '''<span class="card-restriction">Только для Повстанцев или Пиратов. Двойная карта.</span>%DUALCARD%%LINEBREAK%<strong>Сторона A:</strong>%LINEBREAK%<strong>Атака:</strong> Атакуйте 1 корабль. Если эта атака попадает, вы должны выбрать 1 другой корабль на расстоянии 1 от защищающегося. Этот корабль получает 1 повреждение.%LINEBREAK%Затем переверните эту карту.%LINEBREAK%<strong>Сторона Б:</strong>%LINEBREAK%(Перезарядка) В начале фазы Боя, вы можете получить жетон Отключения оружия, чтобы перевернуть эту карту.'''
'Wookiee Commandos':
name: "Вуки комPI:NAME:<NAME>END_PIандос"
text: '''Атакуя, вы можете перебросить ваши результаты %FOCUS%.'''
'Synced Turret':
name: "Синхронная турель"
text: '''<strong>Атака (Захват цели):</strong> Атакуйте 1 корабль (даже если он находится вне вашей арки огня).%LINEBREAK%Если защищающийся находится в вашей арке огня, вы можете перебросить количество кубиков атаки, равное значению вашего основного оружия.'''
'Unguided Rockets':
name: "Неуправляемые ракеты"
text: '''<strong>Атака (Концентрация):</strong> Атакуйте 1 корабль.%LINEBREAK%Ваши кубики атаки могут быть модифицированы только с помощью использования жетона Концентрации.'''
'Intensity':
name: "Интенсивность"
text: '''%SMALLSHIPONLY% %DUALCARD%%LINEBREAK%<strong>Сторона A:</strong> После того, как вы выполните действие Ускорения или Бочку, вы можете назначить 1 жетон Концентрации или Уклонения на ваш корабль. Если вы делаете это, переверните эту карту.%LINEBREAK%<strong>Сторона Б:</strong> (Истощение) В конце фазы боя, вы можете потратить 1 жетон Концентрации или Уклонения, чтобы перевернуть эту карту.'''
'Jabba the Hutt':
name: "PI:NAME:<NAME>END_PI"
text: '''%SCUMONLY%%LINEBREAK%Когда вы экипируете эту карту, положите 1 жетон Внезаконности на каждую карту улучшения %ILLICIT% в вашем отряде. Когда вы должны сбросить карту Улучшения, вместо этого вы можете сбросить 1 жетон Внезаконности с этой карты.'''
'IG-RM Thug Droids':
name: "Дроиды-головорезы IG-RM"
text: '''Атакуя, вы можете заменить 1 из ваших результатов %HIT% на результат %CRIT%.'''
'Selflessness':
name: "Самоотверженность"
text: '''%SMALLSHIPONLY% %REBELONLY%%LINEBREAK%Когда дружественный корабльт на расстоянии 1 получает попадание от атаки, вы можете сбросить эту карту, чтобы получить все неотмененные результаты %HIT% вместо корабля-цели.'''
'Breach Specialist':
name: "Специалист по пробоинам"
text: '''Когда вы получаете карту повреждений лицом вверх, вы можете потратить 1 жетон Усиления, чтобы перевернуть ее лицом вниз (не отрабатывая ее эффект). Если вы делаете это, то до конца хода, когда вы получаете карту .'''
'Bomblet Generator':
name: "PI:NAME:<NAME>END_PI"
text: '''Когда вы открываете маневр, вы можете <strong>сбросить</strong> 1 жетон Минибомбы.%LINEBREAK%Этот жетон <strong>взрывается</strong> в конце фазы Активации.%LINEBREAK%<strong>Жетон минибомбы:</strong> Когда этот жетон взрывается, каждый корабль на расстоянии 1 бросает 2 кубика атаки и получает все выброшенные повреждения(%HIT%) и критические повреждения (%CRIT%). Затем уберите этот жетон.'''
'Cad Bane':
name: "PI:NAME:<NAME>END_PI"
text: '''%SCUMONLY%%LINEBREAK%Ваша панель улучшений получает значок %BOMB%. Один раз за ход, когда вражеский корабль бросает кубики атаки из-за взрыва дружественной бомбы, вы можете выбрать любое количество пустых или %FOCUS% результатов. Он должен перебросить эти результаты.'''
'Minefield Mapper':
name: "Карта минных полей"
text: '''Во время расстановки, после шага "Расстановка сил", вы можете сбросить любое количество карт улучшений %BOMB%. Расположите все соответствующие жетоны бомб на игровом поле на расстоянии 3 и дальше от вражеских кораблей.'''
'R4-E1':
text: '''Вы можете выполнять действия на ваших картах улучшения %TORPEDO% и %BOMB%, даже находясь под Стрессом. После выполнения действия этим способом, вы можете сбросить эту карту, чтобы убрать 1 жетон Стресса с вашего корабля.'''
'Cruise Missiles':
name: "Крейсирующие ракеты"
text: '''<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Вы можете бросить дополнительные кубики атаки, равные по количеству скорости маневра, который вы выполнили в этот ход, до максимума в 4 дополнительных кубика.'''
'Ion Dischargers':
name: "Ионные разрядники"
text: '''После получения ионного жетона, вы можете выбрать вражеский корабль на расстоянии 1. Если вы делаете это, сбросьте ионный жетон. Затем тот корабль может решить получить 1 ионный жетон. Если он делает это - сбросьте эту карту.'''
'HarPI:NAME:<NAME>END_PI MPI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадает, после отрабатывания атаки, назначьте защищающемуся карту состояния "Загарпунен!".'''
'Ordnance Silos':
name: "PI:NAME:<NAME>END_PI"
ship: "Бомбардировщик B/SF-17"
text: '''<span class="card-restriction">Только бомбардировщик B/SF-17.</span>%LINEBREAK%Когда вы экипируете эту карту, положите 3 жетона Боеприпасов на каждую экипированную карту улучшений %BOMB%. Когда вы должны сбросить карту улучшений, вместо этого вы можете сбросить с этой карты жетон Боеприпасов.'''
'Trajectory Simulator':
name: "Симулятор траектории"
text: '''Вы можете запускать бомбы, используя шаблон (%STRAIGHT% 5) вместо того, стобы их сбрасывать. Вы не можете таким способом сбрасывать бомбы с указателем "<strong>Действие:</strong>".'''
'Jamming Beam':
name: "Луч заклинивания"
text: '''<strong>Атака:</strong> Атакуйте 1 корабль.%LINEBREAK%Если эта атака попадает, назначьте защищающемуся 1 жетон Заклинивания. Затем отмените <strong>все</strong> результаты кубиков.'''
'Linked Battery':
name: "Спаренная батарея"
text: '''%SMALLSHIPONLY%%LINEBREAK%Атакуя основным или %CANNON% вспомогательным оружием, вы можете перебросить 1 кубик атаки.'''
'Saturation Salvo':
name: "Плотный залп"
text: '''После того, как вы выполняете атаку вспомогательным оружием %TORPEDO% или %MISSILE%, которая не попала, каждый корабль на расстоянии 1 от защищающегося со значением Маневренности ниже, чем стоимость карты улучшения %TORPEDO% или %MISSILE% в очках отряда, должен бросить 1 кубик атаки и получить любое выброшенное повреждение (%HIT%) или критическое повреждение (%CRIT%).'''
'Contraband Cybernetics':
name: "Контрабандная кибернетика"
text: '''Когда вы становитесь активным кораблем во время фазы Активации, вы можете сбросить эту карту и получить 1 жетон стресса. Если вы делаете это, до конца хода вы можете выполнять действия и красные маневры, даже находясь под Стрессом.'''
'Maul':
name: "PI:NAME:<NAME>END_PIол"
text: '''%SCUMONLY% <span class="card-restriction">Игнорируйте это ограничение, если ваш отряд содержит Эзру Бриджера."</span>%LINEBREAK%Атакуя, если вы не под Стрессом, вы можете получить любое количество жетонов Стрееса, чтобы перебросить равное количество кубиков атаки.%LINEBREAK% После выполнения атаки, завершившейся попаданием, вы можете убрать 1 из ваших жетонов Стресса.'''
'Courier Droid':
name: "Дроид-курьер"
text: '''В начале шага "Расположение сил", вы можете выбрать считать ваше умение пилота равным "0" или "8" до конца этого шага.'''
'"Chopper" (Astromech)':
text: '''<strong>Действие: </strong>Сбросьте 1 другую экипированную карту улучшений, чтобы восстановить 1 щит.'''
'Flight-Assist Astromech':
name: "Полетный астромех"
text: '''Вы не можете атаковать корабли вне вашей арки огня.%LINEBREAK%После того, как вы выполните маневр, если вы не перекрываете корабль или преграду и не имеете кораблей врага в вашей арке огня на расстоянии 1-3, вы можете выполнить свободное действие Бочку или Ускорение.'''
'Advanced Optics':
name: "Улучшенная оптика"
text: '''Вы не можете иметь более 1 жетона Концентрации.%LINEBREAK%Во время фазы Завершения, не убирайте неиспользованный жетон Концентрации с вашего корабля.'''
'Scrambler Missiles':
name: "Ракеты с помехами"
text: '''<strong>Атака (Захват цели):</strong> Используйте захват цели и сбросьте эту карту чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадает, защищающийся и каждый другой корабль на расстоянии 1 получает 1 жетон Заклинивания. Затем отмените <strong>все</strong> результаты кубиков.'''
'R5-TK':
text: '''Вы можете заявлять захват цели на дружественные корабли.%LINEBREAK%Вы можете атаковать дружественные корабли.'''
'Threat Tracker':
name: "Детектор угроз"
text: '''%SMALLSHIPONLY%%LINEBREAK%Когда вражеский корабль в важей арке огня на расстоянии 1-2 становится активным кораблем во время фазы Боя, вы можете потратить захват цели на этом корабле, чтобы выполнить свободное действие Ускорение или Бочку, если оно есть на вашей панели действий.'''
'Debris Gambit':
name: "Уклонение в астероидах"
text: '''%SMALLSHIPONLY%%LINEBREAK%<strong>Действие:</strong> Назначьте 1 жетон Уклонения на ваш корабль за каждую преграду на расстоянии 1, до максимума в 2 жетона Уклонения.'''
'Targeting Scrambler':
name: "Помехи наведения"
text: '''В начале фазы Планирования, вы можете получить жетон Оружие выведено из строя, чтобы выбрать корабль на расстоянии 1-3 и назначить ему состояние "Помехи".'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''После того, как другой дружественный корабль на расстоянии 1 становится защищающимся, если вы находитесь в арке огня атакующего на расстоянии 1-3, атакующий получает 1 жетон Стресса.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%REBELONLY%%LINEBREAK%Атакуя, вы можете получить 1 повреждение, чтобы заменить все ваши результаты %FOCUS% на результаты %CRIT%.'''
'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''Во время расстановки, перед шагом "Расстановка сил", назначьте состояние "Оптимизированный прототип" на дружественный корабль Галактической Империи с 3 или меньшим количеством щитов.'''
'Tactical Officer':
text: '''%IMPERIALONLY%%LINEBREAK%Your action bar gains %COORDINATE%.'''
'ISB Slicer':
text: '''After you perform a jam action against an enemy ship, you may choose a ship at Range 1 of that ship that is not jammed and assign it 1 jam token.'''
'Thrust Corrector':
text: '''When defending, if you have 3 or fewer stress tokens, you may receive 1 stress token to cancel all of your dice results. If you do, add 1 %EVADE% result to your roll. Your dice cannot be modified again during this attack.%LINEBREAK%You can equip this Upgrade only if your hull value is "4" or lower.'''
modification_translations =
"Stealth Device":
name: "Маскировочное устройство"
text: """Увеличьте вашу Маневренность на 1. Если вы получаете попадание от атаки, сбросьте эту карту."""
"Shield Upgrade":
name: "Улучшенный щит"
text: """Ваше значение Щита увеличивается на 1."""
"Engine Upgrade":
name: "Улучшенный двигатель"
text: """Ваша панель действий получает значок %BOOST%."""
"Anti-Pursuit Lasers":
name: "Оборонительные лазеры"
text: """После того, как вражеский корабль выполняет маневр, приводящий к перекрытию им вашего корабля, бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, вражеский корабль получает 1 повреждение."""
"Targeting Computer":
name: "Компьютер наведения"
text: """Ваша панель действий получает значок %TARGETLOCK%."""
"Hull Upgrade":
name: "Укрепление корпуса"
text: """Ваше значение Корпуса повышается на 1."""
"Munitions Failsafe":
name: "Корректор промаха"
text: """Атакуя вспомогательным оружием, которое обязывает сбросить его для выполнения атаки, не сбрасывайте его, если атака не попала."""
"Stygium Particle Accelerator":
name: "Стигийский ускоритель частиц"
text: """Когда вы размаскировываетесь или выполняете действие Маскировки, вы можете выполнить свободное действие Уклонения."""
"Advanced Cloaking Device":
name: "Улучшеный маскировочный прибор"
text: """<span class="card-restriction">Только для TIE Фантом.</span><br /><br />После выполнения атаки, вы можете выполнить свободное действие Маскировки."""
ship: "TIE Фантом"
"Combat Retrofit":
name: "Боевое оснащение"
text: """<span class="card-restriction">Только для GR-75.</span><br /><br />Увеличьте ваше значение Корпуса на 2 и значение Щита на 1."""
ship: 'Средний транспорт GR-75'
"B-Wing/E2":
text: """<span class="card-restriction">Только для Б-Крыла.</span><br /><br />Ваша панель улучшений получает значок улучшения %CREW%."""
ship: "Б-Крыл"
"Countermeasures":
name: "Контрмеры"
text: """В начале фазы Боя, вы можете сбросить эту карту, чтобы повысить вашу Маневренность на 1 до конца хода. Затем вы можете убрать 1 вражеский захват цели с вашего корабля."""
"Experimental Interface":
name: "Экспериментальный интерфейс"
text: """Один раз за ход, после выполнения вами действия, вы можете выполнить 1 свободное действие с экипированной карты улучшений с указателем "<strong>Действие:</strong>". Затем получите 1 жетон Стресса."""
"Tactical Jammer":
name: "Тактический глушитель"
text: """Ваш корабль может служить преградой для вражеских атак."""
"Autothrusters":
name: "Автоускорители"
text: """Защищаясь, еслим вы далее расстояния 2 или находитесь вне арки огня атакующего, вы можете заменить 1 из ваших пустых результатов на результат %EVADE%. Вы можете экипировать это карту только при наличии значка %BOOST%."""
"Twin Ion Engine Mk. II":
name: "Двойной ионный двигатель Мк.II"
text: """<span class="card-restriction">Только для TIE.</span>%LINEBREAK%Вы можете считать все маневры крена (%BANKLEFT% и %BANKRIGHT%) зелеными маневрами."""
"Maneuvering Fins":
name: "Маневровые кили"
text: """<span class="card-restriction">Только для YV-666.</span>%LINEBREAK%Когда вы открываете маневр поворота (%TURNLEFT% или %TURNRIGHT%), вы можете повернуть ваш диск маневров на соответствующий маневр крена (%BANKLEFT% или %BANKRIGHT%) с той же скоростью."""
"Ion Projector":
name: "Ионный проектор"
text: """%LARGESHIPONLY%%LINEBREAK%После того, как вражеский корабль выполняет маневр, приводящий к перекрытию им вашего корабля, бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, вражеский корабль получает 1 ионный жетон."""
"Advanced SLAM":
name: "Улучшенный ССДУ"
text: """После выполнения действия ССДУ, если вы не перекрываете преграду или другой корабль, вы можете выполнить свободное действие с вашей панели действий."""
'Integrated Astromech':
name: "Интегрированный астромех"
text: '''<span class="card-restriction">Только для Икс-Крыла.</span>%LINEBREAK%Когда вы получаете карту повреждений, вы можете сбросить 1 из ваших карту улучшений %ASTROMECH% чтобы сбросить эту карту повреждений.'''
'Optimized Generators':
name: "Оптимизированные генераторы"
text: '''%HUGESHIPONLY%%LINEBREAK%Один раз за ход, когда вы назначаете энергию на экипированную карту улучшений, получите 2 энергии.'''
'Automated Protocols':
name: "Автоматизированные протоколы"
text: '''%HUGESHIPONLY%%LINEBREAK%Один раз за ход, после выполнения действия, не являющегося действием Восстановления или Усиления, вы можете потратить 1 энергии, чтобы выполнить свободное действие Восстановления или Усиления.'''
'Ordnance Tubes':
name: "Ракетные шахты"
text: '''%HUGESHIPONLY%%LINEBREAK%Вы можете считать каждый из ваших значков улучшений %HARDPOINT% как значок %TORPEDO% или %MISSILE%.%LINEBREAK%Когда вы должны сбросить карту улучшений %TORPEDO% или %MISSILE%, не сбрасывайте ее.'''
'Long-Range Scanners':
name: "Сканеры дальнего действия"
text: '''Вы можете объявлять захват цели на корабли на расстоянии 3 и дальше. Вы не можете объявлять захват цели на корабли на расстоянии 1-2. Вы можете екипировать эту карту только если у вас есть %TORPEDO% и %MISSILE% на вашей панели улучшений.'''
"Guidance Chips":
name: "Чипы наведения"
text: """Один раз за ход, атакуя вспомогательным оружием %TORPEDO% или %MISSILE%, вы можете заменить один результат кубика на %HIT% (или на результат %CRIT% , если значение вашего основного оружия "3" или больше)."""
'Vectored Thrusters':
name: "Векторные ускорители"
text: '''%SMALLSHIPONLY%%LINEBREAK%Ваша панель действий получает значок %BARRELROLL%.'''
'Smuggling Compartment':
name: "Отсек контрабанды"
text: '''<span class="card-restriction">Только для YT-1300 и YT-2400.</span>%LINEBREAK%Ваша панель улучшений получает значок %ILLICIT%.%LINEBREAK%Вы можете экипировать 1 дополнительное Модификационное улучшение, которое стоит 3 или меньше очков отряда.'''
'Gyroscopic Targeting':
name: "Гироскопическое наведение"
ship: "Корабль-преследователь класса Копьеносец"
text: '''<span class="card-restriction">Только для Корабля-преследователя класса Копьеносец.</span>%LINEBREAK%В конце фазы Боя, если в этом ходу вы выполняли маневр со скоростью 3, 4 или 5, вы можете повернуть вашу мобильную арку огня.'''
'Captured TIE':
ship: "TIE истребитель"
name: "TIE захваченный"
text: '''<span class="card-restriction">только для TIE.</span>%REBELONLY%%LINEBREAK%Вражеские корабли с умением пилота ниже вашего не могут объявлять вас целью атаки. После того, как вы выполните атаку или останетесь единственным дружественным кораблем, сбросьте эту карту.'''
'Spacetug Tractor Array':
name: "Матрица космической тяги"
ship: "Квадджампер"
text: '''<span class="card-restriction">Только для Квадджампера.</span>%LINEBREAK%<strong>Действие:</strong> Выберите корабль в вашей арке огня на расстоянии 1 и назначьте ему жетон ЛPI:NAME:<NAME>END_PI ЗPI:NAME:<NAME>END_PI. Если это дружественный корабль, отработайте эффект жетона ЛучPI:NAME:<NAME>END_PI ЗPI:NAME:<NAME>END_PIата, как если бы это был вражеский корабль.'''
'Lightweight Frame':
name: "Облегченный каркас"
text: '''<span class="card-restriction">только для TIE.</span>%LINEBREAK%Защищаясь, после броска кубиков защиты, если кубиков атаки больше, чем кубиков защиты, бросьте 1 дополнительный кубик защиты.%LINEBREAK%Вы не можете экипировать эту карту, если ваша Маневренность "3" или выше.'''
'Pulsed Ray Shield':
name: "Импульсный лучевой щит"
text: '''<span class="card-restriction">Только для Повстанцев и Пиратов.</span>%LINEBREAK%Во время фазы Завершения, вы можете получить 1 ионный жетон чтобы восстановить 1 щит (до максимального значения щитов). Вы можете экипировать эту карту только если ваше значение Щитов "1".'''
'Deflective Plating':
name: "Отражающее покрытие"
ship: "Бомбардировщик B/SF-17"
text: '''<span class="card-restriction">Только для бомбардировщика B/SF-17.</span>%LINEBREAK%Когда взрывается дружественный жетон бомбы, вы можете выбрать не получать соответствующий эффект. Если вы делаете это, бросьте кубик атаки. При результате %HIT%, сбросьте эту карту.'''
'Multi-spectral Camouflage':
text: '''%SMALLSHIPONLY%%LINEBREAK%After you receive a red target lock token, if you have only 1 red target lock token, roll 1 defense die. On an %EVADE% result, remove 1 red target lock token.'''
title_translations =
"Slave I":
name: "Раб 1"
text: """<span class="card-restriction">Только для Огнедыщащего-31.</span><br /><br />Ваша панель улучшений получает значок улучшения %TORPEDO%."""
"Millennium Falcon":
name: "Тысячелетний сокол"
text: """<span class="card-restriction">Только для YT-1300.</span><br /><br />Ваша панель действий получает значок %EVADE%."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для HWK-290.</span><br /><br />Во время фазы Завершения, не убирайте неиспользованные жетоны Концентрации с вашего корабля."""
"ST-321":
text: """<span class="card-restriction">Только для шаттла класса <em>Лямбда</em>.</span><br /><br />При объявлении захвата цели, вы можете захватывать вражеский корабль по всему игровому полю."""
ship: "Шаттл класса Лямбда"
"Royal Guard TIE":
name: "TIE королевской PI:NAME:<NAME>END_PIи"
ship: "TIE перехватчик"
text: """<span class="card-restriction">Только для TIE перехватчика.</span><br /><br />Вы можете экипировать до двух различных Модификационных улучшений (вместо 1).<br /><br />Вы не можете экипировать эту карту, если ваше умение пилота "4" или ниже."""
"PI:NAME:<NAME>END_PIride":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для носовой части CR90.</span><br /><br />Когда вы выполняете действие Координации, вы можете выбрать 2 дружественных корабля (вместо 1). Каждый из этих кораблей может выполнить 1 свободное действие."""
ship: "Корвет CR90 (Нос)"
"A-Wing Test Pilot":
name: "PI:NAME:<NAME>END_PI-исPI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для А-Крыла.</span><br /><br />Ваша панель улучшений получает 1 значок %ELITE%.<br /><br />Вы не можете экипировать 2 одинаковых карты улучшений %ELITE%. Вы не можете экипировать эту карту, если ваше умение пилота "1" или ниже."""
ship: "А-Крыл"
"Tantive IV":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для носовой части CR90.</span><br /><br />Ваша панель улучшений носовой секции получает 1 дополнительный значок %CREW% и 1 дополнительный значок %TEAM%."""
ship: "Корвет CR90 (Нос)"
"Bright Hope":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для GR-75.</span><br /><br />Действие усиления, назначенное на вашу носовую часть, добавляет 2 результата %EVADE% вместо 1."""
ship: 'Средний транспорт GR-75'
"Quantum Storm":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для GR-75.</span><br /><br />В начале фазы Завершения, если у вас 1 или меньше жетонов энергии, получите 1 жетон энергии."""
ship: 'Средний транспорт GR-75'
"DutyPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для GR-75./span><br /><br />При выполнении действия Заклинивания, вы можете выбрать вражеский корабль на расстоянии 1-3 (вместо 1-2)."""
ship: 'Средний транспорт GR-75'
"PI:NAME:<NAME>END_PI Light":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для носовой секции CR90.</span><br /><br />Защищаясь, один раз за атаку, если вы получаете карту повреждений лицом вверх, вы можете сбросить ее и вытянуть другую карту повреждений лицом вверх."""
"Outrider":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для YT-2400.</span><br /><br />Когда у вас есть экипированная карта улучшения %CANNON%, вы <strong>не можете</strong> выполнять атаки основным оружием и можете выполнять атаки вспомогательным оружием %CANNON% против кораблей вне вашей арки огня."""
"Andrasta":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для Огнедышащего-31.</span><br /><br />Ваша панель улучшений получает 2 дополнительных значка %BOMB%."""
"TIE/x1":
ship: "TIE улучшенный"
text: """<span class="card-restriction">Только для TIE улучшенного.</span>%LINEBREAK%Ваша панель улучшений получает значок %SYSTEM%.%LINEBREAK%Если вы экипируете улучшение %SYSTEM%, его стоимость в очках отряда снижается на 4 (до минимума в 0)."""
"BTL-A4 Y-Wing":
name: "BTL-A4 У-Крыл"
text: """<span class="card-restriction">Только для У-Крыла.</span><br /><br />Вы не можете атаковать корабли вне вашей арки огня. После выполнения атаки основным оружием, вы можете немедленно выполнить атаку вспомогательным оружием %TURRET%."""
ship: "У-Крыл"
"IG-2000":
name: "IG-2000"
text: """<span class="card-restriction">Только для Агрессора.</span><br /><br />Вы получаете способности пилотов каждого другого дружественного корабля с картой улучшения <em>IG-2000</em> (в дополнение к вашей собственной способности пилота)."""
ship: "Агрессор"
"Virago":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для Звездной Гадюки.</span><br /><br />Ваша панель улучшений получает значки %SYSTEM% и %ILLICIT%.<br /><br />Вы не можете экипировать эту карту, если ваше умение пилота "3" или ниже."""
ship: 'Звездная гадюка'
'"Heavy Scyk" Interceptor (Cannon)':
name: 'Перехватчик "Тяжелый СPI:NAME:<NAME>END_PIк" (Пушечный)'
text: """<span class="card-restriction">Только для перехватчика M3-A.</span><br /><br />Ваша панель улучшений получает значок %CANNON%. Ваше значение Корпуса повышается на 1."""
ship: 'Перехватчик M3-A'
'"Heavy Scyk" Interceptor (Missile)':
name: 'Перехватчик "Тяжелый Сцик" (Ракетный)'
text: """<span class="card-restriction">Только для перехватчика M3-A.</span><br /><br />Ваша панель улучшений получает значок %MISSILE%. Ваше значение Корпуса повышается на 1."""
ship: 'Перехватчик M3-A'
'"Heavy Scyk" Interceptor (Torpedo)':
name: 'Перехватчик "Тяжелый Сцик" (Торпедный)'
text: """<span class="card-restriction">Только для перехватчика M3-A.</span><br /><br />Ваша панель улучшений получает значок %TORPEDO%. Ваше значение Корпуса повышается на 1."""
ship: 'Перехватчик M3-A'
"Dauntless":
name: "Неустрашимый"
text: """<span class="card-restriction">Только для VT-49 Дециматора.</span><br /><br />После выполнения маневра, который привел к наложению на другой корабль, вы можете выполнить 1 свободное действие. Затем получите 1 жетон Стресса."""
ship: 'VT-49 Дециматор'
"Ghost":
name: "Призрак"
text: """<span class="card-restriction">Только для VCX-100.</span>%LINEBREAK%Екипируйте карту названия <em>PI:NAME:<NAME>END_PIом</em> на дружественный Атакующий Шаттл, и пристыкуйте его к этому кораблю.%LINEBREAK%После выполнения маневра, вы можете отстыковать его из ваших задних направляющих."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Когда вы пристыкованы, <em>Призрак</em> может выполнять атаки его основным оружием, используя его специальную арку огня, а также, в конце фазы Боя, он может выполнить дополнительную атаку экипированной %TURRET%. Если он не может выполнить эту атаку, он не может атаковать снова в этот ход."""
ship: 'Атакующий шаттл'
"TIE/v1":
text: """<span class="card-restriction">Только для TIE улучшенного прототипа.</span>%LINEBREAK%После того, как вы получаете захват цели на другой корабль, вы можете выполнить свободное действие Уклонения."""
ship: 'TIE улучшенный прототип'
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для Звездного истребителя G-1A.</span>%LINEBREAK%Ваша панель действий получает значок %BARRELROLL%.%LINEBREAK%Вы <strong>должны</strong> экипировать 1 карту улучшений "Луч захвата"(считая ее стоимость в очках отряда как обычно)."""
ship: 'Звездный истребитель G-1A'
"Punishing One":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для Джампмастера 5000.</span>%LINEBREAK%Увеличивает значение вашего основного оружия на 1."""
ship: 'Джампмастер 5000'
"HPI:NAME:<NAME>END_PI's Tooth":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для YV-666.</span>%LINEBREAK%После того, как вы уничтожены, но перед тем, как убрать корабль с игрового поля, вы можете </strong>выставить корабль <span>Щенок Наштаха</span>.%LINEBREAK%El <span>Щенок Наштаха</span> не может атаковать в этот ход."""
"AssPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для кормовой секции корвета класса <em>Рейдер</em>.</span>%LINEBREAK%Защищаясь, если целевая секция имеет жетон Усиления, вы можете заменить 1 результат %FOCUS% на 1 результат %EVADE%."""
"Instigator":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для кормовой секции корвета класса <em>Рейдер</em>.</span>%LINEBREAK%После того, как вы выполняете действие Восстановления, восстановите 1 дополнительный щит."""
"Impetuous":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Только для кормовой секции корвета класса <em>Рейдер</em>.</span>%LINEBREAK%После того, как вы выполняете атаку, уничтожившую вражеский корабль, вы можете получить захват цели."""
'TIE/x7':
text: '''<span class="card-restriction">Только для TIE защитника.</span>%LINEBREAK%Ваша панель улучшений теряет значки улучшений %CANNON% и %MISSILE%.%LINEBREAK%После выполнения маневра со скоростью 3, 4 или 5, если вы не перекрываете преграду или корабль, вы можете выполнить свободное действие Уклонения.'''
ship: 'TIE защитник'
'TIE/D':
text: '''<span class="card-restriction">Только для TIE защитника.</span>%LINEBREAK%Один раз за ход, после того, как вы выполнили атаку вспомогательным оружием %CANNON%, которое стоит 3 или менее очков отряда, вы можете выполнить атаку основным оружием.'''
ship: 'TIE защитник'
'TIE Shuttle':
name: "PI:NAME:<NAME>END_PI"
text: '''<span class="card-restriction">Только для TIE бомбардировщика.</span>%LINEBREAK%Ваша панель улучшений теряет все значки улучшений %TORPEDO%, %MISSILE% и %BOMB% и получает 2 значка улучшений %CREW%. Вы не можете экипировать карту улучшений %CREW%, которая стоит больше 4 очков отряда.'''
ship: 'TIE бомбардировщик'
'Requiem':
name: "PI:NAME:<NAME>END_PI"
text: '''%GOZANTIONLY%%LINEBREAK%Когда вы выставляете корабль, считайте его навык пилота равным "8" до конца хода.'''
'Vector':
name: "Вектор"
text: '''%GOZANTIONLY%%LINEBREAK%После выполнения маневра, вы можете разместить до 4 присоединенных кораблей (вместо 2).'''
'Suppressor':
name: "Подавитель"
text: '''%GOZANTIONLY%%LINEBREAK%Один раз за ход, после получения захвата цели на врага, вы можете убрать 1 жетон Концентрации, Уклонения или синий жетон захвата цели с этого корабля.'''
'Black One':
name: "PI:NAME:<NAME>END_PI"
text: '''<span class="card-restriction">Только для Икс-Крыла Т-70.</span>%LINEBREAK%После того, как вы выполнили действие Ускорения или Бочку, вы можете снять 1 вражеский захват цели с дружественного корабля на расстоянии 1. Вы не можете экипировать эту карту, если ваш навык пилота "6" или ниже.'''
ship: "Икс-Крыл T-70"
'Millennium Falcon (TFA)':
name: "Тысячелетний Сокол (ПС)"
text: '''После выполнения маневра крена со скоростью 3 (%BANKLEFT% или %BANKRIGHT%), если вы не касаетесь другого корабля и не находитесь под Стрессом, вы можете получить 1 жетон Стресса, чтобы развернуть ваш корабль на 180°.'''
'Alliance Overhaul':
name: "Обновления Альянса"
text: '''<span class="card-restriction">Только для ARC-170.</span>%LINEBREAK%Атакуя основным оружием в вашей основной арке огня, вы можете бросить 1 дополнительный кубик атаки. Атакуя в вашей дополнительной арке огня, вы можете заменить 1 из ваших результатов %FOCUS% на 1 результат %CRIT%.'''
'Special Ops Training':
ship: "Истребитель TIE/сс"
name: "Специальная оперативная подготовка"
text: '''<span class="card-restriction">Только для TIE/сс.</span>%LINEBREAK%Атакуя основным оружием в вашей основной арке огня, вы можете бросить 1 дополнительный кубик атаки. Если вы не делаете этого, вы можете выполнить дополнительную атаку в вашей вспомогательной арке огня.'''
'Concord Dawn Protector':
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель Протектората"
text: '''<span class="card-restriction">Только для истребителя Протектората.</span>%LINEBREAK%Защищаясь, если вы назходитесь в арке огня атакующего на расстоянии 1, и атакующий находится в вашей арке огня, добавьте 1 результат %EVADE%.'''
'Shadow Caster':
name: "Наводящий Тень"
ship: "Корабль-преследователь класса Копьеносец"
text: '''<span class="card-restriction">Только для Корабля-преследователя класса Копьеносец</span>%LINEBREAK%После того, как вы выполнили атаку, которая попала, если защищающийся находится в вашей мобильной арке огня на расстоянии 1-2, вы можете назначить защищающемуся 1 жетон Луча захвата.'''
# Wave X
'''Sabine's Masterpiece''':
ship: "TIE истребитель"
name: "PI:NAME:<NAME>END_PI"
text: '''<span class="card-restriction">Только для TIE истребителя.</span>%REBELONLY%%LINEBREAK%Ваша панель улучшений получает значки улучшений %CREW% и %ILLICIT%.'''
'''Kylo Ren's Shuttle''':
ship: "Шаттл класса Ипсилон"
name: "PI:NAME:<NAME>END_PI"
text: '''<span class="card-restriction">Только для шаттла класса Ипсилон.</span>%LINEBREAK%В конце фазы Боя, выберите вражеский корабль на расстоянии 1-2, не имеющий стресса. Его владелец должен назначить ему жетон Стресса, или назначить жетон Стресса на другой его корабль на расстоянии 1-2 от вас.'''
'''Pivot Wing''':
name: "PI:NAME:<NAME>END_PI"
ship: "Ю-Крыл"
text: '''<span class="card-restriction">Только для Ю-Крыла.</span> %DUALCARD%%LINEBREAK%<strong>Сторона A (Боевое положение):</strong> Ваша Маневренность увеличивается на 1.%LINEBREAK%После выполнения маневра, вы можете перевернуть эту карту.%LINEBREAK%<strong>Сторона Б (Положение посадки):</strong> Когда вы открываете маневр (%STOP% 0), вы можете повернуть ваш корабль на 180°.%LINEBREAK%После выполнения маневра, вы можете перевернуть эту карту.'''
'''Adaptive Ailerons''':
name: "PI:NAME:<NAME>END_PI"
ship: "TIE ударник"
text: '''<span class="card-restriction">Только для TIE ударника.</span>%LINEBREAK%Сразу перед открытием вашего диска, если у вас нет Стресса, вы <strong>должны</strong> выполнить белый маневр (%BANKLEFT% 1), (%STRAIGHT% 1) или (%BANKRIGHT% 1).'''
# C-ROC
'''Merchant One''':
name: "PI:NAME:<NAME>END_PI"
ship: "Крейсер C-ROC"
text: '''<span class="card-restriction">Только для крейсера C-ROC.</span>%LINEBREAK%Ваша панель улучшений получает 1 дополнительный значок улучшения %CREW% и 1 дополнительный значок улучшения %TEAM%, а также теряет 1 значок улучшения %CARGO%.'''
'''"Light Scyk" Interceptor''':
name: 'PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI"'
ship: "Перехватчик M3-A"
text: '''<span class="card-restriction">Только для Перехватчика M3-A.</span>%LINEBREAK%Все получаемые вами карты повреждений отрабатываются в открытую. Вы можете считать все маневры крена (%BANKLEFT% или %BANKRIGHT%) зелеными маневрами. Вы не можете экипировать Модификационные улучшения.'''
'''Insatiable Worrt''':
name: "PI:NAME:<NAME>END_PI"
ship: "Крейсер C-ROC"
text: '''После выполнения действия Восстановления, получите 3 энергии.'''
'''Broken Horn''':
name: "PI:NAME:<NAME>END_PI"
ship: "Крейсер C-ROC"
text: '''Защищаясь, если у вас есть жетон Усиления, вы можете добавить дополнительный результат %EVADE%. Если вы делаете это, после защиты, сбросьте ваш жетон Усиления.'''
'HPI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Бомбардировщик Скуррг H-6"
text: '''<span class="card-restriction">Только для бомбардировщика Скуррг H-6.</span>%LINEBREAK%Ваша панель улучшений получает значки %SYSTEM% и %SALVAGEDASTROMECH% и теряет значок улучшения %CREW%.%LINEBREAK%Вы не можете экипировать неуникальные карты улучшения %SALVAGEDASTROMECH%.'''
'PI:NAME:<NAME>END_PIsai':
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель Кихраксз"
text: '''<span class="card-restriction">Только для истребителя Кихраксз.</span>%LINEBREAK%Стоимость в очках отряда для каждого из экипированных улучшений снижается на 1 (до минимума в 0).%LINEBREAK%Вы можете экипировать до 3 различных Модификационных улучшений.'''
'StarViper Mk. II':
name: "PI:NAME:<NAME>END_PI"
ship: "Звездна ГадюPI:NAME:<NAME>END_PI"
text: '''<span class="card-restriction">Только для Звездной Гадюки.</span>%LINEBREAK%Вы можете экипировать до 2 различных улучшений Названий.%LINEBREAK%Выполняя действие Бочку, вы <strong>должны</strong> использовать шаблон (%BANKLEFT% 1) или (%BANKRIGHT% 1) вместо шаблона (%STRAIGHT% 1).'''
'XG-1 Assault Configuration':
ship: "Звездное Крыло класса Альфа"
name: "Штурмовая конфигурация XG-1"
text: '''<span class="card-restriction">Только для Звездного Крыла класса Альфа.</span>%LINEBREAK%Ваша панель улучшений получает 2 значка %CANNON%.%LINEBREAK%Вы можете выполнять атаки вспомогательным оружием %CANNON%, стоящим 2 или менее очков отряда, даже если у вас есть жетон Выведения оружия из строя.'''
'Enforcer':
name: "PI:NAME:<NAME>END_PI"
ship: "Истребитель M12-L Кимогила"
text: '''<span class="card-restriction">Только для истребителя M12-L Кимогила.</span>%LINEBREAK%После защиты, если атакующий находится в вашей арки прицельного огня, атакующий получает 1 жетон Стресса.'''
'Ghost (Phantom II)':
name: "Призрак (Фантом II)"
text: '''<span class="card-restriction">Только для VCX-100.</span>%LINEBREAK%Экипируйте карту Названия <em>Фантом II</em> на дружественный шаттл класса <em>Колчан</em> и пристыкуйте его к вашему кораблю.%LINEBREAK%После выполнения маневра, вы можете отстыковать его с ваших задних направляющих.'''
'PhPI:NAME:<NAME>END_PI II':
name: "PI:NAME:<NAME>END_PI"
ship: "Шаттл класса Колчан"
text: '''Когда вы пристыкованы, <em>Призрак</em> может выполнять атаки основным оружием в своей специальной арке огня.%LINEBREAK%Пока вы пристыкованы, до конца фазы Активации, <em>Призрак</em> может выполнять свободное действие Координации.'''
'First Order Vanguard':
name: "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
ship: "TIE глушитель"
text: '''<span class="card-restriction">Только для TIE глушителя.</span>%LINEBREAK%Атакуя, если ащищающийся - единственный вражеский корабль в вашей арке огня на расстоянии 1-3, вы можете перебросить 1 кубик атаки.%LINEBREAK%Защищаясь, вы можете сбросить эту карту, чтобы перебросить все ваши кубики защиты.'''
'Os-1 Arsenal Loadout':
name: "Загрузка арсенала Os-1"
ship: "Звездное Крыло класса Альфа"
text: '''<span class="card-restriction">Только для Звездного Крыла класса Альфа.</span>%LINEBREAK%Ваша панель улучшений получает значки %TORPEDO% и %MISSILE%.%LINEBREAK%Вы можете выполнять атаки вспомогательным оружием %TORPEDO% и %MISSILE% против кораблей, находящихся в вашем захвате, даже если у вас есть жетон Оружия выведенного из строя.'''
'Crossfire Formation':
name: "Построение перекрестного огня"
ship: "Бомбардировщик B/SF-17"
text: '''<span class="card-restriction">Только для Бомбардировщика B/SF-17.</span>%LINEBREAK%Защищаясь, если есть по меньшей мере 1 дружественный корабль Сопротивления на расстоянии 1-2 от атакующего, вы можете добавить 1 результат %FOCUS% к вашему броску.'''
'Advanced Ailerons':
text: '''<span class="card-restriction">TIE Reaper only.</span>%LINEBREAK%Treat your (%BANKLEFT% 3) and (%BANKRIGHT% 3) maneuvers as white.%LINEBREAK%Immediately before you reveal your dial, if you are not stressed, you must execute a white (%BANKLEFT% 1), (%STRAIGHT% 1), or (%BANKRIGHT% 1) maneuver.'''
condition_translations =
'''I'll Show You the Dark Side''':
name: "Я Покажу Тебе Темную Сторону"
text: '''Когда эта карта назначена, если она уже не находится в игре, игрок, который ее назначил, выбирает из колоды 1 карту повреждений с указателем <strong><em>Пилот</em></strong> и может положить ее на эту карту лицом вверх. Затем перетасуйте колоду карт повреждений.%LINEBREAK% Когда вы получаете критическое повреждение во время атаки, вместо него вы отрабатываете выбранную карту повреждений.%LINEBREAK%Когда на этой карте нет больше карты повреждений, уберите ее.'''
'Suppressive Fire':
name: "Подавляющий огонь"
text: '''Атакуя корабль, не являющийся кораблем "Капитан Рекс", бросьте на 1 кубик атаки меньше.%LINEBREAK% Когда вы объявляете атаку против "Капитана Рекса" или "Капитан Рекс" уничтожен - уберите эту карту.%LINEBREAK%В конце фазы Боя, если "Капитан Рекс" не выполнял атаку в эту фазу, уберите эту карту.'''
'Fanatical Devotion':
name: "Фанатическая преданность"
text: '''Защищаясь, вы не можете использовать жетоны Концентрации.%LINEBREAK%Атакуя, если вы используете жетон Концентрации, чтобы заменить все результаты %FOCUS% на результаты %HIT%, отложите в сторону первый результат %FOCUS%, который вы заменили. Отставленный в сторону результат %HIT% не может быть отменен кубиками защиты, но защищающийся может отменять результаты %CRIT% до него.%LINEBREAK%Во время фазы Завершения, уберите эту карту.'''
'A Debt to Pay':
name: "Счет к оплате"
text: '''Атакуя корабль, имеющий карту улучшения "Личные счеты", вы можете заменить 1 результат %FOCUS% на результат %CRIT%.'''
'Shadowed':
name: "Затененный"
text: '''"ТPI:NAME:<NAME>END_PI" считается имеющим значение умения пилота, которое у вас было после фазы расстановки.%LINEBREAK%Умение пилота "Твика" не меняется, если ваше значение умения пилота изменяется или вы уничтожены.'''
'Mimicked':
name: "Мимикрированный"
text: '''"PI:NAME:<NAME>END_PIик" считается имеющим вашу способность пилота.%LINEBREAK%"Твик" не может применить карту Состояния, используя вашу способность пилота.%LINEBREAK%"Твик" не теряет вашу способность пилота, если вы уничтожены.'''
'Harpooned!':
name: "Загарпунен!"
text: '''Когда в вас попадает атака, если хотя бы 1 результат %CRIT% не отменен, каждый другой корабль на расстоянии 1 получает 1 повреждение. Затем сбросьте эту карту и получите 1 карту повреждений лицом вниз.%LINEBREAK%Когда вы уничтожены, каждый корабль на расстоянии 1 получает 1 повреждение.%LINEBREAK%<strong>Действие:</strong> Сбросьте эту карту. Затем бросьте 1 кубик атаки. При результате %HIT% или %CRIT%, получите 1 повреждение.'''
'Rattled':
name: "Разбитый"
text: '''Когда вы получаете повреждение или критическое повреждение от бомбы, вы получаете 1 дополнительное критическое повреждение. Затем сбросьте эту карту.%LINEBREAK%<strong>Действие:</strong> Бросьте 1 кубик атакию. При результате %FOCUS% или %HIT%, сбросьте эту карту.'''
'Scrambled':
name: "Помехи"
text: '''Атакуя корабль на расстоянии 1, оснащенный улучшением "Помехи наведения", вы не можете модифицировать кубики атаки.%LINEBREAK%В конце фазы Боя, сбросьте эту карту.'''
'Optimized Prototype':
name: "Оптимизированный прототип"
text: '''Increase your shield value by 1.%LINEBREAK%Once per round, when performing a primary weapon attack, you may spend 1 die result to remove 1 shield from the defender.%LINEBREAK%After you perform a primary weapon attack, a friendly ship at Range 1-2 equipped with the "Director Krennic" Upgrade card may acquire a target lock on the defender.'''
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations, condition_translations |
[
{
"context": "quest, response, next) ->\n\t#response.cookie 'u', 'Sam|Eubank|sameubank@gmail.com', {signed: true}\n\tnext()\n",
"end": 80,
"score": 0.9963711500167847,
"start": 70,
"tag": "NAME",
"value": "Sam|Eubank"
},
{
"context": "onse, next) ->\n\t#response.cookie 'u', 'Sam|Euba... | lib/auth.coffee | eubsoft/radedit | 1 | module.exports = (request, response, next) ->
#response.cookie 'u', 'Sam|Eubank|sameubank@gmail.com', {signed: true}
next()
| 158454 | module.exports = (request, response, next) ->
#response.cookie 'u', '<NAME>|<EMAIL>', {signed: true}
next()
| true | module.exports = (request, response, next) ->
#response.cookie 'u', 'PI:NAME:<NAME>END_PI|PI:EMAIL:<EMAIL>END_PI', {signed: true}
next()
|
[
{
"context": "f msg.content == \"Reacting!\" && msg.author.id == \"169554882674556930\"\n msg.addReaction(\"%F0%9F%91%BB\")\n else if ms",
"end": 6811,
"score": 0.9260463714599609,
"start": 6793,
"tag": "PASSWORD",
"value": "169554882674556930"
}
] | discordClient/test.coffee | motorlatitude/MotorBot | 4 | DiscordClient = require './discordClient.coffee'
youtubeStream = require 'ytdl-core'
keys = require '../keys.json'
Table = require('cli-table')
dc = new DiscordClient({token: keys.token})
dc.on("ready", (msg) ->
#console.log "discordClient is ready and sending HB"
)
songList = ["https://www.youtube.com/watch?v=CkQGvs-SYbk","https://www.youtube.com/watch?v=p7_qZSYAxoQ","https://www.youtube.com/watch?v=vmF64VaquYQ","https://www.youtube.com/watch?v=cyBEQD6065s","https://www.youtube.com/watch?v=gb2ZEzqHH2g","https://www.youtube.com/watch?v=P48RCKp6iVU"]
musicPlayers = {}
soundboard = {}
yStream = {}
voiceConnections = {}
playNextTrack = (guild_id) ->
requestUrl = songList.shift()
if requestUrl
yStream[guild_id] = youtubeStream(requestUrl,{quality: 'lowest', filter: 'audioonly'})
yStream[guild_id].on("error", (e) ->
console.log("Error Occurred Loading Youtube Video")
)
yStream[guild_id].on("info", (info, format) ->
voiceConnections[guild_id].playFromStream(yStream[guild_id]).then((audioPlayer) ->
musicPlayers[guild_id] = audioPlayer
musicPlayers[guild_id].on('ready', () ->
musicPlayers[guild_id].play()
)
musicPlayers[guild_id].on("paused", () ->
if soundboard[guild_id]
soundboard[guild_id].play()
)
#musicPlayers[guild_id].pause()
musicPlayers[guild_id].on("streamDone", () ->
musicPlayers[guild_id] = undefined
playNextTrack(guild_id)
)
)
)
dc.on("message", (msg) ->
if msg.content.match(/^\!v\sjoin/)
channelName = msg.content.replace(/^\!v\sjoin\s/,"")
joined = false
if channelName
for channel in dc.guilds[msg.guild_id].channels
if channel.name == channelName && channel.type == 2
channel.join().then((VoiceConnection) ->
voiceConnections[msg.guild_id] = VoiceConnection
)
joined = true
break
if !joined
for channel in dc.guilds[msg.guild_id].channels
if channel.type == 2
channel.join().then((VoiceConnection) ->
voiceConnections[msg.guild_id] = VoiceConnection
)
break
else if msg.content == "!v leave"
dc.leaveVoiceChannel(msg.guild_id)
else if msg.content == "!v play"
if !musicPlayers[msg.guild_id]
playNextTrack(msg.guild_id)
else
musicPlayers[msg.guild_id].play()
else if msg.content == "!v play force"
yStream[msg.guild_id].end()
musicPlayers[msg.guild_id].stop()
musicPlayers[msg.guild_id] = undefined
playNextTrack(msg.guild_id)
else if msg.content == "!v stop"
yStream[msg.guild_id].end()
musicPlayers[msg.guild_id].stop()
else if msg.content == "!v pause"
musicPlayers[msg.guild_id].pause()
else if msg.content == "!sb"
if !soundboard[msg.guild_id]
voiceConnections[msg.guild_id].playFromFile("../soundboard/DootDiddly.mp3").then((audioPlayer) ->
soundboard[msg.guild_id] = audioPlayer
soundboard[msg.guild_id].on('ready', () ->
if musicPlayers[msg.guild_id]
musicPlayers[msg.guild_id].pause()
else
soundboard[msg.guild_id].play()
)
soundboard[msg.guild_id].on('streamDone', () ->
soundboard[msg.guild_id] = undefined
if musicPlayers[msg.guild_id]
musicPlayers[msg.guild_id].play()
)
)
else if msg.content == "!ping"
msg.channel.sendMessage("pong!")
else if msg.content == "!dev client status"
server = msg.guild_id
content = "Motorbot is connected to your gateway server on **"+dc.internals.gateway+"** with an average ping of **"+Math.round(dc.internals.avgPing*100)/100+"ms**. The last ping was **"+dc.internals.pings[dc.internals.pings.length-1]+"ms**."
msg.channel.sendMessage(content)
else if msg.content.match(/^\!dev voice status/)
additionalParams = msg.content.replace(/^\!dev voice status\s/gmi,"")
server = msg.guild_id
if dc.voiceHandlers[server]
bytes = dc.voiceHandlers[server].bytesTransmitted
units = "Bytes"
if bytes > 1024
bytes = (Math.round((bytes/1024)*100)/100)
units = "KB"
if bytes > 1024
bytes = (Math.round((bytes/1024)*100)/100)
units = "MB"
if bytes > 1024
bytes = (Math.round((bytes/1024)*100)/100)
units = "GB"
content = "Motorbot is connected to your voice server on **"+dc.voiceHandlers[server].endpoint+"** with an average ping of **"+Math.round(dc.voiceHandlers[server].avgPing*100)/100+"ms**. The last ping was **"+dc.voiceHandlers[server].pings[dc.voiceHandlers[server].pings.length-1]+"ms**.\n"
if additionalParams == "detailed"
table = new Table({
#head: ["Parameter","Value"]
style: {'padding-left':1, 'padding-right':1, head:[], border:[]}
})
avgPing = (Math.round(dc.voiceHandlers[server].avgPing*100)/100)
connectedTime = (Math.round(((new Date().getTime() - dc.voiceHandlers[server].connectTime)/1000)*10)/10)
table.push(["Endpoint",dc.voiceHandlers[server].endpoint])
table.push(["Local Port",dc.voiceHandlers[server].localPort])
table.push(["Average Ping",avgPing+"ms"])
table.push(["Last Ping",dc.voiceHandlers[server].pings[dc.voiceHandlers[server].pings.length-1]+"ms"])
table.push(["Heartbeats Sent",dc.voiceHandlers[server].pings.length])
table.push(["Bytes Transmitted",bytes+" "+units])
table.push(["Sequence",dc.voiceHandlers[server].sequence])
table.push(["Timestamp",dc.voiceHandlers[server].timestamp])
table.push(["Source ID (ssrc)",dc.voiceHandlers[server].ssrc])
table.push(["mode","xsalsa20_poly1305"])
table.push(["User ID",dc.voiceHandlers[server].user_id])
table.push(["Session",dc.voiceHandlers[server].session_id])
table.push(["Token",dc.voiceHandlers[server].token])
table.push(["Connected",connectedTime+"s"])
content = "```markdown\n"+table.toString()+"\n```"
if !dc.voiceHandlers[server].pings[0]
content += "\n```diff\n- Status: Unknown - Too soon to tell\n```"
else if avgPing >= 35
content += "\n```diff\n- Status: Poor - Pings a bit high, switch servers?\n```"
else if connectedTime >= 172800
content += "\n```diff\n- Status: Sweating - Been working for at least 48 hours straight\n```"
else
content += "\n```diff\n+ Status: Awesome\n```"
msg.channel.sendMessage(content)
else
msg.channel.sendMessage("```diff\n- Not Currently in voice channel\n```")
else if msg.content == "!react"
msg.channel.sendMessage("Reacting!")
else if msg.content == "Reacting!" && msg.author.id == "169554882674556930"
msg.addReaction("%F0%9F%91%BB")
else if msg.content == "getMessages"
console.log "Getting Messages"
msg.channel.getMessages({limit: 5}).then((messages) ->
console.log messages[0]
).catch((err) ->
console.log err.statusMessage
)
else if msg.content == "getInvites"
msg.channel.getInvites().then((invites) ->
console.log invites
).catch((err) ->
console.log err.statusMessage
)
else if msg.content == "createInvite"
msg.channel.createInvite().then((invite) ->
console.log invite
).catch((err) ->
console.log err.statusMessage
)
else if msg.content == "triggerTyping"
msg.channel.triggerTyping()
else if msg.content.match(/^setChannelName\s/gmi)
name = msg.content.replace(/^setChannelName\s/gmi,"")
msg.channel.setChannelName(name)
else if msg.content.match(/^setUserLimit\s/gmi)
user_limit = parseInt(msg.content.replace(/^setUserLimit\s/gmi,""))
dc.channels["194904787924418561"].setUserLimit(user_limit)
)
dc.connect()
| 134497 | DiscordClient = require './discordClient.coffee'
youtubeStream = require 'ytdl-core'
keys = require '../keys.json'
Table = require('cli-table')
dc = new DiscordClient({token: keys.token})
dc.on("ready", (msg) ->
#console.log "discordClient is ready and sending HB"
)
songList = ["https://www.youtube.com/watch?v=CkQGvs-SYbk","https://www.youtube.com/watch?v=p7_qZSYAxoQ","https://www.youtube.com/watch?v=vmF64VaquYQ","https://www.youtube.com/watch?v=cyBEQD6065s","https://www.youtube.com/watch?v=gb2ZEzqHH2g","https://www.youtube.com/watch?v=P48RCKp6iVU"]
musicPlayers = {}
soundboard = {}
yStream = {}
voiceConnections = {}
playNextTrack = (guild_id) ->
requestUrl = songList.shift()
if requestUrl
yStream[guild_id] = youtubeStream(requestUrl,{quality: 'lowest', filter: 'audioonly'})
yStream[guild_id].on("error", (e) ->
console.log("Error Occurred Loading Youtube Video")
)
yStream[guild_id].on("info", (info, format) ->
voiceConnections[guild_id].playFromStream(yStream[guild_id]).then((audioPlayer) ->
musicPlayers[guild_id] = audioPlayer
musicPlayers[guild_id].on('ready', () ->
musicPlayers[guild_id].play()
)
musicPlayers[guild_id].on("paused", () ->
if soundboard[guild_id]
soundboard[guild_id].play()
)
#musicPlayers[guild_id].pause()
musicPlayers[guild_id].on("streamDone", () ->
musicPlayers[guild_id] = undefined
playNextTrack(guild_id)
)
)
)
dc.on("message", (msg) ->
if msg.content.match(/^\!v\sjoin/)
channelName = msg.content.replace(/^\!v\sjoin\s/,"")
joined = false
if channelName
for channel in dc.guilds[msg.guild_id].channels
if channel.name == channelName && channel.type == 2
channel.join().then((VoiceConnection) ->
voiceConnections[msg.guild_id] = VoiceConnection
)
joined = true
break
if !joined
for channel in dc.guilds[msg.guild_id].channels
if channel.type == 2
channel.join().then((VoiceConnection) ->
voiceConnections[msg.guild_id] = VoiceConnection
)
break
else if msg.content == "!v leave"
dc.leaveVoiceChannel(msg.guild_id)
else if msg.content == "!v play"
if !musicPlayers[msg.guild_id]
playNextTrack(msg.guild_id)
else
musicPlayers[msg.guild_id].play()
else if msg.content == "!v play force"
yStream[msg.guild_id].end()
musicPlayers[msg.guild_id].stop()
musicPlayers[msg.guild_id] = undefined
playNextTrack(msg.guild_id)
else if msg.content == "!v stop"
yStream[msg.guild_id].end()
musicPlayers[msg.guild_id].stop()
else if msg.content == "!v pause"
musicPlayers[msg.guild_id].pause()
else if msg.content == "!sb"
if !soundboard[msg.guild_id]
voiceConnections[msg.guild_id].playFromFile("../soundboard/DootDiddly.mp3").then((audioPlayer) ->
soundboard[msg.guild_id] = audioPlayer
soundboard[msg.guild_id].on('ready', () ->
if musicPlayers[msg.guild_id]
musicPlayers[msg.guild_id].pause()
else
soundboard[msg.guild_id].play()
)
soundboard[msg.guild_id].on('streamDone', () ->
soundboard[msg.guild_id] = undefined
if musicPlayers[msg.guild_id]
musicPlayers[msg.guild_id].play()
)
)
else if msg.content == "!ping"
msg.channel.sendMessage("pong!")
else if msg.content == "!dev client status"
server = msg.guild_id
content = "Motorbot is connected to your gateway server on **"+dc.internals.gateway+"** with an average ping of **"+Math.round(dc.internals.avgPing*100)/100+"ms**. The last ping was **"+dc.internals.pings[dc.internals.pings.length-1]+"ms**."
msg.channel.sendMessage(content)
else if msg.content.match(/^\!dev voice status/)
additionalParams = msg.content.replace(/^\!dev voice status\s/gmi,"")
server = msg.guild_id
if dc.voiceHandlers[server]
bytes = dc.voiceHandlers[server].bytesTransmitted
units = "Bytes"
if bytes > 1024
bytes = (Math.round((bytes/1024)*100)/100)
units = "KB"
if bytes > 1024
bytes = (Math.round((bytes/1024)*100)/100)
units = "MB"
if bytes > 1024
bytes = (Math.round((bytes/1024)*100)/100)
units = "GB"
content = "Motorbot is connected to your voice server on **"+dc.voiceHandlers[server].endpoint+"** with an average ping of **"+Math.round(dc.voiceHandlers[server].avgPing*100)/100+"ms**. The last ping was **"+dc.voiceHandlers[server].pings[dc.voiceHandlers[server].pings.length-1]+"ms**.\n"
if additionalParams == "detailed"
table = new Table({
#head: ["Parameter","Value"]
style: {'padding-left':1, 'padding-right':1, head:[], border:[]}
})
avgPing = (Math.round(dc.voiceHandlers[server].avgPing*100)/100)
connectedTime = (Math.round(((new Date().getTime() - dc.voiceHandlers[server].connectTime)/1000)*10)/10)
table.push(["Endpoint",dc.voiceHandlers[server].endpoint])
table.push(["Local Port",dc.voiceHandlers[server].localPort])
table.push(["Average Ping",avgPing+"ms"])
table.push(["Last Ping",dc.voiceHandlers[server].pings[dc.voiceHandlers[server].pings.length-1]+"ms"])
table.push(["Heartbeats Sent",dc.voiceHandlers[server].pings.length])
table.push(["Bytes Transmitted",bytes+" "+units])
table.push(["Sequence",dc.voiceHandlers[server].sequence])
table.push(["Timestamp",dc.voiceHandlers[server].timestamp])
table.push(["Source ID (ssrc)",dc.voiceHandlers[server].ssrc])
table.push(["mode","xsalsa20_poly1305"])
table.push(["User ID",dc.voiceHandlers[server].user_id])
table.push(["Session",dc.voiceHandlers[server].session_id])
table.push(["Token",dc.voiceHandlers[server].token])
table.push(["Connected",connectedTime+"s"])
content = "```markdown\n"+table.toString()+"\n```"
if !dc.voiceHandlers[server].pings[0]
content += "\n```diff\n- Status: Unknown - Too soon to tell\n```"
else if avgPing >= 35
content += "\n```diff\n- Status: Poor - Pings a bit high, switch servers?\n```"
else if connectedTime >= 172800
content += "\n```diff\n- Status: Sweating - Been working for at least 48 hours straight\n```"
else
content += "\n```diff\n+ Status: Awesome\n```"
msg.channel.sendMessage(content)
else
msg.channel.sendMessage("```diff\n- Not Currently in voice channel\n```")
else if msg.content == "!react"
msg.channel.sendMessage("Reacting!")
else if msg.content == "Reacting!" && msg.author.id == "<PASSWORD>"
msg.addReaction("%F0%9F%91%BB")
else if msg.content == "getMessages"
console.log "Getting Messages"
msg.channel.getMessages({limit: 5}).then((messages) ->
console.log messages[0]
).catch((err) ->
console.log err.statusMessage
)
else if msg.content == "getInvites"
msg.channel.getInvites().then((invites) ->
console.log invites
).catch((err) ->
console.log err.statusMessage
)
else if msg.content == "createInvite"
msg.channel.createInvite().then((invite) ->
console.log invite
).catch((err) ->
console.log err.statusMessage
)
else if msg.content == "triggerTyping"
msg.channel.triggerTyping()
else if msg.content.match(/^setChannelName\s/gmi)
name = msg.content.replace(/^setChannelName\s/gmi,"")
msg.channel.setChannelName(name)
else if msg.content.match(/^setUserLimit\s/gmi)
user_limit = parseInt(msg.content.replace(/^setUserLimit\s/gmi,""))
dc.channels["194904787924418561"].setUserLimit(user_limit)
)
dc.connect()
| true | DiscordClient = require './discordClient.coffee'
youtubeStream = require 'ytdl-core'
keys = require '../keys.json'
Table = require('cli-table')
dc = new DiscordClient({token: keys.token})
dc.on("ready", (msg) ->
#console.log "discordClient is ready and sending HB"
)
songList = ["https://www.youtube.com/watch?v=CkQGvs-SYbk","https://www.youtube.com/watch?v=p7_qZSYAxoQ","https://www.youtube.com/watch?v=vmF64VaquYQ","https://www.youtube.com/watch?v=cyBEQD6065s","https://www.youtube.com/watch?v=gb2ZEzqHH2g","https://www.youtube.com/watch?v=P48RCKp6iVU"]
musicPlayers = {}
soundboard = {}
yStream = {}
voiceConnections = {}
playNextTrack = (guild_id) ->
requestUrl = songList.shift()
if requestUrl
yStream[guild_id] = youtubeStream(requestUrl,{quality: 'lowest', filter: 'audioonly'})
yStream[guild_id].on("error", (e) ->
console.log("Error Occurred Loading Youtube Video")
)
yStream[guild_id].on("info", (info, format) ->
voiceConnections[guild_id].playFromStream(yStream[guild_id]).then((audioPlayer) ->
musicPlayers[guild_id] = audioPlayer
musicPlayers[guild_id].on('ready', () ->
musicPlayers[guild_id].play()
)
musicPlayers[guild_id].on("paused", () ->
if soundboard[guild_id]
soundboard[guild_id].play()
)
#musicPlayers[guild_id].pause()
musicPlayers[guild_id].on("streamDone", () ->
musicPlayers[guild_id] = undefined
playNextTrack(guild_id)
)
)
)
dc.on("message", (msg) ->
if msg.content.match(/^\!v\sjoin/)
channelName = msg.content.replace(/^\!v\sjoin\s/,"")
joined = false
if channelName
for channel in dc.guilds[msg.guild_id].channels
if channel.name == channelName && channel.type == 2
channel.join().then((VoiceConnection) ->
voiceConnections[msg.guild_id] = VoiceConnection
)
joined = true
break
if !joined
for channel in dc.guilds[msg.guild_id].channels
if channel.type == 2
channel.join().then((VoiceConnection) ->
voiceConnections[msg.guild_id] = VoiceConnection
)
break
else if msg.content == "!v leave"
dc.leaveVoiceChannel(msg.guild_id)
else if msg.content == "!v play"
if !musicPlayers[msg.guild_id]
playNextTrack(msg.guild_id)
else
musicPlayers[msg.guild_id].play()
else if msg.content == "!v play force"
yStream[msg.guild_id].end()
musicPlayers[msg.guild_id].stop()
musicPlayers[msg.guild_id] = undefined
playNextTrack(msg.guild_id)
else if msg.content == "!v stop"
yStream[msg.guild_id].end()
musicPlayers[msg.guild_id].stop()
else if msg.content == "!v pause"
musicPlayers[msg.guild_id].pause()
else if msg.content == "!sb"
if !soundboard[msg.guild_id]
voiceConnections[msg.guild_id].playFromFile("../soundboard/DootDiddly.mp3").then((audioPlayer) ->
soundboard[msg.guild_id] = audioPlayer
soundboard[msg.guild_id].on('ready', () ->
if musicPlayers[msg.guild_id]
musicPlayers[msg.guild_id].pause()
else
soundboard[msg.guild_id].play()
)
soundboard[msg.guild_id].on('streamDone', () ->
soundboard[msg.guild_id] = undefined
if musicPlayers[msg.guild_id]
musicPlayers[msg.guild_id].play()
)
)
else if msg.content == "!ping"
msg.channel.sendMessage("pong!")
else if msg.content == "!dev client status"
server = msg.guild_id
content = "Motorbot is connected to your gateway server on **"+dc.internals.gateway+"** with an average ping of **"+Math.round(dc.internals.avgPing*100)/100+"ms**. The last ping was **"+dc.internals.pings[dc.internals.pings.length-1]+"ms**."
msg.channel.sendMessage(content)
else if msg.content.match(/^\!dev voice status/)
additionalParams = msg.content.replace(/^\!dev voice status\s/gmi,"")
server = msg.guild_id
if dc.voiceHandlers[server]
bytes = dc.voiceHandlers[server].bytesTransmitted
units = "Bytes"
if bytes > 1024
bytes = (Math.round((bytes/1024)*100)/100)
units = "KB"
if bytes > 1024
bytes = (Math.round((bytes/1024)*100)/100)
units = "MB"
if bytes > 1024
bytes = (Math.round((bytes/1024)*100)/100)
units = "GB"
content = "Motorbot is connected to your voice server on **"+dc.voiceHandlers[server].endpoint+"** with an average ping of **"+Math.round(dc.voiceHandlers[server].avgPing*100)/100+"ms**. The last ping was **"+dc.voiceHandlers[server].pings[dc.voiceHandlers[server].pings.length-1]+"ms**.\n"
if additionalParams == "detailed"
table = new Table({
#head: ["Parameter","Value"]
style: {'padding-left':1, 'padding-right':1, head:[], border:[]}
})
avgPing = (Math.round(dc.voiceHandlers[server].avgPing*100)/100)
connectedTime = (Math.round(((new Date().getTime() - dc.voiceHandlers[server].connectTime)/1000)*10)/10)
table.push(["Endpoint",dc.voiceHandlers[server].endpoint])
table.push(["Local Port",dc.voiceHandlers[server].localPort])
table.push(["Average Ping",avgPing+"ms"])
table.push(["Last Ping",dc.voiceHandlers[server].pings[dc.voiceHandlers[server].pings.length-1]+"ms"])
table.push(["Heartbeats Sent",dc.voiceHandlers[server].pings.length])
table.push(["Bytes Transmitted",bytes+" "+units])
table.push(["Sequence",dc.voiceHandlers[server].sequence])
table.push(["Timestamp",dc.voiceHandlers[server].timestamp])
table.push(["Source ID (ssrc)",dc.voiceHandlers[server].ssrc])
table.push(["mode","xsalsa20_poly1305"])
table.push(["User ID",dc.voiceHandlers[server].user_id])
table.push(["Session",dc.voiceHandlers[server].session_id])
table.push(["Token",dc.voiceHandlers[server].token])
table.push(["Connected",connectedTime+"s"])
content = "```markdown\n"+table.toString()+"\n```"
if !dc.voiceHandlers[server].pings[0]
content += "\n```diff\n- Status: Unknown - Too soon to tell\n```"
else if avgPing >= 35
content += "\n```diff\n- Status: Poor - Pings a bit high, switch servers?\n```"
else if connectedTime >= 172800
content += "\n```diff\n- Status: Sweating - Been working for at least 48 hours straight\n```"
else
content += "\n```diff\n+ Status: Awesome\n```"
msg.channel.sendMessage(content)
else
msg.channel.sendMessage("```diff\n- Not Currently in voice channel\n```")
else if msg.content == "!react"
msg.channel.sendMessage("Reacting!")
else if msg.content == "Reacting!" && msg.author.id == "PI:PASSWORD:<PASSWORD>END_PI"
msg.addReaction("%F0%9F%91%BB")
else if msg.content == "getMessages"
console.log "Getting Messages"
msg.channel.getMessages({limit: 5}).then((messages) ->
console.log messages[0]
).catch((err) ->
console.log err.statusMessage
)
else if msg.content == "getInvites"
msg.channel.getInvites().then((invites) ->
console.log invites
).catch((err) ->
console.log err.statusMessage
)
else if msg.content == "createInvite"
msg.channel.createInvite().then((invite) ->
console.log invite
).catch((err) ->
console.log err.statusMessage
)
else if msg.content == "triggerTyping"
msg.channel.triggerTyping()
else if msg.content.match(/^setChannelName\s/gmi)
name = msg.content.replace(/^setChannelName\s/gmi,"")
msg.channel.setChannelName(name)
else if msg.content.match(/^setUserLimit\s/gmi)
user_limit = parseInt(msg.content.replace(/^setUserLimit\s/gmi,""))
dc.channels["194904787924418561"].setUserLimit(user_limit)
)
dc.connect()
|
[
{
"context": "sicStrategy((username, pwd, done) ->\n if pwd is \"1234\" and username is \"Foo\"\n return done undefined,",
"end": 421,
"score": 0.988470196723938,
"start": 417,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": "pwd, done) ->\n if pwd is \"1234\" and username is... | test/test-authorizations.coffee | OpenCubes/Nap | 1 | chai = require('chai')
should = chai.should()
chai.use(require('chai-things'))
index = require('../index')
mongoose = require("mongoose")
Model = require "../src/model"
Q = require "q"
FS = require 'q-io/fs'
nap = require('../')
someUser = {}
otherUser = {}
passport = require 'passport'
BasicStrategy = require('passport-http').BasicStrategy
passport.use new BasicStrategy((username, pwd, done) ->
if pwd is "1234" and username is "Foo"
return done undefined, {
username: "Foo"
role: "user"
_id: someUser._id
}
if pwd is "password" and username is "username"
return done undefined, {
username: "username"
role: "user"
_id: otherUser._id
}
if pwd is "admin" and username is "admin"
return done undefined, {
username: "admin"
role: "admin"
}
if pwd is "guest" and username is "guest"
done undefined, {
username: "guest",
role: "guest"
}
else done()
)
express = require("express")
app = express()
# app.use express.logger()
app.use (req, res, next) ->
req.headers['authorization'] = "Basic Z3Vlc3Q6Z3Vlc3Q=" unless req.headers['authorization']
next()
# Initialize Passport! Note: no need to use session middleware when each
# request carries authentication credentials, as is the case with HTTP Basic.
app.use passport.initialize()
app.get '/', passport.authenticate("basic", session: false), (req, res) -> res.send req.user
api = nap
mongoose: mongoose
api.add
model: 'Story'
authorship: "author"
authorizations:
get: 'guest'
post: 'user'
put: 'admin'
delete: 'admin'
api.inject app, express.bodyParser, passport.authenticate("basic", session: false), (req, res, next) ->
if req.user.role is "admin"
req.allow = true
return next()
req.allow = switch req.method
when "GET" then true
when "POST" then if req.user and req.user.role isnt "guest" then true
when "PUT", "DELETE" then false
next()
fooToken = 'Basic Rm9vOjEyMzQ='
adminToken = 'Basic YWRtaW46YWRtaW4='
request = require('supertest')(app)
aStory = {}
otherStory = {}
anotherStory = {}
describe 'authorizations', ->
before (done) ->
User = mongoose.model "User"
user = new User login: "Foo", role: "admin"
user.save (err, user) ->
someUser = user
user = new User login: "username", role: "user"
user.save (err, user) ->
otherUser = user
done()
it 'should connect the server with passport', (done) ->
request.get('/').set('Authorization', fooToken).end (err, res) ->
res.body.should.deep.equal username: 'Foo', role: 'user', _id: someUser._id.toString()
done()
describe 'guests', ->
it 'should have access to stories', (done) ->
request.get('/api/stories').end (err, res) ->
res.body.should.have.length 7
aStory = res.body[0]
done()
it 'should have access to one story', (done) ->
request.get("/api/stories/#{aStory._id}").end (err, res) ->
res.body.should.deep.equal aStory
done()
it 'should not be able to post mod', (done) ->
req = request.post("/api/stories")
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 401
done()
catch err
done err
it 'should not be able to put mod', (done) ->
req = request.put("/api/stories/#{aStory._id}")
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 401
request.get("/api/stories/#{aStory._id}").end (err, res) ->
res.body.should.deep.equal aStory
done()
catch err
done err
it 'should not be able to delete mod', (done) ->
req = request.delete("/api/stories/#{aStory._id}")
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 401
request.get("/api/stories/#{aStory._id}").end (err, res) ->
res.body.should.deep.equal aStory
done()
catch err
done err
describe 'users', ->
token = "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" # username:password
it 'should be able to post a mod', (done) ->
req = request.post("/api/stories")
req.set 'Authorization', token
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
otherStory = res.body
done()
catch err
done err
it 'should be able to put his mod', (done) ->
req = request.put("/api/stories/#{otherStory._id}")
req.set 'Authorization', token
req.send title: "This is another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'shouldn\'t be able to put one\'s mod', (done) ->
req = request.put("/api/stories/#{otherStory._id}")
req.set 'Authorization', fooToken
req.send title: "This is not another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 403
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'shouldn\'t be able to delete one\'s mod', (done) ->
req = request.delete("/api/stories/#{otherStory._id}")
req.set 'Authorization', fooToken
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 403
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'should be able to delete his mod', (done) ->
req = request.delete("/api/stories/#{otherStory._id}")
req.set 'Authorization', token
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.should.deep.equal {}
done()
catch err
done err
describe 'admins', ->
before (done) ->
token = "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" # username:password
req = request.post("/api/stories")
req.set 'Authorization', token
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
if err then return done err
res.statusCode.should.equal 200
otherStory = res.body
done()
it 'should be able to post a mod', (done) ->
req = request.post("/api/stories")
req.set 'Authorization', adminToken
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
anotherStory = res.body
done()
catch err
done err
it 'should be able to put his mod', (done) ->
req = request.put("/api/stories/#{anotherStory._id}")
req.set 'Authorization', adminToken
req.send title: "This is another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'should be able to put one\'s mod', (done) ->
req = request.put("/api/stories/#{otherStory._id}")
req.set 'Authorization', adminToken
req.send title: "This is indeed another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.title.should.equal "This is indeed another title"
done()
catch err
done err
it 'should be able to delete one\'s mod', (done) ->
req = request.delete("/api/stories/#{otherStory._id}")
req.set 'Authorization', adminToken
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.should.deep.equal {}
done()
catch err
done err
it 'should be able to delete his mod', (done) ->
req = request.delete("/api/stories/#{anotherStory._id}")
req.set 'Authorization', adminToken
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.should.deep.equal {}
done()
catch err
done err
| 30675 | chai = require('chai')
should = chai.should()
chai.use(require('chai-things'))
index = require('../index')
mongoose = require("mongoose")
Model = require "../src/model"
Q = require "q"
FS = require 'q-io/fs'
nap = require('../')
someUser = {}
otherUser = {}
passport = require 'passport'
BasicStrategy = require('passport-http').BasicStrategy
passport.use new BasicStrategy((username, pwd, done) ->
if pwd is "<PASSWORD>" and username is "Foo"
return done undefined, {
username: "Foo"
role: "user"
_id: someUser._id
}
if pwd is "<PASSWORD>" and username is "username"
return done undefined, {
username: "username"
role: "user"
_id: otherUser._id
}
if pwd is "admin" and username is "admin"
return done undefined, {
username: "admin"
role: "admin"
}
if pwd is "guest" and username is "guest"
done undefined, {
username: "guest",
role: "guest"
}
else done()
)
express = require("express")
app = express()
# app.use express.logger()
app.use (req, res, next) ->
req.headers['authorization'] = "Basic Z3Vlc3Q6Z3Vlc3Q=" unless req.headers['authorization']
next()
# Initialize Passport! Note: no need to use session middleware when each
# request carries authentication credentials, as is the case with HTTP Basic.
app.use passport.initialize()
app.get '/', passport.authenticate("basic", session: false), (req, res) -> res.send req.user
api = nap
mongoose: mongoose
api.add
model: 'Story'
authorship: "author"
authorizations:
get: 'guest'
post: 'user'
put: 'admin'
delete: 'admin'
api.inject app, express.bodyParser, passport.authenticate("basic", session: false), (req, res, next) ->
if req.user.role is "admin"
req.allow = true
return next()
req.allow = switch req.method
when "GET" then true
when "POST" then if req.user and req.user.role isnt "guest" then true
when "PUT", "DELETE" then false
next()
fooToken = '<PASSWORD>='
adminToken = '<PASSWORD>='
request = require('supertest')(app)
aStory = {}
otherStory = {}
anotherStory = {}
describe 'authorizations', ->
before (done) ->
User = mongoose.model "User"
user = new User login: "Foo", role: "admin"
user.save (err, user) ->
someUser = user
user = new User login: "username", role: "user"
user.save (err, user) ->
otherUser = user
done()
it 'should connect the server with passport', (done) ->
request.get('/').set('Authorization', fooToken).end (err, res) ->
res.body.should.deep.equal username: 'Foo', role: 'user', _id: someUser._id.toString()
done()
describe 'guests', ->
it 'should have access to stories', (done) ->
request.get('/api/stories').end (err, res) ->
res.body.should.have.length 7
aStory = res.body[0]
done()
it 'should have access to one story', (done) ->
request.get("/api/stories/#{aStory._id}").end (err, res) ->
res.body.should.deep.equal aStory
done()
it 'should not be able to post mod', (done) ->
req = request.post("/api/stories")
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 401
done()
catch err
done err
it 'should not be able to put mod', (done) ->
req = request.put("/api/stories/#{aStory._id}")
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 401
request.get("/api/stories/#{aStory._id}").end (err, res) ->
res.body.should.deep.equal aStory
done()
catch err
done err
it 'should not be able to delete mod', (done) ->
req = request.delete("/api/stories/#{aStory._id}")
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 401
request.get("/api/stories/#{aStory._id}").end (err, res) ->
res.body.should.deep.equal aStory
done()
catch err
done err
describe 'users', ->
token = "<KEY> # username:password
it 'should be able to post a mod', (done) ->
req = request.post("/api/stories")
req.set 'Authorization', token
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
otherStory = res.body
done()
catch err
done err
it 'should be able to put his mod', (done) ->
req = request.put("/api/stories/#{otherStory._id}")
req.set 'Authorization', token
req.send title: "This is another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'shouldn\'t be able to put one\'s mod', (done) ->
req = request.put("/api/stories/#{otherStory._id}")
req.set 'Authorization', fooToken
req.send title: "This is not another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 403
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'shouldn\'t be able to delete one\'s mod', (done) ->
req = request.delete("/api/stories/#{otherStory._id}")
req.set 'Authorization', fooToken
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 403
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'should be able to delete his mod', (done) ->
req = request.delete("/api/stories/#{otherStory._id}")
req.set 'Authorization', token
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.should.deep.equal {}
done()
catch err
done err
describe 'admins', ->
before (done) ->
token = "Basic <KEY>=" # username:password
req = request.post("/api/stories")
req.set 'Authorization', token
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
if err then return done err
res.statusCode.should.equal 200
otherStory = res.body
done()
it 'should be able to post a mod', (done) ->
req = request.post("/api/stories")
req.set 'Authorization', adminToken
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
anotherStory = res.body
done()
catch err
done err
it 'should be able to put his mod', (done) ->
req = request.put("/api/stories/#{anotherStory._id}")
req.set 'Authorization', adminToken
req.send title: "This is another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'should be able to put one\'s mod', (done) ->
req = request.put("/api/stories/#{otherStory._id}")
req.set 'Authorization', adminToken
req.send title: "This is indeed another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.title.should.equal "This is indeed another title"
done()
catch err
done err
it 'should be able to delete one\'s mod', (done) ->
req = request.delete("/api/stories/#{otherStory._id}")
req.set 'Authorization', adminToken
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.should.deep.equal {}
done()
catch err
done err
it 'should be able to delete his mod', (done) ->
req = request.delete("/api/stories/#{anotherStory._id}")
req.set 'Authorization', adminToken
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.should.deep.equal {}
done()
catch err
done err
| true | chai = require('chai')
should = chai.should()
chai.use(require('chai-things'))
index = require('../index')
mongoose = require("mongoose")
Model = require "../src/model"
Q = require "q"
FS = require 'q-io/fs'
nap = require('../')
someUser = {}
otherUser = {}
passport = require 'passport'
BasicStrategy = require('passport-http').BasicStrategy
passport.use new BasicStrategy((username, pwd, done) ->
if pwd is "PI:PASSWORD:<PASSWORD>END_PI" and username is "Foo"
return done undefined, {
username: "Foo"
role: "user"
_id: someUser._id
}
if pwd is "PI:PASSWORD:<PASSWORD>END_PI" and username is "username"
return done undefined, {
username: "username"
role: "user"
_id: otherUser._id
}
if pwd is "admin" and username is "admin"
return done undefined, {
username: "admin"
role: "admin"
}
if pwd is "guest" and username is "guest"
done undefined, {
username: "guest",
role: "guest"
}
else done()
)
express = require("express")
app = express()
# app.use express.logger()
app.use (req, res, next) ->
req.headers['authorization'] = "Basic Z3Vlc3Q6Z3Vlc3Q=" unless req.headers['authorization']
next()
# Initialize Passport! Note: no need to use session middleware when each
# request carries authentication credentials, as is the case with HTTP Basic.
app.use passport.initialize()
app.get '/', passport.authenticate("basic", session: false), (req, res) -> res.send req.user
api = nap
mongoose: mongoose
api.add
model: 'Story'
authorship: "author"
authorizations:
get: 'guest'
post: 'user'
put: 'admin'
delete: 'admin'
api.inject app, express.bodyParser, passport.authenticate("basic", session: false), (req, res, next) ->
if req.user.role is "admin"
req.allow = true
return next()
req.allow = switch req.method
when "GET" then true
when "POST" then if req.user and req.user.role isnt "guest" then true
when "PUT", "DELETE" then false
next()
fooToken = 'PI:PASSWORD:<PASSWORD>END_PI='
adminToken = 'PI:PASSWORD:<PASSWORD>END_PI='
request = require('supertest')(app)
aStory = {}
otherStory = {}
anotherStory = {}
describe 'authorizations', ->
before (done) ->
User = mongoose.model "User"
user = new User login: "Foo", role: "admin"
user.save (err, user) ->
someUser = user
user = new User login: "username", role: "user"
user.save (err, user) ->
otherUser = user
done()
it 'should connect the server with passport', (done) ->
request.get('/').set('Authorization', fooToken).end (err, res) ->
res.body.should.deep.equal username: 'Foo', role: 'user', _id: someUser._id.toString()
done()
describe 'guests', ->
it 'should have access to stories', (done) ->
request.get('/api/stories').end (err, res) ->
res.body.should.have.length 7
aStory = res.body[0]
done()
it 'should have access to one story', (done) ->
request.get("/api/stories/#{aStory._id}").end (err, res) ->
res.body.should.deep.equal aStory
done()
it 'should not be able to post mod', (done) ->
req = request.post("/api/stories")
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 401
done()
catch err
done err
it 'should not be able to put mod', (done) ->
req = request.put("/api/stories/#{aStory._id}")
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 401
request.get("/api/stories/#{aStory._id}").end (err, res) ->
res.body.should.deep.equal aStory
done()
catch err
done err
it 'should not be able to delete mod', (done) ->
req = request.delete("/api/stories/#{aStory._id}")
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 401
request.get("/api/stories/#{aStory._id}").end (err, res) ->
res.body.should.deep.equal aStory
done()
catch err
done err
describe 'users', ->
token = "PI:KEY:<KEY>END_PI # username:password
it 'should be able to post a mod', (done) ->
req = request.post("/api/stories")
req.set 'Authorization', token
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
otherStory = res.body
done()
catch err
done err
it 'should be able to put his mod', (done) ->
req = request.put("/api/stories/#{otherStory._id}")
req.set 'Authorization', token
req.send title: "This is another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'shouldn\'t be able to put one\'s mod', (done) ->
req = request.put("/api/stories/#{otherStory._id}")
req.set 'Authorization', fooToken
req.send title: "This is not another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 403
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'shouldn\'t be able to delete one\'s mod', (done) ->
req = request.delete("/api/stories/#{otherStory._id}")
req.set 'Authorization', fooToken
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 403
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'should be able to delete his mod', (done) ->
req = request.delete("/api/stories/#{otherStory._id}")
req.set 'Authorization', token
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.should.deep.equal {}
done()
catch err
done err
describe 'admins', ->
before (done) ->
token = "Basic PI:KEY:<KEY>END_PI=" # username:password
req = request.post("/api/stories")
req.set 'Authorization', token
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
if err then return done err
res.statusCode.should.equal 200
otherStory = res.body
done()
it 'should be able to post a mod', (done) ->
req = request.post("/api/stories")
req.set 'Authorization', adminToken
req.send title: "This is a title", body: "This is a bodty"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
anotherStory = res.body
done()
catch err
done err
it 'should be able to put his mod', (done) ->
req = request.put("/api/stories/#{anotherStory._id}")
req.set 'Authorization', adminToken
req.send title: "This is another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
res.body.title.should.equal "This is another title"
done()
catch err
done err
it 'should be able to put one\'s mod', (done) ->
req = request.put("/api/stories/#{otherStory._id}")
req.set 'Authorization', adminToken
req.send title: "This is indeed another title"
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.title.should.equal "This is indeed another title"
done()
catch err
done err
it 'should be able to delete one\'s mod', (done) ->
req = request.delete("/api/stories/#{otherStory._id}")
req.set 'Authorization', adminToken
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.should.deep.equal {}
done()
catch err
done err
it 'should be able to delete his mod', (done) ->
req = request.delete("/api/stories/#{anotherStory._id}")
req.set 'Authorization', adminToken
req.end (err, res) ->
try
if err then return done err
res.statusCode.should.equal 200
request.get("/api/stories/#{otherStory._id}").end (err, res) ->
if err then done err
res.body.should.deep.equal {}
done()
catch err
done err
|
[
{
"context": "y =\n emails: [\n { value: 'foo@bar.com' }\n ]\n displayName: 'Foo Us",
"end": 925,
"score": 0.9998628497123718,
"start": 914,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": "ar.com' }\n ]\n dis... | test/data/test-user.coffee | twistedstream/radbus-api | 2 | # coffeelint: disable=max_line_length
chai = require 'chai'
chai.use require 'chai-as-promised'
should = chai.should()
proxyquire = require 'proxyquire'
Q = require 'q'
# stub dependencies
request =
'@noCallThru': true
crypto =
'@noCallThru': true
# target library under test
target = proxyquire '../../data/user',
'request': request
'crypto': crypto
describe "data/user", ->
describe "#fetch", ->
beforeEach ->
process.env.RADBUS_GOOGLE_API_CLIENT_ID = 'google-api-client-id'
process.env.RADBUS_USER_ID_SALT = 'user-id-salt'
request.get = (options, callback) ->
options.should.have.property 'url'
options.should.have.property 'json', true
options.should.have.deep.property 'headers.Authorization', 'foo-token'
process.nextTick ->
response =
statusCode: 200
body =
emails: [
{ value: 'foo@bar.com' }
]
displayName: 'Foo User'
callback null, response, body
crypto.pbkdf2 = (password, salt, iterations, keylen, callback) ->
password.should.be.equal 'foo@bar.com'
salt.should.be.equal 'user-id-salt'
iterations.should.be.equal 10000
keylen.should.be.equal 512
process.nextTick ->
callback null, 'hashed-foo@bar.com'
afterEach ->
delete process.env.RADBUS_GOOGLE_API_CLIENT_ID
delete process.env.RADBUS_USER_ID_SALT
it "should return the expected error if the Google API client ID env variable isn't set", ->
delete process.env.RADBUS_GOOGLE_API_CLIENT_ID
target.fetch('foo-token')
.should.eventually.be.rejected
.and.match /Missing env variable/
it "should return the expected error if the user ID salt env variable isn't set", ->
delete process.env.RADBUS_USER_ID_SALT
target.fetch('foo-token')
.should.eventually.be.rejected
.and.match /Missing env variable/
it "should return the expected error if there's a problem making the Google+ API call", ->
err = new Error "Request ERROR!"
request.get = (options, callback) ->
process.nextTick -> callback err
target.fetch('foo-token')
.should.eventually.be.rejected
.and.equal err
it "should return null if the Google+ API call didn't return 200", ->
request.get = (options, callback) ->
process.nextTick ->
response =
statusCode: 401
body =
message: "No Googles for you"
callback null, response, body
target.fetch('foo-token')
.should.eventually.be.fulfilled
.and.be.null
it "should return the expected error if there's a problem hashing the user's email", ->
err = new Error "Crypto ERROR!"
crypto.pbkdf2 = (password, salt, iterations, keylen, callback) ->
process.nextTick -> callback err
target.fetch('foo-token')
.should.eventually.be.rejected
.and.equal err
it "should return the expected user information if the Google+ API call and email hasing were successful", ->
target.fetch('foo-token')
.should.eventually.be.fulfilled.then (user) ->
user.should.have.property 'id', 'hashed-foo@bar.com'
user.should.have.property 'displayName', 'Foo User'
| 37126 | # coffeelint: disable=max_line_length
chai = require 'chai'
chai.use require 'chai-as-promised'
should = chai.should()
proxyquire = require 'proxyquire'
Q = require 'q'
# stub dependencies
request =
'@noCallThru': true
crypto =
'@noCallThru': true
# target library under test
target = proxyquire '../../data/user',
'request': request
'crypto': crypto
describe "data/user", ->
describe "#fetch", ->
beforeEach ->
process.env.RADBUS_GOOGLE_API_CLIENT_ID = 'google-api-client-id'
process.env.RADBUS_USER_ID_SALT = 'user-id-salt'
request.get = (options, callback) ->
options.should.have.property 'url'
options.should.have.property 'json', true
options.should.have.deep.property 'headers.Authorization', 'foo-token'
process.nextTick ->
response =
statusCode: 200
body =
emails: [
{ value: '<EMAIL>' }
]
displayName: '<NAME>'
callback null, response, body
crypto.pbkdf2 = (password, salt, iterations, keylen, callback) ->
password.should.be.equal '<EMAIL>'
salt.should.be.equal 'user-id-salt'
iterations.should.be.equal 10000
keylen.should.be.equal 512
process.nextTick ->
callback null, '<EMAIL>'
afterEach ->
delete process.env.RADBUS_GOOGLE_API_CLIENT_ID
delete process.env.RADBUS_USER_ID_SALT
it "should return the expected error if the Google API client ID env variable isn't set", ->
delete process.env.RADBUS_GOOGLE_API_CLIENT_ID
target.fetch('foo-token')
.should.eventually.be.rejected
.and.match /Missing env variable/
it "should return the expected error if the user ID salt env variable isn't set", ->
delete process.env.RADBUS_USER_ID_SALT
target.fetch('foo-token')
.should.eventually.be.rejected
.and.match /Missing env variable/
it "should return the expected error if there's a problem making the Google+ API call", ->
err = new Error "Request ERROR!"
request.get = (options, callback) ->
process.nextTick -> callback err
target.fetch('foo-token')
.should.eventually.be.rejected
.and.equal err
it "should return null if the Google+ API call didn't return 200", ->
request.get = (options, callback) ->
process.nextTick ->
response =
statusCode: 401
body =
message: "No Googles for you"
callback null, response, body
target.fetch('foo-token')
.should.eventually.be.fulfilled
.and.be.null
it "should return the expected error if there's a problem hashing the user's email", ->
err = new Error "Crypto ERROR!"
crypto.pbkdf2 = (password, salt, iterations, keylen, callback) ->
process.nextTick -> callback err
target.fetch('foo-token')
.should.eventually.be.rejected
.and.equal err
it "should return the expected user information if the Google+ API call and email hasing were successful", ->
target.fetch('foo-token')
.should.eventually.be.fulfilled.then (user) ->
user.should.have.property 'id', '<EMAIL>'
user.should.have.property 'displayName', 'Foo User'
| true | # coffeelint: disable=max_line_length
chai = require 'chai'
chai.use require 'chai-as-promised'
should = chai.should()
proxyquire = require 'proxyquire'
Q = require 'q'
# stub dependencies
request =
'@noCallThru': true
crypto =
'@noCallThru': true
# target library under test
target = proxyquire '../../data/user',
'request': request
'crypto': crypto
describe "data/user", ->
describe "#fetch", ->
beforeEach ->
process.env.RADBUS_GOOGLE_API_CLIENT_ID = 'google-api-client-id'
process.env.RADBUS_USER_ID_SALT = 'user-id-salt'
request.get = (options, callback) ->
options.should.have.property 'url'
options.should.have.property 'json', true
options.should.have.deep.property 'headers.Authorization', 'foo-token'
process.nextTick ->
response =
statusCode: 200
body =
emails: [
{ value: 'PI:EMAIL:<EMAIL>END_PI' }
]
displayName: 'PI:NAME:<NAME>END_PI'
callback null, response, body
crypto.pbkdf2 = (password, salt, iterations, keylen, callback) ->
password.should.be.equal 'PI:EMAIL:<EMAIL>END_PI'
salt.should.be.equal 'user-id-salt'
iterations.should.be.equal 10000
keylen.should.be.equal 512
process.nextTick ->
callback null, 'PI:EMAIL:<EMAIL>END_PI'
afterEach ->
delete process.env.RADBUS_GOOGLE_API_CLIENT_ID
delete process.env.RADBUS_USER_ID_SALT
it "should return the expected error if the Google API client ID env variable isn't set", ->
delete process.env.RADBUS_GOOGLE_API_CLIENT_ID
target.fetch('foo-token')
.should.eventually.be.rejected
.and.match /Missing env variable/
it "should return the expected error if the user ID salt env variable isn't set", ->
delete process.env.RADBUS_USER_ID_SALT
target.fetch('foo-token')
.should.eventually.be.rejected
.and.match /Missing env variable/
it "should return the expected error if there's a problem making the Google+ API call", ->
err = new Error "Request ERROR!"
request.get = (options, callback) ->
process.nextTick -> callback err
target.fetch('foo-token')
.should.eventually.be.rejected
.and.equal err
it "should return null if the Google+ API call didn't return 200", ->
request.get = (options, callback) ->
process.nextTick ->
response =
statusCode: 401
body =
message: "No Googles for you"
callback null, response, body
target.fetch('foo-token')
.should.eventually.be.fulfilled
.and.be.null
it "should return the expected error if there's a problem hashing the user's email", ->
err = new Error "Crypto ERROR!"
crypto.pbkdf2 = (password, salt, iterations, keylen, callback) ->
process.nextTick -> callback err
target.fetch('foo-token')
.should.eventually.be.rejected
.and.equal err
it "should return the expected user information if the Google+ API call and email hasing were successful", ->
target.fetch('foo-token')
.should.eventually.be.fulfilled.then (user) ->
user.should.have.property 'id', 'PI:EMAIL:<EMAIL>END_PI'
user.should.have.property 'displayName', 'Foo User'
|
[
{
"context": " options.fn(@) else options.inverse(@)\n\n\n# Credit: Dan Harper (http://github.com/danharper)\n# If Equals: if_eq ",
"end": 981,
"score": 0.9997113347053528,
"start": 971,
"tag": "NAME",
"value": "Dan Harper"
},
{
"context": "erse(@)\n\n\n# Credit: Dan Harper (http://g... | src/content/helpers/helpers-comparisons.coffee | helpers/handlebars-helpers-examples | 8 | ###! comparison helpers ###
module.exports.and = _and = (testA, testB, options) ->
if testA and testB then options.fn(@) else options.inverse(@)
module.exports.gt = gt = (value, test, options) ->
if value > test then options.fn(@) else options.inverse(@)
module.exports.gte = gte = (value, test, options) ->
if value >= test then options.fn(@) else options.inverse(@)
module.exports.is = _is = (value, test, options) ->
if value is test then options.fn(@) else options.inverse(@)
module.exports.isnt = _isnt = (value, test, options) ->
if value isnt test then options.fn(@) else options.inverse(@)
module.exports.lt = lt = (value, test, options) ->
if value < test then options.fn(@) else options.inverse(@)
module.exports.lte = lte = (value, test, options) ->
if value <= test then options.fn(@) else options.inverse(@)
module.exports.or = _or = (testA, testB, options) ->
if testA or testB then options.fn(@) else options.inverse(@)
# Credit: Dan Harper (http://github.com/danharper)
# If Equals: if_eq this compare=that
module.exports.if_eq = if_eq = (context, options) ->
return options.fn(this) if context is options.hash.compare
options.inverse this
# Credit: Dan Harper (http://github.com/danharper)
# Unless Equals: unless_eq this compare=that
module.exports.unless_eq = unless_eq = (context, options) ->
return options.inverse(this) if context is options.hash.compare
options.fn this
# Credit: Dan Harper (http://github.com/danharper)
# If Greater Than: if_gt this compare=that
module.exports.if_gt = if_gt = (context, options) ->
return options.fn(this) if context > options.hash.compare
options.inverse this
# Credit: Dan Harper (http://github.com/danharper)
# Unless Greater Than: unless_gt this compare=that
module.exports.unless_gt = unless_gt = (context, options) ->
return options.inverse(this) if context > options.hash.compare
options.fn this
# Credit: Dan Harper (http://github.com/danharper)
# If Less Than: if_lt this compare=that
module.exports.if_lt = if_lt = (context, options) ->
return options.fn(this) if context < options.hash.compare
options.inverse this
# Credit: Dan Harper (http://github.com/danharper)
# Unless Less Than: unless_lt this compare=that
module.exports.unless_lt = unless_lt = (context, options) ->
return options.inverse(this) if context < options.hash.compare
options.fn this
# Credit: Dan Harper (http://github.com/danharper)
# If Greater Than or Equal To: if_gteq this compare=that
module.exports.if_gteq = if_gteq = (context, options) ->
return options.fn(this) if context >= options.hash.compare
options.inverse this
# Credit: Dan Harper (http://github.com/danharper)
# Unless Greater Than or Equal To: unless_gteq this compare=that
module.exports.unless_gteq = unless_gteq = (context, options) ->
return options.inverse(this) if context >= options.hash.compare
options.fn this
# Credit: Dan Harper (http://github.com/danharper)
# If Less Than or Equal To: if_lteq this compare=that
module.exports.if_lteq = if_lteq = (context, options) ->
return options.fn(this) if context <= options.hash.compare
options.inverse this
# Credit: Dan Harper (http://github.com/danharper)
# Unless Less Than or Equal To: unless_lteq this compare=that
module.exports.unless_lteq = unless_lteq = (context, options) ->
return options.inverse(this) if context <= options.hash.compare
options.fn this
# Credit: Dan Harper (http://github.com/danharper)
# Similar to {{#if}} block helper but accepts multiple arguments.
module.exports.ifAny = ifAny = ->
argLength = arguments_.length - 2
content = arguments_[argLength + 1]
success = true
i = 0
while i < argLength
unless arguments_[i]
success = false
break
i += 1
(if success then content(this) else content.inverse(this))
module.exports.register = (Handlebars, options) ->
Handlebars.registerHelper "and", _and
Handlebars.registerHelper "gt", gt
Handlebars.registerHelper "gte", gte
Handlebars.registerHelper "if_eq", if_eq
Handlebars.registerHelper "if_gt", if_gt
Handlebars.registerHelper "if_gteq", if_gteq
Handlebars.registerHelper "if_lt", if_lt
Handlebars.registerHelper "if_lteq", if_lteq
Handlebars.registerHelper "ifAny", ifAny
Handlebars.registerHelper "is", _is
Handlebars.registerHelper "isnt", _isnt
Handlebars.registerHelper "lt", lt
Handlebars.registerHelper "lte", lte
Handlebars.registerHelper "or", _or
Handlebars.registerHelper "unless_eq", unless_eq
Handlebars.registerHelper "unless_gt", unless_gt
Handlebars.registerHelper "unless_gteq", unless_gteq
Handlebars.registerHelper "unless_lt", unless_lt
Handlebars.registerHelper "unless_lteq", unless_lteq
@
| 40842 | ###! comparison helpers ###
module.exports.and = _and = (testA, testB, options) ->
if testA and testB then options.fn(@) else options.inverse(@)
module.exports.gt = gt = (value, test, options) ->
if value > test then options.fn(@) else options.inverse(@)
module.exports.gte = gte = (value, test, options) ->
if value >= test then options.fn(@) else options.inverse(@)
module.exports.is = _is = (value, test, options) ->
if value is test then options.fn(@) else options.inverse(@)
module.exports.isnt = _isnt = (value, test, options) ->
if value isnt test then options.fn(@) else options.inverse(@)
module.exports.lt = lt = (value, test, options) ->
if value < test then options.fn(@) else options.inverse(@)
module.exports.lte = lte = (value, test, options) ->
if value <= test then options.fn(@) else options.inverse(@)
module.exports.or = _or = (testA, testB, options) ->
if testA or testB then options.fn(@) else options.inverse(@)
# Credit: <NAME> (http://github.com/danharper)
# If Equals: if_eq this compare=that
module.exports.if_eq = if_eq = (context, options) ->
return options.fn(this) if context is options.hash.compare
options.inverse this
# Credit: <NAME> (http://github.com/danharper)
# Unless Equals: unless_eq this compare=that
module.exports.unless_eq = unless_eq = (context, options) ->
return options.inverse(this) if context is options.hash.compare
options.fn this
# Credit: <NAME> (http://github.com/danharper)
# If Greater Than: if_gt this compare=that
module.exports.if_gt = if_gt = (context, options) ->
return options.fn(this) if context > options.hash.compare
options.inverse this
# Credit: <NAME> (http://github.com/danharper)
# Unless Greater Than: unless_gt this compare=that
module.exports.unless_gt = unless_gt = (context, options) ->
return options.inverse(this) if context > options.hash.compare
options.fn this
# Credit: <NAME> (http://github.com/danharper)
# If Less Than: if_lt this compare=that
module.exports.if_lt = if_lt = (context, options) ->
return options.fn(this) if context < options.hash.compare
options.inverse this
# Credit: <NAME> (http://github.com/danharper)
# Unless Less Than: unless_lt this compare=that
module.exports.unless_lt = unless_lt = (context, options) ->
return options.inverse(this) if context < options.hash.compare
options.fn this
# Credit: <NAME> (http://github.com/danharper)
# If Greater Than or Equal To: if_gteq this compare=that
module.exports.if_gteq = if_gteq = (context, options) ->
return options.fn(this) if context >= options.hash.compare
options.inverse this
# Credit: <NAME> (http://github.com/danharper)
# Unless Greater Than or Equal To: unless_gteq this compare=that
module.exports.unless_gteq = unless_gteq = (context, options) ->
return options.inverse(this) if context >= options.hash.compare
options.fn this
# Credit: <NAME> (http://github.com/danharper)
# If Less Than or Equal To: if_lteq this compare=that
module.exports.if_lteq = if_lteq = (context, options) ->
return options.fn(this) if context <= options.hash.compare
options.inverse this
# Credit: <NAME> (http://github.com/danharper)
# Unless Less Than or Equal To: unless_lteq this compare=that
module.exports.unless_lteq = unless_lteq = (context, options) ->
return options.inverse(this) if context <= options.hash.compare
options.fn this
# Credit: <NAME> (http://github.com/danharper)
# Similar to {{#if}} block helper but accepts multiple arguments.
module.exports.ifAny = ifAny = ->
argLength = arguments_.length - 2
content = arguments_[argLength + 1]
success = true
i = 0
while i < argLength
unless arguments_[i]
success = false
break
i += 1
(if success then content(this) else content.inverse(this))
module.exports.register = (Handlebars, options) ->
Handlebars.registerHelper "and", _and
Handlebars.registerHelper "gt", gt
Handlebars.registerHelper "gte", gte
Handlebars.registerHelper "if_eq", if_eq
Handlebars.registerHelper "if_gt", if_gt
Handlebars.registerHelper "if_gteq", if_gteq
Handlebars.registerHelper "if_lt", if_lt
Handlebars.registerHelper "if_lteq", if_lteq
Handlebars.registerHelper "ifAny", ifAny
Handlebars.registerHelper "is", _is
Handlebars.registerHelper "isnt", _isnt
Handlebars.registerHelper "lt", lt
Handlebars.registerHelper "lte", lte
Handlebars.registerHelper "or", _or
Handlebars.registerHelper "unless_eq", unless_eq
Handlebars.registerHelper "unless_gt", unless_gt
Handlebars.registerHelper "unless_gteq", unless_gteq
Handlebars.registerHelper "unless_lt", unless_lt
Handlebars.registerHelper "unless_lteq", unless_lteq
@
| true | ###! comparison helpers ###
module.exports.and = _and = (testA, testB, options) ->
if testA and testB then options.fn(@) else options.inverse(@)
module.exports.gt = gt = (value, test, options) ->
if value > test then options.fn(@) else options.inverse(@)
module.exports.gte = gte = (value, test, options) ->
if value >= test then options.fn(@) else options.inverse(@)
module.exports.is = _is = (value, test, options) ->
if value is test then options.fn(@) else options.inverse(@)
module.exports.isnt = _isnt = (value, test, options) ->
if value isnt test then options.fn(@) else options.inverse(@)
module.exports.lt = lt = (value, test, options) ->
if value < test then options.fn(@) else options.inverse(@)
module.exports.lte = lte = (value, test, options) ->
if value <= test then options.fn(@) else options.inverse(@)
module.exports.or = _or = (testA, testB, options) ->
if testA or testB then options.fn(@) else options.inverse(@)
# Credit: PI:NAME:<NAME>END_PI (http://github.com/danharper)
# If Equals: if_eq this compare=that
module.exports.if_eq = if_eq = (context, options) ->
return options.fn(this) if context is options.hash.compare
options.inverse this
# Credit: PI:NAME:<NAME>END_PI (http://github.com/danharper)
# Unless Equals: unless_eq this compare=that
module.exports.unless_eq = unless_eq = (context, options) ->
return options.inverse(this) if context is options.hash.compare
options.fn this
# Credit: PI:NAME:<NAME>END_PI (http://github.com/danharper)
# If Greater Than: if_gt this compare=that
module.exports.if_gt = if_gt = (context, options) ->
return options.fn(this) if context > options.hash.compare
options.inverse this
# Credit: PI:NAME:<NAME>END_PI (http://github.com/danharper)
# Unless Greater Than: unless_gt this compare=that
module.exports.unless_gt = unless_gt = (context, options) ->
return options.inverse(this) if context > options.hash.compare
options.fn this
# Credit: PI:NAME:<NAME>END_PI (http://github.com/danharper)
# If Less Than: if_lt this compare=that
module.exports.if_lt = if_lt = (context, options) ->
return options.fn(this) if context < options.hash.compare
options.inverse this
# Credit: PI:NAME:<NAME>END_PI (http://github.com/danharper)
# Unless Less Than: unless_lt this compare=that
module.exports.unless_lt = unless_lt = (context, options) ->
return options.inverse(this) if context < options.hash.compare
options.fn this
# Credit: PI:NAME:<NAME>END_PI (http://github.com/danharper)
# If Greater Than or Equal To: if_gteq this compare=that
module.exports.if_gteq = if_gteq = (context, options) ->
return options.fn(this) if context >= options.hash.compare
options.inverse this
# Credit: PI:NAME:<NAME>END_PI (http://github.com/danharper)
# Unless Greater Than or Equal To: unless_gteq this compare=that
module.exports.unless_gteq = unless_gteq = (context, options) ->
return options.inverse(this) if context >= options.hash.compare
options.fn this
# Credit: PI:NAME:<NAME>END_PI (http://github.com/danharper)
# If Less Than or Equal To: if_lteq this compare=that
module.exports.if_lteq = if_lteq = (context, options) ->
return options.fn(this) if context <= options.hash.compare
options.inverse this
# Credit: PI:NAME:<NAME>END_PI (http://github.com/danharper)
# Unless Less Than or Equal To: unless_lteq this compare=that
module.exports.unless_lteq = unless_lteq = (context, options) ->
return options.inverse(this) if context <= options.hash.compare
options.fn this
# Credit: PI:NAME:<NAME>END_PI (http://github.com/danharper)
# Similar to {{#if}} block helper but accepts multiple arguments.
module.exports.ifAny = ifAny = ->
argLength = arguments_.length - 2
content = arguments_[argLength + 1]
success = true
i = 0
while i < argLength
unless arguments_[i]
success = false
break
i += 1
(if success then content(this) else content.inverse(this))
module.exports.register = (Handlebars, options) ->
Handlebars.registerHelper "and", _and
Handlebars.registerHelper "gt", gt
Handlebars.registerHelper "gte", gte
Handlebars.registerHelper "if_eq", if_eq
Handlebars.registerHelper "if_gt", if_gt
Handlebars.registerHelper "if_gteq", if_gteq
Handlebars.registerHelper "if_lt", if_lt
Handlebars.registerHelper "if_lteq", if_lteq
Handlebars.registerHelper "ifAny", ifAny
Handlebars.registerHelper "is", _is
Handlebars.registerHelper "isnt", _isnt
Handlebars.registerHelper "lt", lt
Handlebars.registerHelper "lte", lte
Handlebars.registerHelper "or", _or
Handlebars.registerHelper "unless_eq", unless_eq
Handlebars.registerHelper "unless_gt", unless_gt
Handlebars.registerHelper "unless_gteq", unless_gteq
Handlebars.registerHelper "unless_lt", unless_lt
Handlebars.registerHelper "unless_lteq", unless_lteq
@
|
[
{
"context": "udent\n studentDemo = new studentModel\n name: \"John New\"\n age: 17\n # Sync listener, for when a reques",
"end": 299,
"score": 0.9998787641525269,
"start": 291,
"tag": "NAME",
"value": "John New"
},
{
"context": "udent\n studentDemo = new studentModel\n n... | app/source/models.coffee | alexserver/learning-backbone | 0 | # Models testing
# At this point I'm doing sort of BDD describes, next step, do real BDD.
class studentModel extends Backbone.Model
urlRoot: '/students'
defaults:
name: "Unknown"
age: null
modelCreation = ->
# Creating one student
studentDemo = new studentModel
name: "John New"
age: 17
# Sync listener, for when a request has been done to API
studentDemo.on 'sync', (model, data) ->
console.log 'Model has been synced for insertion', data
# Inserting that student
studentDemo.save {},
success: (model, data) ->
console.log "Model has been saved ", data
modelDestroying data.id
modelChanges = ->
# Creating one student
studentDemo = new studentModel
name: "Alex Server"
age: 33
sex: "M"
city: "Playa del Carmen"
# Adding listener to change
studentDemo.on 'change', (model) ->
console.log 'Model has changed, generic on.change'
console.log 'Model Name has changed!' if model.hasChanged 'name'
console.log "Model previous name was #{model.previous('name')}" if model.hasChanged 'name'
console.log 'Model changed attributes are ', model.changedAttributes()
# Firing the changes
studentDemo.set 'name', 'Alejandro Gomez'
studentDemo.set 'age', 34
studentDemo.set 'city', 'Toronto'
modelFetchingExisting = ->
# Creating one student with existing id
studentDemo = new studentModel
id: 4
studentDemo.fetch
success: (model, data) ->
console.log "Model id:#{studentDemo.id} fetched: ", data
modelUpdating = ->
# Creating one student
studentDemo = new studentModel
id: 4
# Adding listener to sync
studentDemo.on 'sync', (model)->
console.log "Model has been sync for fetching/updating", @attributes
# Fetching data
studentDemo.fetch
success: (model, data)->
console.log "Model id:#{studentDemo.id} fetched for updating: ", data
# Updating the student. // Callback Hell !!
studentDemo.set 'name', 'George from the Jungle'
studentDemo.save()
modelDestroying = (newId) ->
# Creating one student
studentDemo = new studentModel
id: newId
# Adding listener to sync
studentDemo.on 'sync', (model, data) ->
console.log "Model has been synced for destroying", data
# Deleting the model previously created
studentDemo.destroy()
## MAIN processes
modelCreation()
modelChanges()
modelFetchingExisting()
modelUpdating() | 137818 | # Models testing
# At this point I'm doing sort of BDD describes, next step, do real BDD.
class studentModel extends Backbone.Model
urlRoot: '/students'
defaults:
name: "Unknown"
age: null
modelCreation = ->
# Creating one student
studentDemo = new studentModel
name: "<NAME>"
age: 17
# Sync listener, for when a request has been done to API
studentDemo.on 'sync', (model, data) ->
console.log 'Model has been synced for insertion', data
# Inserting that student
studentDemo.save {},
success: (model, data) ->
console.log "Model has been saved ", data
modelDestroying data.id
modelChanges = ->
# Creating one student
studentDemo = new studentModel
name: "<NAME>"
age: 33
sex: "M"
city: "Playa del Carmen"
# Adding listener to change
studentDemo.on 'change', (model) ->
console.log 'Model has changed, generic on.change'
console.log 'Model Name has changed!' if model.hasChanged 'name'
console.log "Model previous name was #{model.previous('name')}" if model.hasChanged 'name'
console.log 'Model changed attributes are ', model.changedAttributes()
# Firing the changes
studentDemo.set 'name', '<NAME>'
studentDemo.set 'age', 34
studentDemo.set 'city', 'Toronto'
modelFetchingExisting = ->
# Creating one student with existing id
studentDemo = new studentModel
id: 4
studentDemo.fetch
success: (model, data) ->
console.log "Model id:#{studentDemo.id} fetched: ", data
modelUpdating = ->
# Creating one student
studentDemo = new studentModel
id: 4
# Adding listener to sync
studentDemo.on 'sync', (model)->
console.log "Model has been sync for fetching/updating", @attributes
# Fetching data
studentDemo.fetch
success: (model, data)->
console.log "Model id:#{studentDemo.id} fetched for updating: ", data
# Updating the student. // Callback Hell !!
studentDemo.set 'name', '<NAME>'
studentDemo.save()
modelDestroying = (newId) ->
# Creating one student
studentDemo = new studentModel
id: newId
# Adding listener to sync
studentDemo.on 'sync', (model, data) ->
console.log "Model has been synced for destroying", data
# Deleting the model previously created
studentDemo.destroy()
## MAIN processes
modelCreation()
modelChanges()
modelFetchingExisting()
modelUpdating() | true | # Models testing
# At this point I'm doing sort of BDD describes, next step, do real BDD.
class studentModel extends Backbone.Model
urlRoot: '/students'
defaults:
name: "Unknown"
age: null
modelCreation = ->
# Creating one student
studentDemo = new studentModel
name: "PI:NAME:<NAME>END_PI"
age: 17
# Sync listener, for when a request has been done to API
studentDemo.on 'sync', (model, data) ->
console.log 'Model has been synced for insertion', data
# Inserting that student
studentDemo.save {},
success: (model, data) ->
console.log "Model has been saved ", data
modelDestroying data.id
modelChanges = ->
# Creating one student
studentDemo = new studentModel
name: "PI:NAME:<NAME>END_PI"
age: 33
sex: "M"
city: "Playa del Carmen"
# Adding listener to change
studentDemo.on 'change', (model) ->
console.log 'Model has changed, generic on.change'
console.log 'Model Name has changed!' if model.hasChanged 'name'
console.log "Model previous name was #{model.previous('name')}" if model.hasChanged 'name'
console.log 'Model changed attributes are ', model.changedAttributes()
# Firing the changes
studentDemo.set 'name', 'PI:NAME:<NAME>END_PI'
studentDemo.set 'age', 34
studentDemo.set 'city', 'Toronto'
modelFetchingExisting = ->
# Creating one student with existing id
studentDemo = new studentModel
id: 4
studentDemo.fetch
success: (model, data) ->
console.log "Model id:#{studentDemo.id} fetched: ", data
modelUpdating = ->
# Creating one student
studentDemo = new studentModel
id: 4
# Adding listener to sync
studentDemo.on 'sync', (model)->
console.log "Model has been sync for fetching/updating", @attributes
# Fetching data
studentDemo.fetch
success: (model, data)->
console.log "Model id:#{studentDemo.id} fetched for updating: ", data
# Updating the student. // Callback Hell !!
studentDemo.set 'name', 'PI:NAME:<NAME>END_PI'
studentDemo.save()
modelDestroying = (newId) ->
# Creating one student
studentDemo = new studentModel
id: newId
# Adding listener to sync
studentDemo.on 'sync', (model, data) ->
console.log "Model has been synced for destroying", data
# Deleting the model previously created
studentDemo.destroy()
## MAIN processes
modelCreation()
modelChanges()
modelFetchingExisting()
modelUpdating() |
[
{
"context": "n/lNf9lqz/wez/////Ke+vpgAAAK1JREFUSMft1sENhDAMBdFIrmBboAjuaWFrsNN/CRwAgUPsTAH556c5WVFKQyuLLYbZf/MLmDHW5yJmjHW5kBljPhczY8zlEmaMvXMZM8ZeuZQZY08uZzZh5dqen+XNhLFBbsiEsW9uzISxTy5gwlifi5gw1uVCJoz5XMyEMZdLmASs/s5NnkFl7M7NmDJ25aZMGTtzc6aMtcqYMtYqY8pYq4wpY60ypuvnsNizA+E6656TNMZlAAAAAElFTkSuQmCC\"\n\t\t\tla... | test/tests/LayerTest.coffee | antoniotrento/Framer | 0 | assert = require "assert"
{expect} = require "chai"
simulate = require "simulate"
describe "Layer", ->
# afterEach ->
# Utils.clearAll()
# beforeEach ->
# Framer.Utils.reset()
describe "Defaults", ->
it "should reset nested defaults", ->
Framer.Defaults.DeviceComponent.animationOptions.curve = "spring"
Framer.resetDefaults()
Framer.Defaults.DeviceComponent.animationOptions.curve.should.equal "ease-in-out"
it "should reset width and height to their previous values", ->
previousWidth = Framer.Defaults.Layer.width
previousHeight = Framer.Defaults.Layer.height
Framer.Defaults.Layer.width = 123
Framer.Defaults.Layer.height = 123
Framer.resetDefaults()
Framer.Defaults.Layer.width.should.equal previousWidth
Framer.Defaults.Layer.height.should.equal previousHeight
it "should set defaults", ->
width = Utils.randomNumber(0, 400)
height = Utils.randomNumber(0, 400)
Framer.Defaults =
Layer:
width: width
height: height
layer = new Layer()
layer.width.should.equal width
layer.height.should.equal height
Framer.resetDefaults()
layer = new Layer()
layer.width.should.equal 100
layer.height.should.equal 100
it "should set default background color", ->
# if the default background color is not set the content layer of scrollcomponent is not hidden when layers are added
layer = new Layer()
Color.equal(layer.backgroundColor, Framer.Defaults.Layer.backgroundColor).should.be.true
Framer.Defaults =
Layer:
backgroundColor: "red"
layer = new Layer()
layer.style.backgroundColor.should.equal new Color("red").toString()
Framer.resetDefaults()
it "should set defaults with override", ->
layer = new Layer x: 50, y: 60
layer.x.should.equal 50
layer.y.should.equal 60
it "should have default animationOptions", ->
layer = new Layer
layer.animationOptions.should.eql {}
describe "Properties", ->
it "should set defaults", ->
layer = new Layer()
layer.x.should.equal 0
layer.y.should.equal 0
layer.z.should.equal 0
layer.width.should.equal 100
layer.height.should.equal 100
it "should set width", ->
layer = new Layer width: 200
layer.width.should.equal 200
layer.style.width.should.equal "200px"
it "should set x not to scientific notation", ->
n = 0.000000000000002
n.toString().should.equal("2e-15")
layer = new Layer
layer.x = n
layer.y = 100
layer.style.webkitTransform.should.equal "translate3d(0px, 100px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set x, y and z to really small values", ->
layer = new Layer
layer.x = 10
layer.y = 10
layer.z = 10
layer.x = 1e-5
layer.y = 1e-6
layer.z = 1e-7
layer.x.should.equal 1e-5
layer.y.should.equal 1e-6
layer.z.should.equal 1e-7
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(0.00001px, 0.000001px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should handle scientific notation in scaleX, Y and Z", ->
layer = new Layer
layer.scaleX = 2
layer.scaleY = 2
layer.scaleZ = 3
layer.scaleX = 1e-7
layer.scaleY = 1e-8
layer.scaleZ = 1e-9
layer.scale = 1e-10
layer.scaleX.should.equal 1e-7
layer.scaleY.should.equal 1e-8
layer.scaleZ.should.equal 1e-9
layer.scale.should.equal 1e-10
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(0, 0, 0) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should handle scientific notation in skew", ->
layer = new Layer
layer.skew = 2
layer.skewX = 2
layer.skewY = 3
layer.skew = 1e-5
layer.skewX = 1e-6
layer.skewY = 1e-7
layer.skew.should.equal 1e-5
layer.skewX.should.equal 1e-6
layer.skewY.should.equal 1e-7
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0.00001deg, 0.00001deg) skewX(0.000001deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set x and y", ->
layer = new Layer
layer.x = 100
layer.x.should.equal 100
layer.y = 50
layer.y.should.equal 50
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(100px, 50px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should handle midX and midY when width and height are 0", ->
box = new Layer
midX: 200
midY: 300
width: 0
height: 0
box.x.should.equal 200
box.y.should.equal 300
it "should set scale", ->
layer = new Layer
layer.scaleX = 100
layer.scaleY = 100
layer.scaleZ = 100
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 50)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(100, 100, 100) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set origin", ->
layer = new Layer
originZ: 80
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.originX = 0.1
layer.originY = 0.2
layer.style.webkitTransformOrigin.should.equal "10% 20%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
layer.originX = 0.5
layer.originY = 0.5
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
it "should preserve 3D by default", ->
layer = new Layer
layer._element.style.webkitTransformStyle.should.equal "preserve-3d"
it "should flatten layer", ->
layer = new Layer
flat: true
layer._element.style.webkitTransformStyle.should.equal "flat"
it "should set local image", ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
layer = new Layer
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
layer.props.image.should.equal fullPath
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.not.equal(-1)
it "should set local image when listening to load events", (done) ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
layer = new Layer
layer.on Events.ImageLoaded, ->
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.not.equal(-1)
done()
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
layer.props.image.should.equal fullPath
layer.style["background-image"].indexOf(imagePath).should.equal(-1)
layer.style["background-image"].indexOf("file://").should.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.equal(-1)
#layer.computedStyle()["background-size"].should.equal "cover"
#layer.computedStyle()["background-repeat"].should.equal "no-repeat"
it "should not append nocache to a base64 encoded image", ->
fullPath = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEwAAABMBAMAAAA1uUwYAAAAAXNSR0IArs4c6QAAABVQTFRFKK/6LFj/g9n/lNf9lqz/wez/////Ke+vpgAAAK1JREFUSMft1sENhDAMBdFIrmBboAjuaWFrsNN/CRwAgUPsTAH556c5WVFKQyuLLYbZf/MLmDHW5yJmjHW5kBljPhczY8zlEmaMvXMZM8ZeuZQZY08uZzZh5dqen+XNhLFBbsiEsW9uzISxTy5gwlifi5gw1uVCJoz5XMyEMZdLmASs/s5NnkFl7M7NmDJ25aZMGTtzc6aMtcqYMtYqY8pYq4wpY60ypuvnsNizA+E6656TNMZlAAAAAElFTkSuQmCC"
layer = new Layer
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
image.should.equal fullPath
layer.style["background-image"].indexOf(fullPath).should.not.equal(-1)
layer.style["background-image"].indexOf("data:").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.equal(-1)
it "should append nocache with an ampersand if url params already exist", (done) ->
prefix = "../"
imagePath = "static/test.png?param=foo"
fullPath = prefix + imagePath
layer = new Layer
layer.on Events.ImageLoaded, ->
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("&nocache=").should.not.equal(-1)
done()
layer.image = fullPath
layer.image.should.equal fullPath
it "should cancel loading when setting image to null", (done) ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
#First set the image directly to something
layer = new Layer
image: "static/test2.png"
#Now add event handlers
layer.on Events.ImageLoadCancelled, ->
layer.style["background-image"].indexOf(imagePath).should.equal(-1)
layer.style["background-image"].indexOf("file://").should.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.equal(-1)
done()
#so we preload the next image
layer.image = fullPath
#set the image no null to cancel the loading
layer.image = null
it "should set image", ->
imagePath = "../static/test.png"
layer = new Layer image: imagePath
layer.image.should.equal imagePath
it "should unset image with null", ->
layer = new Layer image: "../static/test.png"
layer.image = null
layer.image.should.equal ""
it "should unset image with empty string", ->
layer = new Layer image: "../static/test.png"
layer.image = ""
layer.image.should.equal ""
it "should test image property type", ->
f = ->
layer = new Layer
layer.image = {}
f.should.throw()
it "should set name on create", ->
layer = new Layer name: "Test"
layer.name.should.equal "Test"
layer._element.getAttribute("name").should.equal "Test"
it "should set name after create", ->
layer = new Layer
layer.name = "Test"
layer.name.should.equal "Test"
layer._element.getAttribute("name").should.equal "Test"
it "should handle false layer names correctly", ->
layer = new Layer
name: 0
layer.name.should.equal "0"
layer._element.getAttribute("name").should.equal "0"
it "should handle background color with image", ->
# We want the background color to be there until an images
# is set UNLESS we set another backgroundColor explicitly
imagePath = "../static/test.png"
layer = new Layer image: imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer
layer.image = imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer backgroundColor: "red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
layer = new Layer
layer.backgroundColor = "red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
it "should set visible", ->
layer = new Layer
layer.visible.should.equal true
layer.style["display"].should.equal "block"
layer.visible = false
layer.visible.should.equal false
layer.style["display"].should.equal "none"
it "should set clip", ->
layer = new Layer
layer.clip.should.equal false
layer.style["overflow"].should.equal "visible"
layer.clip = true
layer.style["overflow"].should.equal "hidden"
it "should set scroll", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
layer.scroll = false
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
it "should set scroll from properties", ->
layer = new Layer
layer.props = {scroll: false}
layer.scroll.should.equal false
layer.props = {scroll: true}
layer.scroll.should.equal true
it "should set scrollHorizontal", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.ignoreEvents.should.equal true
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
it "should disable ignore events when scroll is set from constructor", ->
layerA = new Layer
scroll: true
layerA.ignoreEvents.should.equal false
it "should set style properties on create", ->
layer = new Layer backgroundColor: "red"
layer.backgroundColor.isEqual(new Color("red")).should.equal true
layer.style["backgroundColor"].should.equal new Color("red").toString()
it "should check value type", ->
f = ->
layer = new Layer
layer.x = "hello"
f.should.throw()
it "should set perspective", ->
layer = new Layer
layer.perspective = 500
layer.style["-webkit-perspective"].should.equal("500")
it "should have a default perspective of 0", ->
layer = new Layer
layer._element.style["webkitPerspective"].should.equal "none"
layer.perspective.should.equal 0
it "should allow the perspective to be changed", ->
layer = new Layer
layer.perspective = 800
layer.perspective.should.equal 800
layer._element.style["webkitPerspective"].should.equal "800"
it "should set the perspective to 'none' if set to 0", ->
layer = new Layer
layer.perspective = 0
layer.perspective.should.equal 0
layer._element.style["webkitPerspective"].should.equal "none"
it "should set the perspective to 'none' if set to none", ->
layer = new Layer
layer.perspective = "none"
layer.perspective.should.equal "none"
layer._element.style["webkitPerspective"].should.equal "none"
it "should set the perspective to 'none' if set to null", ->
layer = new Layer
layer.perspective = null
layer.perspective.should.equal 0
layer._element.style["webkitPerspective"].should.equal "none"
it "should not allow setting the perspective to random string", ->
layer = new Layer
(-> layer.perspective = "bla").should.throw("Layer.perspective: value 'bla' of type 'string' is not valid")
layer.perspective.should.equal 0
layer._element.style["webkitPerspective"].should.equal "none"
it "should have its backface visible by default", ->
layer = new Layer
layer.style["webkitBackfaceVisibility"].should.equal "visible"
it "should allow backface to be hidden", ->
layer = new Layer
layer.backfaceVisible = false
layer.style["webkitBackfaceVisibility"].should.equal "hidden"
it "should set rotation", ->
layer = new Layer
rotationX: 200
rotationY: 200
rotationZ: 200
layer.rotationX.should.equal(200)
layer.rotationY.should.equal(200)
layer.rotationZ.should.equal(200)
it "should proxy rotation", ->
layer = new Layer
layer.rotation = 200
layer.rotation.should.equal(200)
layer.rotationZ.should.equal(200)
layer.rotationZ = 100
layer.rotation.should.equal(100)
layer.rotationZ.should.equal(100)
it "should only set name when explicitly set", ->
layer = new Layer
layer.__framerInstanceInfo = {name: "aap"}
layer.name.should.equal ""
it "it should show the variable name in toInspect()", ->
layer = new Layer
layer.__framerInstanceInfo = {name: "aap"}
(_.startsWith layer.toInspect(), "<Layer aap id:").should.be.true
it "should set htmlIntrinsicSize", ->
layer = new Layer
assert.equal layer.htmlIntrinsicSize, null
layer.htmlIntrinsicSize = "aap"
assert.equal layer.htmlIntrinsicSize, null
layer.htmlIntrinsicSize =
width: 10
assert.equal layer.htmlIntrinsicSize, null
layer.htmlIntrinsicSize =
width: 10
height: 20
layer.htmlIntrinsicSize.should.eql({width: 10, height: 20})
layer.htmlIntrinsicSize = null
assert.equal layer.htmlIntrinsicSize, null
describe "Border Radius", ->
it "should set borderRadius", ->
testBorderRadius = (layer, value) ->
if layer.style["border-top-left-radius"] is "#{value}"
layer.style["border-top-left-radius"].should.equal "#{value}"
layer.style["border-top-right-radius"].should.equal "#{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value}"
else
layer.style["border-top-left-radius"].should.equal "#{value} #{value}"
layer.style["border-top-right-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value} #{value}"
layer = new Layer
layer.borderRadius = 10
layer.borderRadius.should.equal 10
testBorderRadius(layer, "10px")
layer.borderRadius = "50%"
layer.borderRadius.should.equal "50%"
testBorderRadius(layer, "50%")
it "should set borderRadius with objects", ->
testBorderRadius = (layer, tl, tr, bl, br) ->
layer.style["border-top-left-radius"].should.equal "#{tl}"
layer.style["border-top-right-radius"].should.equal "#{tr}"
layer.style["border-bottom-left-radius"].should.equal "#{bl}"
layer.style["border-bottom-right-radius"].should.equal "#{br}"
layer = new Layer
# No matching keys is an error
layer.borderRadius = {aap: 10, noot: 20, mies: 30}
layer.borderRadius.should.equal 0
testBorderRadius(layer, "0px", "0px", "0px", "0px")
# Arrays are not supported either
layer.borderRadius = [1, 2, 3, 4]
layer.borderRadius.should.equal 0
testBorderRadius(layer, "0px", "0px", "0px", "0px")
layer.borderRadius = {topLeft: 10}
layer.borderRadius.topLeft.should.equal 10
testBorderRadius(layer, "10px", "0px", "0px", "0px")
layer.borderRadius = {topLeft: 1, topRight: 2, bottomLeft: 3, bottomRight: 4}
layer.borderRadius.topLeft.should.equal 1
layer.borderRadius.bottomRight.should.equal 4
testBorderRadius(layer, "1px", "2px", "3px", "4px")
it "should copy borderRadius when set with an object", ->
layer = new Layer
borderRadius = {topLeft: 100}
layer.borderRadius = borderRadius
borderRadius.bottomRight = 100
layer.borderRadius.bottomRight.should.equal 0
it "should set sub-properties of borderRadius", ->
layer = new Layer
borderRadius: {topLeft: 100}
layer.borderRadius.bottomRight = 100
layer.borderRadius.topLeft.should.equal(100)
layer.borderRadius.bottomRight.should.equal(100)
layer.style["border-top-left-radius"].should.equal "100px"
layer.style["border-bottom-right-radius"].should.equal "100px"
describe "Border Width", ->
it "should copy borderWidth when set with an object", ->
layer = new Layer
borderWidth = {top: 100}
layer.borderWidth = borderWidth
borderWidth.bottom = 100
layer.borderWidth.bottom.should.equal 0
it "should set sub-properties of borderWidth", ->
layer = new Layer
borderWidth: {top: 10}
layer.borderWidth.bottom = 10
layer.borderWidth.top.should.equal(10)
layer.borderWidth.bottom.should.equal(10)
layer._elementBorder.style["border-top-width"].should.equal "10px"
layer._elementBorder.style["border-bottom-width"].should.equal "10px"
describe "Gradient", ->
it "should set gradient", ->
layer = new Layer
layer.gradient = new Gradient
start: "blue"
end: "red"
angle: 42
layer.gradient.start.isEqual("blue").should.be.true
layer.gradient.end.isEqual("red").should.be.true
layer.gradient.angle.should.equal(42)
layer.style["background-image"].should.equal("linear-gradient(42deg, rgb(0, 0, 255), rgb(255, 0, 0))")
layer.gradient =
start: "yellow"
end: "purple"
layer.gradient.angle.should.equal(0)
layer.style["background-image"].should.equal("linear-gradient(0deg, rgb(255, 255, 0), rgb(128, 0, 128))")
layer.gradient = null
layer.style["background-image"].should.equal("")
it "should copy gradients when set with an object", ->
layer = new Layer
gradient = new Gradient
start: "blue"
layer.gradient = gradient
gradient.start = "yellow"
layer.gradient.start.isEqual("blue").should.be.true
it "should set sub-properties of gradients", ->
layer = new Layer
gradient:
start: "blue"
layer.gradient.end = "yellow"
layer.gradient.start.isEqual("blue").should.be.true
layer.gradient.end.isEqual("yellow").should.be.true
layer.style["background-image"].should.equal("linear-gradient(0deg, rgb(0, 0, 255), rgb(255, 255, 0))")
describe "Filter Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.webkitFilter.should.equal ""
it "should set only the filter that is non default", ->
layer = new Layer
layer.blur = 10
layer.blur.should.equal 10
layer.style.webkitFilter.should.equal "blur(10px)"
layer.contrast = 50
layer.contrast.should.equal 50
layer.style.webkitFilter.should.equal "blur(10px) contrast(50%)"
describe "Shadow Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.boxShadow.should.equal ""
it "should set the shadow", ->
layer = new Layer
layer.shadowX = 10
layer.shadowY = 10
layer.shadowBlur = 10
layer.shadowSpread = 10
layer.shadowX.should.equal 10
layer.shadowY.should.equal 10
layer.shadowBlur.should.equal 10
layer.shadowSpread.should.equal 10
layer.style.boxShadow.should.equal "rgba(123, 123, 123, 0.498039) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = "red"
layer.shadowColor.r.should.equal 255
layer.shadowColor.g.should.equal 0
layer.shadowColor.b.should.equal 0
layer.shadowColor.a.should.equal 1
layer.style.boxShadow.should.equal "rgb(255, 0, 0) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = null
layer.style.boxShadow.should.equal "rgba(0, 0, 0, 0) 10px 10px 10px 10px"
it "should remove all events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on("test", handler)
layerA.removeAllListeners("test")
layerA.listeners("test").length.should.equal 0
it "should add and clean up dom events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
# But never more then one
layerA._domEventManager.listeners(Events.Click).length.should.equal(1)
layerA.removeAllListeners(Events.Click)
# And on removal, we should get rid of the dom event
layerA._domEventManager.listeners(Events.Click).length.should.equal(0)
it "should work with event helpers", (done) ->
layer = new Layer
layer.onMouseOver (event, aLayer) ->
aLayer.should.equal(layer)
@should.equal(layer)
done()
simulate.mouseover(layer._element)
it "should only pass dom events to the event manager", ->
layer = new Layer
layer.on Events.Click, ->
layer.on Events.Move, ->
layer._domEventManager.listenerEvents().should.eql([Events.Click])
describe "Hierarchy", ->
it "should insert in dom", ->
layer = new Layer
assert.equal layer._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layer.superLayer, null
it "should check superLayer", ->
f = -> layer = new Layer superLayer: 1
f.should.throw()
it "should add child", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
assert.equal layerB._element.parentNode, layerA._element
assert.equal layerB.superLayer, layerA
it "should remove child", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerB.superLayer = null
assert.equal layerB._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layerB.superLayer, null
it "should list children", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
assert.deepEqual layerA.children, [layerB, layerC]
layerB.superLayer = null
assert.equal layerA.children.length, 1
assert.deepEqual layerA.children, [layerC]
layerC.superLayer = null
assert.deepEqual layerA.children, []
it "should list sibling root layers", ->
layerA = new Layer
layerB = new Layer
layerC = new Layer
assert layerB in layerA.siblingLayers, true
assert layerC in layerA.siblingLayers, true
it "should list sibling layers", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
assert.deepEqual layerB.siblingLayers, [layerC]
assert.deepEqual layerC.siblingLayers, [layerB]
it "should list ancestors", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerB
assert.deepEqual layerC.ancestors(), [layerB, layerA]
it "should list descendants deeply", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerB
layerA.descendants.should.eql [layerB, layerC]
it "should list descendants", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
layerA.descendants.should.eql [layerB, layerC]
it "should set super/parent with property", ->
layerA = new Layer
layerB = new Layer
layerB.superLayer = layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
it "should set super/parent with with constructor", ->
layerA = new Layer
layerB = new Layer
superLayer: layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
describe "Layering", ->
it "should set at creation", ->
layer = new Layer index: 666
layer.index.should.equal 666
it "should change index", ->
layer = new Layer
layer.index = 666
layer.index.should.equal 666
it "should be in front for root", ->
layerA = new Layer
layerB = new Layer
assert.equal layerB.index, layerA.index + 1
it "should be in front", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should send back and front", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
layerC.sendToBack()
assert.equal layerB.index, 1
assert.equal layerC.index, -1
layerC.bringToFront()
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should place in front", ->
layerA = new Layer
layerB = new Layer superLayer: layerA # 1
layerC = new Layer superLayer: layerA # 2
layerD = new Layer superLayer: layerA # 3
layerB.placeBefore layerC
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 3
it "should place behind", ->
layerA = new Layer
layerB = new Layer superLayer: layerA # 1
layerC = new Layer superLayer: layerA # 2
layerD = new Layer superLayer: layerA # 3
layerC.placeBehind layerB
# TODO: Still something fishy here, but it works
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 4
it "should get a children by name", ->
layerA = new Layer
layerB = new Layer name: "B", superLayer: layerA
layerC = new Layer name: "C", superLayer: layerA
layerD = new Layer name: "C", superLayer: layerA
layerA.childrenWithName("B").should.eql [layerB]
layerA.childrenWithName("C").should.eql [layerC, layerD]
it "should get a siblinglayer by name", ->
layerA = new Layer
layerB = new Layer name: "B", superLayer: layerA
layerC = new Layer name: "C", superLayer: layerA
layerD = new Layer name: "C", superLayer: layerA
layerB.siblingLayersByName("C").should.eql [layerC, layerD]
layerD.siblingLayersByName("B").should.eql [layerB]
it "should get a ancestors", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerB
layerC.ancestors().should.eql [layerB, layerA]
describe "Select Layer", ->
beforeEach ->
Framer.CurrentContext.reset()
it "should select the layer named B", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerA.selectChild('B').should.equal layerB
it "should select the layer named C", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerC = new Layer name: 'C', parent: layerB
layerA.selectChild('B > *').should.equal layerC
it "should have a static method `select`", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerC = new Layer name: 'C', parent: layerB
Layer.select('B > *').should.equal layerC
it "should have a method `selectAllChildren`", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerC = new Layer name: 'C', parent: layerB
layerD = new Layer name: 'D', parent: layerB
layerA.selectAllChildren('B > *').should.eql [layerC, layerD]
it "should have a static method `selectAll`", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA # asdas
layerC = new Layer name: 'C', parent: layerB
layerD = new Layer name: 'D', parent: layerB
Layer.selectAll('A *').should.eql [layerB, layerC, layerD]
describe "Frame", ->
it "should set on create", ->
layer = new Layer frame: {x: 111, y: 222, width: 333, height: 444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set after create", ->
layer = new Layer
layer.frame = {x: 111, y: 222, width: 333, height: 444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set minX on creation", ->
layer = new Layer minX: 200, y: 100, width: 100, height: 100
layer.x.should.equal 200
it "should set midX on creation", ->
layer = new Layer midX: 200, y: 100, width: 100, height: 100
layer.x.should.equal 150
it "should set maxX on creation", ->
layer = new Layer maxX: 200, y: 100, width: 100, height: 100
layer.x.should.equal 100
it "should set minY on creation", ->
layer = new Layer x: 100, minY: 200, width: 100, height: 100
layer.y.should.equal 200
it "should set midY on creation", ->
layer = new Layer x: 100, midY: 200, width: 100, height: 100
layer.y.should.equal 150
it "should set maxY on creation", ->
layer = new Layer x: 100, maxY: 200, width: 100, height: 100
layer.y.should.equal 100
it "should set minX", ->
layer = new Layer y: 100, width: 100, height: 100
layer.minX = 200
layer.x.should.equal 200
it "should set midX", ->
layer = new Layer y: 100, width: 100, height: 100
layer.midX = 200
layer.x.should.equal 150
it "should set maxX", ->
layer = new Layer y: 100, width: 100, height: 100
layer.maxX = 200
layer.x.should.equal 100
it "should set minY", ->
layer = new Layer x: 100, width: 100, height: 100
layer.minY = 200
layer.y.should.equal 200
it "should set midY", ->
layer = new Layer x: 100, width: 100, height: 100
layer.midY = 200
layer.y.should.equal 150
it "should set maxY", ->
layer = new Layer x: 100, width: 100, height: 100
layer.maxY = 200
layer.y.should.equal 100
it "should get and set canvasFrame", ->
layerA = new Layer x: 100, y: 100, width: 100, height: 100
layerB = new Layer x: 300, y: 300, width: 100, height: 100, superLayer: layerA
assert.equal layerB.canvasFrame.x, 400
assert.equal layerB.canvasFrame.y, 400
layerB.canvasFrame = {x: 1000, y: 1000}
assert.equal layerB.canvasFrame.x, 1000
assert.equal layerB.canvasFrame.y, 1000
assert.equal layerB.x, 900
assert.equal layerB.y, 900
layerB.superLayer = null
assert.equal layerB.canvasFrame.x, 900
assert.equal layerB.canvasFrame.y, 900
it "should calculate scale", ->
layerA = new Layer scale: 0.9
layerB = new Layer scale: 0.8, superLayer: layerA
layerB.screenScaleX().should.equal 0.9 * 0.8
layerB.screenScaleY().should.equal 0.9 * 0.8
it "should calculate scaled frame", ->
layerA = new Layer x: 100, width: 500, height: 900, scale: 0.5
layerA.scaledFrame().should.eql {"x": 225, "y": 225, "width": 250, "height": 450}
it "should calculate scaled screen frame", ->
layerA = new Layer x: 100, width: 500, height: 900, scale: 0.5
layerB = new Layer y: 50, width: 600, height: 600, scale: 0.8, superLayer: layerA
layerC = new Layer y: -60, width: 800, height: 700, scale: 1.2, superLayer: layerB
layerA.screenScaledFrame().should.eql {"x": 225, "y": 225, "width": 250, "height": 450}
layerB.screenScaledFrame().should.eql {"x": 255, "y": 280, "width": 240, "height": 240}
layerC.screenScaledFrame().should.eql {"x": 223, "y": 228, "width": 384, "height": 336}
it "should accept point shortcut", ->
layer = new Layer point: 10
layer.x.should.equal 10
layer.y.should.equal 10
it "should accept size shortcut", ->
layer = new Layer size: 10
layer.width.should.equal 10
layer.height.should.equal 10
describe "Center", ->
it "should center", ->
layerA = new Layer width: 200, height: 200
layerB = new Layer width: 100, height: 100, superLayer: layerA
layerB.center()
assert.equal layerB.x, 50
assert.equal layerB.y, 50
it "should center with offset", ->
layerA = new Layer width: 200, height: 200
layerB = new Layer width: 100, height: 100, superLayer: layerA
layerB.centerX(50)
layerB.centerY(50)
assert.equal layerB.x, 100
assert.equal layerB.y, 100
it "should center return layer", ->
layerA = new Layer width: 200, height: 200
layerA.center().should.equal layerA
layerA.centerX().should.equal layerA
layerA.centerY().should.equal layerA
it "should center pixel align", ->
layerA = new Layer width: 200, height: 200
layerB = new Layer width: 111, height: 111, superLayer: layerA
layerB.center().pixelAlign()
assert.equal layerB.x, 44
assert.equal layerB.y, 44
it "should center with border", ->
layer = new Layer
width: 200
height: 200
layer.borderColor = "green"
layer.borderWidth = 30
layer.center()
layerB = new Layer
superLayer: layer
backgroundColor: "red"
layerB.center()
layerB.frame.should.eql {x: 20, y: 20, width: 100, height: 100}
it "should center within outer frame", ->
layerA = new Layer width: 10, height: 10
layerA.center()
assert.equal layerA.x, 195
assert.equal layerA.y, 145
it "should center correctly with dpr set", ->
device = new DeviceComponent()
device.deviceType = "apple-iphone-7-black"
device.context.run ->
layerA = new Layer size: 100
layerA.center()
layerA.context.devicePixelRatio.should.equal 2
layerA.x.should.equal 137
layerA.y.should.equal 283
describe "CSS", ->
it "classList should work", ->
layer = new Layer
layer.classList.add "test"
assert.equal layer.classList.contains("test"), true
assert.equal layer._element.classList.contains("test"), true
describe "DOM", ->
it "should destroy", ->
layer = new Layer
layer.destroy()
(layer in Framer.CurrentContext.layers).should.be.false
assert.equal layer._element.parentNode, null
it "should set text", ->
layer = new Layer
layer.html = "Hello"
layer._element.childNodes[0].should.equal layer._elementHTML
layer._elementHTML.innerHTML.should.equal "Hello"
layer.ignoreEvents.should.equal true
it "should not effect children", ->
layer = new Layer
layer.html = "Hello"
Child = new Layer superLayer: layer
Child._element.offsetTop.should.equal 0
it "should set interactive html and allow pointer events", ->
tags = ["input", "select", "textarea", "option"]
html = ""
for tag in tags
html += "<#{tag}></#{tag}>"
layer = new Layer
layer.html = html
for tag in tags
element = layer.querySelectorAll(tag)[0]
style = window.getComputedStyle(element)
style["pointer-events"].should.equal "auto"
# style["-webkit-user-select"].should.equal "auto"
it "should work with querySelectorAll", ->
layer = new Layer
layer.html = "<input type='button' id='hello'>"
inputElements = layer.querySelectorAll("input")
inputElements.length.should.equal 1
inputElement = _.head(inputElements)
inputElement.getAttribute("id").should.equal "hello"
describe "Force 2D", ->
it "should switch to 2d rendering", ->
layer = new Layer
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
layer.force2d = true
layer.style.webkitTransform.should.equal "translate(0px, 0px) scale(1, 1) skew(0deg, 0deg) rotate(0deg)"
describe "Matrices", ->
it "should have the correct matrix", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
layer.matrix.toString().should.eql "matrix(1.957079, 1.957079, -0.871348, 0.871348, 200.000000, 120.000000)"
it "should have the correct matrix when 2d is forced", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
force2d: true
layer.matrix.toString().should.eql "matrix(2.165466, 1.957079, -1.079734, 0.871348, 200.000000, 120.000000)"
it "should have the correct transform matrix", ->
layer = new Layer
scale: 20
rotation: 5
rotationY: 20
x: 200
y: 120
skew: 21
layer.transformMatrix.toString().should.eql "matrix3d(19.391455, 8.929946, -0.340719, 0.000000, 6.010074, 19.295128, 0.029809, 0.000000, 6.840403, 2.625785, 0.939693, 0.000000, -1020.076470, -1241.253701, 15.545482, 1.000000)"
it "should have the correct screen point", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
roundX = Math.round(layer.convertPointToScreen().x)
roundX.should.eql 184
it "should have the correct screen frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.screenFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 132
boundingBox.height.should.eql 144
it "should use Framer.Defaults when setting the screen frame", ->
Framer.Defaults.Layer.width = 300
Framer.Defaults.Layer.height = 400
box = new Layer
screenFrame:
x: 123
box.stateCycle()
box.x.should.equal 123
box.width.should.equal 300
box.height.should.equal 400
Framer.resetDefaults()
it "should have the correct canvas frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.canvasFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 132
boundingBox.height.should.eql 144
describe "Copy", ->
it "copied Layer should hold set props", ->
X = 100
Y = 200
IMAGE = "../static/test.png"
BORDERRADIUS = 20
layer = new Layer
x: X
y: Y
image: IMAGE
layer.borderRadius = BORDERRADIUS
layer.x.should.eql X
layer.y.should.eql Y
layer.image.should.eql IMAGE
layer.borderRadius.should.eql BORDERRADIUS
copy = layer.copy()
copy.x.should.eql X
copy.y.should.eql Y
copy.image.should.eql IMAGE
copy.borderRadius.should.eql BORDERRADIUS
it "copied Layer should have defaults", ->
layer = new Layer
copy = layer.copy()
copy.width.should.equal 100
copy.height.should.equal 100
it "copied Layer should also copy styles", ->
layer = new Layer
style:
"font-family": "-apple-system"
"font-size": "1.2em"
"text-align": "right"
copy = layer.copy()
copy.style["font-family"].should.equal "-apple-system"
copy.style["font-size"].should.equal "1.2em"
copy.style["text-align"].should.equal "right"
describe "Point conversion", ->
it "should correctly convert points from layer to Screen", ->
point =
x: 200
y: 300
layer = new Layer point: point
screenPoint = layer.convertPointToScreen()
screenPoint.x.should.equal point.x
screenPoint.y.should.equal point.y
it "should correctly convert points from Screen to layer", ->
point =
x: 300
y: 200
layer = new Layer point: point
layerPoint = Screen.convertPointToLayer({}, layer)
layerPoint.x.should.equal -point.x
layerPoint.y.should.equal -point.y
it "should correctly convert points from layer to layer", ->
layerBOffset =
x: 200
y: 400
layerA = new Layer
layerB = new Layer point: layerBOffset
layerAToLayerBPoint = layerA.convertPointToLayer({}, layerB)
layerAToLayerBPoint.x.should.equal -layerBOffset.x
layerAToLayerBPoint.y.should.equal -layerBOffset.y
it "should correctly convert points when layers are nested", ->
layerBOffset =
x: 0
y: 200
layerA = new Layer
layerB = new Layer
parent: layerA
point: layerBOffset
rotation: 90
originX: 0
originY: 0
layerAToLayerBPoint = layerA.convertPointToLayer({}, layerB)
layerAToLayerBPoint.x.should.equal -layerBOffset.y
it "should correctly convert points between multiple layers and transforms", ->
layerA = new Layer
x: 275
layerB = new Layer
y: 400
x: 400
scale: 2
parent: layerA
layerC = new Layer
x: -200
y: 100
rotation: 180
originX: 0
originY: 0
parent: layerB
screenToLayerCPoint = Screen.convertPointToLayer(null, layerC)
screenToLayerCPoint.x.should.equal 112.5
screenToLayerCPoint.y.should.equal 275
it "should correctly convert points from the Canvas to a layer", ->
layerA = new Layer
scale: 2
layerB = new Layer
parent: layerA
originY: 1
rotation: 90
canvasToLayerBPoint = Canvas.convertPointToLayer({}, layerB)
canvasToLayerBPoint.x.should.equal -25
canvasToLayerBPoint.y.should.equal 125
describe "Device Pixel Ratio", ->
it "should default to 1", ->
a = new Layer
a.context.devicePixelRatio.should.equal 1
it "should change all of a layers children", ->
context = new Framer.Context(name: "Test")
context.run ->
a = new Layer
b = new Layer
parent: a
c = new Layer
parent: b
a.context.devicePixelRatio = 3
for l in [a, b, c]
l._element.style.width.should.equal "300px"
describe "containers", ->
it "should return empty when called on rootLayer", ->
a = new Layer name: "a"
a.containers().should.deep.equal []
it "should return all ancestors", ->
a = new Layer name: "a"
b = new Layer parent: a, name: "b"
c = new Layer parent: b, name: "c"
d = new Layer parent: c, name: "d"
names = d.containers().map (l) -> l.name
names.should.deep.equal ["c", "b", "a"]
it "should include the device return all ancestors", ->
device = new DeviceComponent()
device.context.run ->
a = new Layer name: "a"
b = new Layer parent: a, name: "b"
c = new Layer parent: b, name: "c"
d = new Layer parent: c, name: "d"
containers = d.containers(true)
containers.length.should.equal 10
names = containers.map((l) -> l.name)
names.should.eql ["c", "b", "a", undefined, "viewport", "screen", "phone", "phone", "hands", undefined]
describe "constraintValues", ->
it "layout should not break constraints", ->
l = new Layer
x: 100
constraintValues:
aspectRatioLocked: true
l.x.should.equal 100
l.layout()
l.x.should.equal 0
assert.notEqual l.constraintValues, null
it "should break all constraints when setting x", ->
l = new Layer
x: 100
constraintValues:
aspectRatioLocked: true
l.x.should.equal 100
assert.notEqual l.constraintValues, null
l.x = 50
assert.equal l.constraintValues, null
it "should break all constraints when setting y", ->
l = new Layer
y: 100
constraintValues:
aspectRatioLocked: true
l.y.should.equal 100
assert.notEqual l.constraintValues, null
l.y = 50
assert.equal l.constraintValues, null
it "should update the width constraint when setting width", ->
l = new Layer
width: 100
constraintValues:
aspectRatioLocked: true
l.width.should.equal 100
assert.notEqual l.constraintValues, null
l.width = 50
l.constraintValues.width.should.equal 50
it "should update the height constraint when setting height", ->
l = new Layer
height: 100
constraintValues:
aspectRatioLocked: true
l.height.should.equal 100
assert.notEqual l.constraintValues, null
l.height = 50
l.constraintValues.height.should.equal 50
it "should disable the aspectRatioLock and widthFactor constraint when setting width", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
widthFactor: 0.5
width: null
l.layout()
l.width.should.equal 200
assert.notEqual l.constraintValues, null
l.width = 50
l.constraintValues.aspectRatioLocked.should.equal false
assert.equal l.constraintValues.widthFactor, null
it "should disable the aspectRatioLock and heightFactor constraint when setting height", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
heightFactor: 0.5
height: null
l.layout()
l.height.should.equal 150
assert.notEqual l.constraintValues, null
l.height = 50
assert.equal l.constraintValues.heightFactor, null
it "should update the x position when changing width", ->
l = new Layer
width: 100
constraintValues:
left: null
right: 20
l.layout()
l.width.should.equal 100
l.x.should.equal 280
assert.notEqual l.constraintValues, null
l.width = 50
l.x.should.equal 330
it "should update the y position when changing height", ->
l = new Layer
height: 100
constraintValues:
top: null
bottom: 20
l.layout()
l.height.should.equal 100
l.y.should.equal 180
assert.notEqual l.constraintValues, null
l.height = 50
l.y.should.equal 230
it "should update to center the layer when center() is called", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
l.layout()
l.center()
l.x.should.equal 150
l.y.should.equal 100
assert.equal l.constraintValues.left, null
assert.equal l.constraintValues.right, null
assert.equal l.constraintValues.top, null
assert.equal l.constraintValues.bottom, null
assert.equal l.constraintValues.centerAnchorX, 0.5
assert.equal l.constraintValues.centerAnchorY, 0.5
it "should update to center the layer vertically when centerX() is called", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
l.layout()
l.x.should.equal 0
l.centerX()
l.x.should.equal 150
assert.equal l.constraintValues.left, null
assert.equal l.constraintValues.right, null
assert.equal l.constraintValues.centerAnchorX, 0.5
it "should update to center the layer horizontally when centerY() is called", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
l.layout()
l.y.should.equal 0
l.centerY()
l.y.should.equal 100
assert.equal l.constraintValues.top, null
assert.equal l.constraintValues.bottom, null
assert.equal l.constraintValues.centerAnchorY, 0.5
describe "when no constraints are set", ->
it "should not set the width constraint when setting the width", ->
l = new Layer
width: 100
l.width.should.equal 100
assert.equal l.constraintValues, null
l.width = 50
assert.equal l.constraintValues, null
it "should not set the height constraint when setting the height", ->
l = new Layer
height: 100
l.height.should.equal 100
assert.equal l.constraintValues, null
l.height = 50
assert.equal l.constraintValues, null
| 70436 | assert = require "assert"
{expect} = require "chai"
simulate = require "simulate"
describe "Layer", ->
# afterEach ->
# Utils.clearAll()
# beforeEach ->
# Framer.Utils.reset()
describe "Defaults", ->
it "should reset nested defaults", ->
Framer.Defaults.DeviceComponent.animationOptions.curve = "spring"
Framer.resetDefaults()
Framer.Defaults.DeviceComponent.animationOptions.curve.should.equal "ease-in-out"
it "should reset width and height to their previous values", ->
previousWidth = Framer.Defaults.Layer.width
previousHeight = Framer.Defaults.Layer.height
Framer.Defaults.Layer.width = 123
Framer.Defaults.Layer.height = 123
Framer.resetDefaults()
Framer.Defaults.Layer.width.should.equal previousWidth
Framer.Defaults.Layer.height.should.equal previousHeight
it "should set defaults", ->
width = Utils.randomNumber(0, 400)
height = Utils.randomNumber(0, 400)
Framer.Defaults =
Layer:
width: width
height: height
layer = new Layer()
layer.width.should.equal width
layer.height.should.equal height
Framer.resetDefaults()
layer = new Layer()
layer.width.should.equal 100
layer.height.should.equal 100
it "should set default background color", ->
# if the default background color is not set the content layer of scrollcomponent is not hidden when layers are added
layer = new Layer()
Color.equal(layer.backgroundColor, Framer.Defaults.Layer.backgroundColor).should.be.true
Framer.Defaults =
Layer:
backgroundColor: "red"
layer = new Layer()
layer.style.backgroundColor.should.equal new Color("red").toString()
Framer.resetDefaults()
it "should set defaults with override", ->
layer = new Layer x: 50, y: 60
layer.x.should.equal 50
layer.y.should.equal 60
it "should have default animationOptions", ->
layer = new Layer
layer.animationOptions.should.eql {}
describe "Properties", ->
it "should set defaults", ->
layer = new Layer()
layer.x.should.equal 0
layer.y.should.equal 0
layer.z.should.equal 0
layer.width.should.equal 100
layer.height.should.equal 100
it "should set width", ->
layer = new Layer width: 200
layer.width.should.equal 200
layer.style.width.should.equal "200px"
it "should set x not to scientific notation", ->
n = 0.000000000000002
n.toString().should.equal("2e-15")
layer = new Layer
layer.x = n
layer.y = 100
layer.style.webkitTransform.should.equal "translate3d(0px, 100px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set x, y and z to really small values", ->
layer = new Layer
layer.x = 10
layer.y = 10
layer.z = 10
layer.x = 1e-5
layer.y = 1e-6
layer.z = 1e-7
layer.x.should.equal 1e-5
layer.y.should.equal 1e-6
layer.z.should.equal 1e-7
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(0.00001px, 0.000001px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should handle scientific notation in scaleX, Y and Z", ->
layer = new Layer
layer.scaleX = 2
layer.scaleY = 2
layer.scaleZ = 3
layer.scaleX = 1e-7
layer.scaleY = 1e-8
layer.scaleZ = 1e-9
layer.scale = 1e-10
layer.scaleX.should.equal 1e-7
layer.scaleY.should.equal 1e-8
layer.scaleZ.should.equal 1e-9
layer.scale.should.equal 1e-10
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(0, 0, 0) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should handle scientific notation in skew", ->
layer = new Layer
layer.skew = 2
layer.skewX = 2
layer.skewY = 3
layer.skew = 1e-5
layer.skewX = 1e-6
layer.skewY = 1e-7
layer.skew.should.equal 1e-5
layer.skewX.should.equal 1e-6
layer.skewY.should.equal 1e-7
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0.00001deg, 0.00001deg) skewX(0.000001deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set x and y", ->
layer = new Layer
layer.x = 100
layer.x.should.equal 100
layer.y = 50
layer.y.should.equal 50
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(100px, 50px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should handle midX and midY when width and height are 0", ->
box = new Layer
midX: 200
midY: 300
width: 0
height: 0
box.x.should.equal 200
box.y.should.equal 300
it "should set scale", ->
layer = new Layer
layer.scaleX = 100
layer.scaleY = 100
layer.scaleZ = 100
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 50)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(100, 100, 100) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set origin", ->
layer = new Layer
originZ: 80
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.originX = 0.1
layer.originY = 0.2
layer.style.webkitTransformOrigin.should.equal "10% 20%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
layer.originX = 0.5
layer.originY = 0.5
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
it "should preserve 3D by default", ->
layer = new Layer
layer._element.style.webkitTransformStyle.should.equal "preserve-3d"
it "should flatten layer", ->
layer = new Layer
flat: true
layer._element.style.webkitTransformStyle.should.equal "flat"
it "should set local image", ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
layer = new Layer
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
layer.props.image.should.equal fullPath
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.not.equal(-1)
it "should set local image when listening to load events", (done) ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
layer = new Layer
layer.on Events.ImageLoaded, ->
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.not.equal(-1)
done()
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
layer.props.image.should.equal fullPath
layer.style["background-image"].indexOf(imagePath).should.equal(-1)
layer.style["background-image"].indexOf("file://").should.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.equal(-1)
#layer.computedStyle()["background-size"].should.equal "cover"
#layer.computedStyle()["background-repeat"].should.equal "no-repeat"
it "should not append nocache to a base64 encoded image", ->
fullPath = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEwAAABMBAMAAAA1uUwYAAAAAXNSR0IArs4c6QAAABVQTFRFKK/6LFj/g9n/lNf9lqz/wez/////Ke+vpgAAAK1JREFUSMft1sENhDAMBdFI<KEY>"
layer = new Layer
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
image.should.equal fullPath
layer.style["background-image"].indexOf(fullPath).should.not.equal(-1)
layer.style["background-image"].indexOf("data:").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.equal(-1)
it "should append nocache with an ampersand if url params already exist", (done) ->
prefix = "../"
imagePath = "static/test.png?param=foo"
fullPath = prefix + imagePath
layer = new Layer
layer.on Events.ImageLoaded, ->
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("&nocache=").should.not.equal(-1)
done()
layer.image = fullPath
layer.image.should.equal fullPath
it "should cancel loading when setting image to null", (done) ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
#First set the image directly to something
layer = new Layer
image: "static/test2.png"
#Now add event handlers
layer.on Events.ImageLoadCancelled, ->
layer.style["background-image"].indexOf(imagePath).should.equal(-1)
layer.style["background-image"].indexOf("file://").should.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.equal(-1)
done()
#so we preload the next image
layer.image = fullPath
#set the image no null to cancel the loading
layer.image = null
it "should set image", ->
imagePath = "../static/test.png"
layer = new Layer image: imagePath
layer.image.should.equal imagePath
it "should unset image with null", ->
layer = new Layer image: "../static/test.png"
layer.image = null
layer.image.should.equal ""
it "should unset image with empty string", ->
layer = new Layer image: "../static/test.png"
layer.image = ""
layer.image.should.equal ""
it "should test image property type", ->
f = ->
layer = new Layer
layer.image = {}
f.should.throw()
it "should set name on create", ->
layer = new Layer name: "Test"
layer.name.should.equal "Test"
layer._element.getAttribute("name").should.equal "Test"
it "should set name after create", ->
layer = new Layer
layer.name = "Test"
layer.name.should.equal "Test"
layer._element.getAttribute("name").should.equal "Test"
it "should handle false layer names correctly", ->
layer = new Layer
name: 0
layer.name.should.equal "0"
layer._element.getAttribute("name").should.equal "0"
it "should handle background color with image", ->
# We want the background color to be there until an images
# is set UNLESS we set another backgroundColor explicitly
imagePath = "../static/test.png"
layer = new Layer image: imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer
layer.image = imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer backgroundColor: "red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
layer = new Layer
layer.backgroundColor = "red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
it "should set visible", ->
layer = new Layer
layer.visible.should.equal true
layer.style["display"].should.equal "block"
layer.visible = false
layer.visible.should.equal false
layer.style["display"].should.equal "none"
it "should set clip", ->
layer = new Layer
layer.clip.should.equal false
layer.style["overflow"].should.equal "visible"
layer.clip = true
layer.style["overflow"].should.equal "hidden"
it "should set scroll", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
layer.scroll = false
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
it "should set scroll from properties", ->
layer = new Layer
layer.props = {scroll: false}
layer.scroll.should.equal false
layer.props = {scroll: true}
layer.scroll.should.equal true
it "should set scrollHorizontal", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.ignoreEvents.should.equal true
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
it "should disable ignore events when scroll is set from constructor", ->
layerA = new Layer
scroll: true
layerA.ignoreEvents.should.equal false
it "should set style properties on create", ->
layer = new Layer backgroundColor: "red"
layer.backgroundColor.isEqual(new Color("red")).should.equal true
layer.style["backgroundColor"].should.equal new Color("red").toString()
it "should check value type", ->
f = ->
layer = new Layer
layer.x = "hello"
f.should.throw()
it "should set perspective", ->
layer = new Layer
layer.perspective = 500
layer.style["-webkit-perspective"].should.equal("500")
it "should have a default perspective of 0", ->
layer = new Layer
layer._element.style["webkitPerspective"].should.equal "none"
layer.perspective.should.equal 0
it "should allow the perspective to be changed", ->
layer = new Layer
layer.perspective = 800
layer.perspective.should.equal 800
layer._element.style["webkitPerspective"].should.equal "800"
it "should set the perspective to 'none' if set to 0", ->
layer = new Layer
layer.perspective = 0
layer.perspective.should.equal 0
layer._element.style["webkitPerspective"].should.equal "none"
it "should set the perspective to 'none' if set to none", ->
layer = new Layer
layer.perspective = "none"
layer.perspective.should.equal "none"
layer._element.style["webkitPerspective"].should.equal "none"
it "should set the perspective to 'none' if set to null", ->
layer = new Layer
layer.perspective = null
layer.perspective.should.equal 0
layer._element.style["webkitPerspective"].should.equal "none"
it "should not allow setting the perspective to random string", ->
layer = new Layer
(-> layer.perspective = "bla").should.throw("Layer.perspective: value 'bla' of type 'string' is not valid")
layer.perspective.should.equal 0
layer._element.style["webkitPerspective"].should.equal "none"
it "should have its backface visible by default", ->
layer = new Layer
layer.style["webkitBackfaceVisibility"].should.equal "visible"
it "should allow backface to be hidden", ->
layer = new Layer
layer.backfaceVisible = false
layer.style["webkitBackfaceVisibility"].should.equal "hidden"
it "should set rotation", ->
layer = new Layer
rotationX: 200
rotationY: 200
rotationZ: 200
layer.rotationX.should.equal(200)
layer.rotationY.should.equal(200)
layer.rotationZ.should.equal(200)
it "should proxy rotation", ->
layer = new Layer
layer.rotation = 200
layer.rotation.should.equal(200)
layer.rotationZ.should.equal(200)
layer.rotationZ = 100
layer.rotation.should.equal(100)
layer.rotationZ.should.equal(100)
it "should only set name when explicitly set", ->
layer = new Layer
layer.__framerInstanceInfo = {name: "aap"}
layer.name.should.equal ""
it "it should show the variable name in toInspect()", ->
layer = new Layer
layer.__framerInstanceInfo = {name: "aap"}
(_.startsWith layer.toInspect(), "<Layer aap id:").should.be.true
it "should set htmlIntrinsicSize", ->
layer = new Layer
assert.equal layer.htmlIntrinsicSize, null
layer.htmlIntrinsicSize = "aap"
assert.equal layer.htmlIntrinsicSize, null
layer.htmlIntrinsicSize =
width: 10
assert.equal layer.htmlIntrinsicSize, null
layer.htmlIntrinsicSize =
width: 10
height: 20
layer.htmlIntrinsicSize.should.eql({width: 10, height: 20})
layer.htmlIntrinsicSize = null
assert.equal layer.htmlIntrinsicSize, null
describe "Border Radius", ->
it "should set borderRadius", ->
testBorderRadius = (layer, value) ->
if layer.style["border-top-left-radius"] is "#{value}"
layer.style["border-top-left-radius"].should.equal "#{value}"
layer.style["border-top-right-radius"].should.equal "#{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value}"
else
layer.style["border-top-left-radius"].should.equal "#{value} #{value}"
layer.style["border-top-right-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value} #{value}"
layer = new Layer
layer.borderRadius = 10
layer.borderRadius.should.equal 10
testBorderRadius(layer, "10px")
layer.borderRadius = "50%"
layer.borderRadius.should.equal "50%"
testBorderRadius(layer, "50%")
it "should set borderRadius with objects", ->
testBorderRadius = (layer, tl, tr, bl, br) ->
layer.style["border-top-left-radius"].should.equal "#{tl}"
layer.style["border-top-right-radius"].should.equal "#{tr}"
layer.style["border-bottom-left-radius"].should.equal "#{bl}"
layer.style["border-bottom-right-radius"].should.equal "#{br}"
layer = new Layer
# No matching keys is an error
layer.borderRadius = {aap: 10, noot: 20, mies: 30}
layer.borderRadius.should.equal 0
testBorderRadius(layer, "0px", "0px", "0px", "0px")
# Arrays are not supported either
layer.borderRadius = [1, 2, 3, 4]
layer.borderRadius.should.equal 0
testBorderRadius(layer, "0px", "0px", "0px", "0px")
layer.borderRadius = {topLeft: 10}
layer.borderRadius.topLeft.should.equal 10
testBorderRadius(layer, "10px", "0px", "0px", "0px")
layer.borderRadius = {topLeft: 1, topRight: 2, bottomLeft: 3, bottomRight: 4}
layer.borderRadius.topLeft.should.equal 1
layer.borderRadius.bottomRight.should.equal 4
testBorderRadius(layer, "1px", "2px", "3px", "4px")
it "should copy borderRadius when set with an object", ->
layer = new Layer
borderRadius = {topLeft: 100}
layer.borderRadius = borderRadius
borderRadius.bottomRight = 100
layer.borderRadius.bottomRight.should.equal 0
it "should set sub-properties of borderRadius", ->
layer = new Layer
borderRadius: {topLeft: 100}
layer.borderRadius.bottomRight = 100
layer.borderRadius.topLeft.should.equal(100)
layer.borderRadius.bottomRight.should.equal(100)
layer.style["border-top-left-radius"].should.equal "100px"
layer.style["border-bottom-right-radius"].should.equal "100px"
describe "Border Width", ->
it "should copy borderWidth when set with an object", ->
layer = new Layer
borderWidth = {top: 100}
layer.borderWidth = borderWidth
borderWidth.bottom = 100
layer.borderWidth.bottom.should.equal 0
it "should set sub-properties of borderWidth", ->
layer = new Layer
borderWidth: {top: 10}
layer.borderWidth.bottom = 10
layer.borderWidth.top.should.equal(10)
layer.borderWidth.bottom.should.equal(10)
layer._elementBorder.style["border-top-width"].should.equal "10px"
layer._elementBorder.style["border-bottom-width"].should.equal "10px"
describe "Gradient", ->
it "should set gradient", ->
layer = new Layer
layer.gradient = new Gradient
start: "blue"
end: "red"
angle: 42
layer.gradient.start.isEqual("blue").should.be.true
layer.gradient.end.isEqual("red").should.be.true
layer.gradient.angle.should.equal(42)
layer.style["background-image"].should.equal("linear-gradient(42deg, rgb(0, 0, 255), rgb(255, 0, 0))")
layer.gradient =
start: "yellow"
end: "purple"
layer.gradient.angle.should.equal(0)
layer.style["background-image"].should.equal("linear-gradient(0deg, rgb(255, 255, 0), rgb(128, 0, 128))")
layer.gradient = null
layer.style["background-image"].should.equal("")
it "should copy gradients when set with an object", ->
layer = new Layer
gradient = new Gradient
start: "blue"
layer.gradient = gradient
gradient.start = "yellow"
layer.gradient.start.isEqual("blue").should.be.true
it "should set sub-properties of gradients", ->
layer = new Layer
gradient:
start: "blue"
layer.gradient.end = "yellow"
layer.gradient.start.isEqual("blue").should.be.true
layer.gradient.end.isEqual("yellow").should.be.true
layer.style["background-image"].should.equal("linear-gradient(0deg, rgb(0, 0, 255), rgb(255, 255, 0))")
describe "Filter Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.webkitFilter.should.equal ""
it "should set only the filter that is non default", ->
layer = new Layer
layer.blur = 10
layer.blur.should.equal 10
layer.style.webkitFilter.should.equal "blur(10px)"
layer.contrast = 50
layer.contrast.should.equal 50
layer.style.webkitFilter.should.equal "blur(10px) contrast(50%)"
describe "Shadow Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.boxShadow.should.equal ""
it "should set the shadow", ->
layer = new Layer
layer.shadowX = 10
layer.shadowY = 10
layer.shadowBlur = 10
layer.shadowSpread = 10
layer.shadowX.should.equal 10
layer.shadowY.should.equal 10
layer.shadowBlur.should.equal 10
layer.shadowSpread.should.equal 10
layer.style.boxShadow.should.equal "rgba(123, 123, 123, 0.498039) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = "red"
layer.shadowColor.r.should.equal 255
layer.shadowColor.g.should.equal 0
layer.shadowColor.b.should.equal 0
layer.shadowColor.a.should.equal 1
layer.style.boxShadow.should.equal "rgb(255, 0, 0) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = null
layer.style.boxShadow.should.equal "rgba(0, 0, 0, 0) 10px 10px 10px 10px"
it "should remove all events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on("test", handler)
layerA.removeAllListeners("test")
layerA.listeners("test").length.should.equal 0
it "should add and clean up dom events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
# But never more then one
layerA._domEventManager.listeners(Events.Click).length.should.equal(1)
layerA.removeAllListeners(Events.Click)
# And on removal, we should get rid of the dom event
layerA._domEventManager.listeners(Events.Click).length.should.equal(0)
it "should work with event helpers", (done) ->
layer = new Layer
layer.onMouseOver (event, aLayer) ->
aLayer.should.equal(layer)
@should.equal(layer)
done()
simulate.mouseover(layer._element)
it "should only pass dom events to the event manager", ->
layer = new Layer
layer.on Events.Click, ->
layer.on Events.Move, ->
layer._domEventManager.listenerEvents().should.eql([Events.Click])
describe "Hierarchy", ->
it "should insert in dom", ->
layer = new Layer
assert.equal layer._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layer.superLayer, null
it "should check superLayer", ->
f = -> layer = new Layer superLayer: 1
f.should.throw()
it "should add child", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
assert.equal layerB._element.parentNode, layerA._element
assert.equal layerB.superLayer, layerA
it "should remove child", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerB.superLayer = null
assert.equal layerB._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layerB.superLayer, null
it "should list children", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
assert.deepEqual layerA.children, [layerB, layerC]
layerB.superLayer = null
assert.equal layerA.children.length, 1
assert.deepEqual layerA.children, [layerC]
layerC.superLayer = null
assert.deepEqual layerA.children, []
it "should list sibling root layers", ->
layerA = new Layer
layerB = new Layer
layerC = new Layer
assert layerB in layerA.siblingLayers, true
assert layerC in layerA.siblingLayers, true
it "should list sibling layers", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
assert.deepEqual layerB.siblingLayers, [layerC]
assert.deepEqual layerC.siblingLayers, [layerB]
it "should list ancestors", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerB
assert.deepEqual layerC.ancestors(), [layerB, layerA]
it "should list descendants deeply", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerB
layerA.descendants.should.eql [layerB, layerC]
it "should list descendants", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
layerA.descendants.should.eql [layerB, layerC]
it "should set super/parent with property", ->
layerA = new Layer
layerB = new Layer
layerB.superLayer = layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
it "should set super/parent with with constructor", ->
layerA = new Layer
layerB = new Layer
superLayer: layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
describe "Layering", ->
it "should set at creation", ->
layer = new Layer index: 666
layer.index.should.equal 666
it "should change index", ->
layer = new Layer
layer.index = 666
layer.index.should.equal 666
it "should be in front for root", ->
layerA = new Layer
layerB = new Layer
assert.equal layerB.index, layerA.index + 1
it "should be in front", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should send back and front", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
layerC.sendToBack()
assert.equal layerB.index, 1
assert.equal layerC.index, -1
layerC.bringToFront()
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should place in front", ->
layerA = new Layer
layerB = new Layer superLayer: layerA # 1
layerC = new Layer superLayer: layerA # 2
layerD = new Layer superLayer: layerA # 3
layerB.placeBefore layerC
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 3
it "should place behind", ->
layerA = new Layer
layerB = new Layer superLayer: layerA # 1
layerC = new Layer superLayer: layerA # 2
layerD = new Layer superLayer: layerA # 3
layerC.placeBehind layerB
# TODO: Still something fishy here, but it works
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 4
it "should get a children by name", ->
layerA = new Layer
layerB = new Layer name: "B", superLayer: layerA
layerC = new Layer name: "C", superLayer: layerA
layerD = new Layer name: "C", superLayer: layerA
layerA.childrenWithName("B").should.eql [layerB]
layerA.childrenWithName("C").should.eql [layerC, layerD]
it "should get a siblinglayer by name", ->
layerA = new Layer
layerB = new Layer name: "B", superLayer: layerA
layerC = new Layer name: "C", superLayer: layerA
layerD = new Layer name: "C", superLayer: layerA
layerB.siblingLayersByName("C").should.eql [layerC, layerD]
layerD.siblingLayersByName("B").should.eql [layerB]
it "should get a ancestors", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerB
layerC.ancestors().should.eql [layerB, layerA]
describe "Select Layer", ->
beforeEach ->
Framer.CurrentContext.reset()
it "should select the layer named B", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerA.selectChild('B').should.equal layerB
it "should select the layer named C", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerC = new Layer name: 'C', parent: layerB
layerA.selectChild('B > *').should.equal layerC
it "should have a static method `select`", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerC = new Layer name: 'C', parent: layerB
Layer.select('B > *').should.equal layerC
it "should have a method `selectAllChildren`", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerC = new Layer name: 'C', parent: layerB
layerD = new Layer name: 'D', parent: layerB
layerA.selectAllChildren('B > *').should.eql [layerC, layerD]
it "should have a static method `selectAll`", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA # asdas
layerC = new Layer name: 'C', parent: layerB
layerD = new Layer name: 'D', parent: layerB
Layer.selectAll('A *').should.eql [layerB, layerC, layerD]
describe "Frame", ->
it "should set on create", ->
layer = new Layer frame: {x: 111, y: 222, width: 333, height: 444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set after create", ->
layer = new Layer
layer.frame = {x: 111, y: 222, width: 333, height: 444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set minX on creation", ->
layer = new Layer minX: 200, y: 100, width: 100, height: 100
layer.x.should.equal 200
it "should set midX on creation", ->
layer = new Layer midX: 200, y: 100, width: 100, height: 100
layer.x.should.equal 150
it "should set maxX on creation", ->
layer = new Layer maxX: 200, y: 100, width: 100, height: 100
layer.x.should.equal 100
it "should set minY on creation", ->
layer = new Layer x: 100, minY: 200, width: 100, height: 100
layer.y.should.equal 200
it "should set midY on creation", ->
layer = new Layer x: 100, midY: 200, width: 100, height: 100
layer.y.should.equal 150
it "should set maxY on creation", ->
layer = new Layer x: 100, maxY: 200, width: 100, height: 100
layer.y.should.equal 100
it "should set minX", ->
layer = new Layer y: 100, width: 100, height: 100
layer.minX = 200
layer.x.should.equal 200
it "should set midX", ->
layer = new Layer y: 100, width: 100, height: 100
layer.midX = 200
layer.x.should.equal 150
it "should set maxX", ->
layer = new Layer y: 100, width: 100, height: 100
layer.maxX = 200
layer.x.should.equal 100
it "should set minY", ->
layer = new Layer x: 100, width: 100, height: 100
layer.minY = 200
layer.y.should.equal 200
it "should set midY", ->
layer = new Layer x: 100, width: 100, height: 100
layer.midY = 200
layer.y.should.equal 150
it "should set maxY", ->
layer = new Layer x: 100, width: 100, height: 100
layer.maxY = 200
layer.y.should.equal 100
it "should get and set canvasFrame", ->
layerA = new Layer x: 100, y: 100, width: 100, height: 100
layerB = new Layer x: 300, y: 300, width: 100, height: 100, superLayer: layerA
assert.equal layerB.canvasFrame.x, 400
assert.equal layerB.canvasFrame.y, 400
layerB.canvasFrame = {x: 1000, y: 1000}
assert.equal layerB.canvasFrame.x, 1000
assert.equal layerB.canvasFrame.y, 1000
assert.equal layerB.x, 900
assert.equal layerB.y, 900
layerB.superLayer = null
assert.equal layerB.canvasFrame.x, 900
assert.equal layerB.canvasFrame.y, 900
it "should calculate scale", ->
layerA = new Layer scale: 0.9
layerB = new Layer scale: 0.8, superLayer: layerA
layerB.screenScaleX().should.equal 0.9 * 0.8
layerB.screenScaleY().should.equal 0.9 * 0.8
it "should calculate scaled frame", ->
layerA = new Layer x: 100, width: 500, height: 900, scale: 0.5
layerA.scaledFrame().should.eql {"x": 225, "y": 225, "width": 250, "height": 450}
it "should calculate scaled screen frame", ->
layerA = new Layer x: 100, width: 500, height: 900, scale: 0.5
layerB = new Layer y: 50, width: 600, height: 600, scale: 0.8, superLayer: layerA
layerC = new Layer y: -60, width: 800, height: 700, scale: 1.2, superLayer: layerB
layerA.screenScaledFrame().should.eql {"x": 225, "y": 225, "width": 250, "height": 450}
layerB.screenScaledFrame().should.eql {"x": 255, "y": 280, "width": 240, "height": 240}
layerC.screenScaledFrame().should.eql {"x": 223, "y": 228, "width": 384, "height": 336}
it "should accept point shortcut", ->
layer = new Layer point: 10
layer.x.should.equal 10
layer.y.should.equal 10
it "should accept size shortcut", ->
layer = new Layer size: 10
layer.width.should.equal 10
layer.height.should.equal 10
describe "Center", ->
it "should center", ->
layerA = new Layer width: 200, height: 200
layerB = new Layer width: 100, height: 100, superLayer: layerA
layerB.center()
assert.equal layerB.x, 50
assert.equal layerB.y, 50
it "should center with offset", ->
layerA = new Layer width: 200, height: 200
layerB = new Layer width: 100, height: 100, superLayer: layerA
layerB.centerX(50)
layerB.centerY(50)
assert.equal layerB.x, 100
assert.equal layerB.y, 100
it "should center return layer", ->
layerA = new Layer width: 200, height: 200
layerA.center().should.equal layerA
layerA.centerX().should.equal layerA
layerA.centerY().should.equal layerA
it "should center pixel align", ->
layerA = new Layer width: 200, height: 200
layerB = new Layer width: 111, height: 111, superLayer: layerA
layerB.center().pixelAlign()
assert.equal layerB.x, 44
assert.equal layerB.y, 44
it "should center with border", ->
layer = new Layer
width: 200
height: 200
layer.borderColor = "green"
layer.borderWidth = 30
layer.center()
layerB = new Layer
superLayer: layer
backgroundColor: "red"
layerB.center()
layerB.frame.should.eql {x: 20, y: 20, width: 100, height: 100}
it "should center within outer frame", ->
layerA = new Layer width: 10, height: 10
layerA.center()
assert.equal layerA.x, 195
assert.equal layerA.y, 145
it "should center correctly with dpr set", ->
device = new DeviceComponent()
device.deviceType = "apple-iphone-7-black"
device.context.run ->
layerA = new Layer size: 100
layerA.center()
layerA.context.devicePixelRatio.should.equal 2
layerA.x.should.equal 137
layerA.y.should.equal 283
describe "CSS", ->
it "classList should work", ->
layer = new Layer
layer.classList.add "test"
assert.equal layer.classList.contains("test"), true
assert.equal layer._element.classList.contains("test"), true
describe "DOM", ->
it "should destroy", ->
layer = new Layer
layer.destroy()
(layer in Framer.CurrentContext.layers).should.be.false
assert.equal layer._element.parentNode, null
it "should set text", ->
layer = new Layer
layer.html = "Hello"
layer._element.childNodes[0].should.equal layer._elementHTML
layer._elementHTML.innerHTML.should.equal "Hello"
layer.ignoreEvents.should.equal true
it "should not effect children", ->
layer = new Layer
layer.html = "Hello"
Child = new Layer superLayer: layer
Child._element.offsetTop.should.equal 0
it "should set interactive html and allow pointer events", ->
tags = ["input", "select", "textarea", "option"]
html = ""
for tag in tags
html += "<#{tag}></#{tag}>"
layer = new Layer
layer.html = html
for tag in tags
element = layer.querySelectorAll(tag)[0]
style = window.getComputedStyle(element)
style["pointer-events"].should.equal "auto"
# style["-webkit-user-select"].should.equal "auto"
it "should work with querySelectorAll", ->
layer = new Layer
layer.html = "<input type='button' id='hello'>"
inputElements = layer.querySelectorAll("input")
inputElements.length.should.equal 1
inputElement = _.head(inputElements)
inputElement.getAttribute("id").should.equal "hello"
describe "Force 2D", ->
it "should switch to 2d rendering", ->
layer = new Layer
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
layer.force2d = true
layer.style.webkitTransform.should.equal "translate(0px, 0px) scale(1, 1) skew(0deg, 0deg) rotate(0deg)"
describe "Matrices", ->
it "should have the correct matrix", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
layer.matrix.toString().should.eql "matrix(1.957079, 1.957079, -0.871348, 0.871348, 200.000000, 120.000000)"
it "should have the correct matrix when 2d is forced", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
force2d: true
layer.matrix.toString().should.eql "matrix(2.165466, 1.957079, -1.079734, 0.871348, 200.000000, 120.000000)"
it "should have the correct transform matrix", ->
layer = new Layer
scale: 20
rotation: 5
rotationY: 20
x: 200
y: 120
skew: 21
layer.transformMatrix.toString().should.eql "matrix3d(19.391455, 8.929946, -0.340719, 0.000000, 6.010074, 19.295128, 0.029809, 0.000000, 6.840403, 2.625785, 0.939693, 0.000000, -1020.076470, -1241.253701, 15.545482, 1.000000)"
it "should have the correct screen point", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
roundX = Math.round(layer.convertPointToScreen().x)
roundX.should.eql 184
it "should have the correct screen frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.screenFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 132
boundingBox.height.should.eql 144
it "should use Framer.Defaults when setting the screen frame", ->
Framer.Defaults.Layer.width = 300
Framer.Defaults.Layer.height = 400
box = new Layer
screenFrame:
x: 123
box.stateCycle()
box.x.should.equal 123
box.width.should.equal 300
box.height.should.equal 400
Framer.resetDefaults()
it "should have the correct canvas frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.canvasFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 132
boundingBox.height.should.eql 144
describe "Copy", ->
it "copied Layer should hold set props", ->
X = 100
Y = 200
IMAGE = "../static/test.png"
BORDERRADIUS = 20
layer = new Layer
x: X
y: Y
image: IMAGE
layer.borderRadius = BORDERRADIUS
layer.x.should.eql X
layer.y.should.eql Y
layer.image.should.eql IMAGE
layer.borderRadius.should.eql BORDERRADIUS
copy = layer.copy()
copy.x.should.eql X
copy.y.should.eql Y
copy.image.should.eql IMAGE
copy.borderRadius.should.eql BORDERRADIUS
it "copied Layer should have defaults", ->
layer = new Layer
copy = layer.copy()
copy.width.should.equal 100
copy.height.should.equal 100
it "copied Layer should also copy styles", ->
layer = new Layer
style:
"font-family": "-apple-system"
"font-size": "1.2em"
"text-align": "right"
copy = layer.copy()
copy.style["font-family"].should.equal "-apple-system"
copy.style["font-size"].should.equal "1.2em"
copy.style["text-align"].should.equal "right"
describe "Point conversion", ->
it "should correctly convert points from layer to Screen", ->
point =
x: 200
y: 300
layer = new Layer point: point
screenPoint = layer.convertPointToScreen()
screenPoint.x.should.equal point.x
screenPoint.y.should.equal point.y
it "should correctly convert points from Screen to layer", ->
point =
x: 300
y: 200
layer = new Layer point: point
layerPoint = Screen.convertPointToLayer({}, layer)
layerPoint.x.should.equal -point.x
layerPoint.y.should.equal -point.y
it "should correctly convert points from layer to layer", ->
layerBOffset =
x: 200
y: 400
layerA = new Layer
layerB = new Layer point: layerBOffset
layerAToLayerBPoint = layerA.convertPointToLayer({}, layerB)
layerAToLayerBPoint.x.should.equal -layerBOffset.x
layerAToLayerBPoint.y.should.equal -layerBOffset.y
it "should correctly convert points when layers are nested", ->
layerBOffset =
x: 0
y: 200
layerA = new Layer
layerB = new Layer
parent: layerA
point: layerBOffset
rotation: 90
originX: 0
originY: 0
layerAToLayerBPoint = layerA.convertPointToLayer({}, layerB)
layerAToLayerBPoint.x.should.equal -layerBOffset.y
it "should correctly convert points between multiple layers and transforms", ->
layerA = new Layer
x: 275
layerB = new Layer
y: 400
x: 400
scale: 2
parent: layerA
layerC = new Layer
x: -200
y: 100
rotation: 180
originX: 0
originY: 0
parent: layerB
screenToLayerCPoint = Screen.convertPointToLayer(null, layerC)
screenToLayerCPoint.x.should.equal 112.5
screenToLayerCPoint.y.should.equal 275
it "should correctly convert points from the Canvas to a layer", ->
layerA = new Layer
scale: 2
layerB = new Layer
parent: layerA
originY: 1
rotation: 90
canvasToLayerBPoint = Canvas.convertPointToLayer({}, layerB)
canvasToLayerBPoint.x.should.equal -25
canvasToLayerBPoint.y.should.equal 125
describe "Device Pixel Ratio", ->
it "should default to 1", ->
a = new Layer
a.context.devicePixelRatio.should.equal 1
it "should change all of a layers children", ->
context = new Framer.Context(name: "Test")
context.run ->
a = new Layer
b = new Layer
parent: a
c = new Layer
parent: b
a.context.devicePixelRatio = 3
for l in [a, b, c]
l._element.style.width.should.equal "300px"
describe "containers", ->
it "should return empty when called on rootLayer", ->
a = new Layer name: "a"
a.containers().should.deep.equal []
it "should return all ancestors", ->
a = new Layer name: "a"
b = new Layer parent: a, name: "b"
c = new Layer parent: b, name: "c"
d = new Layer parent: c, name: "d"
names = d.containers().map (l) -> l.name
names.should.deep.equal ["c", "b", "a"]
it "should include the device return all ancestors", ->
device = new DeviceComponent()
device.context.run ->
a = new Layer name: "a"
b = new Layer parent: a, name: "b"
c = new Layer parent: b, name: "c"
d = new Layer parent: c, name: "d"
containers = d.containers(true)
containers.length.should.equal 10
names = containers.map((l) -> l.name)
names.should.eql ["c", "b", "a", undefined, "viewport", "screen", "phone", "phone", "hands", undefined]
describe "constraintValues", ->
it "layout should not break constraints", ->
l = new Layer
x: 100
constraintValues:
aspectRatioLocked: true
l.x.should.equal 100
l.layout()
l.x.should.equal 0
assert.notEqual l.constraintValues, null
it "should break all constraints when setting x", ->
l = new Layer
x: 100
constraintValues:
aspectRatioLocked: true
l.x.should.equal 100
assert.notEqual l.constraintValues, null
l.x = 50
assert.equal l.constraintValues, null
it "should break all constraints when setting y", ->
l = new Layer
y: 100
constraintValues:
aspectRatioLocked: true
l.y.should.equal 100
assert.notEqual l.constraintValues, null
l.y = 50
assert.equal l.constraintValues, null
it "should update the width constraint when setting width", ->
l = new Layer
width: 100
constraintValues:
aspectRatioLocked: true
l.width.should.equal 100
assert.notEqual l.constraintValues, null
l.width = 50
l.constraintValues.width.should.equal 50
it "should update the height constraint when setting height", ->
l = new Layer
height: 100
constraintValues:
aspectRatioLocked: true
l.height.should.equal 100
assert.notEqual l.constraintValues, null
l.height = 50
l.constraintValues.height.should.equal 50
it "should disable the aspectRatioLock and widthFactor constraint when setting width", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
widthFactor: 0.5
width: null
l.layout()
l.width.should.equal 200
assert.notEqual l.constraintValues, null
l.width = 50
l.constraintValues.aspectRatioLocked.should.equal false
assert.equal l.constraintValues.widthFactor, null
it "should disable the aspectRatioLock and heightFactor constraint when setting height", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
heightFactor: 0.5
height: null
l.layout()
l.height.should.equal 150
assert.notEqual l.constraintValues, null
l.height = 50
assert.equal l.constraintValues.heightFactor, null
it "should update the x position when changing width", ->
l = new Layer
width: 100
constraintValues:
left: null
right: 20
l.layout()
l.width.should.equal 100
l.x.should.equal 280
assert.notEqual l.constraintValues, null
l.width = 50
l.x.should.equal 330
it "should update the y position when changing height", ->
l = new Layer
height: 100
constraintValues:
top: null
bottom: 20
l.layout()
l.height.should.equal 100
l.y.should.equal 180
assert.notEqual l.constraintValues, null
l.height = 50
l.y.should.equal 230
it "should update to center the layer when center() is called", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
l.layout()
l.center()
l.x.should.equal 150
l.y.should.equal 100
assert.equal l.constraintValues.left, null
assert.equal l.constraintValues.right, null
assert.equal l.constraintValues.top, null
assert.equal l.constraintValues.bottom, null
assert.equal l.constraintValues.centerAnchorX, 0.5
assert.equal l.constraintValues.centerAnchorY, 0.5
it "should update to center the layer vertically when centerX() is called", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
l.layout()
l.x.should.equal 0
l.centerX()
l.x.should.equal 150
assert.equal l.constraintValues.left, null
assert.equal l.constraintValues.right, null
assert.equal l.constraintValues.centerAnchorX, 0.5
it "should update to center the layer horizontally when centerY() is called", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
l.layout()
l.y.should.equal 0
l.centerY()
l.y.should.equal 100
assert.equal l.constraintValues.top, null
assert.equal l.constraintValues.bottom, null
assert.equal l.constraintValues.centerAnchorY, 0.5
describe "when no constraints are set", ->
it "should not set the width constraint when setting the width", ->
l = new Layer
width: 100
l.width.should.equal 100
assert.equal l.constraintValues, null
l.width = 50
assert.equal l.constraintValues, null
it "should not set the height constraint when setting the height", ->
l = new Layer
height: 100
l.height.should.equal 100
assert.equal l.constraintValues, null
l.height = 50
assert.equal l.constraintValues, null
| true | assert = require "assert"
{expect} = require "chai"
simulate = require "simulate"
describe "Layer", ->
# afterEach ->
# Utils.clearAll()
# beforeEach ->
# Framer.Utils.reset()
describe "Defaults", ->
it "should reset nested defaults", ->
Framer.Defaults.DeviceComponent.animationOptions.curve = "spring"
Framer.resetDefaults()
Framer.Defaults.DeviceComponent.animationOptions.curve.should.equal "ease-in-out"
it "should reset width and height to their previous values", ->
previousWidth = Framer.Defaults.Layer.width
previousHeight = Framer.Defaults.Layer.height
Framer.Defaults.Layer.width = 123
Framer.Defaults.Layer.height = 123
Framer.resetDefaults()
Framer.Defaults.Layer.width.should.equal previousWidth
Framer.Defaults.Layer.height.should.equal previousHeight
it "should set defaults", ->
width = Utils.randomNumber(0, 400)
height = Utils.randomNumber(0, 400)
Framer.Defaults =
Layer:
width: width
height: height
layer = new Layer()
layer.width.should.equal width
layer.height.should.equal height
Framer.resetDefaults()
layer = new Layer()
layer.width.should.equal 100
layer.height.should.equal 100
it "should set default background color", ->
# if the default background color is not set the content layer of scrollcomponent is not hidden when layers are added
layer = new Layer()
Color.equal(layer.backgroundColor, Framer.Defaults.Layer.backgroundColor).should.be.true
Framer.Defaults =
Layer:
backgroundColor: "red"
layer = new Layer()
layer.style.backgroundColor.should.equal new Color("red").toString()
Framer.resetDefaults()
it "should set defaults with override", ->
layer = new Layer x: 50, y: 60
layer.x.should.equal 50
layer.y.should.equal 60
it "should have default animationOptions", ->
layer = new Layer
layer.animationOptions.should.eql {}
describe "Properties", ->
it "should set defaults", ->
layer = new Layer()
layer.x.should.equal 0
layer.y.should.equal 0
layer.z.should.equal 0
layer.width.should.equal 100
layer.height.should.equal 100
it "should set width", ->
layer = new Layer width: 200
layer.width.should.equal 200
layer.style.width.should.equal "200px"
it "should set x not to scientific notation", ->
n = 0.000000000000002
n.toString().should.equal("2e-15")
layer = new Layer
layer.x = n
layer.y = 100
layer.style.webkitTransform.should.equal "translate3d(0px, 100px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set x, y and z to really small values", ->
layer = new Layer
layer.x = 10
layer.y = 10
layer.z = 10
layer.x = 1e-5
layer.y = 1e-6
layer.z = 1e-7
layer.x.should.equal 1e-5
layer.y.should.equal 1e-6
layer.z.should.equal 1e-7
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(0.00001px, 0.000001px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should handle scientific notation in scaleX, Y and Z", ->
layer = new Layer
layer.scaleX = 2
layer.scaleY = 2
layer.scaleZ = 3
layer.scaleX = 1e-7
layer.scaleY = 1e-8
layer.scaleZ = 1e-9
layer.scale = 1e-10
layer.scaleX.should.equal 1e-7
layer.scaleY.should.equal 1e-8
layer.scaleZ.should.equal 1e-9
layer.scale.should.equal 1e-10
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(0, 0, 0) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should handle scientific notation in skew", ->
layer = new Layer
layer.skew = 2
layer.skewX = 2
layer.skewY = 3
layer.skew = 1e-5
layer.skewX = 1e-6
layer.skewY = 1e-7
layer.skew.should.equal 1e-5
layer.skewX.should.equal 1e-6
layer.skewY.should.equal 1e-7
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0.00001deg, 0.00001deg) skewX(0.000001deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set x and y", ->
layer = new Layer
layer.x = 100
layer.x.should.equal 100
layer.y = 50
layer.y.should.equal 50
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 0)"
layer.style.webkitTransform.should.equal "translate3d(100px, 50px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should handle midX and midY when width and height are 0", ->
box = new Layer
midX: 200
midY: 300
width: 0
height: 0
box.x.should.equal 200
box.y.should.equal 300
it "should set scale", ->
layer = new Layer
layer.scaleX = 100
layer.scaleY = 100
layer.scaleZ = 100
# layer.style.webkitTransform.should.equal "matrix(1, 0, 0, 1, 100, 50)"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(100, 100, 100) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
it "should set origin", ->
layer = new Layer
originZ: 80
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.originX = 0.1
layer.originY = 0.2
layer.style.webkitTransformOrigin.should.equal "10% 20%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
layer.originX = 0.5
layer.originY = 0.5
layer.style.webkitTransformOrigin.should.equal "50% 50%"
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(80px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(-80px)"
it "should preserve 3D by default", ->
layer = new Layer
layer._element.style.webkitTransformStyle.should.equal "preserve-3d"
it "should flatten layer", ->
layer = new Layer
flat: true
layer._element.style.webkitTransformStyle.should.equal "flat"
it "should set local image", ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
layer = new Layer
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
layer.props.image.should.equal fullPath
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.not.equal(-1)
it "should set local image when listening to load events", (done) ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
layer = new Layer
layer.on Events.ImageLoaded, ->
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.not.equal(-1)
done()
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
layer.props.image.should.equal fullPath
layer.style["background-image"].indexOf(imagePath).should.equal(-1)
layer.style["background-image"].indexOf("file://").should.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.equal(-1)
#layer.computedStyle()["background-size"].should.equal "cover"
#layer.computedStyle()["background-repeat"].should.equal "no-repeat"
it "should not append nocache to a base64 encoded image", ->
fullPath = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEwAAABMBAMAAAA1uUwYAAAAAXNSR0IArs4c6QAAABVQTFRFKK/6LFj/g9n/lNf9lqz/wez/////Ke+vpgAAAK1JREFUSMft1sENhDAMBdFIPI:KEY:<KEY>END_PI"
layer = new Layer
layer.image = fullPath
layer.image.should.equal fullPath
image = layer.props.image
image.should.equal fullPath
layer.style["background-image"].indexOf(fullPath).should.not.equal(-1)
layer.style["background-image"].indexOf("data:").should.not.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.equal(-1)
it "should append nocache with an ampersand if url params already exist", (done) ->
prefix = "../"
imagePath = "static/test.png?param=foo"
fullPath = prefix + imagePath
layer = new Layer
layer.on Events.ImageLoaded, ->
layer.style["background-image"].indexOf(imagePath).should.not.equal(-1)
layer.style["background-image"].indexOf("file://").should.not.equal(-1)
layer.style["background-image"].indexOf("&nocache=").should.not.equal(-1)
done()
layer.image = fullPath
layer.image.should.equal fullPath
it "should cancel loading when setting image to null", (done) ->
prefix = "../"
imagePath = "static/test.png"
fullPath = prefix + imagePath
#First set the image directly to something
layer = new Layer
image: "static/test2.png"
#Now add event handlers
layer.on Events.ImageLoadCancelled, ->
layer.style["background-image"].indexOf(imagePath).should.equal(-1)
layer.style["background-image"].indexOf("file://").should.equal(-1)
layer.style["background-image"].indexOf("?nocache=").should.equal(-1)
done()
#so we preload the next image
layer.image = fullPath
#set the image no null to cancel the loading
layer.image = null
it "should set image", ->
imagePath = "../static/test.png"
layer = new Layer image: imagePath
layer.image.should.equal imagePath
it "should unset image with null", ->
layer = new Layer image: "../static/test.png"
layer.image = null
layer.image.should.equal ""
it "should unset image with empty string", ->
layer = new Layer image: "../static/test.png"
layer.image = ""
layer.image.should.equal ""
it "should test image property type", ->
f = ->
layer = new Layer
layer.image = {}
f.should.throw()
it "should set name on create", ->
layer = new Layer name: "Test"
layer.name.should.equal "Test"
layer._element.getAttribute("name").should.equal "Test"
it "should set name after create", ->
layer = new Layer
layer.name = "Test"
layer.name.should.equal "Test"
layer._element.getAttribute("name").should.equal "Test"
it "should handle false layer names correctly", ->
layer = new Layer
name: 0
layer.name.should.equal "0"
layer._element.getAttribute("name").should.equal "0"
it "should handle background color with image", ->
# We want the background color to be there until an images
# is set UNLESS we set another backgroundColor explicitly
imagePath = "../static/test.png"
layer = new Layer image: imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer
layer.image = imagePath
assert.equal layer.backgroundColor.color, null
layer = new Layer backgroundColor: "red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
layer = new Layer
layer.backgroundColor = "red"
layer.image = imagePath
Color.equal(layer.backgroundColor, new Color("red")).should.be.true
it "should set visible", ->
layer = new Layer
layer.visible.should.equal true
layer.style["display"].should.equal "block"
layer.visible = false
layer.visible.should.equal false
layer.style["display"].should.equal "none"
it "should set clip", ->
layer = new Layer
layer.clip.should.equal false
layer.style["overflow"].should.equal "visible"
layer.clip = true
layer.style["overflow"].should.equal "hidden"
it "should set scroll", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
layer.scroll = false
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
it "should set scroll from properties", ->
layer = new Layer
layer.props = {scroll: false}
layer.scroll.should.equal false
layer.props = {scroll: true}
layer.scroll.should.equal true
it "should set scrollHorizontal", ->
layer = new Layer
layer.scroll.should.equal false
layer.style["overflow"].should.equal "visible"
layer.ignoreEvents.should.equal true
layer.scroll = true
layer.scroll.should.equal true
layer.style["overflow"].should.equal "scroll"
layer.ignoreEvents.should.equal false
it "should disable ignore events when scroll is set from constructor", ->
layerA = new Layer
scroll: true
layerA.ignoreEvents.should.equal false
it "should set style properties on create", ->
layer = new Layer backgroundColor: "red"
layer.backgroundColor.isEqual(new Color("red")).should.equal true
layer.style["backgroundColor"].should.equal new Color("red").toString()
it "should check value type", ->
f = ->
layer = new Layer
layer.x = "hello"
f.should.throw()
it "should set perspective", ->
layer = new Layer
layer.perspective = 500
layer.style["-webkit-perspective"].should.equal("500")
it "should have a default perspective of 0", ->
layer = new Layer
layer._element.style["webkitPerspective"].should.equal "none"
layer.perspective.should.equal 0
it "should allow the perspective to be changed", ->
layer = new Layer
layer.perspective = 800
layer.perspective.should.equal 800
layer._element.style["webkitPerspective"].should.equal "800"
it "should set the perspective to 'none' if set to 0", ->
layer = new Layer
layer.perspective = 0
layer.perspective.should.equal 0
layer._element.style["webkitPerspective"].should.equal "none"
it "should set the perspective to 'none' if set to none", ->
layer = new Layer
layer.perspective = "none"
layer.perspective.should.equal "none"
layer._element.style["webkitPerspective"].should.equal "none"
it "should set the perspective to 'none' if set to null", ->
layer = new Layer
layer.perspective = null
layer.perspective.should.equal 0
layer._element.style["webkitPerspective"].should.equal "none"
it "should not allow setting the perspective to random string", ->
layer = new Layer
(-> layer.perspective = "bla").should.throw("Layer.perspective: value 'bla' of type 'string' is not valid")
layer.perspective.should.equal 0
layer._element.style["webkitPerspective"].should.equal "none"
it "should have its backface visible by default", ->
layer = new Layer
layer.style["webkitBackfaceVisibility"].should.equal "visible"
it "should allow backface to be hidden", ->
layer = new Layer
layer.backfaceVisible = false
layer.style["webkitBackfaceVisibility"].should.equal "hidden"
it "should set rotation", ->
layer = new Layer
rotationX: 200
rotationY: 200
rotationZ: 200
layer.rotationX.should.equal(200)
layer.rotationY.should.equal(200)
layer.rotationZ.should.equal(200)
it "should proxy rotation", ->
layer = new Layer
layer.rotation = 200
layer.rotation.should.equal(200)
layer.rotationZ.should.equal(200)
layer.rotationZ = 100
layer.rotation.should.equal(100)
layer.rotationZ.should.equal(100)
it "should only set name when explicitly set", ->
layer = new Layer
layer.__framerInstanceInfo = {name: "aap"}
layer.name.should.equal ""
it "it should show the variable name in toInspect()", ->
layer = new Layer
layer.__framerInstanceInfo = {name: "aap"}
(_.startsWith layer.toInspect(), "<Layer aap id:").should.be.true
it "should set htmlIntrinsicSize", ->
layer = new Layer
assert.equal layer.htmlIntrinsicSize, null
layer.htmlIntrinsicSize = "aap"
assert.equal layer.htmlIntrinsicSize, null
layer.htmlIntrinsicSize =
width: 10
assert.equal layer.htmlIntrinsicSize, null
layer.htmlIntrinsicSize =
width: 10
height: 20
layer.htmlIntrinsicSize.should.eql({width: 10, height: 20})
layer.htmlIntrinsicSize = null
assert.equal layer.htmlIntrinsicSize, null
describe "Border Radius", ->
it "should set borderRadius", ->
testBorderRadius = (layer, value) ->
if layer.style["border-top-left-radius"] is "#{value}"
layer.style["border-top-left-radius"].should.equal "#{value}"
layer.style["border-top-right-radius"].should.equal "#{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value}"
else
layer.style["border-top-left-radius"].should.equal "#{value} #{value}"
layer.style["border-top-right-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-left-radius"].should.equal "#{value} #{value}"
layer.style["border-bottom-right-radius"].should.equal "#{value} #{value}"
layer = new Layer
layer.borderRadius = 10
layer.borderRadius.should.equal 10
testBorderRadius(layer, "10px")
layer.borderRadius = "50%"
layer.borderRadius.should.equal "50%"
testBorderRadius(layer, "50%")
it "should set borderRadius with objects", ->
testBorderRadius = (layer, tl, tr, bl, br) ->
layer.style["border-top-left-radius"].should.equal "#{tl}"
layer.style["border-top-right-radius"].should.equal "#{tr}"
layer.style["border-bottom-left-radius"].should.equal "#{bl}"
layer.style["border-bottom-right-radius"].should.equal "#{br}"
layer = new Layer
# No matching keys is an error
layer.borderRadius = {aap: 10, noot: 20, mies: 30}
layer.borderRadius.should.equal 0
testBorderRadius(layer, "0px", "0px", "0px", "0px")
# Arrays are not supported either
layer.borderRadius = [1, 2, 3, 4]
layer.borderRadius.should.equal 0
testBorderRadius(layer, "0px", "0px", "0px", "0px")
layer.borderRadius = {topLeft: 10}
layer.borderRadius.topLeft.should.equal 10
testBorderRadius(layer, "10px", "0px", "0px", "0px")
layer.borderRadius = {topLeft: 1, topRight: 2, bottomLeft: 3, bottomRight: 4}
layer.borderRadius.topLeft.should.equal 1
layer.borderRadius.bottomRight.should.equal 4
testBorderRadius(layer, "1px", "2px", "3px", "4px")
it "should copy borderRadius when set with an object", ->
layer = new Layer
borderRadius = {topLeft: 100}
layer.borderRadius = borderRadius
borderRadius.bottomRight = 100
layer.borderRadius.bottomRight.should.equal 0
it "should set sub-properties of borderRadius", ->
layer = new Layer
borderRadius: {topLeft: 100}
layer.borderRadius.bottomRight = 100
layer.borderRadius.topLeft.should.equal(100)
layer.borderRadius.bottomRight.should.equal(100)
layer.style["border-top-left-radius"].should.equal "100px"
layer.style["border-bottom-right-radius"].should.equal "100px"
describe "Border Width", ->
it "should copy borderWidth when set with an object", ->
layer = new Layer
borderWidth = {top: 100}
layer.borderWidth = borderWidth
borderWidth.bottom = 100
layer.borderWidth.bottom.should.equal 0
it "should set sub-properties of borderWidth", ->
layer = new Layer
borderWidth: {top: 10}
layer.borderWidth.bottom = 10
layer.borderWidth.top.should.equal(10)
layer.borderWidth.bottom.should.equal(10)
layer._elementBorder.style["border-top-width"].should.equal "10px"
layer._elementBorder.style["border-bottom-width"].should.equal "10px"
describe "Gradient", ->
it "should set gradient", ->
layer = new Layer
layer.gradient = new Gradient
start: "blue"
end: "red"
angle: 42
layer.gradient.start.isEqual("blue").should.be.true
layer.gradient.end.isEqual("red").should.be.true
layer.gradient.angle.should.equal(42)
layer.style["background-image"].should.equal("linear-gradient(42deg, rgb(0, 0, 255), rgb(255, 0, 0))")
layer.gradient =
start: "yellow"
end: "purple"
layer.gradient.angle.should.equal(0)
layer.style["background-image"].should.equal("linear-gradient(0deg, rgb(255, 255, 0), rgb(128, 0, 128))")
layer.gradient = null
layer.style["background-image"].should.equal("")
it "should copy gradients when set with an object", ->
layer = new Layer
gradient = new Gradient
start: "blue"
layer.gradient = gradient
gradient.start = "yellow"
layer.gradient.start.isEqual("blue").should.be.true
it "should set sub-properties of gradients", ->
layer = new Layer
gradient:
start: "blue"
layer.gradient.end = "yellow"
layer.gradient.start.isEqual("blue").should.be.true
layer.gradient.end.isEqual("yellow").should.be.true
layer.style["background-image"].should.equal("linear-gradient(0deg, rgb(0, 0, 255), rgb(255, 255, 0))")
describe "Filter Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.webkitFilter.should.equal ""
it "should set only the filter that is non default", ->
layer = new Layer
layer.blur = 10
layer.blur.should.equal 10
layer.style.webkitFilter.should.equal "blur(10px)"
layer.contrast = 50
layer.contrast.should.equal 50
layer.style.webkitFilter.should.equal "blur(10px) contrast(50%)"
describe "Shadow Properties", ->
it "should set nothing on defaults", ->
layer = new Layer
layer.style.boxShadow.should.equal ""
it "should set the shadow", ->
layer = new Layer
layer.shadowX = 10
layer.shadowY = 10
layer.shadowBlur = 10
layer.shadowSpread = 10
layer.shadowX.should.equal 10
layer.shadowY.should.equal 10
layer.shadowBlur.should.equal 10
layer.shadowSpread.should.equal 10
layer.style.boxShadow.should.equal "rgba(123, 123, 123, 0.498039) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = "red"
layer.shadowColor.r.should.equal 255
layer.shadowColor.g.should.equal 0
layer.shadowColor.b.should.equal 0
layer.shadowColor.a.should.equal 1
layer.style.boxShadow.should.equal "rgb(255, 0, 0) 10px 10px 10px 10px"
# Only after we set a color a shadow should be drawn
layer.shadowColor = null
layer.style.boxShadow.should.equal "rgba(0, 0, 0, 0) 10px 10px 10px 10px"
it "should remove all events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on("test", handler)
layerA.removeAllListeners("test")
layerA.listeners("test").length.should.equal 0
it "should add and clean up dom events", ->
layerA = new Layer
handler = -> console.log "hello"
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
layerA.on(Events.Click, handler)
# But never more then one
layerA._domEventManager.listeners(Events.Click).length.should.equal(1)
layerA.removeAllListeners(Events.Click)
# And on removal, we should get rid of the dom event
layerA._domEventManager.listeners(Events.Click).length.should.equal(0)
it "should work with event helpers", (done) ->
layer = new Layer
layer.onMouseOver (event, aLayer) ->
aLayer.should.equal(layer)
@should.equal(layer)
done()
simulate.mouseover(layer._element)
it "should only pass dom events to the event manager", ->
layer = new Layer
layer.on Events.Click, ->
layer.on Events.Move, ->
layer._domEventManager.listenerEvents().should.eql([Events.Click])
describe "Hierarchy", ->
it "should insert in dom", ->
layer = new Layer
assert.equal layer._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layer.superLayer, null
it "should check superLayer", ->
f = -> layer = new Layer superLayer: 1
f.should.throw()
it "should add child", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
assert.equal layerB._element.parentNode, layerA._element
assert.equal layerB.superLayer, layerA
it "should remove child", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerB.superLayer = null
assert.equal layerB._element.parentNode.id, "FramerContextRoot-Default"
assert.equal layerB.superLayer, null
it "should list children", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
assert.deepEqual layerA.children, [layerB, layerC]
layerB.superLayer = null
assert.equal layerA.children.length, 1
assert.deepEqual layerA.children, [layerC]
layerC.superLayer = null
assert.deepEqual layerA.children, []
it "should list sibling root layers", ->
layerA = new Layer
layerB = new Layer
layerC = new Layer
assert layerB in layerA.siblingLayers, true
assert layerC in layerA.siblingLayers, true
it "should list sibling layers", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
assert.deepEqual layerB.siblingLayers, [layerC]
assert.deepEqual layerC.siblingLayers, [layerB]
it "should list ancestors", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerB
assert.deepEqual layerC.ancestors(), [layerB, layerA]
it "should list descendants deeply", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerB
layerA.descendants.should.eql [layerB, layerC]
it "should list descendants", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
layerA.descendants.should.eql [layerB, layerC]
it "should set super/parent with property", ->
layerA = new Layer
layerB = new Layer
layerB.superLayer = layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
it "should set super/parent with with constructor", ->
layerA = new Layer
layerB = new Layer
superLayer: layerA
layerA.children.should.eql [layerB]
layerA.subLayers.should.eql [layerB]
describe "Layering", ->
it "should set at creation", ->
layer = new Layer index: 666
layer.index.should.equal 666
it "should change index", ->
layer = new Layer
layer.index = 666
layer.index.should.equal 666
it "should be in front for root", ->
layerA = new Layer
layerB = new Layer
assert.equal layerB.index, layerA.index + 1
it "should be in front", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should send back and front", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerA
layerC.sendToBack()
assert.equal layerB.index, 1
assert.equal layerC.index, -1
layerC.bringToFront()
assert.equal layerB.index, 1
assert.equal layerC.index, 2
it "should place in front", ->
layerA = new Layer
layerB = new Layer superLayer: layerA # 1
layerC = new Layer superLayer: layerA # 2
layerD = new Layer superLayer: layerA # 3
layerB.placeBefore layerC
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 3
it "should place behind", ->
layerA = new Layer
layerB = new Layer superLayer: layerA # 1
layerC = new Layer superLayer: layerA # 2
layerD = new Layer superLayer: layerA # 3
layerC.placeBehind layerB
# TODO: Still something fishy here, but it works
assert.equal layerB.index, 2
assert.equal layerC.index, 1
assert.equal layerD.index, 4
it "should get a children by name", ->
layerA = new Layer
layerB = new Layer name: "B", superLayer: layerA
layerC = new Layer name: "C", superLayer: layerA
layerD = new Layer name: "C", superLayer: layerA
layerA.childrenWithName("B").should.eql [layerB]
layerA.childrenWithName("C").should.eql [layerC, layerD]
it "should get a siblinglayer by name", ->
layerA = new Layer
layerB = new Layer name: "B", superLayer: layerA
layerC = new Layer name: "C", superLayer: layerA
layerD = new Layer name: "C", superLayer: layerA
layerB.siblingLayersByName("C").should.eql [layerC, layerD]
layerD.siblingLayersByName("B").should.eql [layerB]
it "should get a ancestors", ->
layerA = new Layer
layerB = new Layer superLayer: layerA
layerC = new Layer superLayer: layerB
layerC.ancestors().should.eql [layerB, layerA]
describe "Select Layer", ->
beforeEach ->
Framer.CurrentContext.reset()
it "should select the layer named B", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerA.selectChild('B').should.equal layerB
it "should select the layer named C", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerC = new Layer name: 'C', parent: layerB
layerA.selectChild('B > *').should.equal layerC
it "should have a static method `select`", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerC = new Layer name: 'C', parent: layerB
Layer.select('B > *').should.equal layerC
it "should have a method `selectAllChildren`", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA
layerC = new Layer name: 'C', parent: layerB
layerD = new Layer name: 'D', parent: layerB
layerA.selectAllChildren('B > *').should.eql [layerC, layerD]
it "should have a static method `selectAll`", ->
layerA = new Layer name: 'A'
layerB = new Layer name: 'B', parent: layerA # asdas
layerC = new Layer name: 'C', parent: layerB
layerD = new Layer name: 'D', parent: layerB
Layer.selectAll('A *').should.eql [layerB, layerC, layerD]
describe "Frame", ->
it "should set on create", ->
layer = new Layer frame: {x: 111, y: 222, width: 333, height: 444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set after create", ->
layer = new Layer
layer.frame = {x: 111, y: 222, width: 333, height: 444}
assert.equal layer.x, 111
assert.equal layer.y, 222
assert.equal layer.width, 333
assert.equal layer.height, 444
it "should set minX on creation", ->
layer = new Layer minX: 200, y: 100, width: 100, height: 100
layer.x.should.equal 200
it "should set midX on creation", ->
layer = new Layer midX: 200, y: 100, width: 100, height: 100
layer.x.should.equal 150
it "should set maxX on creation", ->
layer = new Layer maxX: 200, y: 100, width: 100, height: 100
layer.x.should.equal 100
it "should set minY on creation", ->
layer = new Layer x: 100, minY: 200, width: 100, height: 100
layer.y.should.equal 200
it "should set midY on creation", ->
layer = new Layer x: 100, midY: 200, width: 100, height: 100
layer.y.should.equal 150
it "should set maxY on creation", ->
layer = new Layer x: 100, maxY: 200, width: 100, height: 100
layer.y.should.equal 100
it "should set minX", ->
layer = new Layer y: 100, width: 100, height: 100
layer.minX = 200
layer.x.should.equal 200
it "should set midX", ->
layer = new Layer y: 100, width: 100, height: 100
layer.midX = 200
layer.x.should.equal 150
it "should set maxX", ->
layer = new Layer y: 100, width: 100, height: 100
layer.maxX = 200
layer.x.should.equal 100
it "should set minY", ->
layer = new Layer x: 100, width: 100, height: 100
layer.minY = 200
layer.y.should.equal 200
it "should set midY", ->
layer = new Layer x: 100, width: 100, height: 100
layer.midY = 200
layer.y.should.equal 150
it "should set maxY", ->
layer = new Layer x: 100, width: 100, height: 100
layer.maxY = 200
layer.y.should.equal 100
it "should get and set canvasFrame", ->
layerA = new Layer x: 100, y: 100, width: 100, height: 100
layerB = new Layer x: 300, y: 300, width: 100, height: 100, superLayer: layerA
assert.equal layerB.canvasFrame.x, 400
assert.equal layerB.canvasFrame.y, 400
layerB.canvasFrame = {x: 1000, y: 1000}
assert.equal layerB.canvasFrame.x, 1000
assert.equal layerB.canvasFrame.y, 1000
assert.equal layerB.x, 900
assert.equal layerB.y, 900
layerB.superLayer = null
assert.equal layerB.canvasFrame.x, 900
assert.equal layerB.canvasFrame.y, 900
it "should calculate scale", ->
layerA = new Layer scale: 0.9
layerB = new Layer scale: 0.8, superLayer: layerA
layerB.screenScaleX().should.equal 0.9 * 0.8
layerB.screenScaleY().should.equal 0.9 * 0.8
it "should calculate scaled frame", ->
layerA = new Layer x: 100, width: 500, height: 900, scale: 0.5
layerA.scaledFrame().should.eql {"x": 225, "y": 225, "width": 250, "height": 450}
it "should calculate scaled screen frame", ->
layerA = new Layer x: 100, width: 500, height: 900, scale: 0.5
layerB = new Layer y: 50, width: 600, height: 600, scale: 0.8, superLayer: layerA
layerC = new Layer y: -60, width: 800, height: 700, scale: 1.2, superLayer: layerB
layerA.screenScaledFrame().should.eql {"x": 225, "y": 225, "width": 250, "height": 450}
layerB.screenScaledFrame().should.eql {"x": 255, "y": 280, "width": 240, "height": 240}
layerC.screenScaledFrame().should.eql {"x": 223, "y": 228, "width": 384, "height": 336}
it "should accept point shortcut", ->
layer = new Layer point: 10
layer.x.should.equal 10
layer.y.should.equal 10
it "should accept size shortcut", ->
layer = new Layer size: 10
layer.width.should.equal 10
layer.height.should.equal 10
describe "Center", ->
it "should center", ->
layerA = new Layer width: 200, height: 200
layerB = new Layer width: 100, height: 100, superLayer: layerA
layerB.center()
assert.equal layerB.x, 50
assert.equal layerB.y, 50
it "should center with offset", ->
layerA = new Layer width: 200, height: 200
layerB = new Layer width: 100, height: 100, superLayer: layerA
layerB.centerX(50)
layerB.centerY(50)
assert.equal layerB.x, 100
assert.equal layerB.y, 100
it "should center return layer", ->
layerA = new Layer width: 200, height: 200
layerA.center().should.equal layerA
layerA.centerX().should.equal layerA
layerA.centerY().should.equal layerA
it "should center pixel align", ->
layerA = new Layer width: 200, height: 200
layerB = new Layer width: 111, height: 111, superLayer: layerA
layerB.center().pixelAlign()
assert.equal layerB.x, 44
assert.equal layerB.y, 44
it "should center with border", ->
layer = new Layer
width: 200
height: 200
layer.borderColor = "green"
layer.borderWidth = 30
layer.center()
layerB = new Layer
superLayer: layer
backgroundColor: "red"
layerB.center()
layerB.frame.should.eql {x: 20, y: 20, width: 100, height: 100}
it "should center within outer frame", ->
layerA = new Layer width: 10, height: 10
layerA.center()
assert.equal layerA.x, 195
assert.equal layerA.y, 145
it "should center correctly with dpr set", ->
device = new DeviceComponent()
device.deviceType = "apple-iphone-7-black"
device.context.run ->
layerA = new Layer size: 100
layerA.center()
layerA.context.devicePixelRatio.should.equal 2
layerA.x.should.equal 137
layerA.y.should.equal 283
describe "CSS", ->
it "classList should work", ->
layer = new Layer
layer.classList.add "test"
assert.equal layer.classList.contains("test"), true
assert.equal layer._element.classList.contains("test"), true
describe "DOM", ->
it "should destroy", ->
layer = new Layer
layer.destroy()
(layer in Framer.CurrentContext.layers).should.be.false
assert.equal layer._element.parentNode, null
it "should set text", ->
layer = new Layer
layer.html = "Hello"
layer._element.childNodes[0].should.equal layer._elementHTML
layer._elementHTML.innerHTML.should.equal "Hello"
layer.ignoreEvents.should.equal true
it "should not effect children", ->
layer = new Layer
layer.html = "Hello"
Child = new Layer superLayer: layer
Child._element.offsetTop.should.equal 0
it "should set interactive html and allow pointer events", ->
tags = ["input", "select", "textarea", "option"]
html = ""
for tag in tags
html += "<#{tag}></#{tag}>"
layer = new Layer
layer.html = html
for tag in tags
element = layer.querySelectorAll(tag)[0]
style = window.getComputedStyle(element)
style["pointer-events"].should.equal "auto"
# style["-webkit-user-select"].should.equal "auto"
it "should work with querySelectorAll", ->
layer = new Layer
layer.html = "<input type='button' id='hello'>"
inputElements = layer.querySelectorAll("input")
inputElements.length.should.equal 1
inputElement = _.head(inputElements)
inputElement.getAttribute("id").should.equal "hello"
describe "Force 2D", ->
it "should switch to 2d rendering", ->
layer = new Layer
layer.style.webkitTransform.should.equal "translate3d(0px, 0px, 0px) scale3d(1, 1, 1) skew(0deg, 0deg) skewX(0deg) skewY(0deg) translateZ(0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) translateZ(0px)"
layer.force2d = true
layer.style.webkitTransform.should.equal "translate(0px, 0px) scale(1, 1) skew(0deg, 0deg) rotate(0deg)"
describe "Matrices", ->
it "should have the correct matrix", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
layer.matrix.toString().should.eql "matrix(1.957079, 1.957079, -0.871348, 0.871348, 200.000000, 120.000000)"
it "should have the correct matrix when 2d is forced", ->
layer = new Layer
scale: 2
rotation: 45
x: 200
y: 120
skew: 21
force2d: true
layer.matrix.toString().should.eql "matrix(2.165466, 1.957079, -1.079734, 0.871348, 200.000000, 120.000000)"
it "should have the correct transform matrix", ->
layer = new Layer
scale: 20
rotation: 5
rotationY: 20
x: 200
y: 120
skew: 21
layer.transformMatrix.toString().should.eql "matrix3d(19.391455, 8.929946, -0.340719, 0.000000, 6.010074, 19.295128, 0.029809, 0.000000, 6.840403, 2.625785, 0.939693, 0.000000, -1020.076470, -1241.253701, 15.545482, 1.000000)"
it "should have the correct screen point", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
roundX = Math.round(layer.convertPointToScreen().x)
roundX.should.eql 184
it "should have the correct screen frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.screenFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 132
boundingBox.height.should.eql 144
it "should use Framer.Defaults when setting the screen frame", ->
Framer.Defaults.Layer.width = 300
Framer.Defaults.Layer.height = 400
box = new Layer
screenFrame:
x: 123
box.stateCycle()
box.x.should.equal 123
box.width.should.equal 300
box.height.should.equal 400
Framer.resetDefaults()
it "should have the correct canvas frame", ->
layer = new Layer
rotation: 5
x: 200
y: 120
skew: 21
boundingBox = layer.canvasFrame
boundingBox.x.should.eql 184
boundingBox.y.should.eql 98
boundingBox.width.should.eql 132
boundingBox.height.should.eql 144
describe "Copy", ->
it "copied Layer should hold set props", ->
X = 100
Y = 200
IMAGE = "../static/test.png"
BORDERRADIUS = 20
layer = new Layer
x: X
y: Y
image: IMAGE
layer.borderRadius = BORDERRADIUS
layer.x.should.eql X
layer.y.should.eql Y
layer.image.should.eql IMAGE
layer.borderRadius.should.eql BORDERRADIUS
copy = layer.copy()
copy.x.should.eql X
copy.y.should.eql Y
copy.image.should.eql IMAGE
copy.borderRadius.should.eql BORDERRADIUS
it "copied Layer should have defaults", ->
layer = new Layer
copy = layer.copy()
copy.width.should.equal 100
copy.height.should.equal 100
it "copied Layer should also copy styles", ->
layer = new Layer
style:
"font-family": "-apple-system"
"font-size": "1.2em"
"text-align": "right"
copy = layer.copy()
copy.style["font-family"].should.equal "-apple-system"
copy.style["font-size"].should.equal "1.2em"
copy.style["text-align"].should.equal "right"
describe "Point conversion", ->
it "should correctly convert points from layer to Screen", ->
point =
x: 200
y: 300
layer = new Layer point: point
screenPoint = layer.convertPointToScreen()
screenPoint.x.should.equal point.x
screenPoint.y.should.equal point.y
it "should correctly convert points from Screen to layer", ->
point =
x: 300
y: 200
layer = new Layer point: point
layerPoint = Screen.convertPointToLayer({}, layer)
layerPoint.x.should.equal -point.x
layerPoint.y.should.equal -point.y
it "should correctly convert points from layer to layer", ->
layerBOffset =
x: 200
y: 400
layerA = new Layer
layerB = new Layer point: layerBOffset
layerAToLayerBPoint = layerA.convertPointToLayer({}, layerB)
layerAToLayerBPoint.x.should.equal -layerBOffset.x
layerAToLayerBPoint.y.should.equal -layerBOffset.y
it "should correctly convert points when layers are nested", ->
layerBOffset =
x: 0
y: 200
layerA = new Layer
layerB = new Layer
parent: layerA
point: layerBOffset
rotation: 90
originX: 0
originY: 0
layerAToLayerBPoint = layerA.convertPointToLayer({}, layerB)
layerAToLayerBPoint.x.should.equal -layerBOffset.y
it "should correctly convert points between multiple layers and transforms", ->
layerA = new Layer
x: 275
layerB = new Layer
y: 400
x: 400
scale: 2
parent: layerA
layerC = new Layer
x: -200
y: 100
rotation: 180
originX: 0
originY: 0
parent: layerB
screenToLayerCPoint = Screen.convertPointToLayer(null, layerC)
screenToLayerCPoint.x.should.equal 112.5
screenToLayerCPoint.y.should.equal 275
it "should correctly convert points from the Canvas to a layer", ->
layerA = new Layer
scale: 2
layerB = new Layer
parent: layerA
originY: 1
rotation: 90
canvasToLayerBPoint = Canvas.convertPointToLayer({}, layerB)
canvasToLayerBPoint.x.should.equal -25
canvasToLayerBPoint.y.should.equal 125
describe "Device Pixel Ratio", ->
it "should default to 1", ->
a = new Layer
a.context.devicePixelRatio.should.equal 1
it "should change all of a layers children", ->
context = new Framer.Context(name: "Test")
context.run ->
a = new Layer
b = new Layer
parent: a
c = new Layer
parent: b
a.context.devicePixelRatio = 3
for l in [a, b, c]
l._element.style.width.should.equal "300px"
describe "containers", ->
it "should return empty when called on rootLayer", ->
a = new Layer name: "a"
a.containers().should.deep.equal []
it "should return all ancestors", ->
a = new Layer name: "a"
b = new Layer parent: a, name: "b"
c = new Layer parent: b, name: "c"
d = new Layer parent: c, name: "d"
names = d.containers().map (l) -> l.name
names.should.deep.equal ["c", "b", "a"]
it "should include the device return all ancestors", ->
device = new DeviceComponent()
device.context.run ->
a = new Layer name: "a"
b = new Layer parent: a, name: "b"
c = new Layer parent: b, name: "c"
d = new Layer parent: c, name: "d"
containers = d.containers(true)
containers.length.should.equal 10
names = containers.map((l) -> l.name)
names.should.eql ["c", "b", "a", undefined, "viewport", "screen", "phone", "phone", "hands", undefined]
describe "constraintValues", ->
it "layout should not break constraints", ->
l = new Layer
x: 100
constraintValues:
aspectRatioLocked: true
l.x.should.equal 100
l.layout()
l.x.should.equal 0
assert.notEqual l.constraintValues, null
it "should break all constraints when setting x", ->
l = new Layer
x: 100
constraintValues:
aspectRatioLocked: true
l.x.should.equal 100
assert.notEqual l.constraintValues, null
l.x = 50
assert.equal l.constraintValues, null
it "should break all constraints when setting y", ->
l = new Layer
y: 100
constraintValues:
aspectRatioLocked: true
l.y.should.equal 100
assert.notEqual l.constraintValues, null
l.y = 50
assert.equal l.constraintValues, null
it "should update the width constraint when setting width", ->
l = new Layer
width: 100
constraintValues:
aspectRatioLocked: true
l.width.should.equal 100
assert.notEqual l.constraintValues, null
l.width = 50
l.constraintValues.width.should.equal 50
it "should update the height constraint when setting height", ->
l = new Layer
height: 100
constraintValues:
aspectRatioLocked: true
l.height.should.equal 100
assert.notEqual l.constraintValues, null
l.height = 50
l.constraintValues.height.should.equal 50
it "should disable the aspectRatioLock and widthFactor constraint when setting width", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
widthFactor: 0.5
width: null
l.layout()
l.width.should.equal 200
assert.notEqual l.constraintValues, null
l.width = 50
l.constraintValues.aspectRatioLocked.should.equal false
assert.equal l.constraintValues.widthFactor, null
it "should disable the aspectRatioLock and heightFactor constraint when setting height", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
heightFactor: 0.5
height: null
l.layout()
l.height.should.equal 150
assert.notEqual l.constraintValues, null
l.height = 50
assert.equal l.constraintValues.heightFactor, null
it "should update the x position when changing width", ->
l = new Layer
width: 100
constraintValues:
left: null
right: 20
l.layout()
l.width.should.equal 100
l.x.should.equal 280
assert.notEqual l.constraintValues, null
l.width = 50
l.x.should.equal 330
it "should update the y position when changing height", ->
l = new Layer
height: 100
constraintValues:
top: null
bottom: 20
l.layout()
l.height.should.equal 100
l.y.should.equal 180
assert.notEqual l.constraintValues, null
l.height = 50
l.y.should.equal 230
it "should update to center the layer when center() is called", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
l.layout()
l.center()
l.x.should.equal 150
l.y.should.equal 100
assert.equal l.constraintValues.left, null
assert.equal l.constraintValues.right, null
assert.equal l.constraintValues.top, null
assert.equal l.constraintValues.bottom, null
assert.equal l.constraintValues.centerAnchorX, 0.5
assert.equal l.constraintValues.centerAnchorY, 0.5
it "should update to center the layer vertically when centerX() is called", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
l.layout()
l.x.should.equal 0
l.centerX()
l.x.should.equal 150
assert.equal l.constraintValues.left, null
assert.equal l.constraintValues.right, null
assert.equal l.constraintValues.centerAnchorX, 0.5
it "should update to center the layer horizontally when centerY() is called", ->
l = new Layer
constraintValues:
aspectRatioLocked: true
l.layout()
l.y.should.equal 0
l.centerY()
l.y.should.equal 100
assert.equal l.constraintValues.top, null
assert.equal l.constraintValues.bottom, null
assert.equal l.constraintValues.centerAnchorY, 0.5
describe "when no constraints are set", ->
it "should not set the width constraint when setting the width", ->
l = new Layer
width: 100
l.width.should.equal 100
assert.equal l.constraintValues, null
l.width = 50
assert.equal l.constraintValues, null
it "should not set the height constraint when setting the height", ->
l = new Layer
height: 100
l.height.should.equal 100
assert.equal l.constraintValues, null
l.height = 50
assert.equal l.constraintValues, null
|
[
{
"context": "l\n expect(creds.accessKeyId).to.equal('akid')\n expect(creds.secretAccessKey).to.eq",
"end": 4730,
"score": 0.7713137269020081,
"start": 4726,
"tag": "KEY",
"value": "akid"
}
] | test/credential_provider_chain.spec.coffee | HIVETAXI/hive.taxi.sdk.js | 0 | helpers = require('./helpers')
HiveTaxi = helpers.HiveTaxi
if HiveTaxi.util.isNode()
describe 'HiveTaxi.CredentialProviderChain', ->
describe 'resolve', ->
chain = null
defaultProviders = HiveTaxi.CredentialProviderChain.defaultProviders
beforeEach (done) ->
process.env = {}
chain = new HiveTaxi.CredentialProviderChain [
-> new HiveTaxi.EnvironmentCredentials('HIVE'),
-> new HiveTaxi.EnvironmentCredentials('HIVETAXI')
]
done()
afterEach ->
HiveTaxi.CredentialProviderChain.defaultProviders = defaultProviders
process.env = {}
it 'returns an error by default', ->
chain.resolve (err) ->
expect(err.message).to.equal('Variable HIVETAXI_ACCESS_KEY_ID not set.')
it 'returns HIVE-prefixed credentials found in ENV', ->
process.env['HIVE_ACCESS_KEY_ID'] = 'akid'
process.env['HIVE_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVE_SESSION_TOKEN'] = 'session'
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('akid')
expect(creds.secretAccessKey).to.equal('secret')
expect(creds.sessionToken).to.equal('session')
it 'returns HIVETAXI-prefixed credentials found in ENV', ->
process.env['HIVETAXI_ACCESS_KEY_ID'] = 'akid'
process.env['HIVETAXI_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVETAXI_SESSION_TOKEN'] = 'session'
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('akid')
expect(creds.secretAccessKey).to.equal('secret')
expect(creds.sessionToken).to.equal('session')
it 'prefers HIVE credentials to HIVETAXI credentials', ->
process.env['HIVE_ACCESS_KEY_ID'] = 'akid'
process.env['HIVE_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVE_SESSION_TOKEN'] = 'session'
process.env['HIVETAXI_ACCESS_KEY_ID'] = 'akid2'
process.env['HIVETAXI_SECRET_ACCESS_KEY'] = 'secret2'
process.env['HIVETAXI_SESSION_TOKEN'] = 'session2'
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('akid')
expect(creds.secretAccessKey).to.equal('secret')
expect(creds.sessionToken).to.equal('session')
it 'uses the defaultProviders property on the constructor', ->
# remove default providers
HiveTaxi.CredentialProviderChain.defaultProviders = []
# these should now get ignored
process.env['HIVE_ACCESS_KEY_ID'] = 'akid'
process.env['HIVE_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVE_SESSION_TOKEN'] = 'session'
chain = new HiveTaxi.CredentialProviderChain()
chain.resolve (err) ->
expect(err.message).to.equal('No providers')
it 'calls resolve on each provider in the chain, stopping for akid', ->
staticCreds = accessKeyId: 'abc', secretAccessKey: 'xyz'
chain = new HiveTaxi.CredentialProviderChain([staticCreds])
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('abc')
expect(creds.secretAccessKey).to.equal('xyz')
expect(creds.sessionToken).to.equal(undefined)
it 'accepts providers as functions, elavuating them during resolution', ->
provider = ->
accessKeyId: 'abc', secretAccessKey: 'xyz'
chain = new HiveTaxi.CredentialProviderChain([provider])
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('abc')
expect(creds.secretAccessKey).to.equal('xyz')
expect(creds.sessionToken).to.equal(undefined)
if typeof Promise == 'function'
describe 'resolvePromise', ->
[err, creds, chain, forceError] = []
thenFunction = (c) ->
creds = c
catchFunction = (e) ->
err = e
mockProvider = ->
provider = new helpers.MockCredentialsProvider()
if forceError
provider.forceRefreshError = true
provider
before ->
HiveTaxi.config.setPromisesDependency()
beforeEach ->
err = null
creds = null
chain = new HiveTaxi.CredentialProviderChain([mockProvider])
it 'resolves when creds successfully retrieved from a provider in the chain', ->
forceError = false
# if a promise is returned from a test, then done callback not needed
# and next test will wait for promise to resolve before running
return chain.resolvePromise().then(thenFunction).catch(catchFunction).then ->
expect(err).to.be.null
expect(creds).to.not.be.null
expect(creds.accessKeyId).to.equal('akid')
expect(creds.secretAccessKey).to.equal('secret')
it 'rejects when all providers in chain return an error', ->
forceError = true
return chain.resolvePromise().then(thenFunction).catch(catchFunction).then ->
expect(err).to.not.be.null
expect(err.code).to.equal('MockCredentialsProviderFailure')
expect(creds).to.be.null
| 30189 | helpers = require('./helpers')
HiveTaxi = helpers.HiveTaxi
if HiveTaxi.util.isNode()
describe 'HiveTaxi.CredentialProviderChain', ->
describe 'resolve', ->
chain = null
defaultProviders = HiveTaxi.CredentialProviderChain.defaultProviders
beforeEach (done) ->
process.env = {}
chain = new HiveTaxi.CredentialProviderChain [
-> new HiveTaxi.EnvironmentCredentials('HIVE'),
-> new HiveTaxi.EnvironmentCredentials('HIVETAXI')
]
done()
afterEach ->
HiveTaxi.CredentialProviderChain.defaultProviders = defaultProviders
process.env = {}
it 'returns an error by default', ->
chain.resolve (err) ->
expect(err.message).to.equal('Variable HIVETAXI_ACCESS_KEY_ID not set.')
it 'returns HIVE-prefixed credentials found in ENV', ->
process.env['HIVE_ACCESS_KEY_ID'] = 'akid'
process.env['HIVE_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVE_SESSION_TOKEN'] = 'session'
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('akid')
expect(creds.secretAccessKey).to.equal('secret')
expect(creds.sessionToken).to.equal('session')
it 'returns HIVETAXI-prefixed credentials found in ENV', ->
process.env['HIVETAXI_ACCESS_KEY_ID'] = 'akid'
process.env['HIVETAXI_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVETAXI_SESSION_TOKEN'] = 'session'
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('akid')
expect(creds.secretAccessKey).to.equal('secret')
expect(creds.sessionToken).to.equal('session')
it 'prefers HIVE credentials to HIVETAXI credentials', ->
process.env['HIVE_ACCESS_KEY_ID'] = 'akid'
process.env['HIVE_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVE_SESSION_TOKEN'] = 'session'
process.env['HIVETAXI_ACCESS_KEY_ID'] = 'akid2'
process.env['HIVETAXI_SECRET_ACCESS_KEY'] = 'secret2'
process.env['HIVETAXI_SESSION_TOKEN'] = 'session2'
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('akid')
expect(creds.secretAccessKey).to.equal('secret')
expect(creds.sessionToken).to.equal('session')
it 'uses the defaultProviders property on the constructor', ->
# remove default providers
HiveTaxi.CredentialProviderChain.defaultProviders = []
# these should now get ignored
process.env['HIVE_ACCESS_KEY_ID'] = 'akid'
process.env['HIVE_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVE_SESSION_TOKEN'] = 'session'
chain = new HiveTaxi.CredentialProviderChain()
chain.resolve (err) ->
expect(err.message).to.equal('No providers')
it 'calls resolve on each provider in the chain, stopping for akid', ->
staticCreds = accessKeyId: 'abc', secretAccessKey: 'xyz'
chain = new HiveTaxi.CredentialProviderChain([staticCreds])
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('abc')
expect(creds.secretAccessKey).to.equal('xyz')
expect(creds.sessionToken).to.equal(undefined)
it 'accepts providers as functions, elavuating them during resolution', ->
provider = ->
accessKeyId: 'abc', secretAccessKey: 'xyz'
chain = new HiveTaxi.CredentialProviderChain([provider])
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('abc')
expect(creds.secretAccessKey).to.equal('xyz')
expect(creds.sessionToken).to.equal(undefined)
if typeof Promise == 'function'
describe 'resolvePromise', ->
[err, creds, chain, forceError] = []
thenFunction = (c) ->
creds = c
catchFunction = (e) ->
err = e
mockProvider = ->
provider = new helpers.MockCredentialsProvider()
if forceError
provider.forceRefreshError = true
provider
before ->
HiveTaxi.config.setPromisesDependency()
beforeEach ->
err = null
creds = null
chain = new HiveTaxi.CredentialProviderChain([mockProvider])
it 'resolves when creds successfully retrieved from a provider in the chain', ->
forceError = false
# if a promise is returned from a test, then done callback not needed
# and next test will wait for promise to resolve before running
return chain.resolvePromise().then(thenFunction).catch(catchFunction).then ->
expect(err).to.be.null
expect(creds).to.not.be.null
expect(creds.accessKeyId).to.equal('<KEY>')
expect(creds.secretAccessKey).to.equal('secret')
it 'rejects when all providers in chain return an error', ->
forceError = true
return chain.resolvePromise().then(thenFunction).catch(catchFunction).then ->
expect(err).to.not.be.null
expect(err.code).to.equal('MockCredentialsProviderFailure')
expect(creds).to.be.null
| true | helpers = require('./helpers')
HiveTaxi = helpers.HiveTaxi
if HiveTaxi.util.isNode()
describe 'HiveTaxi.CredentialProviderChain', ->
describe 'resolve', ->
chain = null
defaultProviders = HiveTaxi.CredentialProviderChain.defaultProviders
beforeEach (done) ->
process.env = {}
chain = new HiveTaxi.CredentialProviderChain [
-> new HiveTaxi.EnvironmentCredentials('HIVE'),
-> new HiveTaxi.EnvironmentCredentials('HIVETAXI')
]
done()
afterEach ->
HiveTaxi.CredentialProviderChain.defaultProviders = defaultProviders
process.env = {}
it 'returns an error by default', ->
chain.resolve (err) ->
expect(err.message).to.equal('Variable HIVETAXI_ACCESS_KEY_ID not set.')
it 'returns HIVE-prefixed credentials found in ENV', ->
process.env['HIVE_ACCESS_KEY_ID'] = 'akid'
process.env['HIVE_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVE_SESSION_TOKEN'] = 'session'
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('akid')
expect(creds.secretAccessKey).to.equal('secret')
expect(creds.sessionToken).to.equal('session')
it 'returns HIVETAXI-prefixed credentials found in ENV', ->
process.env['HIVETAXI_ACCESS_KEY_ID'] = 'akid'
process.env['HIVETAXI_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVETAXI_SESSION_TOKEN'] = 'session'
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('akid')
expect(creds.secretAccessKey).to.equal('secret')
expect(creds.sessionToken).to.equal('session')
it 'prefers HIVE credentials to HIVETAXI credentials', ->
process.env['HIVE_ACCESS_KEY_ID'] = 'akid'
process.env['HIVE_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVE_SESSION_TOKEN'] = 'session'
process.env['HIVETAXI_ACCESS_KEY_ID'] = 'akid2'
process.env['HIVETAXI_SECRET_ACCESS_KEY'] = 'secret2'
process.env['HIVETAXI_SESSION_TOKEN'] = 'session2'
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('akid')
expect(creds.secretAccessKey).to.equal('secret')
expect(creds.sessionToken).to.equal('session')
it 'uses the defaultProviders property on the constructor', ->
# remove default providers
HiveTaxi.CredentialProviderChain.defaultProviders = []
# these should now get ignored
process.env['HIVE_ACCESS_KEY_ID'] = 'akid'
process.env['HIVE_SECRET_ACCESS_KEY'] = 'secret'
process.env['HIVE_SESSION_TOKEN'] = 'session'
chain = new HiveTaxi.CredentialProviderChain()
chain.resolve (err) ->
expect(err.message).to.equal('No providers')
it 'calls resolve on each provider in the chain, stopping for akid', ->
staticCreds = accessKeyId: 'abc', secretAccessKey: 'xyz'
chain = new HiveTaxi.CredentialProviderChain([staticCreds])
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('abc')
expect(creds.secretAccessKey).to.equal('xyz')
expect(creds.sessionToken).to.equal(undefined)
it 'accepts providers as functions, elavuating them during resolution', ->
provider = ->
accessKeyId: 'abc', secretAccessKey: 'xyz'
chain = new HiveTaxi.CredentialProviderChain([provider])
chain.resolve (err, creds) ->
expect(creds.accessKeyId).to.equal('abc')
expect(creds.secretAccessKey).to.equal('xyz')
expect(creds.sessionToken).to.equal(undefined)
if typeof Promise == 'function'
describe 'resolvePromise', ->
[err, creds, chain, forceError] = []
thenFunction = (c) ->
creds = c
catchFunction = (e) ->
err = e
mockProvider = ->
provider = new helpers.MockCredentialsProvider()
if forceError
provider.forceRefreshError = true
provider
before ->
HiveTaxi.config.setPromisesDependency()
beforeEach ->
err = null
creds = null
chain = new HiveTaxi.CredentialProviderChain([mockProvider])
it 'resolves when creds successfully retrieved from a provider in the chain', ->
forceError = false
# if a promise is returned from a test, then done callback not needed
# and next test will wait for promise to resolve before running
return chain.resolvePromise().then(thenFunction).catch(catchFunction).then ->
expect(err).to.be.null
expect(creds).to.not.be.null
expect(creds.accessKeyId).to.equal('PI:KEY:<KEY>END_PI')
expect(creds.secretAccessKey).to.equal('secret')
it 'rejects when all providers in chain return an error', ->
forceError = true
return chain.resolvePromise().then(thenFunction).catch(catchFunction).then ->
expect(err).to.not.be.null
expect(err.code).to.equal('MockCredentialsProviderFailure')
expect(creds).to.be.null
|
[
{
"context": "ies:\n\t\t\t\tversion: '2.0.1'\n\t\t\t\tauthor:\n\t\t\t\t\tname: 'Gary'\n\t\t\tfallback: (key) ->\n\t\t\t\tif key is 'x'\n\t\t\t\t\t''\n",
"end": 207,
"score": 0.9997494220733643,
"start": 203,
"tag": "NAME",
"value": "Gary"
}
] | gulpfile.coffee | webyom/gulp-property-merge | 0 | gulp = require 'gulp'
gulp.task 'example', ->
propertyMerge = require './lib/index'
gulp.src('example/src/**/*.html')
.pipe propertyMerge
properties:
version: '2.0.1'
author:
name: 'Gary'
fallback: (key) ->
if key is 'x'
''
else if key is 'y'
false
else
key
.pipe gulp.dest('example/dest')
gulp.task 'default', ['example']
| 70401 | gulp = require 'gulp'
gulp.task 'example', ->
propertyMerge = require './lib/index'
gulp.src('example/src/**/*.html')
.pipe propertyMerge
properties:
version: '2.0.1'
author:
name: '<NAME>'
fallback: (key) ->
if key is 'x'
''
else if key is 'y'
false
else
key
.pipe gulp.dest('example/dest')
gulp.task 'default', ['example']
| true | gulp = require 'gulp'
gulp.task 'example', ->
propertyMerge = require './lib/index'
gulp.src('example/src/**/*.html')
.pipe propertyMerge
properties:
version: '2.0.1'
author:
name: 'PI:NAME:<NAME>END_PI'
fallback: (key) ->
if key is 'x'
''
else if key is 'y'
false
else
key
.pipe gulp.dest('example/dest')
gulp.task 'default', ['example']
|
[
{
"context": " && name?\n @name = name\n @password = password\n @users = []\n @status = \n v",
"end": 164,
"score": 0.9984664916992188,
"start": 156,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "have a Password and Name.'\n if Chatroo... | chatroom.coffee | teamtwofer/chat | 0 | http = require 'http'
class Chatroom
@rooms = {}
constructor: (name, password)->
if password? && name?
@name = name
@password = password
@users = []
@status =
valid: true
console.log 'New Chatroom made'
else
@status =
valid: false
reason: 'A Room Must have a Password and Name.'
if Chatroom.rooms[@name]?
# there's already a chatroom with this name
@status =
valid: false
reason: 'There is already a room with this name.'
@hasRoom: (name) ->
console.log("Chatroom.rooms[name] = #{Chatroom.rooms[name]}")
if Chatroom.rooms[name]?
return true
else
return false
@newChatroom: (name) ->
password = ''
console.log("Creating a new chatroom!")
room = new Chatroom(name, "potato")
console.log("room = #{name}")
Chatroom.rooms[room.name] = room
exports.Chatroom = Chatroom
| 40409 | http = require 'http'
class Chatroom
@rooms = {}
constructor: (name, password)->
if password? && name?
@name = name
@password = <PASSWORD>
@users = []
@status =
valid: true
console.log 'New Chatroom made'
else
@status =
valid: false
reason: 'A Room Must have a Password and Name.'
if Chatroom.rooms[@name]?
# there's already a chatroom with this name
@status =
valid: false
reason: 'There is already a room with this name.'
@hasRoom: (name) ->
console.log("Chatroom.rooms[name] = #{Chatroom.rooms[name]}")
if Chatroom.rooms[name]?
return true
else
return false
@newChatroom: (name) ->
password = ''
console.log("Creating a new chatroom!")
room = new Chatroom(name, "potato")
console.log("room = #{name}")
Chatroom.rooms[room.name] = room
exports.Chatroom = Chatroom
| true | http = require 'http'
class Chatroom
@rooms = {}
constructor: (name, password)->
if password? && name?
@name = name
@password = PI:PASSWORD:<PASSWORD>END_PI
@users = []
@status =
valid: true
console.log 'New Chatroom made'
else
@status =
valid: false
reason: 'A Room Must have a Password and Name.'
if Chatroom.rooms[@name]?
# there's already a chatroom with this name
@status =
valid: false
reason: 'There is already a room with this name.'
@hasRoom: (name) ->
console.log("Chatroom.rooms[name] = #{Chatroom.rooms[name]}")
if Chatroom.rooms[name]?
return true
else
return false
@newChatroom: (name) ->
password = ''
console.log("Creating a new chatroom!")
room = new Chatroom(name, "potato")
console.log("room = #{name}")
Chatroom.rooms[room.name] = room
exports.Chatroom = Chatroom
|
[
{
"context": " you less likely to get into combat.\n *\n * @name Dove\n * @prerequisite Enter 10 battles\n * @effect Le",
"end": 132,
"score": 0.9593607187271118,
"start": 128,
"tag": "NAME",
"value": "Dove"
}
] | src/character/personalities/Dove.coffee | sadbear-/IdleLands | 3 |
Personality = require "../base/Personality"
`/**
* This personality makes you less likely to get into combat.
*
* @name Dove
* @prerequisite Enter 10 battles
* @effect Less likely to get into battles
* @category Personalities
* @package Player
*/`
class Dove extends Personality
constructor: ->
eventModifier: (player, event) -> if event.type is "battle" then -300
@canUse = (player) ->
player.statistics["combat battle start"] >= 10
@desc = "Enter 10 battles"
module.exports = exports = Dove | 46918 |
Personality = require "../base/Personality"
`/**
* This personality makes you less likely to get into combat.
*
* @name <NAME>
* @prerequisite Enter 10 battles
* @effect Less likely to get into battles
* @category Personalities
* @package Player
*/`
class Dove extends Personality
constructor: ->
eventModifier: (player, event) -> if event.type is "battle" then -300
@canUse = (player) ->
player.statistics["combat battle start"] >= 10
@desc = "Enter 10 battles"
module.exports = exports = Dove | true |
Personality = require "../base/Personality"
`/**
* This personality makes you less likely to get into combat.
*
* @name PI:NAME:<NAME>END_PI
* @prerequisite Enter 10 battles
* @effect Less likely to get into battles
* @category Personalities
* @package Player
*/`
class Dove extends Personality
constructor: ->
eventModifier: (player, event) -> if event.type is "battle" then -300
@canUse = (player) ->
player.statistics["combat battle start"] >= 10
@desc = "Enter 10 battles"
module.exports = exports = Dove |
[
{
"context": "heinterface.getABI = (address) ->\n authCode = \"deadbeef\"\n payload = {authCode,address}\n url = \"",
"end": 397,
"score": 0.7894259691238403,
"start": 393,
"tag": "KEY",
"value": "dead"
},
{
"context": "terface.getABI = (address) ->\n authCode = \"deadbee... | source/specificinterface/abicacheinterface.coffee | JhonnyJason/pool-swap-ui-sources | 0 | abicacheinterface = {}
############################################################
#region checkResponse
extractABI = (response) ->
if typeof response.jsonABI != "object"
throw new Error("Unexpected Response: "+response)
return response.jsonABI
#endregion
############################################################
abicacheinterface.getABI = (address) ->
authCode = "deadbeef"
payload = {authCode,address}
url = "https://abi-cache.extensivlyon.coffee/getABI"
response = await @postData(url, payload)
return extractABI(response)
#endregion
module.exports = abicacheinterface
| 184768 | abicacheinterface = {}
############################################################
#region checkResponse
extractABI = (response) ->
if typeof response.jsonABI != "object"
throw new Error("Unexpected Response: "+response)
return response.jsonABI
#endregion
############################################################
abicacheinterface.getABI = (address) ->
authCode = "<KEY> <PASSWORD>"
payload = {authCode,address}
url = "https://abi-cache.extensivlyon.coffee/getABI"
response = await @postData(url, payload)
return extractABI(response)
#endregion
module.exports = abicacheinterface
| true | abicacheinterface = {}
############################################################
#region checkResponse
extractABI = (response) ->
if typeof response.jsonABI != "object"
throw new Error("Unexpected Response: "+response)
return response.jsonABI
#endregion
############################################################
abicacheinterface.getABI = (address) ->
authCode = "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI"
payload = {authCode,address}
url = "https://abi-cache.extensivlyon.coffee/getABI"
response = await @postData(url, payload)
return extractABI(response)
#endregion
module.exports = abicacheinterface
|
[
{
"context": "pleExpected\n done()\n\nauthorsExpected = \"* [Brian Woodward](http://github.com/doowb) \\n* [Jon Schlinkert](h",
"end": 1107,
"score": 0.9998701810836792,
"start": 1093,
"tag": "NAME",
"value": "Brian Woodward"
},
{
"context": "sExpected = \"* [Brian Woodward](... | experimental/tests/readme_test.coffee | helpers/handlebars-helpers-examples | 8 | require "should"
path = require("path")
grunt = require("grunt")
Handlebars = require("handlebars")
require("../../lib/helpers/helpers-markdown").register Handlebars, gfm: true
pkg = grunt.file.readJSON('package.json')
simple = "{{#markdown}}\n## Some Markdown\n\n - one\n - two\n - three\n\n[Click here](http://github.com)\n{{/markdown}}"
simpleExpected = "<h2>Some Markdown</h2>\n<ul>\n<li>one</li>\n<li>two</li>\n<li>three</li>\n</ul>\n<p><a href=\"http://github.com\">Click here</a></p>\n"
describe "markdown", ->
describe "should convert a block of markdown to HTML", ->
it "{{#markdown}}", (done) ->
template = Handlebars.compile(simple)
template().should.equal simpleExpected
done()
describe "md", ->
describe "should convert an imported markdown file to HTML", ->
it "{{md simple1.md}}", (done) ->
filename = path.join(__dirname, "../files/simple1.md")
source = "{{md filename}}"
template = Handlebars.compile(source)
template(filename: filename).should.equal simpleExpected
done()
authorsExpected = "* [Brian Woodward](http://github.com/doowb) \n* [Jon Schlinkert](http://github.com/jonschlinkert) "
describe "authors", ->
describe "{{authors [string]}}", ->
it "should return a list of authors in markdown format, from a user-defined data source", ->
source = "{{authors 'test/files/AUTHORS'}}"
template = Handlebars.compile(source)
template(context).should.equal authorsExpected
# Run this test if you have a correctly formatted AUTHORS file in the root of your project
describe "{{authors}}", ->
it "should return a list of authors in markdown format, from the default data source", ->
source = "{{authors}}"
template = Handlebars.compile(source)
template(context).should.equal authorsExpected
# changelogExpected = "* 2013-04-07\t\t\tv0.1.21\t\t\tAdd markdown helpers back, add more tests.\n* 2013-04-06\t\t\tv0.1.20\t\t\tGeneralized helpers structure, externalized utilities.\n* 2013-04-05\t\t\tv0.1.11\t\t\tNew authors and gist helpers, general cleanup and new tests.\n* 2013-04-04\t\t\tv0.1.10\t\t\tExternalized utility javascript from helpers.js\n* 2013-03-28\t\t\tv0.1.8\t\t\tGruntfile updated with mocha tests for 71 helpers, bug fixes.\n* 2013-03-18\t\t\tv0.1.7\t\t\tNew path helper \"relative\", for resolving relative path from one absolute path to another.\n* 2013-03-16\t\t\tv0.1.3\t\t\tNew helpers, \"formatPhoneNumber\" and \"eachProperty\"\n* 2013-03-15\t\t\tv0.1.2\t\t\tUpdate README.md with documentation, examples.\n* 2013-03-06\t\t\tv0.1.0\t\t\tFirst commit.\n"
# describe "changelog", ->
# describe "{{changelog [string]}}", ->
# it "should return a list of authors in markdown format, from a user-defined data source", ->
# source = "{{changelog 'test/files/CHANGELOG'}}"
# template = Handlebars.compile(source)
# template(context).should.equal changelogExpected
readmeTitleExpected = "[handlebars-helpers v" + pkg.version + "](https://github.com/assemble/handlebars-helpers)"
describe "readme-title", ->
describe "should generate a README title in markdown format, including version from package.json.", ->
it "{{readme-title}}", (done) ->
source = "{{readme-title}}"
template = Handlebars.compile(source)
template().should.equal readmeTitleExpected
done()
travisBadgeExpected = "[](https://travis-ci.org/assemble/handlebars-helpers)"
describe "travis-badge", ->
describe "should create a Travis CI link and badge in markdown format.", ->
it "{{travis-badge}}", (done) ->
source = "{{travis-badge}}"
template = Handlebars.compile(source)
template().should.equal travisBadgeExpected
done()
describe "travis", ->
describe "should create a Travis CI link in markdown format.", ->
it "{{travis}}", (done) ->
source = "{{travis}}"
template = Handlebars.compile(source)
template().should.equal "# [handlebars-helpers v" + pkg.version + "](https://github.com/assemble/handlebars-helpers) [](https://travis-ci.org/assemble/handlebars-helpers)"
done()
describe "travis with branch", ->
describe "should create a Travis CI link with branch in markdown format.", ->
it "{{travis 'master'}}", (done) ->
source = "{{travis 'wip-1.0.0'}}"
template = Handlebars.compile(source)
template().should.equal "# [handlebars-helpers v" + pkg.version + "](https://github.com/assemble/handlebars-helpers) [](https://travis-ci.org/assemble/handlebars-helpers)"
done()
| 81788 | require "should"
path = require("path")
grunt = require("grunt")
Handlebars = require("handlebars")
require("../../lib/helpers/helpers-markdown").register Handlebars, gfm: true
pkg = grunt.file.readJSON('package.json')
simple = "{{#markdown}}\n## Some Markdown\n\n - one\n - two\n - three\n\n[Click here](http://github.com)\n{{/markdown}}"
simpleExpected = "<h2>Some Markdown</h2>\n<ul>\n<li>one</li>\n<li>two</li>\n<li>three</li>\n</ul>\n<p><a href=\"http://github.com\">Click here</a></p>\n"
describe "markdown", ->
describe "should convert a block of markdown to HTML", ->
it "{{#markdown}}", (done) ->
template = Handlebars.compile(simple)
template().should.equal simpleExpected
done()
describe "md", ->
describe "should convert an imported markdown file to HTML", ->
it "{{md simple1.md}}", (done) ->
filename = path.join(__dirname, "../files/simple1.md")
source = "{{md filename}}"
template = Handlebars.compile(source)
template(filename: filename).should.equal simpleExpected
done()
authorsExpected = "* [<NAME>](http://github.com/doowb) \n* [<NAME>](http://github.com/jonschlinkert) "
describe "authors", ->
describe "{{authors [string]}}", ->
it "should return a list of authors in markdown format, from a user-defined data source", ->
source = "{{authors 'test/files/AUTHORS'}}"
template = Handlebars.compile(source)
template(context).should.equal authorsExpected
# Run this test if you have a correctly formatted AUTHORS file in the root of your project
describe "{{authors}}", ->
it "should return a list of authors in markdown format, from the default data source", ->
source = "{{authors}}"
template = Handlebars.compile(source)
template(context).should.equal authorsExpected
# changelogExpected = "* 2013-04-07\t\t\tv0.1.21\t\t\tAdd markdown helpers back, add more tests.\n* 2013-04-06\t\t\tv0.1.20\t\t\tGeneralized helpers structure, externalized utilities.\n* 2013-04-05\t\t\tv0.1.11\t\t\tNew authors and gist helpers, general cleanup and new tests.\n* 2013-04-04\t\t\tv0.1.10\t\t\tExternalized utility javascript from helpers.js\n* 2013-03-28\t\t\tv0.1.8\t\t\tGruntfile updated with mocha tests for 71 helpers, bug fixes.\n* 2013-03-18\t\t\tv0.1.7\t\t\tNew path helper \"relative\", for resolving relative path from one absolute path to another.\n* 2013-03-16\t\t\tv0.1.3\t\t\tNew helpers, \"formatPhoneNumber\" and \"eachProperty\"\n* 2013-03-15\t\t\tv0.1.2\t\t\tUpdate README.md with documentation, examples.\n* 2013-03-06\t\t\tv0.1.0\t\t\tFirst commit.\n"
# describe "changelog", ->
# describe "{{changelog [string]}}", ->
# it "should return a list of authors in markdown format, from a user-defined data source", ->
# source = "{{changelog 'test/files/CHANGELOG'}}"
# template = Handlebars.compile(source)
# template(context).should.equal changelogExpected
readmeTitleExpected = "[handlebars-helpers v" + pkg.version + "](https://github.com/assemble/handlebars-helpers)"
describe "readme-title", ->
describe "should generate a README title in markdown format, including version from package.json.", ->
it "{{readme-title}}", (done) ->
source = "{{readme-title}}"
template = Handlebars.compile(source)
template().should.equal readmeTitleExpected
done()
travisBadgeExpected = "[](https://travis-ci.org/assemble/handlebars-helpers)"
describe "travis-badge", ->
describe "should create a Travis CI link and badge in markdown format.", ->
it "{{travis-badge}}", (done) ->
source = "{{travis-badge}}"
template = Handlebars.compile(source)
template().should.equal travisBadgeExpected
done()
describe "travis", ->
describe "should create a Travis CI link in markdown format.", ->
it "{{travis}}", (done) ->
source = "{{travis}}"
template = Handlebars.compile(source)
template().should.equal "# [handlebars-helpers v" + pkg.version + "](https://github.com/assemble/handlebars-helpers) [](https://travis-ci.org/assemble/handlebars-helpers)"
done()
describe "travis with branch", ->
describe "should create a Travis CI link with branch in markdown format.", ->
it "{{travis 'master'}}", (done) ->
source = "{{travis 'wip-1.0.0'}}"
template = Handlebars.compile(source)
template().should.equal "# [handlebars-helpers v" + pkg.version + "](https://github.com/assemble/handlebars-helpers) [](https://travis-ci.org/assemble/handlebars-helpers)"
done()
| true | require "should"
path = require("path")
grunt = require("grunt")
Handlebars = require("handlebars")
require("../../lib/helpers/helpers-markdown").register Handlebars, gfm: true
pkg = grunt.file.readJSON('package.json')
simple = "{{#markdown}}\n## Some Markdown\n\n - one\n - two\n - three\n\n[Click here](http://github.com)\n{{/markdown}}"
simpleExpected = "<h2>Some Markdown</h2>\n<ul>\n<li>one</li>\n<li>two</li>\n<li>three</li>\n</ul>\n<p><a href=\"http://github.com\">Click here</a></p>\n"
describe "markdown", ->
describe "should convert a block of markdown to HTML", ->
it "{{#markdown}}", (done) ->
template = Handlebars.compile(simple)
template().should.equal simpleExpected
done()
describe "md", ->
describe "should convert an imported markdown file to HTML", ->
it "{{md simple1.md}}", (done) ->
filename = path.join(__dirname, "../files/simple1.md")
source = "{{md filename}}"
template = Handlebars.compile(source)
template(filename: filename).should.equal simpleExpected
done()
authorsExpected = "* [PI:NAME:<NAME>END_PI](http://github.com/doowb) \n* [PI:NAME:<NAME>END_PI](http://github.com/jonschlinkert) "
describe "authors", ->
describe "{{authors [string]}}", ->
it "should return a list of authors in markdown format, from a user-defined data source", ->
source = "{{authors 'test/files/AUTHORS'}}"
template = Handlebars.compile(source)
template(context).should.equal authorsExpected
# Run this test if you have a correctly formatted AUTHORS file in the root of your project
describe "{{authors}}", ->
it "should return a list of authors in markdown format, from the default data source", ->
source = "{{authors}}"
template = Handlebars.compile(source)
template(context).should.equal authorsExpected
# changelogExpected = "* 2013-04-07\t\t\tv0.1.21\t\t\tAdd markdown helpers back, add more tests.\n* 2013-04-06\t\t\tv0.1.20\t\t\tGeneralized helpers structure, externalized utilities.\n* 2013-04-05\t\t\tv0.1.11\t\t\tNew authors and gist helpers, general cleanup and new tests.\n* 2013-04-04\t\t\tv0.1.10\t\t\tExternalized utility javascript from helpers.js\n* 2013-03-28\t\t\tv0.1.8\t\t\tGruntfile updated with mocha tests for 71 helpers, bug fixes.\n* 2013-03-18\t\t\tv0.1.7\t\t\tNew path helper \"relative\", for resolving relative path from one absolute path to another.\n* 2013-03-16\t\t\tv0.1.3\t\t\tNew helpers, \"formatPhoneNumber\" and \"eachProperty\"\n* 2013-03-15\t\t\tv0.1.2\t\t\tUpdate README.md with documentation, examples.\n* 2013-03-06\t\t\tv0.1.0\t\t\tFirst commit.\n"
# describe "changelog", ->
# describe "{{changelog [string]}}", ->
# it "should return a list of authors in markdown format, from a user-defined data source", ->
# source = "{{changelog 'test/files/CHANGELOG'}}"
# template = Handlebars.compile(source)
# template(context).should.equal changelogExpected
readmeTitleExpected = "[handlebars-helpers v" + pkg.version + "](https://github.com/assemble/handlebars-helpers)"
describe "readme-title", ->
describe "should generate a README title in markdown format, including version from package.json.", ->
it "{{readme-title}}", (done) ->
source = "{{readme-title}}"
template = Handlebars.compile(source)
template().should.equal readmeTitleExpected
done()
travisBadgeExpected = "[](https://travis-ci.org/assemble/handlebars-helpers)"
describe "travis-badge", ->
describe "should create a Travis CI link and badge in markdown format.", ->
it "{{travis-badge}}", (done) ->
source = "{{travis-badge}}"
template = Handlebars.compile(source)
template().should.equal travisBadgeExpected
done()
describe "travis", ->
describe "should create a Travis CI link in markdown format.", ->
it "{{travis}}", (done) ->
source = "{{travis}}"
template = Handlebars.compile(source)
template().should.equal "# [handlebars-helpers v" + pkg.version + "](https://github.com/assemble/handlebars-helpers) [](https://travis-ci.org/assemble/handlebars-helpers)"
done()
describe "travis with branch", ->
describe "should create a Travis CI link with branch in markdown format.", ->
it "{{travis 'master'}}", (done) ->
source = "{{travis 'wip-1.0.0'}}"
template = Handlebars.compile(source)
template().should.equal "# [handlebars-helpers v" + pkg.version + "](https://github.com/assemble/handlebars-helpers) [](https://travis-ci.org/assemble/handlebars-helpers)"
done()
|
[
{
"context": " for non-existent types', ->\n expect(lib.at 'Fred').toEqual {}\n expect(lib.at 324234).toEqual ",
"end": 468,
"score": 0.8987912535667419,
"start": 464,
"tag": "NAME",
"value": "Fred"
},
{
"context": " lib = new Olib()\n lib.put()\n lib.put 'Fred'\... | spec/olib-spec.coffee | ibykow/stargame | 0 | people = require './fixtures/people'
Olib = require '../coffee/olib'
describe 'Olib', ->
[lib] = []
afterEach -> Olib.ids = {}
beforeEach ->
lib = new Olib()
lib.put person for person in people
describe 'new', ->
it 'should create a new object library', ->
expect(lib).toBeDefined()
expect(typeof lib.data).toBe 'object'
describe 'at', ->
it 'should return an empty object for non-existent types', ->
expect(lib.at 'Fred').toEqual {}
expect(lib.at 324234).toEqual {}
expect(lib.at null).toEqual {}
it 'should return the values for a given type', ->
dict = lib.at 'Person'
expect(dict).toBeDefined()
expect(typeof dict).toBe 'object'
for person in people
expect(person.id).toBeGreaterThan 0
expect(dict[person.id]).toBe person
describe 'get', ->
it 'should return undefined when given an invalid type and/or id', ->
expect(lib.get()).not.toBeDefined()
expect(lib.get null).not.toBeDefined()
expect(lib.get null, null).not.toBeDefined()
expect(lib.get 'Person').not.toBeDefined()
expect(lib.get 'Person', null).not.toBeDefined()
expect(lib.get 'Person', false).not.toBeDefined()
expect(lib.get 'Person', 0).not.toBeDefined()
expect(lib.get 'FFF').not.toBeDefined()
describe 'put', ->
it 'should insert entries', ->
expect(Olib.ids['Person']).toBe people.length + 1
it 'should ignore invalid entries', ->
lib = new Olib()
lib.put()
lib.put 'Fred'
lib.put 'Fred', 32
lib.put
name: 'Fred'
id: 23
expect(lib.data).toEqual {}
it 'should overwrite existing data', ->
firstPerson = people[0]
expect(lib.get 'Person', firstPerson.id).toBe firstPerson
firstName = firstPerson.name
secondName = firstName + '-Newton'
id = parseInt firstPerson.id
lib.put 'Person', id, name: secondName
secondPerson = lib.get 'Person', id
expect(id).toBe firstPerson.id
expect(secondPerson).not.toBe firstPerson
expect(secondPerson.name).toBe secondName
expect(firstPerson.name).toBe firstName
thirdName = secondName + '-Wilde'
thirdPerson =
name: thirdName
id: id
type: 'Person'
lib.put thirdPerson
person = lib.get 'Person', id
expect(person).toBe thirdPerson
expect(person).not.toBe firstPerson
expect(person).not.toBe secondPerson
expect(person.id).toBe id
expect(person.id).toBe firstPerson.id
expect(person.id).toBe secondPerson.id
expect(person.id).toBe thirdPerson.id
expect(person.name).toBe thirdName
expect(thirdName).not.toBe firstName
expect(thirdName).not.toBe secondName
expect(thirdName).not.toBe firstPerson.name
expect(thirdName).not.toBe secondPerson.name
describe 'remove', ->
it 'should remove entries', ->
expect(Object.keys(lib.at 'Person').length).toBe people.length
person = people[0]
expect(lib.get person.type, person.id).toBe person
lib.remove person
expect(lib.get person.type, person.id).not.toBeDefined()
expect(people[0]).toBe person
| 18043 | people = require './fixtures/people'
Olib = require '../coffee/olib'
describe 'Olib', ->
[lib] = []
afterEach -> Olib.ids = {}
beforeEach ->
lib = new Olib()
lib.put person for person in people
describe 'new', ->
it 'should create a new object library', ->
expect(lib).toBeDefined()
expect(typeof lib.data).toBe 'object'
describe 'at', ->
it 'should return an empty object for non-existent types', ->
expect(lib.at '<NAME>').toEqual {}
expect(lib.at 324234).toEqual {}
expect(lib.at null).toEqual {}
it 'should return the values for a given type', ->
dict = lib.at 'Person'
expect(dict).toBeDefined()
expect(typeof dict).toBe 'object'
for person in people
expect(person.id).toBeGreaterThan 0
expect(dict[person.id]).toBe person
describe 'get', ->
it 'should return undefined when given an invalid type and/or id', ->
expect(lib.get()).not.toBeDefined()
expect(lib.get null).not.toBeDefined()
expect(lib.get null, null).not.toBeDefined()
expect(lib.get 'Person').not.toBeDefined()
expect(lib.get 'Person', null).not.toBeDefined()
expect(lib.get 'Person', false).not.toBeDefined()
expect(lib.get 'Person', 0).not.toBeDefined()
expect(lib.get 'FFF').not.toBeDefined()
describe 'put', ->
it 'should insert entries', ->
expect(Olib.ids['Person']).toBe people.length + 1
it 'should ignore invalid entries', ->
lib = new Olib()
lib.put()
lib.put '<NAME>'
lib.put '<NAME>', 32
lib.put
name: '<NAME>'
id: 23
expect(lib.data).toEqual {}
it 'should overwrite existing data', ->
firstPerson = people[0]
expect(lib.get 'Person', firstPerson.id).toBe firstPerson
firstName = firstPerson.name
secondName = <NAME> + '-<NAME>'
id = parseInt firstPerson.id
lib.put 'Person', id, name: <NAME>Name
secondPerson = lib.get 'Person', id
expect(id).toBe firstPerson.id
expect(secondPerson).not.toBe firstPerson
expect(secondPerson.name).toBe secondName
expect(firstPerson.name).toBe firstName
thirdName = <NAME>Name + '-<NAME>'
thirdPerson =
name: <NAME>Name
id: id
type: 'Person'
lib.put thirdPerson
person = lib.get 'Person', id
expect(person).toBe thirdPerson
expect(person).not.toBe firstPerson
expect(person).not.toBe secondPerson
expect(person.id).toBe id
expect(person.id).toBe firstPerson.id
expect(person.id).toBe secondPerson.id
expect(person.id).toBe thirdPerson.id
expect(person.name).toBe thirdName
expect(thirdName).not.toBe firstName
expect(thirdName).not.toBe secondName
expect(thirdName).not.toBe firstPerson.name
expect(thirdName).not.toBe secondPerson.name
describe 'remove', ->
it 'should remove entries', ->
expect(Object.keys(lib.at 'Person').length).toBe people.length
person = people[0]
expect(lib.get person.type, person.id).toBe person
lib.remove person
expect(lib.get person.type, person.id).not.toBeDefined()
expect(people[0]).toBe person
| true | people = require './fixtures/people'
Olib = require '../coffee/olib'
describe 'Olib', ->
[lib] = []
afterEach -> Olib.ids = {}
beforeEach ->
lib = new Olib()
lib.put person for person in people
describe 'new', ->
it 'should create a new object library', ->
expect(lib).toBeDefined()
expect(typeof lib.data).toBe 'object'
describe 'at', ->
it 'should return an empty object for non-existent types', ->
expect(lib.at 'PI:NAME:<NAME>END_PI').toEqual {}
expect(lib.at 324234).toEqual {}
expect(lib.at null).toEqual {}
it 'should return the values for a given type', ->
dict = lib.at 'Person'
expect(dict).toBeDefined()
expect(typeof dict).toBe 'object'
for person in people
expect(person.id).toBeGreaterThan 0
expect(dict[person.id]).toBe person
describe 'get', ->
it 'should return undefined when given an invalid type and/or id', ->
expect(lib.get()).not.toBeDefined()
expect(lib.get null).not.toBeDefined()
expect(lib.get null, null).not.toBeDefined()
expect(lib.get 'Person').not.toBeDefined()
expect(lib.get 'Person', null).not.toBeDefined()
expect(lib.get 'Person', false).not.toBeDefined()
expect(lib.get 'Person', 0).not.toBeDefined()
expect(lib.get 'FFF').not.toBeDefined()
describe 'put', ->
it 'should insert entries', ->
expect(Olib.ids['Person']).toBe people.length + 1
it 'should ignore invalid entries', ->
lib = new Olib()
lib.put()
lib.put 'PI:NAME:<NAME>END_PI'
lib.put 'PI:NAME:<NAME>END_PI', 32
lib.put
name: 'PI:NAME:<NAME>END_PI'
id: 23
expect(lib.data).toEqual {}
it 'should overwrite existing data', ->
firstPerson = people[0]
expect(lib.get 'Person', firstPerson.id).toBe firstPerson
firstName = firstPerson.name
secondName = PI:NAME:<NAME>END_PI + '-PI:NAME:<NAME>END_PI'
id = parseInt firstPerson.id
lib.put 'Person', id, name: PI:NAME:<NAME>END_PIName
secondPerson = lib.get 'Person', id
expect(id).toBe firstPerson.id
expect(secondPerson).not.toBe firstPerson
expect(secondPerson.name).toBe secondName
expect(firstPerson.name).toBe firstName
thirdName = PI:NAME:<NAME>END_PIName + '-PI:NAME:<NAME>END_PI'
thirdPerson =
name: PI:NAME:<NAME>END_PIName
id: id
type: 'Person'
lib.put thirdPerson
person = lib.get 'Person', id
expect(person).toBe thirdPerson
expect(person).not.toBe firstPerson
expect(person).not.toBe secondPerson
expect(person.id).toBe id
expect(person.id).toBe firstPerson.id
expect(person.id).toBe secondPerson.id
expect(person.id).toBe thirdPerson.id
expect(person.name).toBe thirdName
expect(thirdName).not.toBe firstName
expect(thirdName).not.toBe secondName
expect(thirdName).not.toBe firstPerson.name
expect(thirdName).not.toBe secondPerson.name
describe 'remove', ->
it 'should remove entries', ->
expect(Object.keys(lib.at 'Person').length).toBe people.length
person = people[0]
expect(lib.get person.type, person.id).toBe person
lib.remove person
expect(lib.get person.type, person.id).not.toBeDefined()
expect(people[0]).toBe person
|
[
{
"context": "category: 'arts'\n }\n {\n title: 'Content Partner Liaison'\n description: 'We’re looking for an",
"end": 2042,
"score": 0.8745747804641724,
"start": 2035,
"tag": "NAME",
"value": "Partner"
},
{
"context": ": 'arts'\n }\n {\n title: 'Content P... | src/desktop/apps/jobs/test/fixture.coffee | kanaabe/force | 377 | module.exports =
header:
headline: 'Join Our Team'
description: 'Artsy is redefining the way the world discovers art. Our mission is to make all the world’s art accessible to anyone with an Internet connection. Reaching that goal starts with our people, and so we dedicate serious time and energy to find excellent new team members as passionate about our product as we are. Want to help us? We’d love to hear from you.'
images: [
{ src: 'https://artsy-media-uploads.s3.amazonaws.com/Ubhz4S84L2IoNpM5HJlBXA/artsy_jobsPage_lunch2.jpg' }
{ src: 'https://artsy-media-uploads.s3.amazonaws.com/Xb0dsOOB1fyyNAFCeO7Csg/artsy_jobsPage_alexanderKatWorking%20(1).jpg' }
{ src: 'https://artsy-media-uploads.s3.amazonaws.com/ucMryygHFE421jgk7jKMkQ/artsy_jobsPage_skyline02.jpg' }
]
jobs: [
{
title: 'Student Opportunities'
description: 'We are always looking for extraordinary undergraduates and graduates to join our growing team.'
href: '/job/students'
location: 'New York'
category: 'growth'
}
{
title: 'Art Fair Project Manager'
description: 'We’re looking for an art world professional to manage existing art fair relationships and identify new opportunities to expand Artsy’s presence worldwide.'
href: '/job/art-fair-project-manager'
location: 'New York'
category: 'arts'
}
{
title: 'Art Fair Content Partner Liaison'
description: 'We’re looking for a flawlessly organized individual with a track record of excellence and an eagerness to learn to support our growing Art Fairs team.'
href: '/job/art-fair-content-partner-liaison'
location: 'New York'
category: 'arts'
}
{
title: 'Content Partner Liaison'
description: 'We’re looking for an art world professional to manage existing relationships and identify new opportunities to expand Artsy’s presence worldwide.'
href: '/job/liaison-ny'
location: 'New York'
category: 'arts'
}
{
title: 'Content Partner Liaison'
description: 'We’re looking for an art world professional to manage existing relationships and identify new opportunities to expand Artsy’s presence in Asia.'
href: '/job/liaison-hk'
location: 'Hong Kong'
category: 'arts'
}
{
title: 'Content Partner Liaison'
description: 'Artsy seeks an art world professional to manage existing relationships and identify new opportunities to expand Artsy’s presence in the Western U.S.'
href: '/job/liaison-la'
location: 'Los Angeles'
category: 'arts'
}
{
title: 'Curatorial Liaison'
description: 'Artsy seeks an art world professional to help manage relationships with museums, foundations, photo archives, arts organizations, and other institutions.'
href: '/job/curatorial-liaison'
location: 'New York'
category: 'arts'
}
{
title: 'Communications Intern (Fall)'
description: 'We’re looking for a Communications Intern to help execute press, media, and event initiatives that strengthen and elevate our brand.'
href: '/job/communications-intern'
location: 'New York'
category: 'product'
}
{
title: 'Digital Marketing Intern (Fall)'
description: 'We’re looking for a Digital Marketing Intern to help us build and implement our growth and digital marketing strategies.'
href: '/job/digital-marketing-intern'
location: 'New York'
category: 'growth'
}
{
title: 'Editorial Intern (Fall)'
description: 'We’re looking for a motivated and hard-working individual to help us produce exciting, engaging, and educational context and dialogue around artists and artworks on the site. '
href: '/job/editorial-intern'
location: 'New York'
category: 'arts'
}
{
title: 'Research Intern on the Art Genome Project (Fall)'
description: 'We’re looking for Research Interns who are passionate about creating access to art to contribute to the The Art Genome Project, Artsy’s evolving search technology for discovering art.'
href: '/job/tagp-fall-internship'
location: 'New York'
category: 'arts'
}
{
title: 'Artwork Sales Intern (Fall)'
description: 'We are seeking an engaging and driven individual to assist us in executing Artsy’s ever-evolving sales strategy.'
href: '/job/sales-intern'
location: 'New York'
category: 'arts'
}
{
title: 'Freelance Arts Writer'
description: 'We’re looking for freelance writers with existing arts writing experience to craft editorial pieces around gallery and museum exhibitions, artists’ practices, artist biographies, art fairs, and more.'
href: '/job/freelance-writer'
location: 'New York'
category: 'arts'
}
{
title: 'Full Stack Software Engineer'
description: 'You’re an experienced full stack software engineer with an impressive track record in building complex distributed applications written in Ruby and JavaScript. You have used relational databases and have some experience with document or key-value stores, such as MongoDB or Redis.'
href: '/job/developer'
location: 'New York'
category: 'product'
}
{
title: 'Mobile Engineer'
description: 'You are a full stack software engineer turned mobile, because you believe in a future where every individual carries a powerful and portable micro-computer.'
href: '/job/mobile-engineer'
location: 'New York'
category: 'product'
}
{
title: 'DevOps Engineer'
description: 'You’re an experienced operations engineer passionate about deployment automation in large and complex distributed systems.'
href: '/job/devops-engineer'
location: 'New York'
category: 'product'
}
{
title: 'Product Designer'
description: 'Your mission: define the future of the art experiences. You will drive design projects from start to finish across web, mobile and touch.'
href: '/job/product-designer'
location: 'New York'
category: 'product'
}
]
| 146398 | module.exports =
header:
headline: 'Join Our Team'
description: 'Artsy is redefining the way the world discovers art. Our mission is to make all the world’s art accessible to anyone with an Internet connection. Reaching that goal starts with our people, and so we dedicate serious time and energy to find excellent new team members as passionate about our product as we are. Want to help us? We’d love to hear from you.'
images: [
{ src: 'https://artsy-media-uploads.s3.amazonaws.com/Ubhz4S84L2IoNpM5HJlBXA/artsy_jobsPage_lunch2.jpg' }
{ src: 'https://artsy-media-uploads.s3.amazonaws.com/Xb0dsOOB1fyyNAFCeO7Csg/artsy_jobsPage_alexanderKatWorking%20(1).jpg' }
{ src: 'https://artsy-media-uploads.s3.amazonaws.com/ucMryygHFE421jgk7jKMkQ/artsy_jobsPage_skyline02.jpg' }
]
jobs: [
{
title: 'Student Opportunities'
description: 'We are always looking for extraordinary undergraduates and graduates to join our growing team.'
href: '/job/students'
location: 'New York'
category: 'growth'
}
{
title: 'Art Fair Project Manager'
description: 'We’re looking for an art world professional to manage existing art fair relationships and identify new opportunities to expand Artsy’s presence worldwide.'
href: '/job/art-fair-project-manager'
location: 'New York'
category: 'arts'
}
{
title: 'Art Fair Content Partner Liaison'
description: 'We’re looking for a flawlessly organized individual with a track record of excellence and an eagerness to learn to support our growing Art Fairs team.'
href: '/job/art-fair-content-partner-liaison'
location: 'New York'
category: 'arts'
}
{
title: 'Content Partner Liaison'
description: 'We’re looking for an art world professional to manage existing relationships and identify new opportunities to expand Artsy’s presence worldwide.'
href: '/job/liaison-ny'
location: 'New York'
category: 'arts'
}
{
title: 'Content <NAME> <NAME>'
description: 'We’re looking for an art world professional to manage existing relationships and identify new opportunities to expand Artsy’s presence in Asia.'
href: '/job/liaison-hk'
location: 'Hong Kong'
category: 'arts'
}
{
title: '<NAME> <NAME>'
description: 'Artsy seeks an art world professional to manage existing relationships and identify new opportunities to expand Artsy’s presence in the Western U.S.'
href: '/job/liaison-la'
location: 'Los Angeles'
category: 'arts'
}
{
title: '<NAME>'
description: 'Artsy seeks an art world professional to help manage relationships with museums, foundations, photo archives, arts organizations, and other institutions.'
href: '/job/curatorial-liaison'
location: 'New York'
category: 'arts'
}
{
title: 'Communications Intern (Fall)'
description: 'We’re looking for a Communications Intern to help execute press, media, and event initiatives that strengthen and elevate our brand.'
href: '/job/communications-intern'
location: 'New York'
category: 'product'
}
{
title: 'Digital Marketing Intern (Fall)'
description: 'We’re looking for a Digital Marketing Intern to help us build and implement our growth and digital marketing strategies.'
href: '/job/digital-marketing-intern'
location: 'New York'
category: 'growth'
}
{
title: 'Editorial Intern (Fall)'
description: 'We’re looking for a motivated and hard-working individual to help us produce exciting, engaging, and educational context and dialogue around artists and artworks on the site. '
href: '/job/editorial-intern'
location: 'New York'
category: 'arts'
}
{
title: 'Research Intern on the Art Genome Project (Fall)'
description: 'We’re looking for Research Interns who are passionate about creating access to art to contribute to the The Art Genome Project, Artsy’s evolving search technology for discovering art.'
href: '/job/tagp-fall-internship'
location: 'New York'
category: 'arts'
}
{
title: 'Artwork Sales Intern (Fall)'
description: 'We are seeking an engaging and driven individual to assist us in executing Artsy’s ever-evolving sales strategy.'
href: '/job/sales-intern'
location: 'New York'
category: 'arts'
}
{
title: 'Freelance Arts Writer'
description: 'We’re looking for freelance writers with existing arts writing experience to craft editorial pieces around gallery and museum exhibitions, artists’ practices, artist biographies, art fairs, and more.'
href: '/job/freelance-writer'
location: 'New York'
category: 'arts'
}
{
title: 'Full Stack Software Engineer'
description: 'You’re an experienced full stack software engineer with an impressive track record in building complex distributed applications written in Ruby and JavaScript. You have used relational databases and have some experience with document or key-value stores, such as MongoDB or Redis.'
href: '/job/developer'
location: 'New York'
category: 'product'
}
{
title: 'Mobile Engineer'
description: 'You are a full stack software engineer turned mobile, because you believe in a future where every individual carries a powerful and portable micro-computer.'
href: '/job/mobile-engineer'
location: 'New York'
category: 'product'
}
{
title: 'DevOps Engineer'
description: 'You’re an experienced operations engineer passionate about deployment automation in large and complex distributed systems.'
href: '/job/devops-engineer'
location: 'New York'
category: 'product'
}
{
title: 'Product Designer'
description: 'Your mission: define the future of the art experiences. You will drive design projects from start to finish across web, mobile and touch.'
href: '/job/product-designer'
location: 'New York'
category: 'product'
}
]
| true | module.exports =
header:
headline: 'Join Our Team'
description: 'Artsy is redefining the way the world discovers art. Our mission is to make all the world’s art accessible to anyone with an Internet connection. Reaching that goal starts with our people, and so we dedicate serious time and energy to find excellent new team members as passionate about our product as we are. Want to help us? We’d love to hear from you.'
images: [
{ src: 'https://artsy-media-uploads.s3.amazonaws.com/Ubhz4S84L2IoNpM5HJlBXA/artsy_jobsPage_lunch2.jpg' }
{ src: 'https://artsy-media-uploads.s3.amazonaws.com/Xb0dsOOB1fyyNAFCeO7Csg/artsy_jobsPage_alexanderKatWorking%20(1).jpg' }
{ src: 'https://artsy-media-uploads.s3.amazonaws.com/ucMryygHFE421jgk7jKMkQ/artsy_jobsPage_skyline02.jpg' }
]
jobs: [
{
title: 'Student Opportunities'
description: 'We are always looking for extraordinary undergraduates and graduates to join our growing team.'
href: '/job/students'
location: 'New York'
category: 'growth'
}
{
title: 'Art Fair Project Manager'
description: 'We’re looking for an art world professional to manage existing art fair relationships and identify new opportunities to expand Artsy’s presence worldwide.'
href: '/job/art-fair-project-manager'
location: 'New York'
category: 'arts'
}
{
title: 'Art Fair Content Partner Liaison'
description: 'We’re looking for a flawlessly organized individual with a track record of excellence and an eagerness to learn to support our growing Art Fairs team.'
href: '/job/art-fair-content-partner-liaison'
location: 'New York'
category: 'arts'
}
{
title: 'Content Partner Liaison'
description: 'We’re looking for an art world professional to manage existing relationships and identify new opportunities to expand Artsy’s presence worldwide.'
href: '/job/liaison-ny'
location: 'New York'
category: 'arts'
}
{
title: 'Content PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
description: 'We’re looking for an art world professional to manage existing relationships and identify new opportunities to expand Artsy’s presence in Asia.'
href: '/job/liaison-hk'
location: 'Hong Kong'
category: 'arts'
}
{
title: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
description: 'Artsy seeks an art world professional to manage existing relationships and identify new opportunities to expand Artsy’s presence in the Western U.S.'
href: '/job/liaison-la'
location: 'Los Angeles'
category: 'arts'
}
{
title: 'PI:NAME:<NAME>END_PI'
description: 'Artsy seeks an art world professional to help manage relationships with museums, foundations, photo archives, arts organizations, and other institutions.'
href: '/job/curatorial-liaison'
location: 'New York'
category: 'arts'
}
{
title: 'Communications Intern (Fall)'
description: 'We’re looking for a Communications Intern to help execute press, media, and event initiatives that strengthen and elevate our brand.'
href: '/job/communications-intern'
location: 'New York'
category: 'product'
}
{
title: 'Digital Marketing Intern (Fall)'
description: 'We’re looking for a Digital Marketing Intern to help us build and implement our growth and digital marketing strategies.'
href: '/job/digital-marketing-intern'
location: 'New York'
category: 'growth'
}
{
title: 'Editorial Intern (Fall)'
description: 'We’re looking for a motivated and hard-working individual to help us produce exciting, engaging, and educational context and dialogue around artists and artworks on the site. '
href: '/job/editorial-intern'
location: 'New York'
category: 'arts'
}
{
title: 'Research Intern on the Art Genome Project (Fall)'
description: 'We’re looking for Research Interns who are passionate about creating access to art to contribute to the The Art Genome Project, Artsy’s evolving search technology for discovering art.'
href: '/job/tagp-fall-internship'
location: 'New York'
category: 'arts'
}
{
title: 'Artwork Sales Intern (Fall)'
description: 'We are seeking an engaging and driven individual to assist us in executing Artsy’s ever-evolving sales strategy.'
href: '/job/sales-intern'
location: 'New York'
category: 'arts'
}
{
title: 'Freelance Arts Writer'
description: 'We’re looking for freelance writers with existing arts writing experience to craft editorial pieces around gallery and museum exhibitions, artists’ practices, artist biographies, art fairs, and more.'
href: '/job/freelance-writer'
location: 'New York'
category: 'arts'
}
{
title: 'Full Stack Software Engineer'
description: 'You’re an experienced full stack software engineer with an impressive track record in building complex distributed applications written in Ruby and JavaScript. You have used relational databases and have some experience with document or key-value stores, such as MongoDB or Redis.'
href: '/job/developer'
location: 'New York'
category: 'product'
}
{
title: 'Mobile Engineer'
description: 'You are a full stack software engineer turned mobile, because you believe in a future where every individual carries a powerful and portable micro-computer.'
href: '/job/mobile-engineer'
location: 'New York'
category: 'product'
}
{
title: 'DevOps Engineer'
description: 'You’re an experienced operations engineer passionate about deployment automation in large and complex distributed systems.'
href: '/job/devops-engineer'
location: 'New York'
category: 'product'
}
{
title: 'Product Designer'
description: 'Your mission: define the future of the art experiences. You will drive design projects from start to finish across web, mobile and touch.'
href: '/job/product-designer'
location: 'New York'
category: 'product'
}
]
|
[
{
"context": "ew SftpHelper\n host: host\n username: username\n password: password\n sourceFolder: ",
"end": 5688,
"score": 0.9942387342453003,
"start": 5680,
"tag": "USERNAME",
"value": "username"
},
{
"context": " host\n username: username\n ... | src/coffee/run.coffee | celeste-horgan/sphere-stock-import | 0 | path = require 'path'
_ = require 'underscore'
Promise = require 'bluebird'
fs = Promise.promisifyAll require('fs')
tmp = Promise.promisifyAll require('tmp')
{ExtendedLogger, ProjectCredentialsConfig} = require 'sphere-node-utils'
package_json = require '../package.json'
StockImport = require './stockimport'
SftpHelper = require './sftp'
argv = require('optimist')
.usage('Usage: $0 --projectKey [key] --clientId [id] --clientSecret [secret] --file [file] --logDir [dir] --logLevel [level]')
.describe('projectKey', 'your SPHERE.IO project-key')
.describe('clientId', 'your OAuth client id for the SPHERE.IO API')
.describe('clientSecret', 'your OAuth client secret for the SPHERE.IO API')
.describe('accessToken', 'an OAuth access token for the SPHERE.IO API')
.describe('sphereHost', 'SPHERE.IO API host to connecto to')
.describe('sphereProtocol', 'SPHERE.IO API protocol to connect to')
.describe('sphereAuthHost', 'SPHERE.IO OAuth host to connect to')
.describe('sphereAuthProtocol', 'SPHERE.IO OAuth protocol to connect to')
.describe('file', 'XML or CSV file containing inventory information to import')
.describe('csvDelimiter', 'the delimiter type used in the csv')
.describe('sftpCredentials', 'the path to a JSON file where to read the credentials from')
.describe('sftpHost', 'the SFTP host (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpUsername', 'the SFTP username (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpPassword', 'the SFTP password (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpSource', 'path in the SFTP server from where to read the files')
.describe('sftpTarget', 'path in the SFTP server to where to move the worked files')
.describe('sftpFileRegex', 'a RegEx to filter files when downloading them')
.describe('sftpMaxFilesToProcess', 'how many files need to be processed, if more then one is found')
.describe('sftpContinueOnProblems', 'ignore errors when processing a file and continue with the next one')
.describe('sftpFileWithTimestamp', 'whether the processed file should be renamed by appending a timestamp')
.describe('logLevel', 'log level for file logging')
.describe('logDir', 'directory to store logs')
.describe('logSilent', 'use console to print messages')
.describe('timeout', 'Set timeout for requests')
.default('csvDelimiter', ',')
.default('logLevel', 'info')
.default('logDir', '.')
.default('logSilent', false)
.default('timeout', 60000)
.default('sftpContinueOnProblems', false)
.default('sftpFileWithTimestamp', false)
.demand(['projectKey'])
.argv
logOptions =
name: "#{package_json.name}-#{package_json.version}"
streams: [
{ level: 'error', stream: process.stderr }
{ level: argv.logLevel, path: "#{argv.logDir}/#{package_json.name}.log" }
]
logOptions.silent = argv.logSilent if argv.logSilent
logger = new ExtendedLogger
additionalFields:
project_key: argv.projectKey
logConfig: logOptions
if argv.logSilent
logger.bunyanLogger.trace = -> # noop
logger.bunyanLogger.debug = -> # noop
process.on 'SIGUSR2', -> logger.reopenFileStreams()
process.on 'exit', => process.exit(@exitCode)
importFn = (importer, fileName) ->
throw new Error 'You must provide a file to be processed' unless fileName
logger.debug "About to process file #{fileName}"
mode = importer.getMode fileName
fs.readFileAsync fileName, {encoding: 'utf-8'}
.then (content) ->
logger.debug 'File read, running import'
importer.run(content, mode)
.then ->
message = importer.summaryReport(fileName)
logger.withField({filename: fileName}).info message
Promise.resolve fileName
readJsonFromPath = (path) ->
return Promise.resolve({}) unless path
fs.readFileAsync(path, {encoding: 'utf-8'}).then (content) ->
Promise.resolve JSON.parse(content)
ensureCredentials = (argv) ->
if argv.accessToken
Promise.resolve
config:
project_key: argv.projectKey
access_token: argv.accessToken
else
ProjectCredentialsConfig.create()
.then (credentials) ->
Promise.resolve
config: credentials.enrichCredentials
project_key: argv.projectKey
client_id: argv.clientId
client_secret: argv.clientSecret
ensureCredentials(argv)
.then (credentials) =>
options = _.extend credentials,
timeout: argv.timeout
user_agent: "#{package_json.name} - #{package_json.version}"
csvDelimiter: argv.csvDelimiter
options.host = argv.sphereHost if argv.sphereHost
options.protocol = argv.sphereProtocol if argv.sphereProtocol
if argv.sphereAuthHost
options.oauth_host = argv.sphereAuthHost
options.rejectUnauthorized = false
options.oauth_protocol = argv.sphereAuthProtocol if argv.sphereAuthProtocol
stockimport = new StockImport logger, options
file = argv.file
if file
importFn(stockimport, file)
.then => @exitCode = 0
.catch (error) =>
logger.error error, 'Oops, something went wrong when processing file (no SFTP)!'
@exitCode = 1
.done()
else
tmp.setGracefulCleanup()
readJsonFromPath(argv.sftpCredentials)
.then (sftpCredentials) =>
projectSftpCredentials = sftpCredentials[argv.projectKey] or {}
{host, username, password} = _.defaults projectSftpCredentials,
host: argv.sftpHost
username: argv.sftpUsername
password: argv.sftpPassword
throw new Error 'Missing sftp host' unless host
throw new Error 'Missing sftp username' unless username
throw new Error 'Missing sftp password' unless password
sftpHelper = new SftpHelper
host: host
username: username
password: password
sourceFolder: argv.sftpSource
targetFolder: argv.sftpTarget
fileRegex: argv.sftpFileRegex
logger: logger
# unsafeCleanup: recursively removes the created temporary directory, even when it's not empty
tmp.dirAsync {unsafeCleanup: true}
.then (tmpPath) ->
logger.debug "Tmp folder created at #{tmpPath}"
sftpHelper.download(tmpPath)
.then (files) ->
logger.debug files, "Processing #{files.length} files..."
filesToProcess =
if argv.sftpMaxFilesToProcess and _.isNumber(argv.sftpMaxFilesToProcess) and argv.sftpMaxFilesToProcess > 0
logger.info "Processing max #{argv.sftpMaxFilesToProcess} files"
_.first files, argv.sftpMaxFilesToProcess
else
files
filesSkipped = 0
Promise.map filesToProcess, (file) ->
importFn(stockimport, "#{tmpPath}/#{file}")
.then ->
if argv.sftpFileWithTimestamp
ts = (new Date()).getTime()
filename = switch
when file.match /\.csv$/i then file.substring(0, file.length - 4) + "_#{ts}.csv"
when file.match /\.xml$/i then file.substring(0, file.length - 4) + "_#{ts}.xml"
else file
else
filename = file
logger.debug "Finishing processing file #{file}"
sftpHelper.finish(file, filename)
.then ->
logger.info "File #{filename} was successfully processed and marked as done on remote SFTP server"
Promise.resolve()
.catch (err) ->
if argv.sftpContinueOnProblems
filesSkipped++
logger.warn err, "There was an error processing the file #{file}, skipping and continue"
Promise.resolve()
else
Promise.reject err
, {concurrency: 1}
.then =>
totFiles = _.size(filesToProcess)
if totFiles > 0
logger.info "Import successfully finished: #{totFiles - filesSkipped} out of #{totFiles} files were processed"
else
logger.info "Import successfully finished: there were no new files to be processed"
@exitCode = 0
.catch (error) =>
logger.error error, 'Oops, something went wrong!'
@exitCode = 1
.done()
.catch (err) =>
logger.error err, "Problems on getting sftp credentials from config files."
@exitCode = 1
.done()
.catch (err) =>
logger.error err, "Problems on getting client credentials from config files."
@exitCode = 1
.done()
| 124854 | path = require 'path'
_ = require 'underscore'
Promise = require 'bluebird'
fs = Promise.promisifyAll require('fs')
tmp = Promise.promisifyAll require('tmp')
{ExtendedLogger, ProjectCredentialsConfig} = require 'sphere-node-utils'
package_json = require '../package.json'
StockImport = require './stockimport'
SftpHelper = require './sftp'
argv = require('optimist')
.usage('Usage: $0 --projectKey [key] --clientId [id] --clientSecret [secret] --file [file] --logDir [dir] --logLevel [level]')
.describe('projectKey', 'your SPHERE.IO project-key')
.describe('clientId', 'your OAuth client id for the SPHERE.IO API')
.describe('clientSecret', 'your OAuth client secret for the SPHERE.IO API')
.describe('accessToken', 'an OAuth access token for the SPHERE.IO API')
.describe('sphereHost', 'SPHERE.IO API host to connecto to')
.describe('sphereProtocol', 'SPHERE.IO API protocol to connect to')
.describe('sphereAuthHost', 'SPHERE.IO OAuth host to connect to')
.describe('sphereAuthProtocol', 'SPHERE.IO OAuth protocol to connect to')
.describe('file', 'XML or CSV file containing inventory information to import')
.describe('csvDelimiter', 'the delimiter type used in the csv')
.describe('sftpCredentials', 'the path to a JSON file where to read the credentials from')
.describe('sftpHost', 'the SFTP host (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpUsername', 'the SFTP username (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpPassword', 'the SFTP password (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpSource', 'path in the SFTP server from where to read the files')
.describe('sftpTarget', 'path in the SFTP server to where to move the worked files')
.describe('sftpFileRegex', 'a RegEx to filter files when downloading them')
.describe('sftpMaxFilesToProcess', 'how many files need to be processed, if more then one is found')
.describe('sftpContinueOnProblems', 'ignore errors when processing a file and continue with the next one')
.describe('sftpFileWithTimestamp', 'whether the processed file should be renamed by appending a timestamp')
.describe('logLevel', 'log level for file logging')
.describe('logDir', 'directory to store logs')
.describe('logSilent', 'use console to print messages')
.describe('timeout', 'Set timeout for requests')
.default('csvDelimiter', ',')
.default('logLevel', 'info')
.default('logDir', '.')
.default('logSilent', false)
.default('timeout', 60000)
.default('sftpContinueOnProblems', false)
.default('sftpFileWithTimestamp', false)
.demand(['projectKey'])
.argv
logOptions =
name: "#{package_json.name}-#{package_json.version}"
streams: [
{ level: 'error', stream: process.stderr }
{ level: argv.logLevel, path: "#{argv.logDir}/#{package_json.name}.log" }
]
logOptions.silent = argv.logSilent if argv.logSilent
logger = new ExtendedLogger
additionalFields:
project_key: argv.projectKey
logConfig: logOptions
if argv.logSilent
logger.bunyanLogger.trace = -> # noop
logger.bunyanLogger.debug = -> # noop
process.on 'SIGUSR2', -> logger.reopenFileStreams()
process.on 'exit', => process.exit(@exitCode)
importFn = (importer, fileName) ->
throw new Error 'You must provide a file to be processed' unless fileName
logger.debug "About to process file #{fileName}"
mode = importer.getMode fileName
fs.readFileAsync fileName, {encoding: 'utf-8'}
.then (content) ->
logger.debug 'File read, running import'
importer.run(content, mode)
.then ->
message = importer.summaryReport(fileName)
logger.withField({filename: fileName}).info message
Promise.resolve fileName
readJsonFromPath = (path) ->
return Promise.resolve({}) unless path
fs.readFileAsync(path, {encoding: 'utf-8'}).then (content) ->
Promise.resolve JSON.parse(content)
ensureCredentials = (argv) ->
if argv.accessToken
Promise.resolve
config:
project_key: argv.projectKey
access_token: argv.accessToken
else
ProjectCredentialsConfig.create()
.then (credentials) ->
Promise.resolve
config: credentials.enrichCredentials
project_key: argv.projectKey
client_id: argv.clientId
client_secret: argv.clientSecret
ensureCredentials(argv)
.then (credentials) =>
options = _.extend credentials,
timeout: argv.timeout
user_agent: "#{package_json.name} - #{package_json.version}"
csvDelimiter: argv.csvDelimiter
options.host = argv.sphereHost if argv.sphereHost
options.protocol = argv.sphereProtocol if argv.sphereProtocol
if argv.sphereAuthHost
options.oauth_host = argv.sphereAuthHost
options.rejectUnauthorized = false
options.oauth_protocol = argv.sphereAuthProtocol if argv.sphereAuthProtocol
stockimport = new StockImport logger, options
file = argv.file
if file
importFn(stockimport, file)
.then => @exitCode = 0
.catch (error) =>
logger.error error, 'Oops, something went wrong when processing file (no SFTP)!'
@exitCode = 1
.done()
else
tmp.setGracefulCleanup()
readJsonFromPath(argv.sftpCredentials)
.then (sftpCredentials) =>
projectSftpCredentials = sftpCredentials[argv.projectKey] or {}
{host, username, password} = _.defaults projectSftpCredentials,
host: argv.sftpHost
username: argv.sftpUsername
password: argv.sftpPassword
throw new Error 'Missing sftp host' unless host
throw new Error 'Missing sftp username' unless username
throw new Error 'Missing sftp password' unless password
sftpHelper = new SftpHelper
host: host
username: username
password: <PASSWORD>
sourceFolder: argv.sftpSource
targetFolder: argv.sftpTarget
fileRegex: argv.sftpFileRegex
logger: logger
# unsafeCleanup: recursively removes the created temporary directory, even when it's not empty
tmp.dirAsync {unsafeCleanup: true}
.then (tmpPath) ->
logger.debug "Tmp folder created at #{tmpPath}"
sftpHelper.download(tmpPath)
.then (files) ->
logger.debug files, "Processing #{files.length} files..."
filesToProcess =
if argv.sftpMaxFilesToProcess and _.isNumber(argv.sftpMaxFilesToProcess) and argv.sftpMaxFilesToProcess > 0
logger.info "Processing max #{argv.sftpMaxFilesToProcess} files"
_.first files, argv.sftpMaxFilesToProcess
else
files
filesSkipped = 0
Promise.map filesToProcess, (file) ->
importFn(stockimport, "#{tmpPath}/#{file}")
.then ->
if argv.sftpFileWithTimestamp
ts = (new Date()).getTime()
filename = switch
when file.match /\.csv$/i then file.substring(0, file.length - 4) + "_#{ts}.csv"
when file.match /\.xml$/i then file.substring(0, file.length - 4) + "_#{ts}.xml"
else file
else
filename = file
logger.debug "Finishing processing file #{file}"
sftpHelper.finish(file, filename)
.then ->
logger.info "File #{filename} was successfully processed and marked as done on remote SFTP server"
Promise.resolve()
.catch (err) ->
if argv.sftpContinueOnProblems
filesSkipped++
logger.warn err, "There was an error processing the file #{file}, skipping and continue"
Promise.resolve()
else
Promise.reject err
, {concurrency: 1}
.then =>
totFiles = _.size(filesToProcess)
if totFiles > 0
logger.info "Import successfully finished: #{totFiles - filesSkipped} out of #{totFiles} files were processed"
else
logger.info "Import successfully finished: there were no new files to be processed"
@exitCode = 0
.catch (error) =>
logger.error error, 'Oops, something went wrong!'
@exitCode = 1
.done()
.catch (err) =>
logger.error err, "Problems on getting sftp credentials from config files."
@exitCode = 1
.done()
.catch (err) =>
logger.error err, "Problems on getting client credentials from config files."
@exitCode = 1
.done()
| true | path = require 'path'
_ = require 'underscore'
Promise = require 'bluebird'
fs = Promise.promisifyAll require('fs')
tmp = Promise.promisifyAll require('tmp')
{ExtendedLogger, ProjectCredentialsConfig} = require 'sphere-node-utils'
package_json = require '../package.json'
StockImport = require './stockimport'
SftpHelper = require './sftp'
argv = require('optimist')
.usage('Usage: $0 --projectKey [key] --clientId [id] --clientSecret [secret] --file [file] --logDir [dir] --logLevel [level]')
.describe('projectKey', 'your SPHERE.IO project-key')
.describe('clientId', 'your OAuth client id for the SPHERE.IO API')
.describe('clientSecret', 'your OAuth client secret for the SPHERE.IO API')
.describe('accessToken', 'an OAuth access token for the SPHERE.IO API')
.describe('sphereHost', 'SPHERE.IO API host to connecto to')
.describe('sphereProtocol', 'SPHERE.IO API protocol to connect to')
.describe('sphereAuthHost', 'SPHERE.IO OAuth host to connect to')
.describe('sphereAuthProtocol', 'SPHERE.IO OAuth protocol to connect to')
.describe('file', 'XML or CSV file containing inventory information to import')
.describe('csvDelimiter', 'the delimiter type used in the csv')
.describe('sftpCredentials', 'the path to a JSON file where to read the credentials from')
.describe('sftpHost', 'the SFTP host (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpUsername', 'the SFTP username (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpPassword', 'the SFTP password (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpSource', 'path in the SFTP server from where to read the files')
.describe('sftpTarget', 'path in the SFTP server to where to move the worked files')
.describe('sftpFileRegex', 'a RegEx to filter files when downloading them')
.describe('sftpMaxFilesToProcess', 'how many files need to be processed, if more then one is found')
.describe('sftpContinueOnProblems', 'ignore errors when processing a file and continue with the next one')
.describe('sftpFileWithTimestamp', 'whether the processed file should be renamed by appending a timestamp')
.describe('logLevel', 'log level for file logging')
.describe('logDir', 'directory to store logs')
.describe('logSilent', 'use console to print messages')
.describe('timeout', 'Set timeout for requests')
.default('csvDelimiter', ',')
.default('logLevel', 'info')
.default('logDir', '.')
.default('logSilent', false)
.default('timeout', 60000)
.default('sftpContinueOnProblems', false)
.default('sftpFileWithTimestamp', false)
.demand(['projectKey'])
.argv
logOptions =
name: "#{package_json.name}-#{package_json.version}"
streams: [
{ level: 'error', stream: process.stderr }
{ level: argv.logLevel, path: "#{argv.logDir}/#{package_json.name}.log" }
]
logOptions.silent = argv.logSilent if argv.logSilent
logger = new ExtendedLogger
additionalFields:
project_key: argv.projectKey
logConfig: logOptions
if argv.logSilent
logger.bunyanLogger.trace = -> # noop
logger.bunyanLogger.debug = -> # noop
process.on 'SIGUSR2', -> logger.reopenFileStreams()
process.on 'exit', => process.exit(@exitCode)
importFn = (importer, fileName) ->
throw new Error 'You must provide a file to be processed' unless fileName
logger.debug "About to process file #{fileName}"
mode = importer.getMode fileName
fs.readFileAsync fileName, {encoding: 'utf-8'}
.then (content) ->
logger.debug 'File read, running import'
importer.run(content, mode)
.then ->
message = importer.summaryReport(fileName)
logger.withField({filename: fileName}).info message
Promise.resolve fileName
readJsonFromPath = (path) ->
return Promise.resolve({}) unless path
fs.readFileAsync(path, {encoding: 'utf-8'}).then (content) ->
Promise.resolve JSON.parse(content)
ensureCredentials = (argv) ->
if argv.accessToken
Promise.resolve
config:
project_key: argv.projectKey
access_token: argv.accessToken
else
ProjectCredentialsConfig.create()
.then (credentials) ->
Promise.resolve
config: credentials.enrichCredentials
project_key: argv.projectKey
client_id: argv.clientId
client_secret: argv.clientSecret
ensureCredentials(argv)
.then (credentials) =>
options = _.extend credentials,
timeout: argv.timeout
user_agent: "#{package_json.name} - #{package_json.version}"
csvDelimiter: argv.csvDelimiter
options.host = argv.sphereHost if argv.sphereHost
options.protocol = argv.sphereProtocol if argv.sphereProtocol
if argv.sphereAuthHost
options.oauth_host = argv.sphereAuthHost
options.rejectUnauthorized = false
options.oauth_protocol = argv.sphereAuthProtocol if argv.sphereAuthProtocol
stockimport = new StockImport logger, options
file = argv.file
if file
importFn(stockimport, file)
.then => @exitCode = 0
.catch (error) =>
logger.error error, 'Oops, something went wrong when processing file (no SFTP)!'
@exitCode = 1
.done()
else
tmp.setGracefulCleanup()
readJsonFromPath(argv.sftpCredentials)
.then (sftpCredentials) =>
projectSftpCredentials = sftpCredentials[argv.projectKey] or {}
{host, username, password} = _.defaults projectSftpCredentials,
host: argv.sftpHost
username: argv.sftpUsername
password: argv.sftpPassword
throw new Error 'Missing sftp host' unless host
throw new Error 'Missing sftp username' unless username
throw new Error 'Missing sftp password' unless password
sftpHelper = new SftpHelper
host: host
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
sourceFolder: argv.sftpSource
targetFolder: argv.sftpTarget
fileRegex: argv.sftpFileRegex
logger: logger
# unsafeCleanup: recursively removes the created temporary directory, even when it's not empty
tmp.dirAsync {unsafeCleanup: true}
.then (tmpPath) ->
logger.debug "Tmp folder created at #{tmpPath}"
sftpHelper.download(tmpPath)
.then (files) ->
logger.debug files, "Processing #{files.length} files..."
filesToProcess =
if argv.sftpMaxFilesToProcess and _.isNumber(argv.sftpMaxFilesToProcess) and argv.sftpMaxFilesToProcess > 0
logger.info "Processing max #{argv.sftpMaxFilesToProcess} files"
_.first files, argv.sftpMaxFilesToProcess
else
files
filesSkipped = 0
Promise.map filesToProcess, (file) ->
importFn(stockimport, "#{tmpPath}/#{file}")
.then ->
if argv.sftpFileWithTimestamp
ts = (new Date()).getTime()
filename = switch
when file.match /\.csv$/i then file.substring(0, file.length - 4) + "_#{ts}.csv"
when file.match /\.xml$/i then file.substring(0, file.length - 4) + "_#{ts}.xml"
else file
else
filename = file
logger.debug "Finishing processing file #{file}"
sftpHelper.finish(file, filename)
.then ->
logger.info "File #{filename} was successfully processed and marked as done on remote SFTP server"
Promise.resolve()
.catch (err) ->
if argv.sftpContinueOnProblems
filesSkipped++
logger.warn err, "There was an error processing the file #{file}, skipping and continue"
Promise.resolve()
else
Promise.reject err
, {concurrency: 1}
.then =>
totFiles = _.size(filesToProcess)
if totFiles > 0
logger.info "Import successfully finished: #{totFiles - filesSkipped} out of #{totFiles} files were processed"
else
logger.info "Import successfully finished: there were no new files to be processed"
@exitCode = 0
.catch (error) =>
logger.error error, 'Oops, something went wrong!'
@exitCode = 1
.done()
.catch (err) =>
logger.error err, "Problems on getting sftp credentials from config files."
@exitCode = 1
.done()
.catch (err) =>
logger.error err, "Problems on getting client credentials from config files."
@exitCode = 1
.done()
|
[
{
"context": "ever, it soon became apparent to a gentleman named Vernon Dvorak that the intensity of a tropical cyclone could be",
"end": 7030,
"score": 0.9983288645744324,
"start": 7017,
"tag": "NAME",
"value": "Vernon Dvorak"
},
{
"context": "mg src=\"images/about/science-team/chri... | app/lib/en-us.coffee | zooniverse/Cyclone-Center | 2 | module.exports =
navigation:
home: 'Home'
classify: 'Investigate'
about: 'About'
profile: 'Profile'
talk: 'Talk'
blog: 'Blog'
home:
projectHeader: 'Cyclone<br>Center'
projectHeaderSuper: 'Welcome to'
projectTag: 'Tropical cyclones are still a mystery.<br />We need your help to decipher them.'
intro:
header: 'What is Cyclone Center?'
content:'''
<p>
The climatology of tropical cyclones is limited by uncertainties in the historical record. Patterns in storms imagery are best recognized by the human eye, so we need your help analyzing these storms.
</p>
<p>Are you ready to start investigating?</p>
'''
getStarted: 'Get Started'
learnMore: 'Learn More'
stats:
activeUsers: 'Active Users'
observations: 'Observations'
stormsComplete: 'Images Complete'
talk:
header: 'Recent Storm Comments from Talk'
latestTalk: 'Loading latest talk discussions...'
viewDiscussion: 'View the discussion'
blog:
header: 'The Cyclone Center Blog'
loadingLatestPost: 'Loading latest post...'
previousPostTitle: 'Previous Posts'
loadingPreviousPost: 'Loading previous posts...'
getInvolved: 'Ready to get involved?'
about:
header: 'About Cyclone Center'
subHeader: 'The what, why, how, and who of Cyclone Center.'
credit: 'Image credit: WP:WPTC/M, NASA'
youtubeLink: 'Youtube'
overview:
header: '<div class="about-top-header">Scientists and Volunteers Team Up to Solve Storms</div>'
navigation: 'About Cyclone Center'
content: '''
<section>
<div class="about-container">
<img src="./images/about/about-example1.jpg" alt="Storm example">
<div>
<h2 class="about-non-italic-header">We don't understand all the mysteries of tropical cyclones</h2>
<p>In particular, research is inconsistent about the wind speeds of these storms, making it difficult to understand how climate change has affected the nature and strength of cyclones.</p>
<p class="image-credit">Image credit: NASA JPL</p>
</div>
</div>
</section>
<section>
<div class="about-container">
<img src="./images/about/about-example2.png" alt="Storm example">
<div>
<h2 class="about-non-italic-header">Infrared satellite images may hold the answers.</h2>
<p>We have nearly 300,000 satellite images of tropical cyclones since 1978. When these images are classified with the "Dvorak technique," we can extract critical information about the storms.</p>
</div>
<div class="about-container">
</section>
<section>
<div class="about-container">
<img src="./images/about/about-eye.png" alt="Stylized eye using storm imagery">
<div>
<h2 class="about-non-italic-header">Human eyes are best for finding information in these images.</h2>
<p>By answering a few simple questions, volunteers can apply a modified Dvorak technique to interpret satellite images even more effectively than the best computers.</p>
</div>
</div>
</section>
<section>
<div class="about-container center about-col">
<h2 class="about-non-italic-header">You can help us learn, and predict future cyclone behavior.</h2>
<p>The work of Cyclone Center volunteers will help us create a new database of information about cyclones, which will help climatologists better estimate the intensity of future storms.</p>
</div>
</section>
<section>
<div class="about-container center about-col">
<h2 class="about-non-italic-header">Are you ready to help?</h2>
<a href="#/classify">Get started investigating!</a>
</div>
</section>
'''
howItWorks:
header: 'Snapshots of Cyclones'
navigation: 'How It Works'
content:'''
<p>The images you see on Cyclone Center were observed by infrared sensors on weather satellites. These sensors provide an estimate of the temperature at the tops of clouds. Cloud top temperatures are very important because they give us an idea of how tall the clouds are. Temperature decreases with height in the lower atmosphere (up to 10 miles), so cold clouds are taller than warm clouds. Taller clouds are responsible for the heavy rain and thunderstorms that drive tropical cyclones.</p>
<p>In the Cyclone Center images, the cloud top temperatures are represented by a range of colors. The scale on the image below shows the temperatures in degrees Celsius that correspond with each color.</p>
<p>Black and gray are the warmest, indicating temperatures from 9°C (48°F) to 30°C (86°F). Often these will be the temperatures we experience at the land or ocean surface, but they can also be associated with very shallow clouds. Shades of pink go down to -30°C (-22°F). In our images, these are almost always associated with shallow clouds. Red, orange, and yellow come next, and they indicate medium-level clouds.</p>
<p>In most images, the coldest clouds you see will be shades of blue. Sometimes you’ll even see a cloud that’s so cold it shows up as white. These clouds are colder than -85°C (-121°F). Coastlines and political borders are also drawn in white, so make sure the white clouds are surrounded by dark blue. Otherwise, you might just be looking at a small island.</p>
<p>Sometimes there is a problem with parts of the satellite data. These missing data will show up as black lines in the images. Just ignore them and carry on with the analysis when you see them.</p>
<div id="image-diagram">
<img src="images/about/diagram.jpg" />
</div>
<h2>The <span data-popup="#mr-dvorak bottom cameo">Dvorak</span> Technique</h2>
<p>Prior to the 1960s, tropical cyclones were rarely observed unless they moved close to populated areas, happened to move near an unfortunate ship or occurred in the North Atlantic or Western Pacific (where routine aircraft flights monitored tropical weather systems). Fortunately, geostationary satellites were developed and launched during the 1960s. These satellites orbit the earth at very high altitudes (~22,300 miles or 35,900 km), allowing them to orbit at the same speed as the earth rotates. This allows for the satellite to always “see” the same large area and thus continuously monitor the oceans for tropical cyclone activity.</p>
<p>Despite this important advance, scientists and forecasters still had little hope of determining how strong the winds were (“intensity”) in a tropical cyclone from just looking at a picture of it. Only a very small fraction of tropical cyclones were measured directly by specially designed aircraft. However, it soon became apparent to a gentleman named Vernon Dvorak that the intensity of a tropical cyclone could be skillfully approximated by simply analyzing the cloud patterns and temperatures from a single satellite image. Dvorak developed and improved his method (now called the “Dvorak Technique”) in the 1970s and early 1980s.</p>
<p>The technique consists of a set of 10 steps, which can be simplified to produce the answers to four important questions:</p>
<ol>
<li>Where is the center of the system?</li>
<li>What type of cloud pattern best describes the system?</li>
<li>How organized or intense is the cloud pattern?</li>
<li>Does the system look stronger or weaker than 24 hours ago?</li>
</ol>
<p>Sometimes the answers to these questions are not clear, making the application of the Dvorak technique subjective. Tropical cyclone analysts and forecasters must be trained to successfully apply the many rules and constraints that the technique makes. Even then, experts frequently disagree, which has led to numerous inconsistencies in the tropical cyclone record.</p>
<p>The Dvorak technique was adopted by many of the world’s tropical cyclone forecast centers and remains today as one of the most important tools for estimating tropical cyclone intensity. In this project, you are using a version of the Dvorak technique for classifying tropical cyclones that have formed since the late 1970s. We hope that the application of thousands of classifiers will help resolve the differences in the global tropical cyclone record and improve our understanding of how the nature of these storms may have changed through time.</p>
'''
organizations:
header: 'Organizations Partnering in Cyclone Center'
navigation: 'Organizations'
content:'''
<div class="team-member">
<img src="images/about/organizations/cisc.png" alt="CISC logo" />
<h4>Cooperative Institute for Climate and Satellites</h4>
<p>The Cooperative Institute for Climate and Satellites (CICS), established under a cooperative agreement with the National Oceanic and Atmospheric Administration (NOAA) in 2009, is a consortium of research institutions that focuses on enhancing the collective interdisciplinary understanding of the state and evolution of the full Earth System. The CICS consortium is led by the University of Maryland, College Park and North Carolina State University on behalf of the University of North Carolina (UNC) System. CICS-NC is hosted by NC State University.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/noaa.png" alt="NOAA logo" />
<h4>NOAA'S National Climatic Data Center (NCDC)</h4>
<p>NCDC maintains the world's largest climate data archive and provides climatological services and data to every sector of the United States economy and to users worldwide. The archive contains paleoclimatic data to centuries-old journals to data less than an hour old. The Center's mission is to preserve these data and make them available to the general public, business, industry, government and researchers.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/rpi.png" alt="RPI logo" />
<h4>Risk Prediction Initiative</h4>
<p>The Risk Prediction Initiative (RPI2.0) funds academic research relevant to the insurance and (re)insurance industry and assists in translating this research into usable and actionable results for our member companies. Our experienced management team combines expert knowledge of climate-related natural disasters with a background in risk management. We help scientists refocus their interests on needs and time-scales relevant to the (re)insurance industry, in addition to stimulating and supporting high-level research on natural hazards such as hurricanes, typhoons and tornadoes. We are located within the Bermuda Institute of Ocean Science and as a result we have long standing relationships with many leading scientists, allowing our members direct access to the scientific community. We offer our members unique access to scientific, engineering and economic knowledge aimed at answering business relevant questions.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/asheville.png" alt="UNC-Asheville logo" />
<h4>University of North Carolina at Asheville</h4>
<p>UNC Asheville, the only designated public liberal arts university in North Carolina, offers more than 30 majors ranging from chemistry, atmospheric sciences and environmental studies to art, new media and international studies. The university is known for its award-winning undergraduate research and humanities programs.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/zooniverse.png" alt="Zooniverse logo" />
<h4>The Zooniverse</h4>
<p>The Zooniverse and the suite of projects it contains is produced, maintained and developed by the Citizen Science Alliance. The member institutions of the CSA work with many academic and other partners around the world to produce projects that use the efforts and ability of volunteers to help scientists and researchers deal with the flood of data that confronts them.</p>
</div>
'''
team:
header: 'Meet the Cyclone Center Team'
navigation: 'Team'
content:'''
<h3>Science team</h3>
<div class="team-member">
<img src="images/about/science-team/chris.jpg" alt="Chris Hennon" />
<h4>Chris Hennon</h4>
<p>Chris Hennon is an associate professor of atmospheric sciences at the University of North Carolina at Asheville. Specializing in tropical cyclone formation, Chris came to Asheville after spending two years as a visiting scientist at the U.S. National Hurricane Center in Miami, Florida. Chris enjoys golf, racquetball, and chess in his free time.</p>
</div>
<div class="team-member">
<img src="images/about/science-team/ken.jpg" alt="Ken Knapps" />
<h4>Ken Knapp</h4>
<p>Ken Knapp is a meteorologist at NOAA’s National Climatic Data Center in Asheville, NC. His research interests include using satellite data to observe hurricanes, clouds, and other climate variables. His career took a tropical turn in 2005 when an NCDC customer requested satellite imagery of all tropical cyclones, rejuvenating an interest in hurricanes that began with his 7th grade science fair project.</p>
</div>
<div class="team-member">
<img src="images/about/science-team/carl.jpg" alt="Carl Schreck" />
<h4>Carl Schreck</h4>
<p>Carl Schreck is a research meteorologist at the Cooperative Institute for Climate and Satellites (CICS-NC). He is exploring tropical weather patterns to better understand and predict how hurricanes and other tropical cyclones form. Carl’s fascination with hurricanes began when Hurricane Fran struck his hometown of Raleigh, NC in 1996.</p>
</div>
<div class="team-member">
<img src="images/about/science-team/scott.jpg" alt="Scott Stevens" />
<h4>Scott Stevens</h4>
<p>Scott Stevens is a research associate at the Cooperative Institute for Climate and Satellites (CICS-NC). He is working on the development of a new rainfall dataset using NOAA’s network of NEXRAD radars, specializing in data analysis and organization. He is a private pilot and enjoys baseball and traveling in his spare time.</p>
</div>
<hr />
<h3>Development team</h3>
<div class="team-member">
<img src="images/about/dev-team/kelly.jpg" alt="Kelly Borden" />
<h4>Kelly Borden</h4>
<p>Kelly is an archaeologist by training but an educator by passion. While working at the Museum of Science and Industry and the Adler Planetarium she became an enthusiastic science educator eager to bring science to the masses. When not pondering the wonders of science, Kelly can often be found baking or spending time with her herd of cats – Murray, Ada, & Kepler.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/brian.jpg" alt="Brian Carstensen" />
<h4>Brian Carstensen</h4>
<p>Brian is a web developer working on the Zooniverse family of projects at the Adler Planearium. Brian has a degree in graphic design from Columbia College in Chicago, and worked in that field for a number of years before finding a niche in web development.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/chris.jpg" alt="Chris Lintott" />
<h4>Chris Lintott</h4>
<p>Chris Lintott leads the Zooniverse team, and in his copious spare time is a researcher at the University of Oxford specialising in galaxy formation and evolution. A keen popularizer of science, he is best known as co-presenter of the BBC's long running Sky at Night program. He's currently drinking a lot of sherry.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/david.jpg" alt="David Miller" />
<h4>David Miller</h4>
<p>As a visual communicator, David is passionate about tellings stories through clear, clean, and effective design. Before joining the Zooniverse team as Visual Designer, David worked for The Raindance Film Festival, the News 21 Initiative's Apart From War, Syracuse Magazine, and as a freelance designer for his small business, Miller Visual. David is a graduate of the S.I. Newhouse School of Public Communications at Syracuse University, where he studied Visual & Interactive Communications.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/michael.jpg" alt="Michael Parrish" />
<h4>Michael Parrish</h4>
<p>Michael has a degree in Computer Science and has been working with The Zooniverse for the past three years as a Software Developer. Aside from web development; new technologies, science, AI, reptiles, and coffee tend to occupy his attention.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/arfon.jpg" alt="Arfon Smith" />
<h4>Arfon Smith</h4>
<p>As an undergraduate, Arfon studied Chemistry at the University of Sheffield before completing his Ph.D. in Astrochemistry at The University of Nottingham in 2006. He worked as a senior developer at the Wellcome Trust Sanger Institute (Human Genome Project) in Cambridge before joining the Galaxy Zoo team in Oxford. Over the past 3 years he has been responsible for leading the development of a platform for citizen science called Zooniverse. In August of 2011 he took up the position of Director of Citizen Science at the Adler Planetarium where he continues to lead the software and infrastructure development for the Zooniverse.</p>
</div>
'''
profile:
hello: 'Hello'
imageCount: 'Images Marked'
favoriteCount: 'Favorite Count'
recents: 'Recents'
favorites: 'Favorites'
siteIntro:
one:
image: './images/site-intro/welcome.jpg'
title: 'Welcome!'
content: "Welcome to Cyclone Center! With this project, we’re trying to learn more about how tropical cyclones form and change. By answering a few simple questions about these satellite images, you’ll help climatologists to predict future storm behavior."
two:
image: './images/site-intro/stronger-storm.gif'
title: 'Pick the stronger storm'
content: "You’ll be given two satellite images and asked to select the stronger storm. After that, you’ll be asked additional questions about the <strong>image on the right.</strong> Please note that <strong>this may not always be the stronger storm.</strong>"
three:
image: './images/site-intro/additional-questions.gif'
title: 'Answer additional questions'
content: "If you need help identifying the storm type, scroll down for a guide. Once you have picked a storm type, you’ll be asked a few more questions about the nature, size, and strength of the storm."
four:
image: './images/site-intro/tutorial.gif'
title: 'Give it a shot'
content: "Don’t worry if you’re unsure—each image will be shown to many people, and your best guess is far more helpful to us than nothing! If you need step-by-step guidance, you can also click the “tutorial” link for a walkthrough."
five:
image: './images/site-intro/final.jpg'
title: 'Discuss and read more!'
content: "Want to learn more, or discuss what you’ve seen? Chat with other Cyclone Center volunteers on our Talk page, or check out the Cyclone Center blog for more information. Happy stormwatching!"
nextButtonText: 'Next'
finishButtonText: 'Finish'
classify:
header: 'Investigations—Classify the cyclone by answering the questions below.'
favorite: 'Favorite'
continue: 'Continue'
finish: 'Finish'
restart: 'Restart Image'
guide: 'Guide'
favorite: 'Favorite'
favorited: 'Favorited'
talkSubject: 'Discuss the image'
talkGroup: 'Discuss the storm'
share: 'Share on Facebook'
tweet: 'Tweet this'
next: 'Next'
restartTutorial: 'Tutorial'
slideTutorial: 'Site Intro'
cycloneFieldGuide: 'Cyclone Field Guide'
notSignedIn: '''
You're not logged in! Logged in volunteers can keep track of what they've worked on, and receive credit for their work in publications. It also helps us combine everyone's classifications more efficiently.
'''
pleaseSignIn: '''
Please log in now
'''
or: 'or'
signUp: '''
sign up for a new account.
'''
matches:
postTropical: 'Post-Tropical'
edge: 'Edge'
noStorm: 'No Storm'
categories:
eye: 'Eye'
embedded: 'Embedded'
curved: 'Curved'
shear: 'Shear'
other: 'Other'
strengths:
older: 'Left'
olderTop: 'Top'
same: "They're about the same"
current: 'Right'
currentBottom: 'Bottom'
steps:
stronger:
instruction: 'Choose the storm image that appears <strong>stronger</strong>.'
explanation: '''
<h2>Choose the storm image that appears stronger</h2>
<p>To determine which storm is stronger, consider two questions:</p>
<h2>Which storm has colder clouds?</h2>
<p>Colder colors in infrared satellite imagery indicate taller clouds that release more energy into a storm. Stronger storms have more of these cold clouds near their centers.</p>
<h2>How organized are the clouds?</h2>
<p>Stronger storms have tighter spirals, especially near the center where the cold clouds become more circular. For example, storms with an eye are almost always stronger than storms without one. The strongest cyclones have eyes that are more circular, smaller and/or warmer in the middle.</p>
<h2>Use the images below as a guide:</h2>
<img src="images/field-guide/strength-chart.jpg" />
'''
catAndMatch:
instruction: 'Pick the cyclone type, then choose the closest match.'
explanation: '''
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/eye-6.0.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Eye Storms</h3>
<p>These are the easiest storms to spot and the most powerful of tropical cyclones. They have a characteristic ‘eye’ in the center which is warmer than the surrounding cooler clouds called the ‘eyewall’. Sometimes the eye will be pink or gray but it can also just be a circular area of clouds warmer than those surrounding it.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/embed-4.5.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Embedded Center Storms</h3>
<p>These storms have a roundish area of colder clouds near the center. They are weaker than eye and stronger than curved-band storms. Weak embedded center storms can look like curved bands, strong embedded center storms may be starting to form an eye.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/band-2.5.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Curved Band Storms</h3>
<p>These can be hard to identify - they’re more disorganized than eyes or embedded centers. Look for a comma shape storm without a round area of cold clouds at the center.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/shear-2.5.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Shear Storms</h3>
<p>Most easily recognised by a flattened side with all the colors squeezed very close together. A vertical shear causes the tallest clouds to be displaced to one side of the storm.</p>
</div>
</div>
<div class="guide-group">
<h3>Other Categories</h3>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/other-post-tropical.png" width="175" height="175" />
</div>
<div class="guide-description">
<p><strong>Post tropical:</strong> If the storm doesn’t fit any of the other categories then it might be a post-tropical storm. These are identified by large amounts of warm clouds (gray and pink) and often have a long tail extending from the center.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/other-limb.png" width="175" height="175" /><br />
</div>
<div class="guide-description">
<p><strong>Edge:</strong> Sometimes the images will be skewed because of the limited view of the satellite. In this case try and classify the storm as normal - if that’s not possible then mark it as ‘edge’.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/other-no-storm.png" width="175" height="175" />
</div>
<div class="guide-description">
<p><strong>No storm:</strong> Early in a storm’s lifetime it might not be possible to say anything about its shape. If there is no evidence of an organised spiral structure then mark ‘no storm’.</p>
</div>
</div>
'''
center:
heading: 'Click the <strong>center</strong> of the storm.'
explanation: '''
<section class="for-embedded center-embedded-center">
<h2>Finding the Center (Embedded Center)</h2>
<img src="images/field-guide/center-embedded-center.jpg" class="example"/>
<p>In an Embedded Center storm the center is embedded within the coldest clouds; no eye is present.</p>
<h3>What to look for:</h3>
<p>Follow the swirl of clouds inward to a single point, traveling along a spiral. The center isn’t necessarily under the coldest clouds, so be careful not to get distracted by a spot of colder colors.</p>
<p>Here the clouds are spiraling inward along the black arrows. It may be tempting to click the area of dark blue clouds, but if you follow the arrows all the way in, you’ll see that the focus of circulation is actually slightly to the southeast, shown by the white crosshairs.</p>
</section>
<section class="for-curved center-curved-band">
<h2>Click the center of the storm (Curved Band)</h2>
<img src="images/field-guide/center-curved-band.jpg" class="example" />
<p>The center of circulation in a Curved Band storm can be found by following the spirals inward to a single point.</p>
<h3>What to look for:</h3>
<p>Curved Band storms sometimes spiral around a wedge of warmer clouds. The center of the storm is often near where the cold spiral meets this warm wedge.</p>
</section>
<section class="for-shear center-shear">
<h2>Click on the Storm Center (Shear)</h2>
<img src="images/field-guide/center-shear.jpg" class="example" />
<p>These are called Shear storms because they are encountering a cold front, or other large weather system, whose winds vary, or shear, with height. This shear tilts the storm over to one side.</p>
<h3>What to look for:</h3>
<p>The asymmetry of a Shear storm makes it tricky to find it’s center because tall clouds are prevented from developing on one side of the cyclone. Sometimes, like in this example, you can still see a small swirl in the gray and pink (warmer) clouds. If you see one of these, follow the swirl as it spirals into the center.</p>
<p>Shallow clouds may be difficult to find on infrared images. If you have trouble with the swirl method, look at the shield of cold clouds. In Shear storms, the colors will be very close together on one side of the storm, sometimes aligned in a straight line. That’s where the cold clouds are developing, before being blown away by the shear. The center of the storm will usually be nearby.</p>
</section>
'''
centerEyeSize:
heading: 'Click the <strong>center</strong> of the storm, then pick the size closest to the eye edge.'
explanation: '''
<h2>Click the center of the storm, then choose the size of the eye.</h2>
<img src="./images/field-guide/center-eye.jpg" class="example" />
<p>A cyclone’s eye, a mostly cloudless and rain free area, forms at its center of circulation.</p>
<h3>What to look for:</h3>
<p>Identify the eye and center of the storm:</p>
<p>Look for a very warm area near the center of the storm surrounded by a ring of very cold clouds. Finding the center of the storm is easy, it’s the center of the eye.</p>
<h3>Eye size:</h3>
<p>Select the circle that best matches the size of the eye and drag it with your mouse so that it traces the eye. Think of the edge of the eye as the point where the colors are closest together. If you need to change the size, click on a different-sized circle.</p>
<p><strong>Why it’s important:</strong> Storms with smaller eyes typically have tighter and stronger circulation, and are therefore a stronger storm.</p>
'''
surrounding:
heading: 'Which colors completely surround the eye?'
explanation: '''
<h2>Which colors completely surround the eye?</h2>
<img src="./images/field-guide/surrounding.jpg" class="example" />
<p>A tropical cyclone’s eye is surrounded by a ring of tall clouds called the eyewall.</p>
<h3>What to look for:</h3>
<p>Look for the coldest color completely surrounding the eye of the cyclone in an unbroken ring. It doesn’t matter how thick or thin the ring is, or even if it’s not circular, only that it is continuous all the way around.</p>
<p>Think of these storms as a layer cake, with warmer cloud layers underneath colder ones. If you removed all of the light blue colors, you would see yellow beneath them, and orange beneath those. In the example below, the cyan ring doesn’t quite connect all the way around, but the light blue beneath it does. Since the light blue completes a ring, that means that yellow, orange, and all the layers of the cake beneath it also wrap all the way around. You only need to select light blue.</p>
<p><strong>Why it’s important:</strong> Cloud temperatures decrease with height, so stronger storms can be identified by finding the coldest cloud tops. By identifying which colors surround the eye of the storm in the eyewall, you’ll determine how tall these clouds are, helping to estimate the strength of the cyclone.</p>
'''
exceeding:
heading: 'Choose the colors completely surrounding the eye at least 0.5° thick.'
instruction: 'Drag your mouse over the image to reveal a measuring tool.'
explanation: '''
<h2>Choose the colors completely surrounding the eye that is at least 0.5° thick</h2>
<img src="./images/field-guide/exceeding.jpg" class="example" />
<h3>What to look for:</h3>
<p>Hover over the image to make a small measuring tool appear. Find the coldest color completely surrounding the eye that also completely fills the circle at all points around the ring. The light blue wrapped all the way around the storm is thick enough in most places, but not southwest of the eye. In that region there is some yellow peaking through the measuring tool. That small bit of yellow is enough to eliminate the light blue for this step.</p>
<p>The yellow might not seem thick enough either. However, remember how a storm is like a layer cake. If one ring isn’t quite thick enough, imagine removing it and exposing the next warmer color below, and so forth until you find one thick enough. There is a yellow layer underneath the blue one, so we can consider these blues as part of the yellow. In that case, the yellow is more than thick enough.</p>
<p><strong>Why it’s important:</strong> This tells us not only how tall the clouds are, but how widespread as well. Storms with a larger area of cold clouds are typically more intense.</p>
'''
feature:
heading: 'Choose the image that matches the banding feature. <span class="thickness"></span>'
explanation: '''
<h2>Does the band wrap less than a quarter, about a quarter, half or more?</h2>
<img src="./images/field-guide/feature-embedded-center.jpg" class="example" />
<p>Strong tropical cyclones often have long spiral bands. A band is defined as a spiral arm that is orange or colder, separated from the main storm by a wedge of red or warmer clouds.</p>
<h3>What to look for:</h3>
<p>You’ll determine how far the band wraps around the storm. Choose an icon from the three below the image to indicate whether the band wraps less than a quarter way around the storm, a quarter-way around the storm, or halfway or more around the storm. If a storm doesn’t have spiral bands select the first icon.</p>
<p>The example here has a wide band along the north side of the storm. This band is relatively short and it doesn’t wrap very far around the storm’s center. In this case, choose the first icon.</p>
'''
blue:
heading: 'Which colors wrap most of the way around the band?'
explanation: '''
<h2>Which colors wrap most of the way around the band?</h2>
<img src="./images/field-guide/color.jpg" class="example" />
<h3>What to look for:</h3>
<p>You’ll identify the primary color of the Curved Band itself. Simply look at the band and choose the coldest color that extends along most of the band. In this example there are some patches of light blue, and even cyan, but they are too sparse to be considered widespread, so you would choose yellow.</p>
<p><strong>Why is this important:</strong> This provides information on the cyclone’s strength. Colder, taller clouds release more energy into a tropical cyclone. We identify these taller storms in infrared satellite images by looking for colder cloud tops. Remember white and blue represent the coldest clouds and pink and grey represent the warmest clouds. Stronger tropical cyclones will have more of these tall, cold clouds.</p>
'''
curve:
heading: 'How far does the main band wrap?'
explanation: '''
<h2>How far does the main band wrap?</h2>
<img src="./images/field-guide/wrap.jpg" class="example" />
<p>A Curved Band storm’s strength is measured by the length of the band. The longer the band, the stronger the storm.</p>
<h3>What to look for:</h3>
<p>Focus on how far around the band wraps, and click on the picture that best matches it. In this example, the band wraps around about one-half of a full circle, so we’d choose the second picture.</p>
'''
red:
heading: 'Click the nearest red point to the storm center.'
explanation: '''
<h2>Click the red point nearest to the storm center that is associated with the main cloud feature</h2>
<img src="./images/field-guide/red.jpg" class="example" />
<h3>What to look for:</h3>
<p>You’re marking the distance from the center that you marked in the last step to the storm’s main thunderstorms. Click the red point closest to the center that you previously marked.</p>
<p>Here, the center (marked with a white crosshair) is just outside the main thunderstorms. Sometimes the center will be within the cold colors, but we’ll still need to know how far the center is from the edge of the coldest clouds. Click the edge of the main storm (the nearest red point), and a second crosshair will appear. The distance between these clicks will tell us the storm’s strength.</p>
<p><strong>Why is this important:</strong> This tells us how tilted or straight the storm is, and therefore, how strong it is.</p>
'''
reveal:
heading: 'Scroll down to learn more about this cyclone, or click next to move onto the next storm.'
tutorialSubject: '(Tutorial image)'
estimated: 'Possible wind speed, based on your classification:'
windAndPressure: 'Wind speed and pressure'
tutorial:
welcome:
header: '''Welcome to Cyclone Center!'''
details: '''
By comparing satellite images to assess storm type and strength, you’re helping meteorologists understand the history of tropical cyclone weather patterns.
This tutorial will show you how to identify tropical cyclone type and strength. Let’s go!
'''
temperature:
header: '''Cloud Color & Temperature'''
details: '''
White and blue clouds are the coldest and pink and grey clouds are the warmest.
This is important to keep in mind as you are categorize storm type and strength.
'''
chooseStronger:
header: '''Storm Strength'''
details: '''
To determine which is stronger look for the presence of colder clouds and a more organized system.
The image on the right has more cold clouds and is more organized, so let’s select it as the stronger storm.
'''
instruction: '''Click the storm image on the right.'''
postStronger:
header: '''Storm Strength'''
details: '''
And click continue to move to the next step...
'''
instruction: '''Click "Continue".'''
chooseEmbeddedType:
header: '''Cyclone Type'''
details: '''
Now let’s figure out what type of storm we’re looking at.
There are four main types of tropical cyclones – Eye, Embedded Center, Curved Band, and Shear.
Let’s checkout embedded centers first. We can choose a different type if we find this one doesn't match.
'''
instruction: '''Choose "Embedded Center".'''
chooseEyeType:
header: '''Cyclone Type'''
details: '''
These images look similar, but not quite right. Let’s try a different storm type. Select Eye.
'''
instruction: '''Choose "Eye" instead.'''
chooseMatch:
header: '''Cyclone Type'''
details: '''
From left to right the storm images get stronger.
The clouds in this storm seem very cold and organized, similar to those in the fourth image.
Let's choose it as our closest match.
'''
instruction: '''Click the fourth eye image.'''
postMatch:
header: '''Cyclone Type'''
details: '''
This looks like a close match, and even if it's off by a bit, our classifications will be compared against other volunteers' classifications of the same image. Let's move on.
'''
instruction: '''Click "Continue".'''
chooseCenter:
header: '''Center and Eye Size'''
details: '''
Now let's click the center of the storm. For an eye storm, it's simply the center of the eye.
'''
instruction: '''Click the center of the storm.'''
chooseSize:
header: '''Center and Eye Size'''
details: '''
Choose the size that most closely matches the eyewall. For more help, you can always check the guide below.
'''
instruction: '''Choose the second circle.'''
postChooseSize:
header: '''Center and Eye Size'''
details: '''
That looks like a great fit. If you're unsure, remember that your classification is one of many, so just do your best!
'''
instruction: '''Click "Continue".'''
chooseSurrounding:
header: '''Coldest Surrounding Clouds'''
details: '''
Now we need to determine the coldest unbroken ring around the eye.
Moving from the eye out, we can see that the beige, orange, red, yellow, and light blue bands are all continuous.
The cyan band is broken, so let's choose the light blue as the coldest continuous band.
'''
instruction: '''Choose the teal/blue swatch, 6th from the left.'''
postSurrounding:
header: '''Coldest Surrounding Clouds'''
details: '''Great!'''
instruction: '''Click "Continue".'''
chooseColdestThick:
header: '''Coldest Surrounding Thick Band of Clouds'''
details: '''
Now we want to do the same thing, but only for band 0.5° thick.
Hovering over the image will show you a box you can use to measure that thickness.
Choose the color that fills that box all the way around.
Remember: Colder color include warmer colors.
Here, it appears the teal/blue band is thick enough all the way around the eye.
'''
instruction: '''Choose the teal/blue swatch again.'''
postColdestThick:
header: '''Coldest Surrounding Thick Band of Clouds'''
details: '''
Excellent.
'''
instruction: '''Click "Continue".'''
chooseBandingFeature:
header: '''Banding Feature'''
details: '''
Now let's identify the length of the storm's spiral bands.
This storm doesn't have very strong banding, so let's choose the first option.
'''
instruction: '''Choose the first option.'''
postBandingFeature:
header: '''Banding Feature'''
details: '''
We're almost finished!
'''
instruction: '''Click "Continue" one more time.'''
goodLuck:
header: '''Good Luck!'''
details: '''
Now you’re ready to classify tropical cyclones! Remember to check-out the ? Buttons for more information if you have questions.
Classifying storms is tricky, but we know that our volunteers do a great job. Just do your best, your opinion is important.
Click Next storm to move to your next storm.
'''
instruction: '''Click "Next" to get started on your own!'''
progress:
start: "Welcome, new stormwatcher! You can help us best by observing at least 4 storms. It’s quick, easy, and fun. When you’re ready, you can get started below!"
25: "Congratulations! You’ve just identified your first storm. Could you do at least 3 more?"
50: "Two storms down, two to go! You’re doing great; keep it up!"
75: "All right! You’re almost there! Just one storm left!"
100: "Great job, stormwatcher! You’ve observed 4 storms and already helped our project tremendously. Now that you’re a pro, why not keep going?"
| 83925 | module.exports =
navigation:
home: 'Home'
classify: 'Investigate'
about: 'About'
profile: 'Profile'
talk: 'Talk'
blog: 'Blog'
home:
projectHeader: 'Cyclone<br>Center'
projectHeaderSuper: 'Welcome to'
projectTag: 'Tropical cyclones are still a mystery.<br />We need your help to decipher them.'
intro:
header: 'What is Cyclone Center?'
content:'''
<p>
The climatology of tropical cyclones is limited by uncertainties in the historical record. Patterns in storms imagery are best recognized by the human eye, so we need your help analyzing these storms.
</p>
<p>Are you ready to start investigating?</p>
'''
getStarted: 'Get Started'
learnMore: 'Learn More'
stats:
activeUsers: 'Active Users'
observations: 'Observations'
stormsComplete: 'Images Complete'
talk:
header: 'Recent Storm Comments from Talk'
latestTalk: 'Loading latest talk discussions...'
viewDiscussion: 'View the discussion'
blog:
header: 'The Cyclone Center Blog'
loadingLatestPost: 'Loading latest post...'
previousPostTitle: 'Previous Posts'
loadingPreviousPost: 'Loading previous posts...'
getInvolved: 'Ready to get involved?'
about:
header: 'About Cyclone Center'
subHeader: 'The what, why, how, and who of Cyclone Center.'
credit: 'Image credit: WP:WPTC/M, NASA'
youtubeLink: 'Youtube'
overview:
header: '<div class="about-top-header">Scientists and Volunteers Team Up to Solve Storms</div>'
navigation: 'About Cyclone Center'
content: '''
<section>
<div class="about-container">
<img src="./images/about/about-example1.jpg" alt="Storm example">
<div>
<h2 class="about-non-italic-header">We don't understand all the mysteries of tropical cyclones</h2>
<p>In particular, research is inconsistent about the wind speeds of these storms, making it difficult to understand how climate change has affected the nature and strength of cyclones.</p>
<p class="image-credit">Image credit: NASA JPL</p>
</div>
</div>
</section>
<section>
<div class="about-container">
<img src="./images/about/about-example2.png" alt="Storm example">
<div>
<h2 class="about-non-italic-header">Infrared satellite images may hold the answers.</h2>
<p>We have nearly 300,000 satellite images of tropical cyclones since 1978. When these images are classified with the "Dvorak technique," we can extract critical information about the storms.</p>
</div>
<div class="about-container">
</section>
<section>
<div class="about-container">
<img src="./images/about/about-eye.png" alt="Stylized eye using storm imagery">
<div>
<h2 class="about-non-italic-header">Human eyes are best for finding information in these images.</h2>
<p>By answering a few simple questions, volunteers can apply a modified Dvorak technique to interpret satellite images even more effectively than the best computers.</p>
</div>
</div>
</section>
<section>
<div class="about-container center about-col">
<h2 class="about-non-italic-header">You can help us learn, and predict future cyclone behavior.</h2>
<p>The work of Cyclone Center volunteers will help us create a new database of information about cyclones, which will help climatologists better estimate the intensity of future storms.</p>
</div>
</section>
<section>
<div class="about-container center about-col">
<h2 class="about-non-italic-header">Are you ready to help?</h2>
<a href="#/classify">Get started investigating!</a>
</div>
</section>
'''
howItWorks:
header: 'Snapshots of Cyclones'
navigation: 'How It Works'
content:'''
<p>The images you see on Cyclone Center were observed by infrared sensors on weather satellites. These sensors provide an estimate of the temperature at the tops of clouds. Cloud top temperatures are very important because they give us an idea of how tall the clouds are. Temperature decreases with height in the lower atmosphere (up to 10 miles), so cold clouds are taller than warm clouds. Taller clouds are responsible for the heavy rain and thunderstorms that drive tropical cyclones.</p>
<p>In the Cyclone Center images, the cloud top temperatures are represented by a range of colors. The scale on the image below shows the temperatures in degrees Celsius that correspond with each color.</p>
<p>Black and gray are the warmest, indicating temperatures from 9°C (48°F) to 30°C (86°F). Often these will be the temperatures we experience at the land or ocean surface, but they can also be associated with very shallow clouds. Shades of pink go down to -30°C (-22°F). In our images, these are almost always associated with shallow clouds. Red, orange, and yellow come next, and they indicate medium-level clouds.</p>
<p>In most images, the coldest clouds you see will be shades of blue. Sometimes you’ll even see a cloud that’s so cold it shows up as white. These clouds are colder than -85°C (-121°F). Coastlines and political borders are also drawn in white, so make sure the white clouds are surrounded by dark blue. Otherwise, you might just be looking at a small island.</p>
<p>Sometimes there is a problem with parts of the satellite data. These missing data will show up as black lines in the images. Just ignore them and carry on with the analysis when you see them.</p>
<div id="image-diagram">
<img src="images/about/diagram.jpg" />
</div>
<h2>The <span data-popup="#mr-dvorak bottom cameo">Dvorak</span> Technique</h2>
<p>Prior to the 1960s, tropical cyclones were rarely observed unless they moved close to populated areas, happened to move near an unfortunate ship or occurred in the North Atlantic or Western Pacific (where routine aircraft flights monitored tropical weather systems). Fortunately, geostationary satellites were developed and launched during the 1960s. These satellites orbit the earth at very high altitudes (~22,300 miles or 35,900 km), allowing them to orbit at the same speed as the earth rotates. This allows for the satellite to always “see” the same large area and thus continuously monitor the oceans for tropical cyclone activity.</p>
<p>Despite this important advance, scientists and forecasters still had little hope of determining how strong the winds were (“intensity”) in a tropical cyclone from just looking at a picture of it. Only a very small fraction of tropical cyclones were measured directly by specially designed aircraft. However, it soon became apparent to a gentleman named <NAME> that the intensity of a tropical cyclone could be skillfully approximated by simply analyzing the cloud patterns and temperatures from a single satellite image. Dvorak developed and improved his method (now called the “Dvorak Technique”) in the 1970s and early 1980s.</p>
<p>The technique consists of a set of 10 steps, which can be simplified to produce the answers to four important questions:</p>
<ol>
<li>Where is the center of the system?</li>
<li>What type of cloud pattern best describes the system?</li>
<li>How organized or intense is the cloud pattern?</li>
<li>Does the system look stronger or weaker than 24 hours ago?</li>
</ol>
<p>Sometimes the answers to these questions are not clear, making the application of the Dvorak technique subjective. Tropical cyclone analysts and forecasters must be trained to successfully apply the many rules and constraints that the technique makes. Even then, experts frequently disagree, which has led to numerous inconsistencies in the tropical cyclone record.</p>
<p>The Dvorak technique was adopted by many of the world’s tropical cyclone forecast centers and remains today as one of the most important tools for estimating tropical cyclone intensity. In this project, you are using a version of the Dvorak technique for classifying tropical cyclones that have formed since the late 1970s. We hope that the application of thousands of classifiers will help resolve the differences in the global tropical cyclone record and improve our understanding of how the nature of these storms may have changed through time.</p>
'''
organizations:
header: 'Organizations Partnering in Cyclone Center'
navigation: 'Organizations'
content:'''
<div class="team-member">
<img src="images/about/organizations/cisc.png" alt="CISC logo" />
<h4>Cooperative Institute for Climate and Satellites</h4>
<p>The Cooperative Institute for Climate and Satellites (CICS), established under a cooperative agreement with the National Oceanic and Atmospheric Administration (NOAA) in 2009, is a consortium of research institutions that focuses on enhancing the collective interdisciplinary understanding of the state and evolution of the full Earth System. The CICS consortium is led by the University of Maryland, College Park and North Carolina State University on behalf of the University of North Carolina (UNC) System. CICS-NC is hosted by NC State University.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/noaa.png" alt="NOAA logo" />
<h4>NOAA'S National Climatic Data Center (NCDC)</h4>
<p>NCDC maintains the world's largest climate data archive and provides climatological services and data to every sector of the United States economy and to users worldwide. The archive contains paleoclimatic data to centuries-old journals to data less than an hour old. The Center's mission is to preserve these data and make them available to the general public, business, industry, government and researchers.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/rpi.png" alt="RPI logo" />
<h4>Risk Prediction Initiative</h4>
<p>The Risk Prediction Initiative (RPI2.0) funds academic research relevant to the insurance and (re)insurance industry and assists in translating this research into usable and actionable results for our member companies. Our experienced management team combines expert knowledge of climate-related natural disasters with a background in risk management. We help scientists refocus their interests on needs and time-scales relevant to the (re)insurance industry, in addition to stimulating and supporting high-level research on natural hazards such as hurricanes, typhoons and tornadoes. We are located within the Bermuda Institute of Ocean Science and as a result we have long standing relationships with many leading scientists, allowing our members direct access to the scientific community. We offer our members unique access to scientific, engineering and economic knowledge aimed at answering business relevant questions.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/asheville.png" alt="UNC-Asheville logo" />
<h4>University of North Carolina at Asheville</h4>
<p>UNC Asheville, the only designated public liberal arts university in North Carolina, offers more than 30 majors ranging from chemistry, atmospheric sciences and environmental studies to art, new media and international studies. The university is known for its award-winning undergraduate research and humanities programs.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/zooniverse.png" alt="Zooniverse logo" />
<h4>The Zooniverse</h4>
<p>The Zooniverse and the suite of projects it contains is produced, maintained and developed by the Citizen Science Alliance. The member institutions of the CSA work with many academic and other partners around the world to produce projects that use the efforts and ability of volunteers to help scientists and researchers deal with the flood of data that confronts them.</p>
</div>
'''
team:
header: 'Meet the Cyclone Center Team'
navigation: 'Team'
content:'''
<h3>Science team</h3>
<div class="team-member">
<img src="images/about/science-team/chris.jpg" alt="<NAME>" />
<h4><NAME></h4>
<p><NAME> is an associate professor of atmospheric sciences at the University of North Carolina at Asheville. Specializing in tropical cyclone formation, <NAME> came to Asheville after spending two years as a visiting scientist at the U.S. National Hurricane Center in Miami, Florida. <NAME> enjoys golf, racquetball, and chess in his free time.</p>
</div>
<div class="team-member">
<img src="images/about/science-team/ken.jpg" alt="<NAME>" />
<h4><NAME></h4>
<p><NAME> is a meteorologist at NOAA’s National Climatic Data Center in Asheville, NC. His research interests include using satellite data to observe hurricanes, clouds, and other climate variables. His career took a tropical turn in 2005 when an NCDC customer requested satellite imagery of all tropical cyclones, rejuvenating an interest in hurricanes that began with his 7th grade science fair project.</p>
</div>
<div class="team-member">
<img src="images/about/science-team/carl.jpg" alt="<NAME>" />
<h4><NAME></h4>
<p><NAME> is a research meteorologist at the Cooperative Institute for Climate and Satellites (CICS-NC). He is exploring tropical weather patterns to better understand and predict how hurricanes and other tropical cyclones form. <NAME>’s fascination with hurricanes began when Hurric<NAME> struck his hometown of Raleigh, NC in 1996.</p>
</div>
<div class="team-member">
<img src="images/about/science-team/scott.jpg" alt="<NAME>" />
<h4><NAME></h4>
<p><NAME> is a research associate at the Cooperative Institute for Climate and Satellites (CICS-NC). He is working on the development of a new rainfall dataset using NOAA’s network of NEXRAD radars, specializing in data analysis and organization. He is a private pilot and enjoys baseball and traveling in his spare time.</p>
</div>
<hr />
<h3>Development team</h3>
<div class="team-member">
<img src="images/about/dev-team/kelly.jpg" alt="<NAME>" />
<h4><NAME></h4>
<p><NAME> is an archaeologist by training but an educator by passion. While working at the Museum of Science and Industry and the Adler Planetarium she became an enthusiastic science educator eager to bring science to the masses. When not pondering the wonders of science, <NAME> can often be found baking or spending time with her herd of cats – <NAME>, <NAME>, & <NAME>.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/brian.jpg" alt="<NAME>" />
<h4><NAME></h4>
<p><NAME> is a web developer working on the Zooniverse family of projects at the Adler Planearium. <NAME> has a degree in graphic design from Columbia College in Chicago, and worked in that field for a number of years before finding a niche in web development.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/chris.jpg" alt="<NAME>" />
<h4><NAME></h4>
<p><NAME> leads the Zooniverse team, and in his copious spare time is a researcher at the University of Oxford specialising in galaxy formation and evolution. A keen popularizer of science, he is best known as co-presenter of the BBC's long running Sky at Night program. He's currently drinking a lot of sherry.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/david.jpg" alt="<NAME>" />
<h4><NAME></h4>
<p>As a visual communicator, <NAME> is passionate about tellings stories through clear, clean, and effective design. Before joining the Zooniverse team as Visual Designer, <NAME> worked for The Raindance Film Festival, the News 21 Initiative's Apart From War, Syracuse Magazine, and as a freelance designer for his small business, <NAME>iller Visual. <NAME> is a graduate of the S.I. Newhouse School of Public Communications at Syracuse University, where he studied Visual & Interactive Communications.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/m<NAME>.jpg" alt="<NAME>" />
<h4><NAME></h4>
<p><NAME> has a degree in Computer Science and has been working with The Zooniverse for the past three years as a Software Developer. Aside from web development; new technologies, science, AI, reptiles, and coffee tend to occupy his attention.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/arfon.jpg" alt="<NAME>" />
<h4><NAME></h4>
<p>As an undergraduate, <NAME>rfon studied Chemistry at the University of Sheffield before completing his Ph.D. in Astrochemistry at The University of Nottingham in 2006. He worked as a senior developer at the Wellcome Trust Sanger Institute (Human Genome Project) in Cambridge before joining the Galaxy Zoo team in Oxford. Over the past 3 years he has been responsible for leading the development of a platform for citizen science called Zooniverse. In August of 2011 he took up the position of Director of Citizen Science at the Adler Planetarium where he continues to lead the software and infrastructure development for the Zooniverse.</p>
</div>
'''
profile:
hello: 'Hello'
imageCount: 'Images Marked'
favoriteCount: 'Favorite Count'
recents: 'Recents'
favorites: 'Favorites'
siteIntro:
one:
image: './images/site-intro/welcome.jpg'
title: 'Welcome!'
content: "Welcome to Cyclone Center! With this project, we’re trying to learn more about how tropical cyclones form and change. By answering a few simple questions about these satellite images, you’ll help climatologists to predict future storm behavior."
two:
image: './images/site-intro/stronger-storm.gif'
title: 'Pick the stronger storm'
content: "You’ll be given two satellite images and asked to select the stronger storm. After that, you’ll be asked additional questions about the <strong>image on the right.</strong> Please note that <strong>this may not always be the stronger storm.</strong>"
three:
image: './images/site-intro/additional-questions.gif'
title: 'Answer additional questions'
content: "If you need help identifying the storm type, scroll down for a guide. Once you have picked a storm type, you’ll be asked a few more questions about the nature, size, and strength of the storm."
four:
image: './images/site-intro/tutorial.gif'
title: 'Give it a shot'
content: "Don’t worry if you’re unsure—each image will be shown to many people, and your best guess is far more helpful to us than nothing! If you need step-by-step guidance, you can also click the “tutorial” link for a walkthrough."
five:
image: './images/site-intro/final.jpg'
title: 'Discuss and read more!'
content: "Want to learn more, or discuss what you’ve seen? Chat with other Cyclone Center volunteers on our Talk page, or check out the Cyclone Center blog for more information. Happy stormwatching!"
nextButtonText: 'Next'
finishButtonText: 'Finish'
classify:
header: 'Investigations—Classify the cyclone by answering the questions below.'
favorite: 'Favorite'
continue: 'Continue'
finish: 'Finish'
restart: 'Restart Image'
guide: 'Guide'
favorite: 'Favorite'
favorited: 'Favorited'
talkSubject: 'Discuss the image'
talkGroup: 'Discuss the storm'
share: 'Share on Facebook'
tweet: 'Tweet this'
next: 'Next'
restartTutorial: 'Tutorial'
slideTutorial: 'Site Intro'
cycloneFieldGuide: 'Cyclone Field Guide'
notSignedIn: '''
You're not logged in! Logged in volunteers can keep track of what they've worked on, and receive credit for their work in publications. It also helps us combine everyone's classifications more efficiently.
'''
pleaseSignIn: '''
Please log in now
'''
or: 'or'
signUp: '''
sign up for a new account.
'''
matches:
postTropical: 'Post-Tropical'
edge: 'Edge'
noStorm: 'No Storm'
categories:
eye: 'Eye'
embedded: 'Embedded'
curved: 'Curved'
shear: 'Shear'
other: 'Other'
strengths:
older: 'Left'
olderTop: 'Top'
same: "They're about the same"
current: 'Right'
currentBottom: 'Bottom'
steps:
stronger:
instruction: 'Choose the storm image that appears <strong>stronger</strong>.'
explanation: '''
<h2>Choose the storm image that appears stronger</h2>
<p>To determine which storm is stronger, consider two questions:</p>
<h2>Which storm has colder clouds?</h2>
<p>Colder colors in infrared satellite imagery indicate taller clouds that release more energy into a storm. Stronger storms have more of these cold clouds near their centers.</p>
<h2>How organized are the clouds?</h2>
<p>Stronger storms have tighter spirals, especially near the center where the cold clouds become more circular. For example, storms with an eye are almost always stronger than storms without one. The strongest cyclones have eyes that are more circular, smaller and/or warmer in the middle.</p>
<h2>Use the images below as a guide:</h2>
<img src="images/field-guide/strength-chart.jpg" />
'''
catAndMatch:
instruction: 'Pick the cyclone type, then choose the closest match.'
explanation: '''
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/eye-6.0.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Eye Storms</h3>
<p>These are the easiest storms to spot and the most powerful of tropical cyclones. They have a characteristic ‘eye’ in the center which is warmer than the surrounding cooler clouds called the ‘eyewall’. Sometimes the eye will be pink or gray but it can also just be a circular area of clouds warmer than those surrounding it.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/embed-4.5.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Embedded Center Storms</h3>
<p>These storms have a roundish area of colder clouds near the center. They are weaker than eye and stronger than curved-band storms. Weak embedded center storms can look like curved bands, strong embedded center storms may be starting to form an eye.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/band-2.5.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Curved Band Storms</h3>
<p>These can be hard to identify - they’re more disorganized than eyes or embedded centers. Look for a comma shape storm without a round area of cold clouds at the center.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/shear-2.5.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Shear Storms</h3>
<p>Most easily recognised by a flattened side with all the colors squeezed very close together. A vertical shear causes the tallest clouds to be displaced to one side of the storm.</p>
</div>
</div>
<div class="guide-group">
<h3>Other Categories</h3>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/other-post-tropical.png" width="175" height="175" />
</div>
<div class="guide-description">
<p><strong>Post tropical:</strong> If the storm doesn’t fit any of the other categories then it might be a post-tropical storm. These are identified by large amounts of warm clouds (gray and pink) and often have a long tail extending from the center.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/other-limb.png" width="175" height="175" /><br />
</div>
<div class="guide-description">
<p><strong>Edge:</strong> Sometimes the images will be skewed because of the limited view of the satellite. In this case try and classify the storm as normal - if that’s not possible then mark it as ‘edge’.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/other-no-storm.png" width="175" height="175" />
</div>
<div class="guide-description">
<p><strong>No storm:</strong> Early in a storm’s lifetime it might not be possible to say anything about its shape. If there is no evidence of an organised spiral structure then mark ‘no storm’.</p>
</div>
</div>
'''
center:
heading: 'Click the <strong>center</strong> of the storm.'
explanation: '''
<section class="for-embedded center-embedded-center">
<h2>Finding the Center (Embedded Center)</h2>
<img src="images/field-guide/center-embedded-center.jpg" class="example"/>
<p>In an Embedded Center storm the center is embedded within the coldest clouds; no eye is present.</p>
<h3>What to look for:</h3>
<p>Follow the swirl of clouds inward to a single point, traveling along a spiral. The center isn’t necessarily under the coldest clouds, so be careful not to get distracted by a spot of colder colors.</p>
<p>Here the clouds are spiraling inward along the black arrows. It may be tempting to click the area of dark blue clouds, but if you follow the arrows all the way in, you’ll see that the focus of circulation is actually slightly to the southeast, shown by the white crosshairs.</p>
</section>
<section class="for-curved center-curved-band">
<h2>Click the center of the storm (Curved Band)</h2>
<img src="images/field-guide/center-curved-band.jpg" class="example" />
<p>The center of circulation in a Curved Band storm can be found by following the spirals inward to a single point.</p>
<h3>What to look for:</h3>
<p>Curved Band storms sometimes spiral around a wedge of warmer clouds. The center of the storm is often near where the cold spiral meets this warm wedge.</p>
</section>
<section class="for-shear center-shear">
<h2>Click on the Storm Center (Shear)</h2>
<img src="images/field-guide/center-shear.jpg" class="example" />
<p>These are called Shear storms because they are encountering a cold front, or other large weather system, whose winds vary, or shear, with height. This shear tilts the storm over to one side.</p>
<h3>What to look for:</h3>
<p>The asymmetry of a Shear storm makes it tricky to find it’s center because tall clouds are prevented from developing on one side of the cyclone. Sometimes, like in this example, you can still see a small swirl in the gray and pink (warmer) clouds. If you see one of these, follow the swirl as it spirals into the center.</p>
<p>Shallow clouds may be difficult to find on infrared images. If you have trouble with the swirl method, look at the shield of cold clouds. In Shear storms, the colors will be very close together on one side of the storm, sometimes aligned in a straight line. That’s where the cold clouds are developing, before being blown away by the shear. The center of the storm will usually be nearby.</p>
</section>
'''
centerEyeSize:
heading: 'Click the <strong>center</strong> of the storm, then pick the size closest to the eye edge.'
explanation: '''
<h2>Click the center of the storm, then choose the size of the eye.</h2>
<img src="./images/field-guide/center-eye.jpg" class="example" />
<p>A cyclone’s eye, a mostly cloudless and rain free area, forms at its center of circulation.</p>
<h3>What to look for:</h3>
<p>Identify the eye and center of the storm:</p>
<p>Look for a very warm area near the center of the storm surrounded by a ring of very cold clouds. Finding the center of the storm is easy, it’s the center of the eye.</p>
<h3>Eye size:</h3>
<p>Select the circle that best matches the size of the eye and drag it with your mouse so that it traces the eye. Think of the edge of the eye as the point where the colors are closest together. If you need to change the size, click on a different-sized circle.</p>
<p><strong>Why it’s important:</strong> Storms with smaller eyes typically have tighter and stronger circulation, and are therefore a stronger storm.</p>
'''
surrounding:
heading: 'Which colors completely surround the eye?'
explanation: '''
<h2>Which colors completely surround the eye?</h2>
<img src="./images/field-guide/surrounding.jpg" class="example" />
<p>A tropical cyclone’s eye is surrounded by a ring of tall clouds called the eyewall.</p>
<h3>What to look for:</h3>
<p>Look for the coldest color completely surrounding the eye of the cyclone in an unbroken ring. It doesn’t matter how thick or thin the ring is, or even if it’s not circular, only that it is continuous all the way around.</p>
<p>Think of these storms as a layer cake, with warmer cloud layers underneath colder ones. If you removed all of the light blue colors, you would see yellow beneath them, and orange beneath those. In the example below, the cyan ring doesn’t quite connect all the way around, but the light blue beneath it does. Since the light blue completes a ring, that means that yellow, orange, and all the layers of the cake beneath it also wrap all the way around. You only need to select light blue.</p>
<p><strong>Why it’s important:</strong> Cloud temperatures decrease with height, so stronger storms can be identified by finding the coldest cloud tops. By identifying which colors surround the eye of the storm in the eyewall, you’ll determine how tall these clouds are, helping to estimate the strength of the cyclone.</p>
'''
exceeding:
heading: 'Choose the colors completely surrounding the eye at least 0.5° thick.'
instruction: 'Drag your mouse over the image to reveal a measuring tool.'
explanation: '''
<h2>Choose the colors completely surrounding the eye that is at least 0.5° thick</h2>
<img src="./images/field-guide/exceeding.jpg" class="example" />
<h3>What to look for:</h3>
<p>Hover over the image to make a small measuring tool appear. Find the coldest color completely surrounding the eye that also completely fills the circle at all points around the ring. The light blue wrapped all the way around the storm is thick enough in most places, but not southwest of the eye. In that region there is some yellow peaking through the measuring tool. That small bit of yellow is enough to eliminate the light blue for this step.</p>
<p>The yellow might not seem thick enough either. However, remember how a storm is like a layer cake. If one ring isn’t quite thick enough, imagine removing it and exposing the next warmer color below, and so forth until you find one thick enough. There is a yellow layer underneath the blue one, so we can consider these blues as part of the yellow. In that case, the yellow is more than thick enough.</p>
<p><strong>Why it’s important:</strong> This tells us not only how tall the clouds are, but how widespread as well. Storms with a larger area of cold clouds are typically more intense.</p>
'''
feature:
heading: 'Choose the image that matches the banding feature. <span class="thickness"></span>'
explanation: '''
<h2>Does the band wrap less than a quarter, about a quarter, half or more?</h2>
<img src="./images/field-guide/feature-embedded-center.jpg" class="example" />
<p>Strong tropical cyclones often have long spiral bands. A band is defined as a spiral arm that is orange or colder, separated from the main storm by a wedge of red or warmer clouds.</p>
<h3>What to look for:</h3>
<p>You’ll determine how far the band wraps around the storm. Choose an icon from the three below the image to indicate whether the band wraps less than a quarter way around the storm, a quarter-way around the storm, or halfway or more around the storm. If a storm doesn’t have spiral bands select the first icon.</p>
<p>The example here has a wide band along the north side of the storm. This band is relatively short and it doesn’t wrap very far around the storm’s center. In this case, choose the first icon.</p>
'''
blue:
heading: 'Which colors wrap most of the way around the band?'
explanation: '''
<h2>Which colors wrap most of the way around the band?</h2>
<img src="./images/field-guide/color.jpg" class="example" />
<h3>What to look for:</h3>
<p>You’ll identify the primary color of the Curved Band itself. Simply look at the band and choose the coldest color that extends along most of the band. In this example there are some patches of light blue, and even cyan, but they are too sparse to be considered widespread, so you would choose yellow.</p>
<p><strong>Why is this important:</strong> This provides information on the cyclone’s strength. Colder, taller clouds release more energy into a tropical cyclone. We identify these taller storms in infrared satellite images by looking for colder cloud tops. Remember white and blue represent the coldest clouds and pink and grey represent the warmest clouds. Stronger tropical cyclones will have more of these tall, cold clouds.</p>
'''
curve:
heading: 'How far does the main band wrap?'
explanation: '''
<h2>How far does the main band wrap?</h2>
<img src="./images/field-guide/wrap.jpg" class="example" />
<p>A Curved Band storm’s strength is measured by the length of the band. The longer the band, the stronger the storm.</p>
<h3>What to look for:</h3>
<p>Focus on how far around the band wraps, and click on the picture that best matches it. In this example, the band wraps around about one-half of a full circle, so we’d choose the second picture.</p>
'''
red:
heading: 'Click the nearest red point to the storm center.'
explanation: '''
<h2>Click the red point nearest to the storm center that is associated with the main cloud feature</h2>
<img src="./images/field-guide/red.jpg" class="example" />
<h3>What to look for:</h3>
<p>You’re marking the distance from the center that you marked in the last step to the storm’s main thunderstorms. Click the red point closest to the center that you previously marked.</p>
<p>Here, the center (marked with a white crosshair) is just outside the main thunderstorms. Sometimes the center will be within the cold colors, but we’ll still need to know how far the center is from the edge of the coldest clouds. Click the edge of the main storm (the nearest red point), and a second crosshair will appear. The distance between these clicks will tell us the storm’s strength.</p>
<p><strong>Why is this important:</strong> This tells us how tilted or straight the storm is, and therefore, how strong it is.</p>
'''
reveal:
heading: 'Scroll down to learn more about this cyclone, or click next to move onto the next storm.'
tutorialSubject: '(Tutorial image)'
estimated: 'Possible wind speed, based on your classification:'
windAndPressure: 'Wind speed and pressure'
tutorial:
welcome:
header: '''Welcome to Cyclone Center!'''
details: '''
By comparing satellite images to assess storm type and strength, you’re helping meteorologists understand the history of tropical cyclone weather patterns.
This tutorial will show you how to identify tropical cyclone type and strength. Let’s go!
'''
temperature:
header: '''Cloud Color & Temperature'''
details: '''
White and blue clouds are the coldest and pink and grey clouds are the warmest.
This is important to keep in mind as you are categorize storm type and strength.
'''
chooseStronger:
header: '''Storm Strength'''
details: '''
To determine which is stronger look for the presence of colder clouds and a more organized system.
The image on the right has more cold clouds and is more organized, so let’s select it as the stronger storm.
'''
instruction: '''Click the storm image on the right.'''
postStronger:
header: '''Storm Strength'''
details: '''
And click continue to move to the next step...
'''
instruction: '''Click "Continue".'''
chooseEmbeddedType:
header: '''Cyclone Type'''
details: '''
Now let’s figure out what type of storm we’re looking at.
There are four main types of tropical cyclones – Eye, Embedded Center, Curved Band, and Shear.
Let’s checkout embedded centers first. We can choose a different type if we find this one doesn't match.
'''
instruction: '''Choose "Embedded Center".'''
chooseEyeType:
header: '''Cyclone Type'''
details: '''
These images look similar, but not quite right. Let’s try a different storm type. Select Eye.
'''
instruction: '''Choose "Eye" instead.'''
chooseMatch:
header: '''Cyclone Type'''
details: '''
From left to right the storm images get stronger.
The clouds in this storm seem very cold and organized, similar to those in the fourth image.
Let's choose it as our closest match.
'''
instruction: '''Click the fourth eye image.'''
postMatch:
header: '''Cyclone Type'''
details: '''
This looks like a close match, and even if it's off by a bit, our classifications will be compared against other volunteers' classifications of the same image. Let's move on.
'''
instruction: '''Click "Continue".'''
chooseCenter:
header: '''Center and Eye Size'''
details: '''
Now let's click the center of the storm. For an eye storm, it's simply the center of the eye.
'''
instruction: '''Click the center of the storm.'''
chooseSize:
header: '''Center and Eye Size'''
details: '''
Choose the size that most closely matches the eyewall. For more help, you can always check the guide below.
'''
instruction: '''Choose the second circle.'''
postChooseSize:
header: '''Center and Eye Size'''
details: '''
That looks like a great fit. If you're unsure, remember that your classification is one of many, so just do your best!
'''
instruction: '''Click "Continue".'''
chooseSurrounding:
header: '''Coldest Surrounding Clouds'''
details: '''
Now we need to determine the coldest unbroken ring around the eye.
Moving from the eye out, we can see that the beige, orange, red, yellow, and light blue bands are all continuous.
The cyan band is broken, so let's choose the light blue as the coldest continuous band.
'''
instruction: '''Choose the teal/blue swatch, 6th from the left.'''
postSurrounding:
header: '''Coldest Surrounding Clouds'''
details: '''Great!'''
instruction: '''Click "Continue".'''
chooseColdestThick:
header: '''Coldest Surrounding Thick Band of Clouds'''
details: '''
Now we want to do the same thing, but only for band 0.5° thick.
Hovering over the image will show you a box you can use to measure that thickness.
Choose the color that fills that box all the way around.
Remember: Colder color include warmer colors.
Here, it appears the teal/blue band is thick enough all the way around the eye.
'''
instruction: '''Choose the teal/blue swatch again.'''
postColdestThick:
header: '''Coldest Surrounding Thick Band of Clouds'''
details: '''
Excellent.
'''
instruction: '''Click "Continue".'''
chooseBandingFeature:
header: '''Banding Feature'''
details: '''
Now let's identify the length of the storm's spiral bands.
This storm doesn't have very strong banding, so let's choose the first option.
'''
instruction: '''Choose the first option.'''
postBandingFeature:
header: '''Banding Feature'''
details: '''
We're almost finished!
'''
instruction: '''Click "Continue" one more time.'''
goodLuck:
header: '''Good Luck!'''
details: '''
Now you’re ready to classify tropical cyclones! Remember to check-out the ? Buttons for more information if you have questions.
Classifying storms is tricky, but we know that our volunteers do a great job. Just do your best, your opinion is important.
Click Next storm to move to your next storm.
'''
instruction: '''Click "Next" to get started on your own!'''
progress:
start: "Welcome, new stormwatcher! You can help us best by observing at least 4 storms. It’s quick, easy, and fun. When you’re ready, you can get started below!"
25: "Congratulations! You’ve just identified your first storm. Could you do at least 3 more?"
50: "Two storms down, two to go! You’re doing great; keep it up!"
75: "All right! You’re almost there! Just one storm left!"
100: "Great job, stormwatcher! You’ve observed 4 storms and already helped our project tremendously. Now that you’re a pro, why not keep going?"
| true | module.exports =
navigation:
home: 'Home'
classify: 'Investigate'
about: 'About'
profile: 'Profile'
talk: 'Talk'
blog: 'Blog'
home:
projectHeader: 'Cyclone<br>Center'
projectHeaderSuper: 'Welcome to'
projectTag: 'Tropical cyclones are still a mystery.<br />We need your help to decipher them.'
intro:
header: 'What is Cyclone Center?'
content:'''
<p>
The climatology of tropical cyclones is limited by uncertainties in the historical record. Patterns in storms imagery are best recognized by the human eye, so we need your help analyzing these storms.
</p>
<p>Are you ready to start investigating?</p>
'''
getStarted: 'Get Started'
learnMore: 'Learn More'
stats:
activeUsers: 'Active Users'
observations: 'Observations'
stormsComplete: 'Images Complete'
talk:
header: 'Recent Storm Comments from Talk'
latestTalk: 'Loading latest talk discussions...'
viewDiscussion: 'View the discussion'
blog:
header: 'The Cyclone Center Blog'
loadingLatestPost: 'Loading latest post...'
previousPostTitle: 'Previous Posts'
loadingPreviousPost: 'Loading previous posts...'
getInvolved: 'Ready to get involved?'
about:
header: 'About Cyclone Center'
subHeader: 'The what, why, how, and who of Cyclone Center.'
credit: 'Image credit: WP:WPTC/M, NASA'
youtubeLink: 'Youtube'
overview:
header: '<div class="about-top-header">Scientists and Volunteers Team Up to Solve Storms</div>'
navigation: 'About Cyclone Center'
content: '''
<section>
<div class="about-container">
<img src="./images/about/about-example1.jpg" alt="Storm example">
<div>
<h2 class="about-non-italic-header">We don't understand all the mysteries of tropical cyclones</h2>
<p>In particular, research is inconsistent about the wind speeds of these storms, making it difficult to understand how climate change has affected the nature and strength of cyclones.</p>
<p class="image-credit">Image credit: NASA JPL</p>
</div>
</div>
</section>
<section>
<div class="about-container">
<img src="./images/about/about-example2.png" alt="Storm example">
<div>
<h2 class="about-non-italic-header">Infrared satellite images may hold the answers.</h2>
<p>We have nearly 300,000 satellite images of tropical cyclones since 1978. When these images are classified with the "Dvorak technique," we can extract critical information about the storms.</p>
</div>
<div class="about-container">
</section>
<section>
<div class="about-container">
<img src="./images/about/about-eye.png" alt="Stylized eye using storm imagery">
<div>
<h2 class="about-non-italic-header">Human eyes are best for finding information in these images.</h2>
<p>By answering a few simple questions, volunteers can apply a modified Dvorak technique to interpret satellite images even more effectively than the best computers.</p>
</div>
</div>
</section>
<section>
<div class="about-container center about-col">
<h2 class="about-non-italic-header">You can help us learn, and predict future cyclone behavior.</h2>
<p>The work of Cyclone Center volunteers will help us create a new database of information about cyclones, which will help climatologists better estimate the intensity of future storms.</p>
</div>
</section>
<section>
<div class="about-container center about-col">
<h2 class="about-non-italic-header">Are you ready to help?</h2>
<a href="#/classify">Get started investigating!</a>
</div>
</section>
'''
howItWorks:
header: 'Snapshots of Cyclones'
navigation: 'How It Works'
content:'''
<p>The images you see on Cyclone Center were observed by infrared sensors on weather satellites. These sensors provide an estimate of the temperature at the tops of clouds. Cloud top temperatures are very important because they give us an idea of how tall the clouds are. Temperature decreases with height in the lower atmosphere (up to 10 miles), so cold clouds are taller than warm clouds. Taller clouds are responsible for the heavy rain and thunderstorms that drive tropical cyclones.</p>
<p>In the Cyclone Center images, the cloud top temperatures are represented by a range of colors. The scale on the image below shows the temperatures in degrees Celsius that correspond with each color.</p>
<p>Black and gray are the warmest, indicating temperatures from 9°C (48°F) to 30°C (86°F). Often these will be the temperatures we experience at the land or ocean surface, but they can also be associated with very shallow clouds. Shades of pink go down to -30°C (-22°F). In our images, these are almost always associated with shallow clouds. Red, orange, and yellow come next, and they indicate medium-level clouds.</p>
<p>In most images, the coldest clouds you see will be shades of blue. Sometimes you’ll even see a cloud that’s so cold it shows up as white. These clouds are colder than -85°C (-121°F). Coastlines and political borders are also drawn in white, so make sure the white clouds are surrounded by dark blue. Otherwise, you might just be looking at a small island.</p>
<p>Sometimes there is a problem with parts of the satellite data. These missing data will show up as black lines in the images. Just ignore them and carry on with the analysis when you see them.</p>
<div id="image-diagram">
<img src="images/about/diagram.jpg" />
</div>
<h2>The <span data-popup="#mr-dvorak bottom cameo">Dvorak</span> Technique</h2>
<p>Prior to the 1960s, tropical cyclones were rarely observed unless they moved close to populated areas, happened to move near an unfortunate ship or occurred in the North Atlantic or Western Pacific (where routine aircraft flights monitored tropical weather systems). Fortunately, geostationary satellites were developed and launched during the 1960s. These satellites orbit the earth at very high altitudes (~22,300 miles or 35,900 km), allowing them to orbit at the same speed as the earth rotates. This allows for the satellite to always “see” the same large area and thus continuously monitor the oceans for tropical cyclone activity.</p>
<p>Despite this important advance, scientists and forecasters still had little hope of determining how strong the winds were (“intensity”) in a tropical cyclone from just looking at a picture of it. Only a very small fraction of tropical cyclones were measured directly by specially designed aircraft. However, it soon became apparent to a gentleman named PI:NAME:<NAME>END_PI that the intensity of a tropical cyclone could be skillfully approximated by simply analyzing the cloud patterns and temperatures from a single satellite image. Dvorak developed and improved his method (now called the “Dvorak Technique”) in the 1970s and early 1980s.</p>
<p>The technique consists of a set of 10 steps, which can be simplified to produce the answers to four important questions:</p>
<ol>
<li>Where is the center of the system?</li>
<li>What type of cloud pattern best describes the system?</li>
<li>How organized or intense is the cloud pattern?</li>
<li>Does the system look stronger or weaker than 24 hours ago?</li>
</ol>
<p>Sometimes the answers to these questions are not clear, making the application of the Dvorak technique subjective. Tropical cyclone analysts and forecasters must be trained to successfully apply the many rules and constraints that the technique makes. Even then, experts frequently disagree, which has led to numerous inconsistencies in the tropical cyclone record.</p>
<p>The Dvorak technique was adopted by many of the world’s tropical cyclone forecast centers and remains today as one of the most important tools for estimating tropical cyclone intensity. In this project, you are using a version of the Dvorak technique for classifying tropical cyclones that have formed since the late 1970s. We hope that the application of thousands of classifiers will help resolve the differences in the global tropical cyclone record and improve our understanding of how the nature of these storms may have changed through time.</p>
'''
organizations:
header: 'Organizations Partnering in Cyclone Center'
navigation: 'Organizations'
content:'''
<div class="team-member">
<img src="images/about/organizations/cisc.png" alt="CISC logo" />
<h4>Cooperative Institute for Climate and Satellites</h4>
<p>The Cooperative Institute for Climate and Satellites (CICS), established under a cooperative agreement with the National Oceanic and Atmospheric Administration (NOAA) in 2009, is a consortium of research institutions that focuses on enhancing the collective interdisciplinary understanding of the state and evolution of the full Earth System. The CICS consortium is led by the University of Maryland, College Park and North Carolina State University on behalf of the University of North Carolina (UNC) System. CICS-NC is hosted by NC State University.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/noaa.png" alt="NOAA logo" />
<h4>NOAA'S National Climatic Data Center (NCDC)</h4>
<p>NCDC maintains the world's largest climate data archive and provides climatological services and data to every sector of the United States economy and to users worldwide. The archive contains paleoclimatic data to centuries-old journals to data less than an hour old. The Center's mission is to preserve these data and make them available to the general public, business, industry, government and researchers.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/rpi.png" alt="RPI logo" />
<h4>Risk Prediction Initiative</h4>
<p>The Risk Prediction Initiative (RPI2.0) funds academic research relevant to the insurance and (re)insurance industry and assists in translating this research into usable and actionable results for our member companies. Our experienced management team combines expert knowledge of climate-related natural disasters with a background in risk management. We help scientists refocus their interests on needs and time-scales relevant to the (re)insurance industry, in addition to stimulating and supporting high-level research on natural hazards such as hurricanes, typhoons and tornadoes. We are located within the Bermuda Institute of Ocean Science and as a result we have long standing relationships with many leading scientists, allowing our members direct access to the scientific community. We offer our members unique access to scientific, engineering and economic knowledge aimed at answering business relevant questions.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/asheville.png" alt="UNC-Asheville logo" />
<h4>University of North Carolina at Asheville</h4>
<p>UNC Asheville, the only designated public liberal arts university in North Carolina, offers more than 30 majors ranging from chemistry, atmospheric sciences and environmental studies to art, new media and international studies. The university is known for its award-winning undergraduate research and humanities programs.</p>
</div>
<div class="team-member">
<img src="images/about/organizations/zooniverse.png" alt="Zooniverse logo" />
<h4>The Zooniverse</h4>
<p>The Zooniverse and the suite of projects it contains is produced, maintained and developed by the Citizen Science Alliance. The member institutions of the CSA work with many academic and other partners around the world to produce projects that use the efforts and ability of volunteers to help scientists and researchers deal with the flood of data that confronts them.</p>
</div>
'''
team:
header: 'Meet the Cyclone Center Team'
navigation: 'Team'
content:'''
<h3>Science team</h3>
<div class="team-member">
<img src="images/about/science-team/chris.jpg" alt="PI:NAME:<NAME>END_PI" />
<h4>PI:NAME:<NAME>END_PI</h4>
<p>PI:NAME:<NAME>END_PI is an associate professor of atmospheric sciences at the University of North Carolina at Asheville. Specializing in tropical cyclone formation, PI:NAME:<NAME>END_PI came to Asheville after spending two years as a visiting scientist at the U.S. National Hurricane Center in Miami, Florida. PI:NAME:<NAME>END_PI enjoys golf, racquetball, and chess in his free time.</p>
</div>
<div class="team-member">
<img src="images/about/science-team/ken.jpg" alt="PI:NAME:<NAME>END_PI" />
<h4>PI:NAME:<NAME>END_PI</h4>
<p>PI:NAME:<NAME>END_PI is a meteorologist at NOAA’s National Climatic Data Center in Asheville, NC. His research interests include using satellite data to observe hurricanes, clouds, and other climate variables. His career took a tropical turn in 2005 when an NCDC customer requested satellite imagery of all tropical cyclones, rejuvenating an interest in hurricanes that began with his 7th grade science fair project.</p>
</div>
<div class="team-member">
<img src="images/about/science-team/carl.jpg" alt="PI:NAME:<NAME>END_PI" />
<h4>PI:NAME:<NAME>END_PI</h4>
<p>PI:NAME:<NAME>END_PI is a research meteorologist at the Cooperative Institute for Climate and Satellites (CICS-NC). He is exploring tropical weather patterns to better understand and predict how hurricanes and other tropical cyclones form. PI:NAME:<NAME>END_PI’s fascination with hurricanes began when HurricPI:NAME:<NAME>END_PI struck his hometown of Raleigh, NC in 1996.</p>
</div>
<div class="team-member">
<img src="images/about/science-team/scott.jpg" alt="PI:NAME:<NAME>END_PI" />
<h4>PI:NAME:<NAME>END_PI</h4>
<p>PI:NAME:<NAME>END_PI is a research associate at the Cooperative Institute for Climate and Satellites (CICS-NC). He is working on the development of a new rainfall dataset using NOAA’s network of NEXRAD radars, specializing in data analysis and organization. He is a private pilot and enjoys baseball and traveling in his spare time.</p>
</div>
<hr />
<h3>Development team</h3>
<div class="team-member">
<img src="images/about/dev-team/kelly.jpg" alt="PI:NAME:<NAME>END_PI" />
<h4>PI:NAME:<NAME>END_PI</h4>
<p>PI:NAME:<NAME>END_PI is an archaeologist by training but an educator by passion. While working at the Museum of Science and Industry and the Adler Planetarium she became an enthusiastic science educator eager to bring science to the masses. When not pondering the wonders of science, PI:NAME:<NAME>END_PI can often be found baking or spending time with her herd of cats – PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, & PI:NAME:<NAME>END_PI.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/brian.jpg" alt="PI:NAME:<NAME>END_PI" />
<h4>PI:NAME:<NAME>END_PI</h4>
<p>PI:NAME:<NAME>END_PI is a web developer working on the Zooniverse family of projects at the Adler Planearium. PI:NAME:<NAME>END_PI has a degree in graphic design from Columbia College in Chicago, and worked in that field for a number of years before finding a niche in web development.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/chris.jpg" alt="PI:NAME:<NAME>END_PI" />
<h4>PI:NAME:<NAME>END_PI</h4>
<p>PI:NAME:<NAME>END_PI leads the Zooniverse team, and in his copious spare time is a researcher at the University of Oxford specialising in galaxy formation and evolution. A keen popularizer of science, he is best known as co-presenter of the BBC's long running Sky at Night program. He's currently drinking a lot of sherry.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/david.jpg" alt="PI:NAME:<NAME>END_PI" />
<h4>PI:NAME:<NAME>END_PI</h4>
<p>As a visual communicator, PI:NAME:<NAME>END_PI is passionate about tellings stories through clear, clean, and effective design. Before joining the Zooniverse team as Visual Designer, PI:NAME:<NAME>END_PI worked for The Raindance Film Festival, the News 21 Initiative's Apart From War, Syracuse Magazine, and as a freelance designer for his small business, PI:NAME:<NAME>END_PIiller Visual. PI:NAME:<NAME>END_PI is a graduate of the S.I. Newhouse School of Public Communications at Syracuse University, where he studied Visual & Interactive Communications.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/mPI:NAME:<NAME>END_PI.jpg" alt="PI:NAME:<NAME>END_PI" />
<h4>PI:NAME:<NAME>END_PI</h4>
<p>PI:NAME:<NAME>END_PI has a degree in Computer Science and has been working with The Zooniverse for the past three years as a Software Developer. Aside from web development; new technologies, science, AI, reptiles, and coffee tend to occupy his attention.</p>
</div>
<div class="team-member">
<img src="images/about/dev-team/arfon.jpg" alt="PI:NAME:<NAME>END_PI" />
<h4>PI:NAME:<NAME>END_PI</h4>
<p>As an undergraduate, PI:NAME:<NAME>END_PIrfon studied Chemistry at the University of Sheffield before completing his Ph.D. in Astrochemistry at The University of Nottingham in 2006. He worked as a senior developer at the Wellcome Trust Sanger Institute (Human Genome Project) in Cambridge before joining the Galaxy Zoo team in Oxford. Over the past 3 years he has been responsible for leading the development of a platform for citizen science called Zooniverse. In August of 2011 he took up the position of Director of Citizen Science at the Adler Planetarium where he continues to lead the software and infrastructure development for the Zooniverse.</p>
</div>
'''
profile:
hello: 'Hello'
imageCount: 'Images Marked'
favoriteCount: 'Favorite Count'
recents: 'Recents'
favorites: 'Favorites'
siteIntro:
one:
image: './images/site-intro/welcome.jpg'
title: 'Welcome!'
content: "Welcome to Cyclone Center! With this project, we’re trying to learn more about how tropical cyclones form and change. By answering a few simple questions about these satellite images, you’ll help climatologists to predict future storm behavior."
two:
image: './images/site-intro/stronger-storm.gif'
title: 'Pick the stronger storm'
content: "You’ll be given two satellite images and asked to select the stronger storm. After that, you’ll be asked additional questions about the <strong>image on the right.</strong> Please note that <strong>this may not always be the stronger storm.</strong>"
three:
image: './images/site-intro/additional-questions.gif'
title: 'Answer additional questions'
content: "If you need help identifying the storm type, scroll down for a guide. Once you have picked a storm type, you’ll be asked a few more questions about the nature, size, and strength of the storm."
four:
image: './images/site-intro/tutorial.gif'
title: 'Give it a shot'
content: "Don’t worry if you’re unsure—each image will be shown to many people, and your best guess is far more helpful to us than nothing! If you need step-by-step guidance, you can also click the “tutorial” link for a walkthrough."
five:
image: './images/site-intro/final.jpg'
title: 'Discuss and read more!'
content: "Want to learn more, or discuss what you’ve seen? Chat with other Cyclone Center volunteers on our Talk page, or check out the Cyclone Center blog for more information. Happy stormwatching!"
nextButtonText: 'Next'
finishButtonText: 'Finish'
classify:
header: 'Investigations—Classify the cyclone by answering the questions below.'
favorite: 'Favorite'
continue: 'Continue'
finish: 'Finish'
restart: 'Restart Image'
guide: 'Guide'
favorite: 'Favorite'
favorited: 'Favorited'
talkSubject: 'Discuss the image'
talkGroup: 'Discuss the storm'
share: 'Share on Facebook'
tweet: 'Tweet this'
next: 'Next'
restartTutorial: 'Tutorial'
slideTutorial: 'Site Intro'
cycloneFieldGuide: 'Cyclone Field Guide'
notSignedIn: '''
You're not logged in! Logged in volunteers can keep track of what they've worked on, and receive credit for their work in publications. It also helps us combine everyone's classifications more efficiently.
'''
pleaseSignIn: '''
Please log in now
'''
or: 'or'
signUp: '''
sign up for a new account.
'''
matches:
postTropical: 'Post-Tropical'
edge: 'Edge'
noStorm: 'No Storm'
categories:
eye: 'Eye'
embedded: 'Embedded'
curved: 'Curved'
shear: 'Shear'
other: 'Other'
strengths:
older: 'Left'
olderTop: 'Top'
same: "They're about the same"
current: 'Right'
currentBottom: 'Bottom'
steps:
stronger:
instruction: 'Choose the storm image that appears <strong>stronger</strong>.'
explanation: '''
<h2>Choose the storm image that appears stronger</h2>
<p>To determine which storm is stronger, consider two questions:</p>
<h2>Which storm has colder clouds?</h2>
<p>Colder colors in infrared satellite imagery indicate taller clouds that release more energy into a storm. Stronger storms have more of these cold clouds near their centers.</p>
<h2>How organized are the clouds?</h2>
<p>Stronger storms have tighter spirals, especially near the center where the cold clouds become more circular. For example, storms with an eye are almost always stronger than storms without one. The strongest cyclones have eyes that are more circular, smaller and/or warmer in the middle.</p>
<h2>Use the images below as a guide:</h2>
<img src="images/field-guide/strength-chart.jpg" />
'''
catAndMatch:
instruction: 'Pick the cyclone type, then choose the closest match.'
explanation: '''
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/eye-6.0.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Eye Storms</h3>
<p>These are the easiest storms to spot and the most powerful of tropical cyclones. They have a characteristic ‘eye’ in the center which is warmer than the surrounding cooler clouds called the ‘eyewall’. Sometimes the eye will be pink or gray but it can also just be a circular area of clouds warmer than those surrounding it.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/embed-4.5.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Embedded Center Storms</h3>
<p>These storms have a roundish area of colder clouds near the center. They are weaker than eye and stronger than curved-band storms. Weak embedded center storms can look like curved bands, strong embedded center storms may be starting to form an eye.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/band-2.5.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Curved Band Storms</h3>
<p>These can be hard to identify - they’re more disorganized than eyes or embedded centers. Look for a comma shape storm without a round area of cold clouds at the center.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/shear-2.5.thumb.png" width="175" height="175" />
</div>
<div class="guide-description">
<h3>Shear Storms</h3>
<p>Most easily recognised by a flattened side with all the colors squeezed very close together. A vertical shear causes the tallest clouds to be displaced to one side of the storm.</p>
</div>
</div>
<div class="guide-group">
<h3>Other Categories</h3>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/other-post-tropical.png" width="175" height="175" />
</div>
<div class="guide-description">
<p><strong>Post tropical:</strong> If the storm doesn’t fit any of the other categories then it might be a post-tropical storm. These are identified by large amounts of warm clouds (gray and pink) and often have a long tail extending from the center.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/other-limb.png" width="175" height="175" /><br />
</div>
<div class="guide-description">
<p><strong>Edge:</strong> Sometimes the images will be skewed because of the limited view of the satellite. In this case try and classify the storm as normal - if that’s not possible then mark it as ‘edge’.</p>
</div>
</div>
<div class="guide-group">
<div class="guide-image">
<img src="./images/matches/other-no-storm.png" width="175" height="175" />
</div>
<div class="guide-description">
<p><strong>No storm:</strong> Early in a storm’s lifetime it might not be possible to say anything about its shape. If there is no evidence of an organised spiral structure then mark ‘no storm’.</p>
</div>
</div>
'''
center:
heading: 'Click the <strong>center</strong> of the storm.'
explanation: '''
<section class="for-embedded center-embedded-center">
<h2>Finding the Center (Embedded Center)</h2>
<img src="images/field-guide/center-embedded-center.jpg" class="example"/>
<p>In an Embedded Center storm the center is embedded within the coldest clouds; no eye is present.</p>
<h3>What to look for:</h3>
<p>Follow the swirl of clouds inward to a single point, traveling along a spiral. The center isn’t necessarily under the coldest clouds, so be careful not to get distracted by a spot of colder colors.</p>
<p>Here the clouds are spiraling inward along the black arrows. It may be tempting to click the area of dark blue clouds, but if you follow the arrows all the way in, you’ll see that the focus of circulation is actually slightly to the southeast, shown by the white crosshairs.</p>
</section>
<section class="for-curved center-curved-band">
<h2>Click the center of the storm (Curved Band)</h2>
<img src="images/field-guide/center-curved-band.jpg" class="example" />
<p>The center of circulation in a Curved Band storm can be found by following the spirals inward to a single point.</p>
<h3>What to look for:</h3>
<p>Curved Band storms sometimes spiral around a wedge of warmer clouds. The center of the storm is often near where the cold spiral meets this warm wedge.</p>
</section>
<section class="for-shear center-shear">
<h2>Click on the Storm Center (Shear)</h2>
<img src="images/field-guide/center-shear.jpg" class="example" />
<p>These are called Shear storms because they are encountering a cold front, or other large weather system, whose winds vary, or shear, with height. This shear tilts the storm over to one side.</p>
<h3>What to look for:</h3>
<p>The asymmetry of a Shear storm makes it tricky to find it’s center because tall clouds are prevented from developing on one side of the cyclone. Sometimes, like in this example, you can still see a small swirl in the gray and pink (warmer) clouds. If you see one of these, follow the swirl as it spirals into the center.</p>
<p>Shallow clouds may be difficult to find on infrared images. If you have trouble with the swirl method, look at the shield of cold clouds. In Shear storms, the colors will be very close together on one side of the storm, sometimes aligned in a straight line. That’s where the cold clouds are developing, before being blown away by the shear. The center of the storm will usually be nearby.</p>
</section>
'''
centerEyeSize:
heading: 'Click the <strong>center</strong> of the storm, then pick the size closest to the eye edge.'
explanation: '''
<h2>Click the center of the storm, then choose the size of the eye.</h2>
<img src="./images/field-guide/center-eye.jpg" class="example" />
<p>A cyclone’s eye, a mostly cloudless and rain free area, forms at its center of circulation.</p>
<h3>What to look for:</h3>
<p>Identify the eye and center of the storm:</p>
<p>Look for a very warm area near the center of the storm surrounded by a ring of very cold clouds. Finding the center of the storm is easy, it’s the center of the eye.</p>
<h3>Eye size:</h3>
<p>Select the circle that best matches the size of the eye and drag it with your mouse so that it traces the eye. Think of the edge of the eye as the point where the colors are closest together. If you need to change the size, click on a different-sized circle.</p>
<p><strong>Why it’s important:</strong> Storms with smaller eyes typically have tighter and stronger circulation, and are therefore a stronger storm.</p>
'''
surrounding:
heading: 'Which colors completely surround the eye?'
explanation: '''
<h2>Which colors completely surround the eye?</h2>
<img src="./images/field-guide/surrounding.jpg" class="example" />
<p>A tropical cyclone’s eye is surrounded by a ring of tall clouds called the eyewall.</p>
<h3>What to look for:</h3>
<p>Look for the coldest color completely surrounding the eye of the cyclone in an unbroken ring. It doesn’t matter how thick or thin the ring is, or even if it’s not circular, only that it is continuous all the way around.</p>
<p>Think of these storms as a layer cake, with warmer cloud layers underneath colder ones. If you removed all of the light blue colors, you would see yellow beneath them, and orange beneath those. In the example below, the cyan ring doesn’t quite connect all the way around, but the light blue beneath it does. Since the light blue completes a ring, that means that yellow, orange, and all the layers of the cake beneath it also wrap all the way around. You only need to select light blue.</p>
<p><strong>Why it’s important:</strong> Cloud temperatures decrease with height, so stronger storms can be identified by finding the coldest cloud tops. By identifying which colors surround the eye of the storm in the eyewall, you’ll determine how tall these clouds are, helping to estimate the strength of the cyclone.</p>
'''
exceeding:
heading: 'Choose the colors completely surrounding the eye at least 0.5° thick.'
instruction: 'Drag your mouse over the image to reveal a measuring tool.'
explanation: '''
<h2>Choose the colors completely surrounding the eye that is at least 0.5° thick</h2>
<img src="./images/field-guide/exceeding.jpg" class="example" />
<h3>What to look for:</h3>
<p>Hover over the image to make a small measuring tool appear. Find the coldest color completely surrounding the eye that also completely fills the circle at all points around the ring. The light blue wrapped all the way around the storm is thick enough in most places, but not southwest of the eye. In that region there is some yellow peaking through the measuring tool. That small bit of yellow is enough to eliminate the light blue for this step.</p>
<p>The yellow might not seem thick enough either. However, remember how a storm is like a layer cake. If one ring isn’t quite thick enough, imagine removing it and exposing the next warmer color below, and so forth until you find one thick enough. There is a yellow layer underneath the blue one, so we can consider these blues as part of the yellow. In that case, the yellow is more than thick enough.</p>
<p><strong>Why it’s important:</strong> This tells us not only how tall the clouds are, but how widespread as well. Storms with a larger area of cold clouds are typically more intense.</p>
'''
feature:
heading: 'Choose the image that matches the banding feature. <span class="thickness"></span>'
explanation: '''
<h2>Does the band wrap less than a quarter, about a quarter, half or more?</h2>
<img src="./images/field-guide/feature-embedded-center.jpg" class="example" />
<p>Strong tropical cyclones often have long spiral bands. A band is defined as a spiral arm that is orange or colder, separated from the main storm by a wedge of red or warmer clouds.</p>
<h3>What to look for:</h3>
<p>You’ll determine how far the band wraps around the storm. Choose an icon from the three below the image to indicate whether the band wraps less than a quarter way around the storm, a quarter-way around the storm, or halfway or more around the storm. If a storm doesn’t have spiral bands select the first icon.</p>
<p>The example here has a wide band along the north side of the storm. This band is relatively short and it doesn’t wrap very far around the storm’s center. In this case, choose the first icon.</p>
'''
blue:
heading: 'Which colors wrap most of the way around the band?'
explanation: '''
<h2>Which colors wrap most of the way around the band?</h2>
<img src="./images/field-guide/color.jpg" class="example" />
<h3>What to look for:</h3>
<p>You’ll identify the primary color of the Curved Band itself. Simply look at the band and choose the coldest color that extends along most of the band. In this example there are some patches of light blue, and even cyan, but they are too sparse to be considered widespread, so you would choose yellow.</p>
<p><strong>Why is this important:</strong> This provides information on the cyclone’s strength. Colder, taller clouds release more energy into a tropical cyclone. We identify these taller storms in infrared satellite images by looking for colder cloud tops. Remember white and blue represent the coldest clouds and pink and grey represent the warmest clouds. Stronger tropical cyclones will have more of these tall, cold clouds.</p>
'''
curve:
heading: 'How far does the main band wrap?'
explanation: '''
<h2>How far does the main band wrap?</h2>
<img src="./images/field-guide/wrap.jpg" class="example" />
<p>A Curved Band storm’s strength is measured by the length of the band. The longer the band, the stronger the storm.</p>
<h3>What to look for:</h3>
<p>Focus on how far around the band wraps, and click on the picture that best matches it. In this example, the band wraps around about one-half of a full circle, so we’d choose the second picture.</p>
'''
red:
heading: 'Click the nearest red point to the storm center.'
explanation: '''
<h2>Click the red point nearest to the storm center that is associated with the main cloud feature</h2>
<img src="./images/field-guide/red.jpg" class="example" />
<h3>What to look for:</h3>
<p>You’re marking the distance from the center that you marked in the last step to the storm’s main thunderstorms. Click the red point closest to the center that you previously marked.</p>
<p>Here, the center (marked with a white crosshair) is just outside the main thunderstorms. Sometimes the center will be within the cold colors, but we’ll still need to know how far the center is from the edge of the coldest clouds. Click the edge of the main storm (the nearest red point), and a second crosshair will appear. The distance between these clicks will tell us the storm’s strength.</p>
<p><strong>Why is this important:</strong> This tells us how tilted or straight the storm is, and therefore, how strong it is.</p>
'''
reveal:
heading: 'Scroll down to learn more about this cyclone, or click next to move onto the next storm.'
tutorialSubject: '(Tutorial image)'
estimated: 'Possible wind speed, based on your classification:'
windAndPressure: 'Wind speed and pressure'
tutorial:
welcome:
header: '''Welcome to Cyclone Center!'''
details: '''
By comparing satellite images to assess storm type and strength, you’re helping meteorologists understand the history of tropical cyclone weather patterns.
This tutorial will show you how to identify tropical cyclone type and strength. Let’s go!
'''
temperature:
header: '''Cloud Color & Temperature'''
details: '''
White and blue clouds are the coldest and pink and grey clouds are the warmest.
This is important to keep in mind as you are categorize storm type and strength.
'''
chooseStronger:
header: '''Storm Strength'''
details: '''
To determine which is stronger look for the presence of colder clouds and a more organized system.
The image on the right has more cold clouds and is more organized, so let’s select it as the stronger storm.
'''
instruction: '''Click the storm image on the right.'''
postStronger:
header: '''Storm Strength'''
details: '''
And click continue to move to the next step...
'''
instruction: '''Click "Continue".'''
chooseEmbeddedType:
header: '''Cyclone Type'''
details: '''
Now let’s figure out what type of storm we’re looking at.
There are four main types of tropical cyclones – Eye, Embedded Center, Curved Band, and Shear.
Let’s checkout embedded centers first. We can choose a different type if we find this one doesn't match.
'''
instruction: '''Choose "Embedded Center".'''
chooseEyeType:
header: '''Cyclone Type'''
details: '''
These images look similar, but not quite right. Let’s try a different storm type. Select Eye.
'''
instruction: '''Choose "Eye" instead.'''
chooseMatch:
header: '''Cyclone Type'''
details: '''
From left to right the storm images get stronger.
The clouds in this storm seem very cold and organized, similar to those in the fourth image.
Let's choose it as our closest match.
'''
instruction: '''Click the fourth eye image.'''
postMatch:
header: '''Cyclone Type'''
details: '''
This looks like a close match, and even if it's off by a bit, our classifications will be compared against other volunteers' classifications of the same image. Let's move on.
'''
instruction: '''Click "Continue".'''
chooseCenter:
header: '''Center and Eye Size'''
details: '''
Now let's click the center of the storm. For an eye storm, it's simply the center of the eye.
'''
instruction: '''Click the center of the storm.'''
chooseSize:
header: '''Center and Eye Size'''
details: '''
Choose the size that most closely matches the eyewall. For more help, you can always check the guide below.
'''
instruction: '''Choose the second circle.'''
postChooseSize:
header: '''Center and Eye Size'''
details: '''
That looks like a great fit. If you're unsure, remember that your classification is one of many, so just do your best!
'''
instruction: '''Click "Continue".'''
chooseSurrounding:
header: '''Coldest Surrounding Clouds'''
details: '''
Now we need to determine the coldest unbroken ring around the eye.
Moving from the eye out, we can see that the beige, orange, red, yellow, and light blue bands are all continuous.
The cyan band is broken, so let's choose the light blue as the coldest continuous band.
'''
instruction: '''Choose the teal/blue swatch, 6th from the left.'''
postSurrounding:
header: '''Coldest Surrounding Clouds'''
details: '''Great!'''
instruction: '''Click "Continue".'''
chooseColdestThick:
header: '''Coldest Surrounding Thick Band of Clouds'''
details: '''
Now we want to do the same thing, but only for band 0.5° thick.
Hovering over the image will show you a box you can use to measure that thickness.
Choose the color that fills that box all the way around.
Remember: Colder color include warmer colors.
Here, it appears the teal/blue band is thick enough all the way around the eye.
'''
instruction: '''Choose the teal/blue swatch again.'''
postColdestThick:
header: '''Coldest Surrounding Thick Band of Clouds'''
details: '''
Excellent.
'''
instruction: '''Click "Continue".'''
chooseBandingFeature:
header: '''Banding Feature'''
details: '''
Now let's identify the length of the storm's spiral bands.
This storm doesn't have very strong banding, so let's choose the first option.
'''
instruction: '''Choose the first option.'''
postBandingFeature:
header: '''Banding Feature'''
details: '''
We're almost finished!
'''
instruction: '''Click "Continue" one more time.'''
goodLuck:
header: '''Good Luck!'''
details: '''
Now you’re ready to classify tropical cyclones! Remember to check-out the ? Buttons for more information if you have questions.
Classifying storms is tricky, but we know that our volunteers do a great job. Just do your best, your opinion is important.
Click Next storm to move to your next storm.
'''
instruction: '''Click "Next" to get started on your own!'''
progress:
start: "Welcome, new stormwatcher! You can help us best by observing at least 4 storms. It’s quick, easy, and fun. When you’re ready, you can get started below!"
25: "Congratulations! You’ve just identified your first storm. Could you do at least 3 more?"
50: "Two storms down, two to go! You’re doing great; keep it up!"
75: "All right! You’re almost there! Just one storm left!"
100: "Great job, stormwatcher! You’ve observed 4 storms and already helped our project tremendously. Now that you’re a pro, why not keep going?"
|
[
{
"context": "escryer.com/grunt-pagespeed\n#\n# Copyright (c) 2013 James Cryer\n# http://www.jamescryer.com\n# Licensed under the ",
"end": 98,
"score": 0.9998682737350464,
"start": 87,
"tag": "NAME",
"value": "James Cryer"
}
] | tasks/lib/config.coffee | paulradzkov/grunt-pagespeed | 0 | #
# grunt-pagespeed
# http://www.jamescryer.com/grunt-pagespeed
#
# Copyright (c) 2013 James Cryer
# http://www.jamescryer.com
# Licensed under the MIT license.
#
'use strict';
exports.init = (grunt) ->
exports = {}
config = {}
DEFAULT_THRESHOLD = 70
DEFAULT_FORMAT = 'cli'
key = ->
config["key"] if config["key"]
format = ->
return config["format"] if config["format"]
return DEFAULT_FORMAT unless config["format"]
nokey = ->
config["nokey"] if config["nokey"]
url = ->
config["url"] if config["url"]
urls = ->
return config["urls"] if config["urls"]
[] unless config["urls"]
paths = ->
return config["paths"] if config["paths"]
[''] unless config["paths"]
locale = ->
grunt.fatal("Locale key is mandatory") unless config["locale"]
config["locale"] if config["locale"]
strategy = ->
config["strategy"] if config["strategy"]
timeout = ->
config["timeout"] if config["timeout"]
file = ->
config["file"] + ".json" if config["file"]
filepath = ->
config["filepath"] if config["filepath"]
format = ->
return "json" if config["file"]
return config["format"] if config["format"] && config['format'].match(/json|cli|tap/)
'cli' unless config["format"] && config['format'].match(/json|cli|tap/)
threshold = ->
return DEFAULT_THRESHOLD unless config["threshold"]
config["threshold"]
exports.params = (options) ->
config = options
unless key() or nokey()
grunt.fatal("Please supply a key or use the nokey option")
params = for index, path of paths()
param = {}
param["key"] = key() if config["key"]
param["nokey"] = nokey() if config["nokey"]
param["url"] = url() + path
param["locale"] = locale()
param["strategy"] = strategy()
param["threshold"] = threshold()
param["filepath"] = filepath()
param["file"] = file()
param["format"] = format() if config["format"]
param
params
exports.threshold = threshold
return exports
| 131467 | #
# grunt-pagespeed
# http://www.jamescryer.com/grunt-pagespeed
#
# Copyright (c) 2013 <NAME>
# http://www.jamescryer.com
# Licensed under the MIT license.
#
'use strict';
exports.init = (grunt) ->
exports = {}
config = {}
DEFAULT_THRESHOLD = 70
DEFAULT_FORMAT = 'cli'
key = ->
config["key"] if config["key"]
format = ->
return config["format"] if config["format"]
return DEFAULT_FORMAT unless config["format"]
nokey = ->
config["nokey"] if config["nokey"]
url = ->
config["url"] if config["url"]
urls = ->
return config["urls"] if config["urls"]
[] unless config["urls"]
paths = ->
return config["paths"] if config["paths"]
[''] unless config["paths"]
locale = ->
grunt.fatal("Locale key is mandatory") unless config["locale"]
config["locale"] if config["locale"]
strategy = ->
config["strategy"] if config["strategy"]
timeout = ->
config["timeout"] if config["timeout"]
file = ->
config["file"] + ".json" if config["file"]
filepath = ->
config["filepath"] if config["filepath"]
format = ->
return "json" if config["file"]
return config["format"] if config["format"] && config['format'].match(/json|cli|tap/)
'cli' unless config["format"] && config['format'].match(/json|cli|tap/)
threshold = ->
return DEFAULT_THRESHOLD unless config["threshold"]
config["threshold"]
exports.params = (options) ->
config = options
unless key() or nokey()
grunt.fatal("Please supply a key or use the nokey option")
params = for index, path of paths()
param = {}
param["key"] = key() if config["key"]
param["nokey"] = nokey() if config["nokey"]
param["url"] = url() + path
param["locale"] = locale()
param["strategy"] = strategy()
param["threshold"] = threshold()
param["filepath"] = filepath()
param["file"] = file()
param["format"] = format() if config["format"]
param
params
exports.threshold = threshold
return exports
| true | #
# grunt-pagespeed
# http://www.jamescryer.com/grunt-pagespeed
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI
# http://www.jamescryer.com
# Licensed under the MIT license.
#
'use strict';
exports.init = (grunt) ->
exports = {}
config = {}
DEFAULT_THRESHOLD = 70
DEFAULT_FORMAT = 'cli'
key = ->
config["key"] if config["key"]
format = ->
return config["format"] if config["format"]
return DEFAULT_FORMAT unless config["format"]
nokey = ->
config["nokey"] if config["nokey"]
url = ->
config["url"] if config["url"]
urls = ->
return config["urls"] if config["urls"]
[] unless config["urls"]
paths = ->
return config["paths"] if config["paths"]
[''] unless config["paths"]
locale = ->
grunt.fatal("Locale key is mandatory") unless config["locale"]
config["locale"] if config["locale"]
strategy = ->
config["strategy"] if config["strategy"]
timeout = ->
config["timeout"] if config["timeout"]
file = ->
config["file"] + ".json" if config["file"]
filepath = ->
config["filepath"] if config["filepath"]
format = ->
return "json" if config["file"]
return config["format"] if config["format"] && config['format'].match(/json|cli|tap/)
'cli' unless config["format"] && config['format'].match(/json|cli|tap/)
threshold = ->
return DEFAULT_THRESHOLD unless config["threshold"]
config["threshold"]
exports.params = (options) ->
config = options
unless key() or nokey()
grunt.fatal("Please supply a key or use the nokey option")
params = for index, path of paths()
param = {}
param["key"] = key() if config["key"]
param["nokey"] = nokey() if config["nokey"]
param["url"] = url() + path
param["locale"] = locale()
param["strategy"] = strategy()
param["threshold"] = threshold()
param["filepath"] = filepath()
param["file"] = file()
param["format"] = format() if config["format"]
param
params
exports.threshold = threshold
return exports
|
[
{
"context": " saltApiAuth =\n user: auth.user\n token: auth.token\n ",
"end": 5571,
"score": 0.9682371020317078,
"start": 5562,
"tag": "USERNAME",
"value": "auth.user"
},
{
"context": " user: auth.user\n ... | halite/lattice/app/main.coffee | CARFAX/halite | 212 | # To compile do
# $ coffee -c main.coffee
# this creates main.js in same directory
# To automatically compile
# $ coffee -w -c main.coffee &
# angular.module() call registers demo for injection into other angular components
# assign to window.myApp if we want to have a global handle to the module
# Main App Module
mainApp = angular.module("MainApp", ['ngRoute', 'ngCookies', 'ngAnimate',
'appConfigSrvc', 'appPrefSrvc',
'appDataSrvc', 'appStoreSrvc', 'appUtilSrvc', 'appFltr', 'appDrtv',
'saltApiSrvc', 'demoSrvc', 'errorReportingSrvc', 'highstateCheckSrvc', 'eventSrvc', 'jobSrvc', 'saltSrvc',
'fetchActivesSrvc'])
mainApp.constant 'MainConstants',
name: 'Halite'
owner: 'SaltStack'
mainApp.config ["Configuration", "MainConstants", "$locationProvider",
"$routeProvider", "$httpProvider",
(Configuration, MainConstants, $locationProvider, $routeProvider, $httpProvider) ->
$locationProvider.html5Mode(true)
#console.log("Configuration")
#console.log(Configuration)
#console.log("MainConstants")
#console.log(MainConstants)
#using absolute urls here in html5 mode
base = Configuration.baseUrl # for use in coffeescript string interpolation #{base}
#$httpProvider.defaults.useXDomain = true;
#delete $httpProvider.defaults.headers.common['X-Requested-With']
for name, item of Configuration.views
if item.label? # item is a view
$routeProvider.when item.route,
templateUrl: item.template
controller: item.controller
else # item is a list of views
for view in item
$routeProvider.when view.route,
templateUrl: view.template
controller: view.controller
$routeProvider.otherwise
redirectTo: Configuration.views.otherwise.route
return true
]
mainApp.controller 'NavbarCtlr', ['$scope', '$rootScope', '$location', '$route',
'$routeParams', 'Configuration', 'AppPref', 'AppData',
'LocalStore', 'SessionStore', 'SaltApiSrvc',
($scope, $rootScope, $location, $route, $routeParams, Configuration, AppPref,
AppData, LocalStore, SessionStore, SaltApiSrvc) ->
#console.log("NavbarCtlr")
$scope.location = $location
$scope.route = $route
$scope.winLoc = window.location
$scope.baseUrl = Configuration.baseUrl
$scope.debug = AppPref.get('debug')
$scope.errorMsg = ''
$scope.isCollapsed = true;
$scope.loggedIn = if SessionStore.get('loggedIn')? then SessionStore.get('loggedIn') else false
$scope.username = SessionStore.get('saltApiAuth')?.user
$scope.views = Configuration.views
$scope.navery =
'navs': {}
'activate': (navact) ->
navact.state = 'active'
for label, nav of @navs
if nav != navact
nav.state = 'inactive'
return true
'update': (newPath, oldPath) ->
for label, nav of @navs
if newPath.match(nav.matcher)?
@activate(nav)
return true
return true
'load': (views) ->
for name, item of views
if item.label? #item is vies
@navs[item.label] =
state: 'inactive'
matcher: item.matcher
else # item is list of views
for view in item
@navs[view.label] =
state: 'inactive'
matcher: view.matcher
$scope.navery.load($scope.views)
$scope.$watch('location.path()', (newPath, oldPath) ->
$scope.navery.update(newPath, oldPath)
return true
)
$scope.login =
username: ""
password: ""
$scope.logoutUser = () ->
$scope.errorMsg = ""
$scope.username = null
$scope.loggedIn = false
$scope.login =
username: ""
password: ""
$scope.saltApiLogoutPromise = SaltApiSrvc.logout $scope
$scope.saltApiLogoutPromise.success (data, status, headers, config) ->
#console.log("SaltApi Logout success")
#console.log data
if data?.return?[0]?
SessionStore.set('loggedIn',$scope.loggedIn)
SessionStore.remove('saltApiAuth')
$rootScope.$broadcast('ToggleAuth', $scope.loggedIn)
#console.log SessionStore.get('loggedIn')
#console.log SessionStore.get('saltApiAuth')
return true
return true
$scope.loginUser = () ->
$scope.errorMsg = ""
#console.log "Logging in as #{$scope.login.username} with #{$scope.login.password}"
$scope.saltApiLoginPromise = SaltApiSrvc.login $scope, $scope.login.username, $scope.login.password
$scope.saltApiLoginPromise.success (data, status, headers, config) ->
#console.log("SaltApi Login success")
#console.log data
if data?.return?[0]?
auth = data.return[0]
saltApiAuth =
user: auth.user
token: auth.token
eauth: auth.eauth
start: auth.start
expire: auth.expire
perms: auth.perms[0]
$scope.loggedIn = true
SessionStore.set('loggedIn', $scope.loggedIn)
$scope.username = saltApiAuth.user
SessionStore.set('saltApiAuth', saltApiAuth )
$rootScope.$broadcast('ToggleAuth', $scope.loggedIn)
#console.log SessionStore.get('loggedIn')
#console.log SessionStore.get('saltApiAuth')
return true
return true
$scope.loginFormError = () ->
msg = ""
if $scope.loginForm.$dirty and $scope.loginForm.$invalid
requiredFields = ["username", "password"]
erroredFields =
for name in requiredFields when $scope.loginForm[name].$error.required
$scope.loginForm[name].$name.substring(0,1).toUpperCase() + $scope.loginForm[name].$name.substring(1)
if erroredFields
msg = erroredFields.join(" & ") + " missing!"
return msg
return true
]
mainApp.controller 'RouteCtlr', ['$scope', '$location', '$route', '$routeParams',
'Configuration', 'AppPref',
($scope, $location, $route, $$routeParams, Configuration, AppPref) ->
#console.log "RouteCtlr"
$scope.location = $location
$scope.route = $route
$scope.winLoc = window.location
$scope.baseUrl = Configuration.baseUrl
$scope.debug = AppPref.get('debug')
$scope.errorMsg = ''
return true
]
| 167446 | # To compile do
# $ coffee -c main.coffee
# this creates main.js in same directory
# To automatically compile
# $ coffee -w -c main.coffee &
# angular.module() call registers demo for injection into other angular components
# assign to window.myApp if we want to have a global handle to the module
# Main App Module
mainApp = angular.module("MainApp", ['ngRoute', 'ngCookies', 'ngAnimate',
'appConfigSrvc', 'appPrefSrvc',
'appDataSrvc', 'appStoreSrvc', 'appUtilSrvc', 'appFltr', 'appDrtv',
'saltApiSrvc', 'demoSrvc', 'errorReportingSrvc', 'highstateCheckSrvc', 'eventSrvc', 'jobSrvc', 'saltSrvc',
'fetchActivesSrvc'])
mainApp.constant 'MainConstants',
name: 'Halite'
owner: 'SaltStack'
mainApp.config ["Configuration", "MainConstants", "$locationProvider",
"$routeProvider", "$httpProvider",
(Configuration, MainConstants, $locationProvider, $routeProvider, $httpProvider) ->
$locationProvider.html5Mode(true)
#console.log("Configuration")
#console.log(Configuration)
#console.log("MainConstants")
#console.log(MainConstants)
#using absolute urls here in html5 mode
base = Configuration.baseUrl # for use in coffeescript string interpolation #{base}
#$httpProvider.defaults.useXDomain = true;
#delete $httpProvider.defaults.headers.common['X-Requested-With']
for name, item of Configuration.views
if item.label? # item is a view
$routeProvider.when item.route,
templateUrl: item.template
controller: item.controller
else # item is a list of views
for view in item
$routeProvider.when view.route,
templateUrl: view.template
controller: view.controller
$routeProvider.otherwise
redirectTo: Configuration.views.otherwise.route
return true
]
mainApp.controller 'NavbarCtlr', ['$scope', '$rootScope', '$location', '$route',
'$routeParams', 'Configuration', 'AppPref', 'AppData',
'LocalStore', 'SessionStore', 'SaltApiSrvc',
($scope, $rootScope, $location, $route, $routeParams, Configuration, AppPref,
AppData, LocalStore, SessionStore, SaltApiSrvc) ->
#console.log("NavbarCtlr")
$scope.location = $location
$scope.route = $route
$scope.winLoc = window.location
$scope.baseUrl = Configuration.baseUrl
$scope.debug = AppPref.get('debug')
$scope.errorMsg = ''
$scope.isCollapsed = true;
$scope.loggedIn = if SessionStore.get('loggedIn')? then SessionStore.get('loggedIn') else false
$scope.username = SessionStore.get('saltApiAuth')?.user
$scope.views = Configuration.views
$scope.navery =
'navs': {}
'activate': (navact) ->
navact.state = 'active'
for label, nav of @navs
if nav != navact
nav.state = 'inactive'
return true
'update': (newPath, oldPath) ->
for label, nav of @navs
if newPath.match(nav.matcher)?
@activate(nav)
return true
return true
'load': (views) ->
for name, item of views
if item.label? #item is vies
@navs[item.label] =
state: 'inactive'
matcher: item.matcher
else # item is list of views
for view in item
@navs[view.label] =
state: 'inactive'
matcher: view.matcher
$scope.navery.load($scope.views)
$scope.$watch('location.path()', (newPath, oldPath) ->
$scope.navery.update(newPath, oldPath)
return true
)
$scope.login =
username: ""
password: ""
$scope.logoutUser = () ->
$scope.errorMsg = ""
$scope.username = null
$scope.loggedIn = false
$scope.login =
username: ""
password: ""
$scope.saltApiLogoutPromise = SaltApiSrvc.logout $scope
$scope.saltApiLogoutPromise.success (data, status, headers, config) ->
#console.log("SaltApi Logout success")
#console.log data
if data?.return?[0]?
SessionStore.set('loggedIn',$scope.loggedIn)
SessionStore.remove('saltApiAuth')
$rootScope.$broadcast('ToggleAuth', $scope.loggedIn)
#console.log SessionStore.get('loggedIn')
#console.log SessionStore.get('saltApiAuth')
return true
return true
$scope.loginUser = () ->
$scope.errorMsg = ""
#console.log "Logging in as #{$scope.login.username} with #{$scope.login.password}"
$scope.saltApiLoginPromise = SaltApiSrvc.login $scope, $scope.login.username, $scope.login.password
$scope.saltApiLoginPromise.success (data, status, headers, config) ->
#console.log("SaltApi Login success")
#console.log data
if data?.return?[0]?
auth = data.return[0]
saltApiAuth =
user: auth.user
token: <PASSWORD>.token
eauth: auth.eauth
start: auth.start
expire: auth.expire
perms: auth.perms[0]
$scope.loggedIn = true
SessionStore.set('loggedIn', $scope.loggedIn)
$scope.username = saltApiAuth.user
SessionStore.set('saltApiAuth', saltApiAuth )
$rootScope.$broadcast('ToggleAuth', $scope.loggedIn)
#console.log SessionStore.get('loggedIn')
#console.log SessionStore.get('saltApiAuth')
return true
return true
$scope.loginFormError = () ->
msg = ""
if $scope.loginForm.$dirty and $scope.loginForm.$invalid
requiredFields = ["username", "password"]
erroredFields =
for name in requiredFields when $scope.loginForm[name].$error.required
$scope.loginForm[name].$name.substring(0,1).toUpperCase() + $scope.loginForm[name].$name.substring(1)
if erroredFields
msg = erroredFields.join(" & ") + " missing!"
return msg
return true
]
mainApp.controller 'RouteCtlr', ['$scope', '$location', '$route', '$routeParams',
'Configuration', 'AppPref',
($scope, $location, $route, $$routeParams, Configuration, AppPref) ->
#console.log "RouteCtlr"
$scope.location = $location
$scope.route = $route
$scope.winLoc = window.location
$scope.baseUrl = Configuration.baseUrl
$scope.debug = AppPref.get('debug')
$scope.errorMsg = ''
return true
]
| true | # To compile do
# $ coffee -c main.coffee
# this creates main.js in same directory
# To automatically compile
# $ coffee -w -c main.coffee &
# angular.module() call registers demo for injection into other angular components
# assign to window.myApp if we want to have a global handle to the module
# Main App Module
mainApp = angular.module("MainApp", ['ngRoute', 'ngCookies', 'ngAnimate',
'appConfigSrvc', 'appPrefSrvc',
'appDataSrvc', 'appStoreSrvc', 'appUtilSrvc', 'appFltr', 'appDrtv',
'saltApiSrvc', 'demoSrvc', 'errorReportingSrvc', 'highstateCheckSrvc', 'eventSrvc', 'jobSrvc', 'saltSrvc',
'fetchActivesSrvc'])
mainApp.constant 'MainConstants',
name: 'Halite'
owner: 'SaltStack'
mainApp.config ["Configuration", "MainConstants", "$locationProvider",
"$routeProvider", "$httpProvider",
(Configuration, MainConstants, $locationProvider, $routeProvider, $httpProvider) ->
$locationProvider.html5Mode(true)
#console.log("Configuration")
#console.log(Configuration)
#console.log("MainConstants")
#console.log(MainConstants)
#using absolute urls here in html5 mode
base = Configuration.baseUrl # for use in coffeescript string interpolation #{base}
#$httpProvider.defaults.useXDomain = true;
#delete $httpProvider.defaults.headers.common['X-Requested-With']
for name, item of Configuration.views
if item.label? # item is a view
$routeProvider.when item.route,
templateUrl: item.template
controller: item.controller
else # item is a list of views
for view in item
$routeProvider.when view.route,
templateUrl: view.template
controller: view.controller
$routeProvider.otherwise
redirectTo: Configuration.views.otherwise.route
return true
]
mainApp.controller 'NavbarCtlr', ['$scope', '$rootScope', '$location', '$route',
'$routeParams', 'Configuration', 'AppPref', 'AppData',
'LocalStore', 'SessionStore', 'SaltApiSrvc',
($scope, $rootScope, $location, $route, $routeParams, Configuration, AppPref,
AppData, LocalStore, SessionStore, SaltApiSrvc) ->
#console.log("NavbarCtlr")
$scope.location = $location
$scope.route = $route
$scope.winLoc = window.location
$scope.baseUrl = Configuration.baseUrl
$scope.debug = AppPref.get('debug')
$scope.errorMsg = ''
$scope.isCollapsed = true;
$scope.loggedIn = if SessionStore.get('loggedIn')? then SessionStore.get('loggedIn') else false
$scope.username = SessionStore.get('saltApiAuth')?.user
$scope.views = Configuration.views
$scope.navery =
'navs': {}
'activate': (navact) ->
navact.state = 'active'
for label, nav of @navs
if nav != navact
nav.state = 'inactive'
return true
'update': (newPath, oldPath) ->
for label, nav of @navs
if newPath.match(nav.matcher)?
@activate(nav)
return true
return true
'load': (views) ->
for name, item of views
if item.label? #item is vies
@navs[item.label] =
state: 'inactive'
matcher: item.matcher
else # item is list of views
for view in item
@navs[view.label] =
state: 'inactive'
matcher: view.matcher
$scope.navery.load($scope.views)
$scope.$watch('location.path()', (newPath, oldPath) ->
$scope.navery.update(newPath, oldPath)
return true
)
$scope.login =
username: ""
password: ""
$scope.logoutUser = () ->
$scope.errorMsg = ""
$scope.username = null
$scope.loggedIn = false
$scope.login =
username: ""
password: ""
$scope.saltApiLogoutPromise = SaltApiSrvc.logout $scope
$scope.saltApiLogoutPromise.success (data, status, headers, config) ->
#console.log("SaltApi Logout success")
#console.log data
if data?.return?[0]?
SessionStore.set('loggedIn',$scope.loggedIn)
SessionStore.remove('saltApiAuth')
$rootScope.$broadcast('ToggleAuth', $scope.loggedIn)
#console.log SessionStore.get('loggedIn')
#console.log SessionStore.get('saltApiAuth')
return true
return true
$scope.loginUser = () ->
$scope.errorMsg = ""
#console.log "Logging in as #{$scope.login.username} with #{$scope.login.password}"
$scope.saltApiLoginPromise = SaltApiSrvc.login $scope, $scope.login.username, $scope.login.password
$scope.saltApiLoginPromise.success (data, status, headers, config) ->
#console.log("SaltApi Login success")
#console.log data
if data?.return?[0]?
auth = data.return[0]
saltApiAuth =
user: auth.user
token: PI:PASSWORD:<PASSWORD>END_PI.token
eauth: auth.eauth
start: auth.start
expire: auth.expire
perms: auth.perms[0]
$scope.loggedIn = true
SessionStore.set('loggedIn', $scope.loggedIn)
$scope.username = saltApiAuth.user
SessionStore.set('saltApiAuth', saltApiAuth )
$rootScope.$broadcast('ToggleAuth', $scope.loggedIn)
#console.log SessionStore.get('loggedIn')
#console.log SessionStore.get('saltApiAuth')
return true
return true
$scope.loginFormError = () ->
msg = ""
if $scope.loginForm.$dirty and $scope.loginForm.$invalid
requiredFields = ["username", "password"]
erroredFields =
for name in requiredFields when $scope.loginForm[name].$error.required
$scope.loginForm[name].$name.substring(0,1).toUpperCase() + $scope.loginForm[name].$name.substring(1)
if erroredFields
msg = erroredFields.join(" & ") + " missing!"
return msg
return true
]
mainApp.controller 'RouteCtlr', ['$scope', '$location', '$route', '$routeParams',
'Configuration', 'AppPref',
($scope, $location, $route, $$routeParams, Configuration, AppPref) ->
#console.log "RouteCtlr"
$scope.location = $location
$scope.route = $route
$scope.winLoc = window.location
$scope.baseUrl = Configuration.baseUrl
$scope.debug = AppPref.get('debug')
$scope.errorMsg = ''
return true
]
|
[
{
"context": "e elements have no interactive handlers.\n# @author Ethan Cohen\n###\n\n# ------------------------------------------",
"end": 129,
"score": 0.9998645782470703,
"start": 118,
"tag": "NAME",
"value": "Ethan Cohen"
},
{
"context": "can uncomment these tests once https://gi... | src/tests/rules/no-noninteractive-element-interactions.coffee | danielbayley/eslint-plugin-coffee | 21 | ### eslint-env jest ###
###*
# @fileoverview Enforce non-interactive elements have no interactive handlers.
# @author Ethan Cohen
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{configs} = require 'eslint-plugin-jsx-a11y'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require(
'eslint-plugin-jsx-a11y/lib/rules/no-noninteractive-element-interactions'
)
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
errorMessage =
'Non-interactive elements should not be assigned mouse or keyboard event listeners.'
expectedError =
message: errorMessage
type: 'JSXOpeningElement'
ruleName = 'no-noninteractive-element-interactions'
alwaysValid = [
code: '<TestComponent onClick={doFoo} />'
,
code: '<Button onClick={doFoo} />'
,
### All flavors of input ###
code: '<input onClick={() => undefined} />'
,
code: '<input type="button" onClick={() => undefined} />'
,
code: '<input type="checkbox" onClick={() => undefined} />'
,
code: '<input type="color" onClick={() => undefined} />'
,
code: '<input type="date" onClick={() => undefined} />'
,
code: '<input type="datetime" onClick={() => undefined} />'
,
code: '<input type="datetime-local" onClick={() => undefined} />'
,
code: '<input type="email" onClick={() => undefined} />'
,
code: '<input type="file" onClick={() => undefined} />'
,
code: '<input type="image" onClick={() => undefined} />'
,
code: '<input type="month" onClick={() => undefined} />'
,
code: '<input type="number" onClick={() => undefined} />'
,
code: '<input type="password" onClick={() => undefined} />'
,
code: '<input type="radio" onClick={() => undefined} />'
,
code: '<input type="range" onClick={() => undefined} />'
,
code: '<input type="reset" onClick={() => undefined} />'
,
code: '<input type="search" onClick={() => undefined} />'
,
code: '<input type="submit" onClick={() => undefined} />'
,
code: '<input type="tel" onClick={() => undefined} />'
,
code: '<input type="text" onClick={() => undefined} />'
,
code: '<input type="time" onClick={() => undefined} />'
,
code: '<input type="url" onClick={() => undefined} />'
,
code: '<input type="week" onClick={() => undefined} />'
,
code: '<input type="hidden" onClick={() => undefined} />'
,
### End all flavors of input ###
code: '<a onClick={() => undefined} />'
,
code: '<a onClick={() => {}} />'
,
code: '<a tabIndex="0" onClick={() => undefined} />'
,
code: '<a onClick={() => undefined} href="http://x.y.z" />'
,
code: '<a onClick={() => undefined} href="http://x.y.z" tabIndex="0" />'
,
code: '<area onClick={() => {}} />'
,
code: '<button onClick={() => undefined} className="foo" />'
,
code: '<menuitem onClick={() => {}} />'
,
code: '<option onClick={() => undefined} className="foo" />'
,
code: '<select onClick={() => undefined} className="foo" />'
,
code: '<textarea onClick={() => undefined} className="foo" />'
,
code: '<tr onClick={() => {}} />'
,
### HTML elements with neither an interactive or non-interactive valence (static) ###
code: '<acronym onClick={() => {}} />'
,
code: '<address onClick={() => {}} />'
,
code: '<applet onClick={() => {}} />'
,
code: '<audio onClick={() => {}} />'
,
code: '<b onClick={() => {}} />'
,
code: '<base onClick={() => {}} />'
,
code: '<bdi onClick={() => {}} />'
,
code: '<bdo onClick={() => {}} />'
,
code: '<big onClick={() => {}} />'
,
code: '<blink onClick={() => {}} />'
,
code: '<body onLoad={() => {}} />'
,
code: '<canvas onClick={() => {}} />'
,
code: '<center onClick={() => {}} />'
,
code: '<cite onClick={() => {}} />'
,
code: '<code onClick={() => {}} />'
,
code: '<col onClick={() => {}} />'
,
code: '<colgroup onClick={() => {}} />'
,
code: '<content onClick={() => {}} />'
,
code: '<data onClick={() => {}} />'
,
code: '<datalist onClick={() => {}} />'
,
code: '<del onClick={() => {}} />'
,
code: '<div />'
,
code: '<div className="foo" />'
,
code: '<div className="foo" {...props} />'
,
code: '<div onClick={() => undefined} aria-hidden />'
,
code: '<div onClick={() => undefined} aria-hidden={true} />'
,
code: '<div onClick={() => undefined} />'
,
code: '<div onClick={() => undefined} role={undefined} />'
,
code: '<div onClick={() => undefined} {...props} />'
,
code: '<div onClick={null} />'
,
code: '<div onKeyUp={() => undefined} aria-hidden={false} />'
,
code: '<em onClick={() => {}} />'
,
code: '<embed onClick={() => {}} />'
,
code: '<font onClick={() => {}} />'
,
code: '<font onSubmit={() => {}} />'
,
code: '<frameset onClick={() => {}} />'
,
code: '<head onClick={() => {}} />'
,
code: '<header onClick={() => {}} />'
,
code: '<hgroup onClick={() => {}} />'
,
code: '<html onClick={() => {}} />'
,
code: '<i onClick={() => {}} />'
,
code: '<iframe onLoad={() => {}} />'
,
code: '''
<iframe
name="embeddedExternalPayment"
ref="embeddedExternalPayment"
style={iframeStyle}
onLoad={this.handleLoadIframe}
/>
'''
,
code: '<img {...props} onError={() => {}} />'
,
code: '<img onLoad={() => {}} />'
,
code: '<ins onClick={() => {}} />'
,
code: '<kbd onClick={() => {}} />'
,
code: '<keygen onClick={() => {}} />'
,
code: '<link onClick={() => {}} />'
,
code: '<main onClick={null} />'
,
code: '<map onClick={() => {}} />'
,
code: '<meta onClick={() => {}} />'
,
code: '<noembed onClick={() => {}} />'
,
code: '<noscript onClick={() => {}} />'
,
code: '<object onClick={() => {}} />'
,
code: '<param onClick={() => {}} />'
,
code: '<picture onClick={() => {}} />'
,
code: '<q onClick={() => {}} />'
,
code: '<rp onClick={() => {}} />'
,
code: '<rt onClick={() => {}} />'
,
code: '<rtc onClick={() => {}} />'
,
code: '<s onClick={() => {}} />'
,
code: '<samp onClick={() => {}} />'
,
code: '<script onClick={() => {}} />'
,
# TODO: can uncomment these tests once https://github.com/evcohen/eslint-plugin-jsx-a11y/commit/8e0d22 gets released
# ,
# code: '<section onClick={() => {}} />'
code: '<small onClick={() => {}} />'
,
code: '<source onClick={() => {}} />'
,
code: '<spacer onClick={() => {}} />'
,
code: '<span onClick={() => {}} />'
,
code: '<strike onClick={() => {}} />'
,
code: '<strong onClick={() => {}} />'
,
code: '<style onClick={() => {}} />'
,
code: '<sub onClick={() => {}} />'
,
code: '<summary onClick={() => {}} />'
,
code: '<sup onClick={() => {}} />'
,
code: '<th onClick={() => {}} />'
,
code: '<title onClick={() => {}} />'
,
code: '<track onClick={() => {}} />'
,
code: '<tt onClick={() => {}} />'
,
code: '<u onClick={() => {}} />'
,
code: '<var onClick={() => {}} />'
,
code: '<video onClick={() => {}} />'
,
code: '<wbr onClick={() => {}} />'
,
code: '<xmp onClick={() => {}} />'
,
### HTML elements attributed with an interactive role ###
code: '<div role="button" onClick={() => {}} />'
,
code: '<div role="checkbox" onClick={() => {}} />'
,
code: '<div role="columnheader" onClick={() => {}} />'
,
code: '<div role="combobox" onClick={() => {}} />'
,
code: '<div role="grid" onClick={() => {}} />'
,
code: '<div role="gridcell" onClick={() => {}} />'
,
code: '<div role="link" onClick={() => {}} />'
,
code: '<div role="listbox" onClick={() => {}} />'
,
code: '<div role="menu" onClick={() => {}} />'
,
code: '<div role="menubar" onClick={() => {}} />'
,
code: '<div role="menuitem" onClick={() => {}} />'
,
code: '<div role="menuitemcheckbox" onClick={() => {}} />'
,
code: '<div role="menuitemradio" onClick={() => {}} />'
,
code: '<div role="option" onClick={() => {}} />'
,
code: '<div role="progressbar" onClick={() => {}} />'
,
code: '<div role="radio" onClick={() => {}} />'
,
code: '<div role="radiogroup" onClick={() => {}} />'
,
code: '<div role="row" onClick={() => {}} />'
,
code: '<div role="rowheader" onClick={() => {}} />'
,
code: '<div role="searchbox" onClick={() => {}} />'
,
code: '<div role="slider" onClick={() => {}} />'
,
code: '<div role="spinbutton" onClick={() => {}} />'
,
code: '<div role="switch" onClick={() => {}} />'
,
code: '<div role="tab" onClick={() => {}} />'
,
code: '<div role="textbox" onClick={() => {}} />'
,
code: '<div role="treeitem" onClick={() => {}} />'
,
### Presentation is a special case role that indicates intentional static semantics ###
code: '<div role="presentation" onClick={() => {}} />'
,
### HTML elements attributed with an abstract role ###
code: '<div role="command" onClick={() => {}} />'
,
code: '<div role="composite" onClick={() => {}} />'
,
code: '<div role="input" onClick={() => {}} />'
,
code: '<div role="landmark" onClick={() => {}} />'
,
code: '<div role="range" onClick={() => {}} />'
,
code: '<div role="roletype" onClick={() => {}} />'
,
code: '<div role="sectionhead" onClick={() => {}} />'
,
code: '<div role="select" onClick={() => {}} />'
,
code: '<div role="structure" onClick={() => {}} />'
,
code: '<div role="tablist" onClick={() => {}} />'
,
code: '<div role="toolbar" onClick={() => {}} />'
,
code: '<div role="tree" onClick={() => {}} />'
,
code: '<div role="treegrid" onClick={() => {}} />'
,
code: '<div role="widget" onClick={() => {}} />'
,
code: '<div role="window" onClick={() => {}} />'
,
# All the possible handlers
code: '<div role="article" onCopy={() => {}} />'
,
code: '<div role="article" onCut={() => {}} />'
,
code: '<div role="article" onPaste={() => {}} />'
,
code: '<div role="article" onCompositionEnd={() => {}} />'
,
code: '<div role="article" onCompositionStart={() => {}} />'
,
code: '<div role="article" onCompositionUpdate={() => {}} />'
,
code: '<div role="article" onChange={() => {}} />'
,
code: '<div role="article" onInput={() => {}} />'
,
code: '<div role="article" onSubmit={() => {}} />'
,
code: '<div role="article" onSelect={() => {}} />'
,
code: '<div role="article" onTouchCancel={() => {}} />'
,
code: '<div role="article" onTouchEnd={() => {}} />'
,
code: '<div role="article" onTouchMove={() => {}} />'
,
code: '<div role="article" onTouchStart={() => {}} />'
,
code: '<div role="article" onScroll={() => {}} />'
,
code: '<div role="article" onWheel={() => {}} />'
,
code: '<div role="article" onAbort={() => {}} />'
,
code: '<div role="article" onCanPlay={() => {}} />'
,
code: '<div role="article" onCanPlayThrough={() => {}} />'
,
code: '<div role="article" onDurationChange={() => {}} />'
,
code: '<div role="article" onEmptied={() => {}} />'
,
code: '<div role="article" onEncrypted={() => {}} />'
,
code: '<div role="article" onEnded={() => {}} />'
,
code: '<div role="article" onLoadedData={() => {}} />'
,
code: '<div role="article" onLoadedMetadata={() => {}} />'
,
code: '<div role="article" onLoadStart={() => {}} />'
,
code: '<div role="article" onPause={() => {}} />'
,
code: '<div role="article" onPlay={() => {}} />'
,
code: '<div role="article" onPlaying={() => {}} />'
,
code: '<div role="article" onProgress={() => {}} />'
,
code: '<div role="article" onRateChange={() => {}} />'
,
code: '<div role="article" onSeeked={() => {}} />'
,
code: '<div role="article" onSeeking={() => {}} />'
,
code: '<div role="article" onStalled={() => {}} />'
,
code: '<div role="article" onSuspend={() => {}} />'
,
code: '<div role="article" onTimeUpdate={() => {}} />'
,
code: '<div role="article" onVolumeChange={() => {}} />'
,
code: '<div role="article" onWaiting={() => {}} />'
,
code: '<div role="article" onAnimationStart={() => {}} />'
,
code: '<div role="article" onAnimationEnd={() => {}} />'
,
code: '<div role="article" onAnimationIteration={() => {}} />'
,
code: '<div role="article" onTransitionEnd={() => {}} />'
]
neverValid = [
### HTML elements with an inherent, non-interactive role ###
code: '<main onClick={() => undefined} />', errors: [expectedError]
,
code: '<article onClick={() => {}} />', errors: [expectedError]
,
# ,
# code: '<aside onClick={() => {}} />', errors: [expectedError]
code: '<blockquote onClick={() => {}} />', errors: [expectedError]
,
# ,
# code: '<body onClick={() => {}} />', errors: [expectedError]
code: '<br onClick={() => {}} />', errors: [expectedError]
,
code: '<caption onClick={() => {}} />', errors: [expectedError]
,
code: '<dd onClick={() => {}} />', errors: [expectedError]
,
code: '<details onClick={() => {}} />', errors: [expectedError]
,
code: '<dfn onClick={() => {}} />', errors: [expectedError]
,
code: '<dl onClick={() => {}} />', errors: [expectedError]
,
code: '<dir onClick={() => {}} />', errors: [expectedError]
,
code: '<dt onClick={() => {}} />', errors: [expectedError]
,
code: '<fieldset onClick={() => {}} />', errors: [expectedError]
,
code: '<figcaption onClick={() => {}} />', errors: [expectedError]
,
code: '<figure onClick={() => {}} />', errors: [expectedError]
,
code: '<footer onClick={() => {}} />', errors: [expectedError]
,
code: '<form onClick={() => {}} />', errors: [expectedError]
,
code: '<frame onClick={() => {}} />', errors: [expectedError]
,
code: '<h1 onClick={() => {}} />', errors: [expectedError]
,
code: '<h2 onClick={() => {}} />', errors: [expectedError]
,
code: '<h3 onClick={() => {}} />', errors: [expectedError]
,
code: '<h4 onClick={() => {}} />', errors: [expectedError]
,
code: '<h5 onClick={() => {}} />', errors: [expectedError]
,
code: '<h6 onClick={() => {}} />', errors: [expectedError]
,
code: '<hr onClick={() => {}} />', errors: [expectedError]
,
code: '<iframe onClick={() => {}} />', errors: [expectedError]
,
code: '<img onClick={() => {}} />', errors: [expectedError]
,
code: '<label onClick={() => {}} />', errors: [expectedError]
,
code: '<legend onClick={() => {}} />', errors: [expectedError]
,
code: '<li onClick={() => {}} />', errors: [expectedError]
,
code: '<mark onClick={() => {}} />', errors: [expectedError]
,
code: '<marquee onClick={() => {}} />', errors: [expectedError]
,
code: '<menu onClick={() => {}} />', errors: [expectedError]
,
code: '<meter onClick={() => {}} />', errors: [expectedError]
,
code: '<nav onClick={() => {}} />', errors: [expectedError]
,
code: '<ol onClick={() => {}} />', errors: [expectedError]
,
# ,
# code: '<optgroup onClick={() => {}} />', errors: [expectedError]
# ,
# code: '<output onClick={() => {}} />', errors: [expectedError]
code: '<p onClick={() => {}} />', errors: [expectedError]
,
code: '<pre onClick={() => {}} />', errors: [expectedError]
,
code: '<progress onClick={() => {}} />', errors: [expectedError]
,
code: '<ruby onClick={() => {}} />', errors: [expectedError]
,
code: '<section onClick={() => {}} aria-label="Aardvark" />'
errors: [expectedError]
,
code: '<section onClick={() => {}} aria-labelledby="js_1" />'
errors: [expectedError]
,
code: '<table onClick={() => {}} />', errors: [expectedError]
,
code: '<tbody onClick={() => {}} />', errors: [expectedError]
,
code: '<td onClick={() => {}} />', errors: [expectedError]
,
code: '<tfoot onClick={() => {}} />', errors: [expectedError]
,
code: '<thead onClick={() => {}} />', errors: [expectedError]
,
code: '<time onClick={() => {}} />', errors: [expectedError]
,
code: '<ol onClick={() => {}} />', errors: [expectedError]
,
code: '<ul onClick={() => {}} />', errors: [expectedError]
,
### HTML elements attributed with a non-interactive role ###
code: '<div role="alert" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="alertdialog" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="application" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="banner" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="cell" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="complementary" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="contentinfo" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="definition" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="dialog" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="directory" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="document" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="feed" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="figure" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="form" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="group" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="heading" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="img" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="list" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="listitem" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="log" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="main" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="marquee" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="math" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="navigation" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="note" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="region" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="rowgroup" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="search" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="separator" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="scrollbar" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="status" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="table" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="tabpanel" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="term" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="timer" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="tooltip" onClick={() => {}} />', errors: [expectedError]
,
# Handlers
code: '<div role="article" onKeyDown={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onKeyPress={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onKeyUp={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onLoad={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onError={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onMouseDown={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseUp={() => {}} />', errors: [expectedError]
]
recommendedOptions = configs.recommended.rules["jsx-a11y/#{ruleName}"][1] or {}
ruleTester.run "#{ruleName}:recommended", rule,
valid:
[
...alwaysValid
,
# All the possible handlers
code: '<div role="article" onCopy={() => {}} />'
,
code: '<div role="article" onCut={() => {}} />'
,
code: '<div role="article" onPaste={() => {}} />'
,
code: '<div role="article" onCompositionEnd={() => {}} />'
,
code: '<div role="article" onCompositionStart={() => {}} />'
,
code: '<div role="article" onCompositionUpdate={() => {}} />'
,
code: '<div role="article" onFocus={() => {}} />'
,
code: '<div role="article" onBlur={() => {}} />'
,
code: '<div role="article" onChange={() => {}} />'
,
code: '<div role="article" onInput={() => {}} />'
,
code: '<div role="article" onSubmit={() => {}} />'
,
code: '<div role="article" onContextMenu={() => {}} />'
,
code: '<div role="article" onDblClick={() => {}} />'
,
code: '<div role="article" onDoubleClick={() => {}} />'
,
code: '<div role="article" onDrag={() => {}} />'
,
code: '<div role="article" onDragEnd={() => {}} />'
,
code: '<div role="article" onDragEnter={() => {}} />'
,
code: '<div role="article" onDragExit={() => {}} />'
,
code: '<div role="article" onDragLeave={() => {}} />'
,
code: '<div role="article" onDragOver={() => {}} />'
,
code: '<div role="article" onDragStart={() => {}} />'
,
code: '<div role="article" onDrop={() => {}} />'
,
code: '<div role="article" onMouseEnter={() => {}} />'
,
code: '<div role="article" onMouseLeave={() => {}} />'
,
code: '<div role="article" onMouseMove={() => {}} />'
,
code: '<div role="article" onMouseOut={() => {}} />'
,
code: '<div role="article" onMouseOver={() => {}} />'
,
code: '<div role="article" onSelect={() => {}} />'
,
code: '<div role="article" onTouchCancel={() => {}} />'
,
code: '<div role="article" onTouchEnd={() => {}} />'
,
code: '<div role="article" onTouchMove={() => {}} />'
,
code: '<div role="article" onTouchStart={() => {}} />'
,
code: '<div role="article" onScroll={() => {}} />'
,
code: '<div role="article" onWheel={() => {}} />'
,
code: '<div role="article" onAbort={() => {}} />'
,
code: '<div role="article" onCanPlay={() => {}} />'
,
code: '<div role="article" onCanPlayThrough={() => {}} />'
,
code: '<div role="article" onDurationChange={() => {}} />'
,
code: '<div role="article" onEmptied={() => {}} />'
,
code: '<div role="article" onEncrypted={() => {}} />'
,
code: '<div role="article" onEnded={() => {}} />'
,
code: '<div role="article" onLoadedData={() => {}} />'
,
code: '<div role="article" onLoadedMetadata={() => {}} />'
,
code: '<div role="article" onLoadStart={() => {}} />'
,
code: '<div role="article" onPause={() => {}} />'
,
code: '<div role="article" onPlay={() => {}} />'
,
code: '<div role="article" onPlaying={() => {}} />'
,
code: '<div role="article" onProgress={() => {}} />'
,
code: '<div role="article" onRateChange={() => {}} />'
,
code: '<div role="article" onSeeked={() => {}} />'
,
code: '<div role="article" onSeeking={() => {}} />'
,
code: '<div role="article" onStalled={() => {}} />'
,
code: '<div role="article" onSuspend={() => {}} />'
,
code: '<div role="article" onTimeUpdate={() => {}} />'
,
code: '<div role="article" onVolumeChange={() => {}} />'
,
code: '<div role="article" onWaiting={() => {}} />'
,
code: '<div role="article" onAnimationStart={() => {}} />'
,
code: '<div role="article" onAnimationEnd={() => {}} />'
,
code: '<div role="article" onAnimationIteration={() => {}} />'
,
code: '<div role="article" onTransitionEnd={() => {}} />'
]
.map ruleOptionsMapperFactory recommendedOptions
.map parserOptionsMapper
invalid:
[...neverValid]
.map(ruleOptionsMapperFactory recommendedOptions)
.map parserOptionsMapper
strictOptions = configs.strict.rules["jsx-a11y/#{ruleName}"][1] or {}
ruleTester.run "#{ruleName}:strict", rule,
valid:
[...alwaysValid]
.map(ruleOptionsMapperFactory strictOptions)
.map(parserOptionsMapper)
invalid:
[
...neverValid
,
# All the possible handlers
code: '<div role="article" onFocus={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onBlur={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onContextMenu={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDblClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDoubleClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDrag={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onDragEnd={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragEnter={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragExit={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragLeave={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragOver={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragStart={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDrop={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onMouseEnter={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseLeave={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseMove={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseOut={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseOver={() => {}} />'
errors: [expectedError]
]
.map ruleOptionsMapperFactory strictOptions
.map parserOptionsMapper
| 138684 | ### eslint-env jest ###
###*
# @fileoverview Enforce non-interactive elements have no interactive handlers.
# @author <NAME>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{configs} = require 'eslint-plugin-jsx-a11y'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require(
'eslint-plugin-jsx-a11y/lib/rules/no-noninteractive-element-interactions'
)
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
errorMessage =
'Non-interactive elements should not be assigned mouse or keyboard event listeners.'
expectedError =
message: errorMessage
type: 'JSXOpeningElement'
ruleName = 'no-noninteractive-element-interactions'
alwaysValid = [
code: '<TestComponent onClick={doFoo} />'
,
code: '<Button onClick={doFoo} />'
,
### All flavors of input ###
code: '<input onClick={() => undefined} />'
,
code: '<input type="button" onClick={() => undefined} />'
,
code: '<input type="checkbox" onClick={() => undefined} />'
,
code: '<input type="color" onClick={() => undefined} />'
,
code: '<input type="date" onClick={() => undefined} />'
,
code: '<input type="datetime" onClick={() => undefined} />'
,
code: '<input type="datetime-local" onClick={() => undefined} />'
,
code: '<input type="email" onClick={() => undefined} />'
,
code: '<input type="file" onClick={() => undefined} />'
,
code: '<input type="image" onClick={() => undefined} />'
,
code: '<input type="month" onClick={() => undefined} />'
,
code: '<input type="number" onClick={() => undefined} />'
,
code: '<input type="password" onClick={() => undefined} />'
,
code: '<input type="radio" onClick={() => undefined} />'
,
code: '<input type="range" onClick={() => undefined} />'
,
code: '<input type="reset" onClick={() => undefined} />'
,
code: '<input type="search" onClick={() => undefined} />'
,
code: '<input type="submit" onClick={() => undefined} />'
,
code: '<input type="tel" onClick={() => undefined} />'
,
code: '<input type="text" onClick={() => undefined} />'
,
code: '<input type="time" onClick={() => undefined} />'
,
code: '<input type="url" onClick={() => undefined} />'
,
code: '<input type="week" onClick={() => undefined} />'
,
code: '<input type="hidden" onClick={() => undefined} />'
,
### End all flavors of input ###
code: '<a onClick={() => undefined} />'
,
code: '<a onClick={() => {}} />'
,
code: '<a tabIndex="0" onClick={() => undefined} />'
,
code: '<a onClick={() => undefined} href="http://x.y.z" />'
,
code: '<a onClick={() => undefined} href="http://x.y.z" tabIndex="0" />'
,
code: '<area onClick={() => {}} />'
,
code: '<button onClick={() => undefined} className="foo" />'
,
code: '<menuitem onClick={() => {}} />'
,
code: '<option onClick={() => undefined} className="foo" />'
,
code: '<select onClick={() => undefined} className="foo" />'
,
code: '<textarea onClick={() => undefined} className="foo" />'
,
code: '<tr onClick={() => {}} />'
,
### HTML elements with neither an interactive or non-interactive valence (static) ###
code: '<acronym onClick={() => {}} />'
,
code: '<address onClick={() => {}} />'
,
code: '<applet onClick={() => {}} />'
,
code: '<audio onClick={() => {}} />'
,
code: '<b onClick={() => {}} />'
,
code: '<base onClick={() => {}} />'
,
code: '<bdi onClick={() => {}} />'
,
code: '<bdo onClick={() => {}} />'
,
code: '<big onClick={() => {}} />'
,
code: '<blink onClick={() => {}} />'
,
code: '<body onLoad={() => {}} />'
,
code: '<canvas onClick={() => {}} />'
,
code: '<center onClick={() => {}} />'
,
code: '<cite onClick={() => {}} />'
,
code: '<code onClick={() => {}} />'
,
code: '<col onClick={() => {}} />'
,
code: '<colgroup onClick={() => {}} />'
,
code: '<content onClick={() => {}} />'
,
code: '<data onClick={() => {}} />'
,
code: '<datalist onClick={() => {}} />'
,
code: '<del onClick={() => {}} />'
,
code: '<div />'
,
code: '<div className="foo" />'
,
code: '<div className="foo" {...props} />'
,
code: '<div onClick={() => undefined} aria-hidden />'
,
code: '<div onClick={() => undefined} aria-hidden={true} />'
,
code: '<div onClick={() => undefined} />'
,
code: '<div onClick={() => undefined} role={undefined} />'
,
code: '<div onClick={() => undefined} {...props} />'
,
code: '<div onClick={null} />'
,
code: '<div onKeyUp={() => undefined} aria-hidden={false} />'
,
code: '<em onClick={() => {}} />'
,
code: '<embed onClick={() => {}} />'
,
code: '<font onClick={() => {}} />'
,
code: '<font onSubmit={() => {}} />'
,
code: '<frameset onClick={() => {}} />'
,
code: '<head onClick={() => {}} />'
,
code: '<header onClick={() => {}} />'
,
code: '<hgroup onClick={() => {}} />'
,
code: '<html onClick={() => {}} />'
,
code: '<i onClick={() => {}} />'
,
code: '<iframe onLoad={() => {}} />'
,
code: '''
<iframe
name="embeddedExternalPayment"
ref="embeddedExternalPayment"
style={iframeStyle}
onLoad={this.handleLoadIframe}
/>
'''
,
code: '<img {...props} onError={() => {}} />'
,
code: '<img onLoad={() => {}} />'
,
code: '<ins onClick={() => {}} />'
,
code: '<kbd onClick={() => {}} />'
,
code: '<keygen onClick={() => {}} />'
,
code: '<link onClick={() => {}} />'
,
code: '<main onClick={null} />'
,
code: '<map onClick={() => {}} />'
,
code: '<meta onClick={() => {}} />'
,
code: '<noembed onClick={() => {}} />'
,
code: '<noscript onClick={() => {}} />'
,
code: '<object onClick={() => {}} />'
,
code: '<param onClick={() => {}} />'
,
code: '<picture onClick={() => {}} />'
,
code: '<q onClick={() => {}} />'
,
code: '<rp onClick={() => {}} />'
,
code: '<rt onClick={() => {}} />'
,
code: '<rtc onClick={() => {}} />'
,
code: '<s onClick={() => {}} />'
,
code: '<samp onClick={() => {}} />'
,
code: '<script onClick={() => {}} />'
,
# TODO: can uncomment these tests once https://github.com/evcohen/eslint-plugin-jsx-a11y/commit/8e0d22 gets released
# ,
# code: '<section onClick={() => {}} />'
code: '<small onClick={() => {}} />'
,
code: '<source onClick={() => {}} />'
,
code: '<spacer onClick={() => {}} />'
,
code: '<span onClick={() => {}} />'
,
code: '<strike onClick={() => {}} />'
,
code: '<strong onClick={() => {}} />'
,
code: '<style onClick={() => {}} />'
,
code: '<sub onClick={() => {}} />'
,
code: '<summary onClick={() => {}} />'
,
code: '<sup onClick={() => {}} />'
,
code: '<th onClick={() => {}} />'
,
code: '<title onClick={() => {}} />'
,
code: '<track onClick={() => {}} />'
,
code: '<tt onClick={() => {}} />'
,
code: '<u onClick={() => {}} />'
,
code: '<var onClick={() => {}} />'
,
code: '<video onClick={() => {}} />'
,
code: '<wbr onClick={() => {}} />'
,
code: '<xmp onClick={() => {}} />'
,
### HTML elements attributed with an interactive role ###
code: '<div role="button" onClick={() => {}} />'
,
code: '<div role="checkbox" onClick={() => {}} />'
,
code: '<div role="columnheader" onClick={() => {}} />'
,
code: '<div role="combobox" onClick={() => {}} />'
,
code: '<div role="grid" onClick={() => {}} />'
,
code: '<div role="gridcell" onClick={() => {}} />'
,
code: '<div role="link" onClick={() => {}} />'
,
code: '<div role="listbox" onClick={() => {}} />'
,
code: '<div role="menu" onClick={() => {}} />'
,
code: '<div role="menubar" onClick={() => {}} />'
,
code: '<div role="menuitem" onClick={() => {}} />'
,
code: '<div role="menuitemcheckbox" onClick={() => {}} />'
,
code: '<div role="menuitemradio" onClick={() => {}} />'
,
code: '<div role="option" onClick={() => {}} />'
,
code: '<div role="progressbar" onClick={() => {}} />'
,
code: '<div role="radio" onClick={() => {}} />'
,
code: '<div role="radiogroup" onClick={() => {}} />'
,
code: '<div role="row" onClick={() => {}} />'
,
code: '<div role="rowheader" onClick={() => {}} />'
,
code: '<div role="searchbox" onClick={() => {}} />'
,
code: '<div role="slider" onClick={() => {}} />'
,
code: '<div role="spinbutton" onClick={() => {}} />'
,
code: '<div role="switch" onClick={() => {}} />'
,
code: '<div role="tab" onClick={() => {}} />'
,
code: '<div role="textbox" onClick={() => {}} />'
,
code: '<div role="treeitem" onClick={() => {}} />'
,
### Presentation is a special case role that indicates intentional static semantics ###
code: '<div role="presentation" onClick={() => {}} />'
,
### HTML elements attributed with an abstract role ###
code: '<div role="command" onClick={() => {}} />'
,
code: '<div role="composite" onClick={() => {}} />'
,
code: '<div role="input" onClick={() => {}} />'
,
code: '<div role="landmark" onClick={() => {}} />'
,
code: '<div role="range" onClick={() => {}} />'
,
code: '<div role="roletype" onClick={() => {}} />'
,
code: '<div role="sectionhead" onClick={() => {}} />'
,
code: '<div role="select" onClick={() => {}} />'
,
code: '<div role="structure" onClick={() => {}} />'
,
code: '<div role="tablist" onClick={() => {}} />'
,
code: '<div role="toolbar" onClick={() => {}} />'
,
code: '<div role="tree" onClick={() => {}} />'
,
code: '<div role="treegrid" onClick={() => {}} />'
,
code: '<div role="widget" onClick={() => {}} />'
,
code: '<div role="window" onClick={() => {}} />'
,
# All the possible handlers
code: '<div role="article" onCopy={() => {}} />'
,
code: '<div role="article" onCut={() => {}} />'
,
code: '<div role="article" onPaste={() => {}} />'
,
code: '<div role="article" onCompositionEnd={() => {}} />'
,
code: '<div role="article" onCompositionStart={() => {}} />'
,
code: '<div role="article" onCompositionUpdate={() => {}} />'
,
code: '<div role="article" onChange={() => {}} />'
,
code: '<div role="article" onInput={() => {}} />'
,
code: '<div role="article" onSubmit={() => {}} />'
,
code: '<div role="article" onSelect={() => {}} />'
,
code: '<div role="article" onTouchCancel={() => {}} />'
,
code: '<div role="article" onTouchEnd={() => {}} />'
,
code: '<div role="article" onTouchMove={() => {}} />'
,
code: '<div role="article" onTouchStart={() => {}} />'
,
code: '<div role="article" onScroll={() => {}} />'
,
code: '<div role="article" onWheel={() => {}} />'
,
code: '<div role="article" onAbort={() => {}} />'
,
code: '<div role="article" onCanPlay={() => {}} />'
,
code: '<div role="article" onCanPlayThrough={() => {}} />'
,
code: '<div role="article" onDurationChange={() => {}} />'
,
code: '<div role="article" onEmptied={() => {}} />'
,
code: '<div role="article" onEncrypted={() => {}} />'
,
code: '<div role="article" onEnded={() => {}} />'
,
code: '<div role="article" onLoadedData={() => {}} />'
,
code: '<div role="article" onLoadedMetadata={() => {}} />'
,
code: '<div role="article" onLoadStart={() => {}} />'
,
code: '<div role="article" onPause={() => {}} />'
,
code: '<div role="article" onPlay={() => {}} />'
,
code: '<div role="article" onPlaying={() => {}} />'
,
code: '<div role="article" onProgress={() => {}} />'
,
code: '<div role="article" onRateChange={() => {}} />'
,
code: '<div role="article" onSeeked={() => {}} />'
,
code: '<div role="article" onSeeking={() => {}} />'
,
code: '<div role="article" onStalled={() => {}} />'
,
code: '<div role="article" onSuspend={() => {}} />'
,
code: '<div role="article" onTimeUpdate={() => {}} />'
,
code: '<div role="article" onVolumeChange={() => {}} />'
,
code: '<div role="article" onWaiting={() => {}} />'
,
code: '<div role="article" onAnimationStart={() => {}} />'
,
code: '<div role="article" onAnimationEnd={() => {}} />'
,
code: '<div role="article" onAnimationIteration={() => {}} />'
,
code: '<div role="article" onTransitionEnd={() => {}} />'
]
neverValid = [
### HTML elements with an inherent, non-interactive role ###
code: '<main onClick={() => undefined} />', errors: [expectedError]
,
code: '<article onClick={() => {}} />', errors: [expectedError]
,
# ,
# code: '<aside onClick={() => {}} />', errors: [expectedError]
code: '<blockquote onClick={() => {}} />', errors: [expectedError]
,
# ,
# code: '<body onClick={() => {}} />', errors: [expectedError]
code: '<br onClick={() => {}} />', errors: [expectedError]
,
code: '<caption onClick={() => {}} />', errors: [expectedError]
,
code: '<dd onClick={() => {}} />', errors: [expectedError]
,
code: '<details onClick={() => {}} />', errors: [expectedError]
,
code: '<dfn onClick={() => {}} />', errors: [expectedError]
,
code: '<dl onClick={() => {}} />', errors: [expectedError]
,
code: '<dir onClick={() => {}} />', errors: [expectedError]
,
code: '<dt onClick={() => {}} />', errors: [expectedError]
,
code: '<fieldset onClick={() => {}} />', errors: [expectedError]
,
code: '<figcaption onClick={() => {}} />', errors: [expectedError]
,
code: '<figure onClick={() => {}} />', errors: [expectedError]
,
code: '<footer onClick={() => {}} />', errors: [expectedError]
,
code: '<form onClick={() => {}} />', errors: [expectedError]
,
code: '<frame onClick={() => {}} />', errors: [expectedError]
,
code: '<h1 onClick={() => {}} />', errors: [expectedError]
,
code: '<h2 onClick={() => {}} />', errors: [expectedError]
,
code: '<h3 onClick={() => {}} />', errors: [expectedError]
,
code: '<h4 onClick={() => {}} />', errors: [expectedError]
,
code: '<h5 onClick={() => {}} />', errors: [expectedError]
,
code: '<h6 onClick={() => {}} />', errors: [expectedError]
,
code: '<hr onClick={() => {}} />', errors: [expectedError]
,
code: '<iframe onClick={() => {}} />', errors: [expectedError]
,
code: '<img onClick={() => {}} />', errors: [expectedError]
,
code: '<label onClick={() => {}} />', errors: [expectedError]
,
code: '<legend onClick={() => {}} />', errors: [expectedError]
,
code: '<li onClick={() => {}} />', errors: [expectedError]
,
code: '<mark onClick={() => {}} />', errors: [expectedError]
,
code: '<marquee onClick={() => {}} />', errors: [expectedError]
,
code: '<menu onClick={() => {}} />', errors: [expectedError]
,
code: '<meter onClick={() => {}} />', errors: [expectedError]
,
code: '<nav onClick={() => {}} />', errors: [expectedError]
,
code: '<ol onClick={() => {}} />', errors: [expectedError]
,
# ,
# code: '<optgroup onClick={() => {}} />', errors: [expectedError]
# ,
# code: '<output onClick={() => {}} />', errors: [expectedError]
code: '<p onClick={() => {}} />', errors: [expectedError]
,
code: '<pre onClick={() => {}} />', errors: [expectedError]
,
code: '<progress onClick={() => {}} />', errors: [expectedError]
,
code: '<ruby onClick={() => {}} />', errors: [expectedError]
,
code: '<section onClick={() => {}} aria-label="Aardvark" />'
errors: [expectedError]
,
code: '<section onClick={() => {}} aria-labelledby="js_1" />'
errors: [expectedError]
,
code: '<table onClick={() => {}} />', errors: [expectedError]
,
code: '<tbody onClick={() => {}} />', errors: [expectedError]
,
code: '<td onClick={() => {}} />', errors: [expectedError]
,
code: '<tfoot onClick={() => {}} />', errors: [expectedError]
,
code: '<thead onClick={() => {}} />', errors: [expectedError]
,
code: '<time onClick={() => {}} />', errors: [expectedError]
,
code: '<ol onClick={() => {}} />', errors: [expectedError]
,
code: '<ul onClick={() => {}} />', errors: [expectedError]
,
### HTML elements attributed with a non-interactive role ###
code: '<div role="alert" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="alertdialog" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="application" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="banner" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="cell" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="complementary" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="contentinfo" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="definition" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="dialog" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="directory" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="document" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="feed" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="figure" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="form" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="group" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="heading" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="img" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="list" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="listitem" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="log" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="main" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="marquee" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="math" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="navigation" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="note" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="region" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="rowgroup" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="search" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="separator" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="scrollbar" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="status" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="table" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="tabpanel" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="term" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="timer" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="tooltip" onClick={() => {}} />', errors: [expectedError]
,
# Handlers
code: '<div role="article" onKeyDown={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onKeyPress={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onKeyUp={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onLoad={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onError={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onMouseDown={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseUp={() => {}} />', errors: [expectedError]
]
recommendedOptions = configs.recommended.rules["jsx-a11y/#{ruleName}"][1] or {}
ruleTester.run "#{ruleName}:recommended", rule,
valid:
[
...alwaysValid
,
# All the possible handlers
code: '<div role="article" onCopy={() => {}} />'
,
code: '<div role="article" onCut={() => {}} />'
,
code: '<div role="article" onPaste={() => {}} />'
,
code: '<div role="article" onCompositionEnd={() => {}} />'
,
code: '<div role="article" onCompositionStart={() => {}} />'
,
code: '<div role="article" onCompositionUpdate={() => {}} />'
,
code: '<div role="article" onFocus={() => {}} />'
,
code: '<div role="article" onBlur={() => {}} />'
,
code: '<div role="article" onChange={() => {}} />'
,
code: '<div role="article" onInput={() => {}} />'
,
code: '<div role="article" onSubmit={() => {}} />'
,
code: '<div role="article" onContextMenu={() => {}} />'
,
code: '<div role="article" onDblClick={() => {}} />'
,
code: '<div role="article" onDoubleClick={() => {}} />'
,
code: '<div role="article" onDrag={() => {}} />'
,
code: '<div role="article" onDragEnd={() => {}} />'
,
code: '<div role="article" onDragEnter={() => {}} />'
,
code: '<div role="article" onDragExit={() => {}} />'
,
code: '<div role="article" onDragLeave={() => {}} />'
,
code: '<div role="article" onDragOver={() => {}} />'
,
code: '<div role="article" onDragStart={() => {}} />'
,
code: '<div role="article" onDrop={() => {}} />'
,
code: '<div role="article" onMouseEnter={() => {}} />'
,
code: '<div role="article" onMouseLeave={() => {}} />'
,
code: '<div role="article" onMouseMove={() => {}} />'
,
code: '<div role="article" onMouseOut={() => {}} />'
,
code: '<div role="article" onMouseOver={() => {}} />'
,
code: '<div role="article" onSelect={() => {}} />'
,
code: '<div role="article" onTouchCancel={() => {}} />'
,
code: '<div role="article" onTouchEnd={() => {}} />'
,
code: '<div role="article" onTouchMove={() => {}} />'
,
code: '<div role="article" onTouchStart={() => {}} />'
,
code: '<div role="article" onScroll={() => {}} />'
,
code: '<div role="article" onWheel={() => {}} />'
,
code: '<div role="article" onAbort={() => {}} />'
,
code: '<div role="article" onCanPlay={() => {}} />'
,
code: '<div role="article" onCanPlayThrough={() => {}} />'
,
code: '<div role="article" onDurationChange={() => {}} />'
,
code: '<div role="article" onEmptied={() => {}} />'
,
code: '<div role="article" onEncrypted={() => {}} />'
,
code: '<div role="article" onEnded={() => {}} />'
,
code: '<div role="article" onLoadedData={() => {}} />'
,
code: '<div role="article" onLoadedMetadata={() => {}} />'
,
code: '<div role="article" onLoadStart={() => {}} />'
,
code: '<div role="article" onPause={() => {}} />'
,
code: '<div role="article" onPlay={() => {}} />'
,
code: '<div role="article" onPlaying={() => {}} />'
,
code: '<div role="article" onProgress={() => {}} />'
,
code: '<div role="article" onRateChange={() => {}} />'
,
code: '<div role="article" onSeeked={() => {}} />'
,
code: '<div role="article" onSeeking={() => {}} />'
,
code: '<div role="article" onStalled={() => {}} />'
,
code: '<div role="article" onSuspend={() => {}} />'
,
code: '<div role="article" onTimeUpdate={() => {}} />'
,
code: '<div role="article" onVolumeChange={() => {}} />'
,
code: '<div role="article" onWaiting={() => {}} />'
,
code: '<div role="article" onAnimationStart={() => {}} />'
,
code: '<div role="article" onAnimationEnd={() => {}} />'
,
code: '<div role="article" onAnimationIteration={() => {}} />'
,
code: '<div role="article" onTransitionEnd={() => {}} />'
]
.map ruleOptionsMapperFactory recommendedOptions
.map parserOptionsMapper
invalid:
[...neverValid]
.map(ruleOptionsMapperFactory recommendedOptions)
.map parserOptionsMapper
strictOptions = configs.strict.rules["jsx-a11y/#{ruleName}"][1] or {}
ruleTester.run "#{ruleName}:strict", rule,
valid:
[...alwaysValid]
.map(ruleOptionsMapperFactory strictOptions)
.map(parserOptionsMapper)
invalid:
[
...neverValid
,
# All the possible handlers
code: '<div role="article" onFocus={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onBlur={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onContextMenu={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDblClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDoubleClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDrag={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onDragEnd={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragEnter={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragExit={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragLeave={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragOver={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragStart={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDrop={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onMouseEnter={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseLeave={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseMove={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseOut={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseOver={() => {}} />'
errors: [expectedError]
]
.map ruleOptionsMapperFactory strictOptions
.map parserOptionsMapper
| true | ### eslint-env jest ###
###*
# @fileoverview Enforce non-interactive elements have no interactive handlers.
# @author PI:NAME:<NAME>END_PI
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{configs} = require 'eslint-plugin-jsx-a11y'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require(
'eslint-plugin-jsx-a11y/lib/rules/no-noninteractive-element-interactions'
)
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
errorMessage =
'Non-interactive elements should not be assigned mouse or keyboard event listeners.'
expectedError =
message: errorMessage
type: 'JSXOpeningElement'
ruleName = 'no-noninteractive-element-interactions'
alwaysValid = [
code: '<TestComponent onClick={doFoo} />'
,
code: '<Button onClick={doFoo} />'
,
### All flavors of input ###
code: '<input onClick={() => undefined} />'
,
code: '<input type="button" onClick={() => undefined} />'
,
code: '<input type="checkbox" onClick={() => undefined} />'
,
code: '<input type="color" onClick={() => undefined} />'
,
code: '<input type="date" onClick={() => undefined} />'
,
code: '<input type="datetime" onClick={() => undefined} />'
,
code: '<input type="datetime-local" onClick={() => undefined} />'
,
code: '<input type="email" onClick={() => undefined} />'
,
code: '<input type="file" onClick={() => undefined} />'
,
code: '<input type="image" onClick={() => undefined} />'
,
code: '<input type="month" onClick={() => undefined} />'
,
code: '<input type="number" onClick={() => undefined} />'
,
code: '<input type="password" onClick={() => undefined} />'
,
code: '<input type="radio" onClick={() => undefined} />'
,
code: '<input type="range" onClick={() => undefined} />'
,
code: '<input type="reset" onClick={() => undefined} />'
,
code: '<input type="search" onClick={() => undefined} />'
,
code: '<input type="submit" onClick={() => undefined} />'
,
code: '<input type="tel" onClick={() => undefined} />'
,
code: '<input type="text" onClick={() => undefined} />'
,
code: '<input type="time" onClick={() => undefined} />'
,
code: '<input type="url" onClick={() => undefined} />'
,
code: '<input type="week" onClick={() => undefined} />'
,
code: '<input type="hidden" onClick={() => undefined} />'
,
### End all flavors of input ###
code: '<a onClick={() => undefined} />'
,
code: '<a onClick={() => {}} />'
,
code: '<a tabIndex="0" onClick={() => undefined} />'
,
code: '<a onClick={() => undefined} href="http://x.y.z" />'
,
code: '<a onClick={() => undefined} href="http://x.y.z" tabIndex="0" />'
,
code: '<area onClick={() => {}} />'
,
code: '<button onClick={() => undefined} className="foo" />'
,
code: '<menuitem onClick={() => {}} />'
,
code: '<option onClick={() => undefined} className="foo" />'
,
code: '<select onClick={() => undefined} className="foo" />'
,
code: '<textarea onClick={() => undefined} className="foo" />'
,
code: '<tr onClick={() => {}} />'
,
### HTML elements with neither an interactive or non-interactive valence (static) ###
code: '<acronym onClick={() => {}} />'
,
code: '<address onClick={() => {}} />'
,
code: '<applet onClick={() => {}} />'
,
code: '<audio onClick={() => {}} />'
,
code: '<b onClick={() => {}} />'
,
code: '<base onClick={() => {}} />'
,
code: '<bdi onClick={() => {}} />'
,
code: '<bdo onClick={() => {}} />'
,
code: '<big onClick={() => {}} />'
,
code: '<blink onClick={() => {}} />'
,
code: '<body onLoad={() => {}} />'
,
code: '<canvas onClick={() => {}} />'
,
code: '<center onClick={() => {}} />'
,
code: '<cite onClick={() => {}} />'
,
code: '<code onClick={() => {}} />'
,
code: '<col onClick={() => {}} />'
,
code: '<colgroup onClick={() => {}} />'
,
code: '<content onClick={() => {}} />'
,
code: '<data onClick={() => {}} />'
,
code: '<datalist onClick={() => {}} />'
,
code: '<del onClick={() => {}} />'
,
code: '<div />'
,
code: '<div className="foo" />'
,
code: '<div className="foo" {...props} />'
,
code: '<div onClick={() => undefined} aria-hidden />'
,
code: '<div onClick={() => undefined} aria-hidden={true} />'
,
code: '<div onClick={() => undefined} />'
,
code: '<div onClick={() => undefined} role={undefined} />'
,
code: '<div onClick={() => undefined} {...props} />'
,
code: '<div onClick={null} />'
,
code: '<div onKeyUp={() => undefined} aria-hidden={false} />'
,
code: '<em onClick={() => {}} />'
,
code: '<embed onClick={() => {}} />'
,
code: '<font onClick={() => {}} />'
,
code: '<font onSubmit={() => {}} />'
,
code: '<frameset onClick={() => {}} />'
,
code: '<head onClick={() => {}} />'
,
code: '<header onClick={() => {}} />'
,
code: '<hgroup onClick={() => {}} />'
,
code: '<html onClick={() => {}} />'
,
code: '<i onClick={() => {}} />'
,
code: '<iframe onLoad={() => {}} />'
,
code: '''
<iframe
name="embeddedExternalPayment"
ref="embeddedExternalPayment"
style={iframeStyle}
onLoad={this.handleLoadIframe}
/>
'''
,
code: '<img {...props} onError={() => {}} />'
,
code: '<img onLoad={() => {}} />'
,
code: '<ins onClick={() => {}} />'
,
code: '<kbd onClick={() => {}} />'
,
code: '<keygen onClick={() => {}} />'
,
code: '<link onClick={() => {}} />'
,
code: '<main onClick={null} />'
,
code: '<map onClick={() => {}} />'
,
code: '<meta onClick={() => {}} />'
,
code: '<noembed onClick={() => {}} />'
,
code: '<noscript onClick={() => {}} />'
,
code: '<object onClick={() => {}} />'
,
code: '<param onClick={() => {}} />'
,
code: '<picture onClick={() => {}} />'
,
code: '<q onClick={() => {}} />'
,
code: '<rp onClick={() => {}} />'
,
code: '<rt onClick={() => {}} />'
,
code: '<rtc onClick={() => {}} />'
,
code: '<s onClick={() => {}} />'
,
code: '<samp onClick={() => {}} />'
,
code: '<script onClick={() => {}} />'
,
# TODO: can uncomment these tests once https://github.com/evcohen/eslint-plugin-jsx-a11y/commit/8e0d22 gets released
# ,
# code: '<section onClick={() => {}} />'
code: '<small onClick={() => {}} />'
,
code: '<source onClick={() => {}} />'
,
code: '<spacer onClick={() => {}} />'
,
code: '<span onClick={() => {}} />'
,
code: '<strike onClick={() => {}} />'
,
code: '<strong onClick={() => {}} />'
,
code: '<style onClick={() => {}} />'
,
code: '<sub onClick={() => {}} />'
,
code: '<summary onClick={() => {}} />'
,
code: '<sup onClick={() => {}} />'
,
code: '<th onClick={() => {}} />'
,
code: '<title onClick={() => {}} />'
,
code: '<track onClick={() => {}} />'
,
code: '<tt onClick={() => {}} />'
,
code: '<u onClick={() => {}} />'
,
code: '<var onClick={() => {}} />'
,
code: '<video onClick={() => {}} />'
,
code: '<wbr onClick={() => {}} />'
,
code: '<xmp onClick={() => {}} />'
,
### HTML elements attributed with an interactive role ###
code: '<div role="button" onClick={() => {}} />'
,
code: '<div role="checkbox" onClick={() => {}} />'
,
code: '<div role="columnheader" onClick={() => {}} />'
,
code: '<div role="combobox" onClick={() => {}} />'
,
code: '<div role="grid" onClick={() => {}} />'
,
code: '<div role="gridcell" onClick={() => {}} />'
,
code: '<div role="link" onClick={() => {}} />'
,
code: '<div role="listbox" onClick={() => {}} />'
,
code: '<div role="menu" onClick={() => {}} />'
,
code: '<div role="menubar" onClick={() => {}} />'
,
code: '<div role="menuitem" onClick={() => {}} />'
,
code: '<div role="menuitemcheckbox" onClick={() => {}} />'
,
code: '<div role="menuitemradio" onClick={() => {}} />'
,
code: '<div role="option" onClick={() => {}} />'
,
code: '<div role="progressbar" onClick={() => {}} />'
,
code: '<div role="radio" onClick={() => {}} />'
,
code: '<div role="radiogroup" onClick={() => {}} />'
,
code: '<div role="row" onClick={() => {}} />'
,
code: '<div role="rowheader" onClick={() => {}} />'
,
code: '<div role="searchbox" onClick={() => {}} />'
,
code: '<div role="slider" onClick={() => {}} />'
,
code: '<div role="spinbutton" onClick={() => {}} />'
,
code: '<div role="switch" onClick={() => {}} />'
,
code: '<div role="tab" onClick={() => {}} />'
,
code: '<div role="textbox" onClick={() => {}} />'
,
code: '<div role="treeitem" onClick={() => {}} />'
,
### Presentation is a special case role that indicates intentional static semantics ###
code: '<div role="presentation" onClick={() => {}} />'
,
### HTML elements attributed with an abstract role ###
code: '<div role="command" onClick={() => {}} />'
,
code: '<div role="composite" onClick={() => {}} />'
,
code: '<div role="input" onClick={() => {}} />'
,
code: '<div role="landmark" onClick={() => {}} />'
,
code: '<div role="range" onClick={() => {}} />'
,
code: '<div role="roletype" onClick={() => {}} />'
,
code: '<div role="sectionhead" onClick={() => {}} />'
,
code: '<div role="select" onClick={() => {}} />'
,
code: '<div role="structure" onClick={() => {}} />'
,
code: '<div role="tablist" onClick={() => {}} />'
,
code: '<div role="toolbar" onClick={() => {}} />'
,
code: '<div role="tree" onClick={() => {}} />'
,
code: '<div role="treegrid" onClick={() => {}} />'
,
code: '<div role="widget" onClick={() => {}} />'
,
code: '<div role="window" onClick={() => {}} />'
,
# All the possible handlers
code: '<div role="article" onCopy={() => {}} />'
,
code: '<div role="article" onCut={() => {}} />'
,
code: '<div role="article" onPaste={() => {}} />'
,
code: '<div role="article" onCompositionEnd={() => {}} />'
,
code: '<div role="article" onCompositionStart={() => {}} />'
,
code: '<div role="article" onCompositionUpdate={() => {}} />'
,
code: '<div role="article" onChange={() => {}} />'
,
code: '<div role="article" onInput={() => {}} />'
,
code: '<div role="article" onSubmit={() => {}} />'
,
code: '<div role="article" onSelect={() => {}} />'
,
code: '<div role="article" onTouchCancel={() => {}} />'
,
code: '<div role="article" onTouchEnd={() => {}} />'
,
code: '<div role="article" onTouchMove={() => {}} />'
,
code: '<div role="article" onTouchStart={() => {}} />'
,
code: '<div role="article" onScroll={() => {}} />'
,
code: '<div role="article" onWheel={() => {}} />'
,
code: '<div role="article" onAbort={() => {}} />'
,
code: '<div role="article" onCanPlay={() => {}} />'
,
code: '<div role="article" onCanPlayThrough={() => {}} />'
,
code: '<div role="article" onDurationChange={() => {}} />'
,
code: '<div role="article" onEmptied={() => {}} />'
,
code: '<div role="article" onEncrypted={() => {}} />'
,
code: '<div role="article" onEnded={() => {}} />'
,
code: '<div role="article" onLoadedData={() => {}} />'
,
code: '<div role="article" onLoadedMetadata={() => {}} />'
,
code: '<div role="article" onLoadStart={() => {}} />'
,
code: '<div role="article" onPause={() => {}} />'
,
code: '<div role="article" onPlay={() => {}} />'
,
code: '<div role="article" onPlaying={() => {}} />'
,
code: '<div role="article" onProgress={() => {}} />'
,
code: '<div role="article" onRateChange={() => {}} />'
,
code: '<div role="article" onSeeked={() => {}} />'
,
code: '<div role="article" onSeeking={() => {}} />'
,
code: '<div role="article" onStalled={() => {}} />'
,
code: '<div role="article" onSuspend={() => {}} />'
,
code: '<div role="article" onTimeUpdate={() => {}} />'
,
code: '<div role="article" onVolumeChange={() => {}} />'
,
code: '<div role="article" onWaiting={() => {}} />'
,
code: '<div role="article" onAnimationStart={() => {}} />'
,
code: '<div role="article" onAnimationEnd={() => {}} />'
,
code: '<div role="article" onAnimationIteration={() => {}} />'
,
code: '<div role="article" onTransitionEnd={() => {}} />'
]
neverValid = [
### HTML elements with an inherent, non-interactive role ###
code: '<main onClick={() => undefined} />', errors: [expectedError]
,
code: '<article onClick={() => {}} />', errors: [expectedError]
,
# ,
# code: '<aside onClick={() => {}} />', errors: [expectedError]
code: '<blockquote onClick={() => {}} />', errors: [expectedError]
,
# ,
# code: '<body onClick={() => {}} />', errors: [expectedError]
code: '<br onClick={() => {}} />', errors: [expectedError]
,
code: '<caption onClick={() => {}} />', errors: [expectedError]
,
code: '<dd onClick={() => {}} />', errors: [expectedError]
,
code: '<details onClick={() => {}} />', errors: [expectedError]
,
code: '<dfn onClick={() => {}} />', errors: [expectedError]
,
code: '<dl onClick={() => {}} />', errors: [expectedError]
,
code: '<dir onClick={() => {}} />', errors: [expectedError]
,
code: '<dt onClick={() => {}} />', errors: [expectedError]
,
code: '<fieldset onClick={() => {}} />', errors: [expectedError]
,
code: '<figcaption onClick={() => {}} />', errors: [expectedError]
,
code: '<figure onClick={() => {}} />', errors: [expectedError]
,
code: '<footer onClick={() => {}} />', errors: [expectedError]
,
code: '<form onClick={() => {}} />', errors: [expectedError]
,
code: '<frame onClick={() => {}} />', errors: [expectedError]
,
code: '<h1 onClick={() => {}} />', errors: [expectedError]
,
code: '<h2 onClick={() => {}} />', errors: [expectedError]
,
code: '<h3 onClick={() => {}} />', errors: [expectedError]
,
code: '<h4 onClick={() => {}} />', errors: [expectedError]
,
code: '<h5 onClick={() => {}} />', errors: [expectedError]
,
code: '<h6 onClick={() => {}} />', errors: [expectedError]
,
code: '<hr onClick={() => {}} />', errors: [expectedError]
,
code: '<iframe onClick={() => {}} />', errors: [expectedError]
,
code: '<img onClick={() => {}} />', errors: [expectedError]
,
code: '<label onClick={() => {}} />', errors: [expectedError]
,
code: '<legend onClick={() => {}} />', errors: [expectedError]
,
code: '<li onClick={() => {}} />', errors: [expectedError]
,
code: '<mark onClick={() => {}} />', errors: [expectedError]
,
code: '<marquee onClick={() => {}} />', errors: [expectedError]
,
code: '<menu onClick={() => {}} />', errors: [expectedError]
,
code: '<meter onClick={() => {}} />', errors: [expectedError]
,
code: '<nav onClick={() => {}} />', errors: [expectedError]
,
code: '<ol onClick={() => {}} />', errors: [expectedError]
,
# ,
# code: '<optgroup onClick={() => {}} />', errors: [expectedError]
# ,
# code: '<output onClick={() => {}} />', errors: [expectedError]
code: '<p onClick={() => {}} />', errors: [expectedError]
,
code: '<pre onClick={() => {}} />', errors: [expectedError]
,
code: '<progress onClick={() => {}} />', errors: [expectedError]
,
code: '<ruby onClick={() => {}} />', errors: [expectedError]
,
code: '<section onClick={() => {}} aria-label="Aardvark" />'
errors: [expectedError]
,
code: '<section onClick={() => {}} aria-labelledby="js_1" />'
errors: [expectedError]
,
code: '<table onClick={() => {}} />', errors: [expectedError]
,
code: '<tbody onClick={() => {}} />', errors: [expectedError]
,
code: '<td onClick={() => {}} />', errors: [expectedError]
,
code: '<tfoot onClick={() => {}} />', errors: [expectedError]
,
code: '<thead onClick={() => {}} />', errors: [expectedError]
,
code: '<time onClick={() => {}} />', errors: [expectedError]
,
code: '<ol onClick={() => {}} />', errors: [expectedError]
,
code: '<ul onClick={() => {}} />', errors: [expectedError]
,
### HTML elements attributed with a non-interactive role ###
code: '<div role="alert" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="alertdialog" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="application" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="banner" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="cell" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="complementary" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="contentinfo" onClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="definition" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="dialog" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="directory" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="document" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="feed" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="figure" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="form" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="group" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="heading" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="img" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="list" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="listitem" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="log" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="main" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="marquee" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="math" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="navigation" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="note" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="region" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="rowgroup" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="search" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="separator" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="scrollbar" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="status" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="table" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="tabpanel" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="term" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="timer" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="tooltip" onClick={() => {}} />', errors: [expectedError]
,
# Handlers
code: '<div role="article" onKeyDown={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onKeyPress={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onKeyUp={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onClick={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onLoad={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onError={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onMouseDown={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseUp={() => {}} />', errors: [expectedError]
]
recommendedOptions = configs.recommended.rules["jsx-a11y/#{ruleName}"][1] or {}
ruleTester.run "#{ruleName}:recommended", rule,
valid:
[
...alwaysValid
,
# All the possible handlers
code: '<div role="article" onCopy={() => {}} />'
,
code: '<div role="article" onCut={() => {}} />'
,
code: '<div role="article" onPaste={() => {}} />'
,
code: '<div role="article" onCompositionEnd={() => {}} />'
,
code: '<div role="article" onCompositionStart={() => {}} />'
,
code: '<div role="article" onCompositionUpdate={() => {}} />'
,
code: '<div role="article" onFocus={() => {}} />'
,
code: '<div role="article" onBlur={() => {}} />'
,
code: '<div role="article" onChange={() => {}} />'
,
code: '<div role="article" onInput={() => {}} />'
,
code: '<div role="article" onSubmit={() => {}} />'
,
code: '<div role="article" onContextMenu={() => {}} />'
,
code: '<div role="article" onDblClick={() => {}} />'
,
code: '<div role="article" onDoubleClick={() => {}} />'
,
code: '<div role="article" onDrag={() => {}} />'
,
code: '<div role="article" onDragEnd={() => {}} />'
,
code: '<div role="article" onDragEnter={() => {}} />'
,
code: '<div role="article" onDragExit={() => {}} />'
,
code: '<div role="article" onDragLeave={() => {}} />'
,
code: '<div role="article" onDragOver={() => {}} />'
,
code: '<div role="article" onDragStart={() => {}} />'
,
code: '<div role="article" onDrop={() => {}} />'
,
code: '<div role="article" onMouseEnter={() => {}} />'
,
code: '<div role="article" onMouseLeave={() => {}} />'
,
code: '<div role="article" onMouseMove={() => {}} />'
,
code: '<div role="article" onMouseOut={() => {}} />'
,
code: '<div role="article" onMouseOver={() => {}} />'
,
code: '<div role="article" onSelect={() => {}} />'
,
code: '<div role="article" onTouchCancel={() => {}} />'
,
code: '<div role="article" onTouchEnd={() => {}} />'
,
code: '<div role="article" onTouchMove={() => {}} />'
,
code: '<div role="article" onTouchStart={() => {}} />'
,
code: '<div role="article" onScroll={() => {}} />'
,
code: '<div role="article" onWheel={() => {}} />'
,
code: '<div role="article" onAbort={() => {}} />'
,
code: '<div role="article" onCanPlay={() => {}} />'
,
code: '<div role="article" onCanPlayThrough={() => {}} />'
,
code: '<div role="article" onDurationChange={() => {}} />'
,
code: '<div role="article" onEmptied={() => {}} />'
,
code: '<div role="article" onEncrypted={() => {}} />'
,
code: '<div role="article" onEnded={() => {}} />'
,
code: '<div role="article" onLoadedData={() => {}} />'
,
code: '<div role="article" onLoadedMetadata={() => {}} />'
,
code: '<div role="article" onLoadStart={() => {}} />'
,
code: '<div role="article" onPause={() => {}} />'
,
code: '<div role="article" onPlay={() => {}} />'
,
code: '<div role="article" onPlaying={() => {}} />'
,
code: '<div role="article" onProgress={() => {}} />'
,
code: '<div role="article" onRateChange={() => {}} />'
,
code: '<div role="article" onSeeked={() => {}} />'
,
code: '<div role="article" onSeeking={() => {}} />'
,
code: '<div role="article" onStalled={() => {}} />'
,
code: '<div role="article" onSuspend={() => {}} />'
,
code: '<div role="article" onTimeUpdate={() => {}} />'
,
code: '<div role="article" onVolumeChange={() => {}} />'
,
code: '<div role="article" onWaiting={() => {}} />'
,
code: '<div role="article" onAnimationStart={() => {}} />'
,
code: '<div role="article" onAnimationEnd={() => {}} />'
,
code: '<div role="article" onAnimationIteration={() => {}} />'
,
code: '<div role="article" onTransitionEnd={() => {}} />'
]
.map ruleOptionsMapperFactory recommendedOptions
.map parserOptionsMapper
invalid:
[...neverValid]
.map(ruleOptionsMapperFactory recommendedOptions)
.map parserOptionsMapper
strictOptions = configs.strict.rules["jsx-a11y/#{ruleName}"][1] or {}
ruleTester.run "#{ruleName}:strict", rule,
valid:
[...alwaysValid]
.map(ruleOptionsMapperFactory strictOptions)
.map(parserOptionsMapper)
invalid:
[
...neverValid
,
# All the possible handlers
code: '<div role="article" onFocus={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onBlur={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onContextMenu={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDblClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDoubleClick={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDrag={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onDragEnd={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragEnter={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragExit={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragLeave={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragOver={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDragStart={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onDrop={() => {}} />', errors: [expectedError]
,
code: '<div role="article" onMouseEnter={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseLeave={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseMove={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseOut={() => {}} />'
errors: [expectedError]
,
code: '<div role="article" onMouseOver={() => {}} />'
errors: [expectedError]
]
.map ruleOptionsMapperFactory strictOptions
.map parserOptionsMapper
|
[
{
"context": "come'\n @html.should.containEql 'PARTICIPANTS: Noah Horowitz, Executive Director'\n @html.should.containEq",
"end": 1609,
"score": 0.9998775720596313,
"start": 1596,
"tag": "NAME",
"value": "Noah Horowitz"
},
{
"context": "71500/20140308T173000&details=PAR... | src/desktop/apps/fair_info/test/templates/events.test.coffee | jo-rs/force | 0 | $ = require 'cheerio'
_ = require 'underscore'
{ fabricate } = require '@artsy/antigravity'
Profile = require '../../../../models/profile'
Fair = require '../../../../models/fair'
FairEvent = require '../../../../models/fair_event'
FairEvents = require '../../../../collections/fair_events'
template = require('jade').compileFile(require.resolve '../../templates/events.jade')
InfoMenu = require '../../../../components/info_menu/index.coffee'
data = _.extend {}, asset: (->), sd: {CURRENT_PATH: '/info/events'}, markdown: (->)
render = (moreData) ->
template _.extend {}, data, moreData
describe 'Events templates', ->
before ->
@profile = new Profile fabricate 'profile'
@fair = new Fair fabricate 'fair'
@infoMenu = new InfoMenu fair: @fair
@infoMenu.infoMenu = {
events: true,
programming: false,
artsyAtTheFair: false,
aboutTheFair: false
}
@fairEvent = new FairEvent fabricate('fair_event'), { fairId: 'armory-show-2013' }
@fairEvent.set venue_address: '711 12th Ave, New York, NY 10019'
@fairEvents = new FairEvents [@fairEvent], { fairId: @fair.id }
describe 'fair with events', ->
beforeEach ->
@html = render({ profile: @profile, fair: @fair, fairEvents: @fairEvents, sortedEvents: @fairEvents.sortedEvents(), infoMenu: @infoMenu.infoMenu })
it 'should render event date and time', ->
@html.should.containEql 'Saturday, March 8'
@html.should.containEql '5:15-5:30PM'
it 'should render event details', ->
@html.should.containEql 'Welcome'
@html.should.containEql 'PARTICIPANTS: Noah Horowitz, Executive Director'
@html.should.containEql 'The New York Times Style Magazine Media Lounge on Pier 94'
it 'should display map icon', ->
@html.should.containEql '<i class="icon-circle-chevron"></i><span>Map</span>'
it 'should not display map icon', ->
@fairEvent.set venue_address: null
@fairEvents = new FairEvents [@fairEvent], { fairId: 'armory-show-2013' }
clientWithoutAdddress = render({ profile: @profile, fair: @fair, fairEvents: @fairEvents, sortedEvents: @fairEvents.sortedEvents(), infoMenu: @infoMenu.infoMenu })
clientWithoutAdddress.should.not.containEql '<i class="icon-circle-chevron"></i><span>Map</span>'
it 'outlook event url should be present', ->
@html.should.containEql "outlook"
it 'google event url should be present', ->
@html.should.containEql "https://www.google.com/calendar/render?action=TEMPLATE&text=Welcome&dates=20140308T171500/20140308T173000&details=PARTICIPANTS:%20Noah%20Horowitz,%20Executive%20Director,%20The%20Armory%20Show%0APhilip%20Tinari,%20Director,%20Ullens%20Center%20for%20Contemporary%20Art%20(UCCA),%20Beijing%0AAdrian%20Cheng,%20Founder%20and%20Chairman,%20K11%20Art%20Foundation,%20Hong%20Kong%0A&location=&sprop=&sprop=name:"
it 'yahoo event url should be present', ->
@html.should.containEql "http://calendar.yahoo.com/?v=60&view=d&type=20&title=Welcome&st=20140308T171500&dur=0015&desc=PARTICIPANTS:%20Noah%20Horowitz,%20Executive%20Director,%20The%20Armory%20Show%0APhilip%20Tinari,%20Director,%20Ullens%20Center%20for%20Contemporary%20Art%20(UCCA),%20Beijing%0AAdrian%20Cheng,%20Founder%20and%20Chairman,%20K11%20Art%20Foundation,%20Hong%20Kong%0A&in_loc="
it 'iCal event url should be present', ->
@html.should.containEql "ical"
| 28803 | $ = require 'cheerio'
_ = require 'underscore'
{ fabricate } = require '@artsy/antigravity'
Profile = require '../../../../models/profile'
Fair = require '../../../../models/fair'
FairEvent = require '../../../../models/fair_event'
FairEvents = require '../../../../collections/fair_events'
template = require('jade').compileFile(require.resolve '../../templates/events.jade')
InfoMenu = require '../../../../components/info_menu/index.coffee'
data = _.extend {}, asset: (->), sd: {CURRENT_PATH: '/info/events'}, markdown: (->)
render = (moreData) ->
template _.extend {}, data, moreData
describe 'Events templates', ->
before ->
@profile = new Profile fabricate 'profile'
@fair = new Fair fabricate 'fair'
@infoMenu = new InfoMenu fair: @fair
@infoMenu.infoMenu = {
events: true,
programming: false,
artsyAtTheFair: false,
aboutTheFair: false
}
@fairEvent = new FairEvent fabricate('fair_event'), { fairId: 'armory-show-2013' }
@fairEvent.set venue_address: '711 12th Ave, New York, NY 10019'
@fairEvents = new FairEvents [@fairEvent], { fairId: @fair.id }
describe 'fair with events', ->
beforeEach ->
@html = render({ profile: @profile, fair: @fair, fairEvents: @fairEvents, sortedEvents: @fairEvents.sortedEvents(), infoMenu: @infoMenu.infoMenu })
it 'should render event date and time', ->
@html.should.containEql 'Saturday, March 8'
@html.should.containEql '5:15-5:30PM'
it 'should render event details', ->
@html.should.containEql 'Welcome'
@html.should.containEql 'PARTICIPANTS: <NAME>, Executive Director'
@html.should.containEql 'The New York Times Style Magazine Media Lounge on Pier 94'
it 'should display map icon', ->
@html.should.containEql '<i class="icon-circle-chevron"></i><span>Map</span>'
it 'should not display map icon', ->
@fairEvent.set venue_address: null
@fairEvents = new FairEvents [@fairEvent], { fairId: 'armory-show-2013' }
clientWithoutAdddress = render({ profile: @profile, fair: @fair, fairEvents: @fairEvents, sortedEvents: @fairEvents.sortedEvents(), infoMenu: @infoMenu.infoMenu })
clientWithoutAdddress.should.not.containEql '<i class="icon-circle-chevron"></i><span>Map</span>'
it 'outlook event url should be present', ->
@html.should.containEql "outlook"
it 'google event url should be present', ->
@html.should.containEql "https://www.google.com/calendar/render?action=TEMPLATE&text=Welcome&dates=20140308T171500/20140308T173000&details=PARTICIPANTS:%20<NAME>%20<NAME>,%20Executive%20Director,%20The%20Armory%20Show%0APhilip%20Tinari,%20Director,%20Ullens%20Center%20for%20Contemporary%20Art%20(UCCA),%20Beijing%0AAdrian%20Cheng,%20Founder%20and%20Chairman,%20K11%20Art%20Foundation,%20Hong%20Kong%0A&location=&sprop=&sprop=name:"
it 'yahoo event url should be present', ->
@html.should.containEql "http://calendar.yahoo.com/?v=60&view=d&type=20&title=Welcome&st=20140308T171500&dur=0015&desc=PARTICIPANTS:%20<NAME>%20<NAME>,%20Executive%20Director,%20The%20Armory%20Show%0APhilip%20Tinari,%20Director,%20Ullens%20Center%20for%20Contemporary%20Art%20(UCCA),%20Beijing%0AAdrian%20Cheng,%20Founder%20and%20Chairman,%20K11%20Art%20Foundation,%20Hong%20Kong%0A&in_loc="
it 'iCal event url should be present', ->
@html.should.containEql "ical"
| true | $ = require 'cheerio'
_ = require 'underscore'
{ fabricate } = require '@artsy/antigravity'
Profile = require '../../../../models/profile'
Fair = require '../../../../models/fair'
FairEvent = require '../../../../models/fair_event'
FairEvents = require '../../../../collections/fair_events'
template = require('jade').compileFile(require.resolve '../../templates/events.jade')
InfoMenu = require '../../../../components/info_menu/index.coffee'
data = _.extend {}, asset: (->), sd: {CURRENT_PATH: '/info/events'}, markdown: (->)
render = (moreData) ->
template _.extend {}, data, moreData
describe 'Events templates', ->
before ->
@profile = new Profile fabricate 'profile'
@fair = new Fair fabricate 'fair'
@infoMenu = new InfoMenu fair: @fair
@infoMenu.infoMenu = {
events: true,
programming: false,
artsyAtTheFair: false,
aboutTheFair: false
}
@fairEvent = new FairEvent fabricate('fair_event'), { fairId: 'armory-show-2013' }
@fairEvent.set venue_address: '711 12th Ave, New York, NY 10019'
@fairEvents = new FairEvents [@fairEvent], { fairId: @fair.id }
describe 'fair with events', ->
beforeEach ->
@html = render({ profile: @profile, fair: @fair, fairEvents: @fairEvents, sortedEvents: @fairEvents.sortedEvents(), infoMenu: @infoMenu.infoMenu })
it 'should render event date and time', ->
@html.should.containEql 'Saturday, March 8'
@html.should.containEql '5:15-5:30PM'
it 'should render event details', ->
@html.should.containEql 'Welcome'
@html.should.containEql 'PARTICIPANTS: PI:NAME:<NAME>END_PI, Executive Director'
@html.should.containEql 'The New York Times Style Magazine Media Lounge on Pier 94'
it 'should display map icon', ->
@html.should.containEql '<i class="icon-circle-chevron"></i><span>Map</span>'
it 'should not display map icon', ->
@fairEvent.set venue_address: null
@fairEvents = new FairEvents [@fairEvent], { fairId: 'armory-show-2013' }
clientWithoutAdddress = render({ profile: @profile, fair: @fair, fairEvents: @fairEvents, sortedEvents: @fairEvents.sortedEvents(), infoMenu: @infoMenu.infoMenu })
clientWithoutAdddress.should.not.containEql '<i class="icon-circle-chevron"></i><span>Map</span>'
it 'outlook event url should be present', ->
@html.should.containEql "outlook"
it 'google event url should be present', ->
@html.should.containEql "https://www.google.com/calendar/render?action=TEMPLATE&text=Welcome&dates=20140308T171500/20140308T173000&details=PARTICIPANTS:%20PI:NAME:<NAME>END_PI%20PI:NAME:<NAME>END_PI,%20Executive%20Director,%20The%20Armory%20Show%0APhilip%20Tinari,%20Director,%20Ullens%20Center%20for%20Contemporary%20Art%20(UCCA),%20Beijing%0AAdrian%20Cheng,%20Founder%20and%20Chairman,%20K11%20Art%20Foundation,%20Hong%20Kong%0A&location=&sprop=&sprop=name:"
it 'yahoo event url should be present', ->
@html.should.containEql "http://calendar.yahoo.com/?v=60&view=d&type=20&title=Welcome&st=20140308T171500&dur=0015&desc=PARTICIPANTS:%20PI:NAME:<NAME>END_PI%20PI:NAME:<NAME>END_PI,%20Executive%20Director,%20The%20Armory%20Show%0APhilip%20Tinari,%20Director,%20Ullens%20Center%20for%20Contemporary%20Art%20(UCCA),%20Beijing%0AAdrian%20Cheng,%20Founder%20and%20Chairman,%20K11%20Art%20Foundation,%20Hong%20Kong%0A&in_loc="
it 'iCal event url should be present', ->
@html.should.containEql "ical"
|
[
{
"context": "ription methods for accessing $ionicPush\n# @author Michael Lin, Snaphappi Inc.\n# \n###\n\nangular\n.module 'ionic.pu",
"end": 123,
"score": 0.9995060563087463,
"start": 112,
"tag": "NAME",
"value": "Michael Lin"
}
] | app/js/services/ionic-push.coffee | mixersoft/ionic-parse-facebook-scaffold | 5 | 'use strict'
###*
# @ngdoc factory
# @name ionicPush
# @description methods for accessing $ionicPush
# @author Michael Lin, Snaphappi Inc.
#
###
angular
.module 'ionic.push', ['auth']
.factory 'ionicPush', [
'$rootScope'
'$q'
'$timeout'
'$http'
'auth.KEYS'
'$ionicPush'
($rootScope, $q, $timeout, $http, KEYS, $ionicPush)->
push = {
headers:
"Authorization": "basic " + KEYS.ionic.b64_auth,
"Content-Type": "application/json",
"X-Ionic-Application-Id": KEYS.ionic.app_id
registerP: (options, handleNotification)->
# $rootScope.$on '$cordovaPush:tokenReceived', (event, data)->
# console.log('Ionic Push: Got token ', data.token, data.platform);
# $scope.user.token = data.token
# # save token to user
# $ionicUser.identify($scope.user).then (resp)->
# console.log('Updated user w/Token ' , $scope.user)
config = _.defaults options, {
canShowAlert: false, # //Can pushes show an alert on your screen?
canSetBadge: true, # //Can pushes update app icon badges?
canPlaySound: true, # //Can notifications play a sound?
canRunActionsOnWake: true, # //Can run actions outside the app,
}
config['onNotification'] = (notification)->
# // Handle new push notifications here
console.log "ionicPush onNotification, msg=", notification
return handleNotification(notification) if handleNotification
return true;
return $ionicPush.register(config)
pushP: (postData, delay=10)->
dfd = $q.defer()
$timeout ()->
options = {
method: 'POST'
url: "https://push.ionic.io/api/v1/push"
headers: push.headers
params: null
data: postData
}
console.log "push $http postData=", JSON.stringify(postData)[0..50]
return $http( options )
.then (resp)->
return dfd.reject(resp.error) if resp.error?
return dfd.resolve resp.data
, (err)->
console.warn "ionic.Push error: ", err
return dfd.reject( err )
return
, delay
return dfd.promise
###
resp={
}
###
}
window.push = push
return push
] | 17198 | 'use strict'
###*
# @ngdoc factory
# @name ionicPush
# @description methods for accessing $ionicPush
# @author <NAME>, Snaphappi Inc.
#
###
angular
.module 'ionic.push', ['auth']
.factory 'ionicPush', [
'$rootScope'
'$q'
'$timeout'
'$http'
'auth.KEYS'
'$ionicPush'
($rootScope, $q, $timeout, $http, KEYS, $ionicPush)->
push = {
headers:
"Authorization": "basic " + KEYS.ionic.b64_auth,
"Content-Type": "application/json",
"X-Ionic-Application-Id": KEYS.ionic.app_id
registerP: (options, handleNotification)->
# $rootScope.$on '$cordovaPush:tokenReceived', (event, data)->
# console.log('Ionic Push: Got token ', data.token, data.platform);
# $scope.user.token = data.token
# # save token to user
# $ionicUser.identify($scope.user).then (resp)->
# console.log('Updated user w/Token ' , $scope.user)
config = _.defaults options, {
canShowAlert: false, # //Can pushes show an alert on your screen?
canSetBadge: true, # //Can pushes update app icon badges?
canPlaySound: true, # //Can notifications play a sound?
canRunActionsOnWake: true, # //Can run actions outside the app,
}
config['onNotification'] = (notification)->
# // Handle new push notifications here
console.log "ionicPush onNotification, msg=", notification
return handleNotification(notification) if handleNotification
return true;
return $ionicPush.register(config)
pushP: (postData, delay=10)->
dfd = $q.defer()
$timeout ()->
options = {
method: 'POST'
url: "https://push.ionic.io/api/v1/push"
headers: push.headers
params: null
data: postData
}
console.log "push $http postData=", JSON.stringify(postData)[0..50]
return $http( options )
.then (resp)->
return dfd.reject(resp.error) if resp.error?
return dfd.resolve resp.data
, (err)->
console.warn "ionic.Push error: ", err
return dfd.reject( err )
return
, delay
return dfd.promise
###
resp={
}
###
}
window.push = push
return push
] | true | 'use strict'
###*
# @ngdoc factory
# @name ionicPush
# @description methods for accessing $ionicPush
# @author PI:NAME:<NAME>END_PI, Snaphappi Inc.
#
###
angular
.module 'ionic.push', ['auth']
.factory 'ionicPush', [
'$rootScope'
'$q'
'$timeout'
'$http'
'auth.KEYS'
'$ionicPush'
($rootScope, $q, $timeout, $http, KEYS, $ionicPush)->
push = {
headers:
"Authorization": "basic " + KEYS.ionic.b64_auth,
"Content-Type": "application/json",
"X-Ionic-Application-Id": KEYS.ionic.app_id
registerP: (options, handleNotification)->
# $rootScope.$on '$cordovaPush:tokenReceived', (event, data)->
# console.log('Ionic Push: Got token ', data.token, data.platform);
# $scope.user.token = data.token
# # save token to user
# $ionicUser.identify($scope.user).then (resp)->
# console.log('Updated user w/Token ' , $scope.user)
config = _.defaults options, {
canShowAlert: false, # //Can pushes show an alert on your screen?
canSetBadge: true, # //Can pushes update app icon badges?
canPlaySound: true, # //Can notifications play a sound?
canRunActionsOnWake: true, # //Can run actions outside the app,
}
config['onNotification'] = (notification)->
# // Handle new push notifications here
console.log "ionicPush onNotification, msg=", notification
return handleNotification(notification) if handleNotification
return true;
return $ionicPush.register(config)
pushP: (postData, delay=10)->
dfd = $q.defer()
$timeout ()->
options = {
method: 'POST'
url: "https://push.ionic.io/api/v1/push"
headers: push.headers
params: null
data: postData
}
console.log "push $http postData=", JSON.stringify(postData)[0..50]
return $http( options )
.then (resp)->
return dfd.reject(resp.error) if resp.error?
return dfd.resolve resp.data
, (err)->
console.warn "ionic.Push error: ", err
return dfd.reject( err )
return
, delay
return dfd.promise
###
resp={
}
###
}
window.push = push
return push
] |
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9985458254814148,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-path-parse-format.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.
# unc
# {method: 'parse', input: [''], message: /Invalid path/}, // omitted because it's hard to trigger!
checkErrors = (path) ->
errors.forEach (errorCase) ->
try
path[errorCase.method].apply path, errorCase.input
catch err
assert.ok err instanceof TypeError
assert.ok errorCase.message.test(err.message), "expected " + errorCase.message + " to match " + err.message
return
assert.fail "should have thrown"
return
return
check = (path, paths) ->
paths.forEach (element, index, array) ->
output = path.parse(element)
assert.strictEqual path.format(output), element
assert.strictEqual output.dir, (if output.dir then path.dirname(element) else "")
assert.strictEqual output.base, path.basename(element)
assert.strictEqual output.ext, path.extname(element)
return
return
assert = require("assert")
path = require("path")
winPaths = [
"C:\\path\\dir\\index.html"
"C:\\another_path\\DIR\\1\\2\\33\\index"
"another_path\\DIR with spaces\\1\\2\\33\\index"
"\\foo\\C:"
"file"
".\\file"
"\\\\server\\share\\file_path"
"\\\\server two\\shared folder\\file path.zip"
"\\\\teela\\admin$\\system32"
"\\\\?\\UNC\\server\\share"
]
unixPaths = [
"/home/user/dir/file.txt"
"/home/user/a dir/another File.zip"
"/home/user/a dir//another&File."
"/home/user/a$$$dir//another File.zip"
"user/dir/another File.zip"
"file"
".\\file"
"./file"
"C:\\foo"
]
errors = [
{
method: "parse"
input: [null]
message: /Parameter 'pathString' must be a string, not/
}
{
method: "parse"
input: [{}]
message: /Parameter 'pathString' must be a string, not object/
}
{
method: "parse"
input: [true]
message: /Parameter 'pathString' must be a string, not boolean/
}
{
method: "parse"
input: [1]
message: /Parameter 'pathString' must be a string, not number/
}
{
method: "parse"
input: []
message: /Parameter 'pathString' must be a string, not undefined/
}
{
method: "format"
input: [null]
message: /Parameter 'pathObject' must be an object, not/
}
{
method: "format"
input: [""]
message: /Parameter 'pathObject' must be an object, not string/
}
{
method: "format"
input: [true]
message: /Parameter 'pathObject' must be an object, not boolean/
}
{
method: "format"
input: [1]
message: /Parameter 'pathObject' must be an object, not number/
}
{
method: "format"
input: [root: true]
message: /'pathObject.root' must be a string or undefined, not boolean/
}
{
method: "format"
input: [root: 12]
message: /'pathObject.root' must be a string or undefined, not number/
}
]
check path.win32, winPaths
check path.posix, unixPaths
checkErrors path.win32
checkErrors path.posix
| 127405 | # 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.
# unc
# {method: 'parse', input: [''], message: /Invalid path/}, // omitted because it's hard to trigger!
checkErrors = (path) ->
errors.forEach (errorCase) ->
try
path[errorCase.method].apply path, errorCase.input
catch err
assert.ok err instanceof TypeError
assert.ok errorCase.message.test(err.message), "expected " + errorCase.message + " to match " + err.message
return
assert.fail "should have thrown"
return
return
check = (path, paths) ->
paths.forEach (element, index, array) ->
output = path.parse(element)
assert.strictEqual path.format(output), element
assert.strictEqual output.dir, (if output.dir then path.dirname(element) else "")
assert.strictEqual output.base, path.basename(element)
assert.strictEqual output.ext, path.extname(element)
return
return
assert = require("assert")
path = require("path")
winPaths = [
"C:\\path\\dir\\index.html"
"C:\\another_path\\DIR\\1\\2\\33\\index"
"another_path\\DIR with spaces\\1\\2\\33\\index"
"\\foo\\C:"
"file"
".\\file"
"\\\\server\\share\\file_path"
"\\\\server two\\shared folder\\file path.zip"
"\\\\teela\\admin$\\system32"
"\\\\?\\UNC\\server\\share"
]
unixPaths = [
"/home/user/dir/file.txt"
"/home/user/a dir/another File.zip"
"/home/user/a dir//another&File."
"/home/user/a$$$dir//another File.zip"
"user/dir/another File.zip"
"file"
".\\file"
"./file"
"C:\\foo"
]
errors = [
{
method: "parse"
input: [null]
message: /Parameter 'pathString' must be a string, not/
}
{
method: "parse"
input: [{}]
message: /Parameter 'pathString' must be a string, not object/
}
{
method: "parse"
input: [true]
message: /Parameter 'pathString' must be a string, not boolean/
}
{
method: "parse"
input: [1]
message: /Parameter 'pathString' must be a string, not number/
}
{
method: "parse"
input: []
message: /Parameter 'pathString' must be a string, not undefined/
}
{
method: "format"
input: [null]
message: /Parameter 'pathObject' must be an object, not/
}
{
method: "format"
input: [""]
message: /Parameter 'pathObject' must be an object, not string/
}
{
method: "format"
input: [true]
message: /Parameter 'pathObject' must be an object, not boolean/
}
{
method: "format"
input: [1]
message: /Parameter 'pathObject' must be an object, not number/
}
{
method: "format"
input: [root: true]
message: /'pathObject.root' must be a string or undefined, not boolean/
}
{
method: "format"
input: [root: 12]
message: /'pathObject.root' must be a string or undefined, not number/
}
]
check path.win32, winPaths
check path.posix, unixPaths
checkErrors path.win32
checkErrors path.posix
| 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.
# unc
# {method: 'parse', input: [''], message: /Invalid path/}, // omitted because it's hard to trigger!
checkErrors = (path) ->
errors.forEach (errorCase) ->
try
path[errorCase.method].apply path, errorCase.input
catch err
assert.ok err instanceof TypeError
assert.ok errorCase.message.test(err.message), "expected " + errorCase.message + " to match " + err.message
return
assert.fail "should have thrown"
return
return
check = (path, paths) ->
paths.forEach (element, index, array) ->
output = path.parse(element)
assert.strictEqual path.format(output), element
assert.strictEqual output.dir, (if output.dir then path.dirname(element) else "")
assert.strictEqual output.base, path.basename(element)
assert.strictEqual output.ext, path.extname(element)
return
return
assert = require("assert")
path = require("path")
winPaths = [
"C:\\path\\dir\\index.html"
"C:\\another_path\\DIR\\1\\2\\33\\index"
"another_path\\DIR with spaces\\1\\2\\33\\index"
"\\foo\\C:"
"file"
".\\file"
"\\\\server\\share\\file_path"
"\\\\server two\\shared folder\\file path.zip"
"\\\\teela\\admin$\\system32"
"\\\\?\\UNC\\server\\share"
]
unixPaths = [
"/home/user/dir/file.txt"
"/home/user/a dir/another File.zip"
"/home/user/a dir//another&File."
"/home/user/a$$$dir//another File.zip"
"user/dir/another File.zip"
"file"
".\\file"
"./file"
"C:\\foo"
]
errors = [
{
method: "parse"
input: [null]
message: /Parameter 'pathString' must be a string, not/
}
{
method: "parse"
input: [{}]
message: /Parameter 'pathString' must be a string, not object/
}
{
method: "parse"
input: [true]
message: /Parameter 'pathString' must be a string, not boolean/
}
{
method: "parse"
input: [1]
message: /Parameter 'pathString' must be a string, not number/
}
{
method: "parse"
input: []
message: /Parameter 'pathString' must be a string, not undefined/
}
{
method: "format"
input: [null]
message: /Parameter 'pathObject' must be an object, not/
}
{
method: "format"
input: [""]
message: /Parameter 'pathObject' must be an object, not string/
}
{
method: "format"
input: [true]
message: /Parameter 'pathObject' must be an object, not boolean/
}
{
method: "format"
input: [1]
message: /Parameter 'pathObject' must be an object, not number/
}
{
method: "format"
input: [root: true]
message: /'pathObject.root' must be a string or undefined, not boolean/
}
{
method: "format"
input: [root: 12]
message: /'pathObject.root' must be a string or undefined, not number/
}
]
check path.win32, winPaths
check path.posix, unixPaths
checkErrors path.win32
checkErrors path.posix
|
[
{
"context": "r\n email: $scope.email,\n password: $scope.password,\n username: $scope.name,\n surname: ",
"end": 479,
"score": 0.9168749451637268,
"start": 465,
"tag": "PASSWORD",
"value": "scope.password"
},
{
"context": " password: $scope.password,\n... | app/controllers/registration.coffee | Nikitzu/Final_Proj | 0 | app = angular.module('myApp')
app.controller 'registration', ['$scope', '$routeParams', 'signupUser', 'loginUser', ($scope, $routeParams, signupUser, loginUser)->
$scope.about = ''
$scope.action = $routeParams.action
$scope.showPopUpMsg = false
$scope.openPopUp = (text) ->
$scope.showPopUpMsg = true
$scope.popUpMsgContent = text
return
$scope.actions =
'signup': ->
signupUser
email: $scope.email,
password: $scope.password,
username: $scope.name,
surname: $scope.surname,
about: $scope.about
'login': ->
loginUser
email: $scope.email,
password: $scope.password
$scope.performAction = ->
$scope.actions[$scope.action]()
.success () ->
$scope.changeAll()
window.location.href = 'http://localhost:8000/app/#/'
return
.error () ->
$scope.openPopUp($scope.translation.INCORRECT_DATA)
return
]
app.directive 'popUpMsg', ->
{
restrict: 'E'
scope: false
template: '<div id="popUpMsg-bg" ng-show="showPopUpMsg"><div id="popUpMsg"><div class="content">{{popUpMsgContent}}</div><button ng-click="closePopUp()">Ok</button></div></div>'
controller: ($scope) ->
$scope.closePopUp = ->
$scope.showPopUpMsg = false
return
return
} | 216150 | app = angular.module('myApp')
app.controller 'registration', ['$scope', '$routeParams', 'signupUser', 'loginUser', ($scope, $routeParams, signupUser, loginUser)->
$scope.about = ''
$scope.action = $routeParams.action
$scope.showPopUpMsg = false
$scope.openPopUp = (text) ->
$scope.showPopUpMsg = true
$scope.popUpMsgContent = text
return
$scope.actions =
'signup': ->
signupUser
email: $scope.email,
password: $<PASSWORD>,
username: $scope.name,
surname: $scope.surname,
about: $scope.about
'login': ->
loginUser
email: $scope.email,
password:<PASSWORD> $<PASSWORD>
$scope.performAction = ->
$scope.actions[$scope.action]()
.success () ->
$scope.changeAll()
window.location.href = 'http://localhost:8000/app/#/'
return
.error () ->
$scope.openPopUp($scope.translation.INCORRECT_DATA)
return
]
app.directive 'popUpMsg', ->
{
restrict: 'E'
scope: false
template: '<div id="popUpMsg-bg" ng-show="showPopUpMsg"><div id="popUpMsg"><div class="content">{{popUpMsgContent}}</div><button ng-click="closePopUp()">Ok</button></div></div>'
controller: ($scope) ->
$scope.closePopUp = ->
$scope.showPopUpMsg = false
return
return
} | true | app = angular.module('myApp')
app.controller 'registration', ['$scope', '$routeParams', 'signupUser', 'loginUser', ($scope, $routeParams, signupUser, loginUser)->
$scope.about = ''
$scope.action = $routeParams.action
$scope.showPopUpMsg = false
$scope.openPopUp = (text) ->
$scope.showPopUpMsg = true
$scope.popUpMsgContent = text
return
$scope.actions =
'signup': ->
signupUser
email: $scope.email,
password: $PI:PASSWORD:<PASSWORD>END_PI,
username: $scope.name,
surname: $scope.surname,
about: $scope.about
'login': ->
loginUser
email: $scope.email,
password:PI:PASSWORD:<PASSWORD>END_PI $PI:PASSWORD:<PASSWORD>END_PI
$scope.performAction = ->
$scope.actions[$scope.action]()
.success () ->
$scope.changeAll()
window.location.href = 'http://localhost:8000/app/#/'
return
.error () ->
$scope.openPopUp($scope.translation.INCORRECT_DATA)
return
]
app.directive 'popUpMsg', ->
{
restrict: 'E'
scope: false
template: '<div id="popUpMsg-bg" ng-show="showPopUpMsg"><div id="popUpMsg"><div class="content">{{popUpMsgContent}}</div><button ng-click="closePopUp()">Ok</button></div></div>'
controller: ($scope) ->
$scope.closePopUp = ->
$scope.showPopUpMsg = false
return
return
} |
[
{
"context": " index: 'pk'\n key0: [] \n key1: ['\\xff']\n \n new Query(@::, options)\n \n ",
"end": 1799,
"score": 0.7981069087982178,
"start": 1796,
"tag": "KEY",
"value": "xff"
}
] | src/provider/foundationdb/activerecord/index.coffee | frisb/formalize | 2 | fdb = require('fdb').apiVersion(200)
deepak = require('deepak')(fdb)
ActiveRecord = require('../../../active/record')
{ObjectID} = require('bson')
initDirectories = require('./initializers/directories')
initSettings = require('./initializers/settings')
#Iterator = require('./iterator')
Query = require('./query')
Adder = require('./functions/add')
IndexAdd = Adder('indexes')
CounterAdd = Adder('counters')
index = (tr, value) ->
if (typeof(tr) is 'function')
value = tr
tr = null
if (typeof(value) is 'function')
v = deepak.pack(value(@))
else
v = ''
IndexAdd.call(@, tr, v)
add = (tr, value) ->
if (typeof(tr) is 'number')
value = tr
tr = null
inc = new Buffer(4)
inc.writeUInt32LE(value || 1, 0)
CounterAdd.call(@, tr, inc)
module.exports = (options) ->
class FoundationDB_ActiveRecord extends ActiveRecord(options)
constructor: (id) ->
id = new ObjectID().toHexString() if (typeof(id) is 'undefined')
if (typeof(@provider.partition) isnt 'undefined')
@partition = @provider.partition
else
@partition = options.partition
@keySize = 0
@valueSize = 0
super(id)
load: require('./functions/load')
save: require('./functions/save')
index: index
add: add
data: (dest, val) ->
if (dest && !val)
val = super(dest)
if (val instanceof Buffer)
val = deepak.unpackValue(val)
@data(dest, val)
return val
return super(dest, val)
#@fetchRaw = (subspace, key0, key1) -> new Iterator(@provider.db, subspace, key0, key1)
@fetch = (options) -> new Query(@::, options)
@all = ->
options =
index: 'pk'
key0: []
key1: ['\xff']
new Query(@::, options)
@count: require('./functions/count')
@reindex = (name) ->
@all().forEachBatch (err, arr) ->
for rec in arr
if (rec.C is 64502)
console.log(rec.data)
@init = (callback) ->
initDirectories @, =>
initSettings @, =>
callback(@)
| 115196 | fdb = require('fdb').apiVersion(200)
deepak = require('deepak')(fdb)
ActiveRecord = require('../../../active/record')
{ObjectID} = require('bson')
initDirectories = require('./initializers/directories')
initSettings = require('./initializers/settings')
#Iterator = require('./iterator')
Query = require('./query')
Adder = require('./functions/add')
IndexAdd = Adder('indexes')
CounterAdd = Adder('counters')
index = (tr, value) ->
if (typeof(tr) is 'function')
value = tr
tr = null
if (typeof(value) is 'function')
v = deepak.pack(value(@))
else
v = ''
IndexAdd.call(@, tr, v)
add = (tr, value) ->
if (typeof(tr) is 'number')
value = tr
tr = null
inc = new Buffer(4)
inc.writeUInt32LE(value || 1, 0)
CounterAdd.call(@, tr, inc)
module.exports = (options) ->
class FoundationDB_ActiveRecord extends ActiveRecord(options)
constructor: (id) ->
id = new ObjectID().toHexString() if (typeof(id) is 'undefined')
if (typeof(@provider.partition) isnt 'undefined')
@partition = @provider.partition
else
@partition = options.partition
@keySize = 0
@valueSize = 0
super(id)
load: require('./functions/load')
save: require('./functions/save')
index: index
add: add
data: (dest, val) ->
if (dest && !val)
val = super(dest)
if (val instanceof Buffer)
val = deepak.unpackValue(val)
@data(dest, val)
return val
return super(dest, val)
#@fetchRaw = (subspace, key0, key1) -> new Iterator(@provider.db, subspace, key0, key1)
@fetch = (options) -> new Query(@::, options)
@all = ->
options =
index: 'pk'
key0: []
key1: ['\<KEY>']
new Query(@::, options)
@count: require('./functions/count')
@reindex = (name) ->
@all().forEachBatch (err, arr) ->
for rec in arr
if (rec.C is 64502)
console.log(rec.data)
@init = (callback) ->
initDirectories @, =>
initSettings @, =>
callback(@)
| true | fdb = require('fdb').apiVersion(200)
deepak = require('deepak')(fdb)
ActiveRecord = require('../../../active/record')
{ObjectID} = require('bson')
initDirectories = require('./initializers/directories')
initSettings = require('./initializers/settings')
#Iterator = require('./iterator')
Query = require('./query')
Adder = require('./functions/add')
IndexAdd = Adder('indexes')
CounterAdd = Adder('counters')
index = (tr, value) ->
if (typeof(tr) is 'function')
value = tr
tr = null
if (typeof(value) is 'function')
v = deepak.pack(value(@))
else
v = ''
IndexAdd.call(@, tr, v)
add = (tr, value) ->
if (typeof(tr) is 'number')
value = tr
tr = null
inc = new Buffer(4)
inc.writeUInt32LE(value || 1, 0)
CounterAdd.call(@, tr, inc)
module.exports = (options) ->
class FoundationDB_ActiveRecord extends ActiveRecord(options)
constructor: (id) ->
id = new ObjectID().toHexString() if (typeof(id) is 'undefined')
if (typeof(@provider.partition) isnt 'undefined')
@partition = @provider.partition
else
@partition = options.partition
@keySize = 0
@valueSize = 0
super(id)
load: require('./functions/load')
save: require('./functions/save')
index: index
add: add
data: (dest, val) ->
if (dest && !val)
val = super(dest)
if (val instanceof Buffer)
val = deepak.unpackValue(val)
@data(dest, val)
return val
return super(dest, val)
#@fetchRaw = (subspace, key0, key1) -> new Iterator(@provider.db, subspace, key0, key1)
@fetch = (options) -> new Query(@::, options)
@all = ->
options =
index: 'pk'
key0: []
key1: ['\PI:KEY:<KEY>END_PI']
new Query(@::, options)
@count: require('./functions/count')
@reindex = (name) ->
@all().forEachBatch (err, arr) ->
for rec in arr
if (rec.C is 64502)
console.log(rec.data)
@init = (callback) ->
initDirectories @, =>
initSettings @, =>
callback(@)
|
[
{
"context": ",\"percentage\":90}\n {\"views\":\"50\",\"name\":\"Российская Федерация\",\"country_id\":20,\"percentage\":5}\n {\"view",
"end": 2724,
"score": 0.9322047233581543,
"start": 2704,
"tag": "NAME",
"value": "Российская Федерация"
},
{
"context": "0,\"perce... | src/Vifeed/FrontendBundle/Tests/unit/mock/statistics-mock.coffee | bzis/zomba | 0 | class StatisticsMock
constructor: (httpBackend) -> @http = httpBackend
mockDataResponseForLastCampaign: ->
@http
.when('GET', '/api/campaigns/14/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"2","paid_views":"2","date":"2014-05-03"}
{"views":"2","paid_views":"1","date":"2014-05-04"}
{"views":"1","paid_views":"1","date":"2014-05-05"}
{"views":"6","paid_views":"6","date":"2014-05-06"}
{"views":"1","paid_views":"1","date":"2014-05-10"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/14/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"11","name":null,"city_id":null,"latitude":null,"longitude":null}
{"views":"1","name":"Москва","city_id":23541,"latitude":"55.7522","longitude":"37.6156"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/14/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"11","name":null,"country_id":null,"percentage":92}
{"views":"1","name":"Российская Федерация","country_id":20,"percentage":8}
]
[200, body, {}]
mockDataResponseForFirstCampaign: ->
@http
.when('GET', '/api/campaigns/1/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"2","paid_views":"1","date":"2014-05-03"}
{"views":"2","paid_views":"0","date":"2014-05-04"}
{"views":"1","paid_views":"1","date":"2014-05-05"}
{"views":"6","paid_views":"2","date":"2014-05-06"}
{"views":"1","paid_views":"1","date":"2014-05-10"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"11","name":null,"city_id":null,"latitude":null,"longitude":null}
{"views":"10","name":"Москва","city_id":23541,"latitude":"55.7522","longitude":"37.6156"}
{"views":"4","name":"Санкт-Петербург","city_id":23540,"latitude":"55.7522","longitude":"37.6156"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"900","name":null,"country_id":null,"percentage":90}
{"views":"50","name":"Российская Федерация","country_id":20,"percentage":5}
{"views":"50","name":"Германия","country_id":1,"percentage":5}
]
[200, body, {}]
mockNoDataResponseForFirstCampaign: ->
@http
.when('GET', '/api/campaigns/1/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
mockOkResponse: ->
@http
.when('GET', '/api/campaigns/1/statistics/daily?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [{}, {}], {}]
@http
.when('GET', '/api/campaigns/999/statistics/daily?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/hourly/today')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/hourly/yesterday')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/geo?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/geo/countries?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/geo/countries/999?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/3/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/3/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/3/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
| 96810 | class StatisticsMock
constructor: (httpBackend) -> @http = httpBackend
mockDataResponseForLastCampaign: ->
@http
.when('GET', '/api/campaigns/14/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"2","paid_views":"2","date":"2014-05-03"}
{"views":"2","paid_views":"1","date":"2014-05-04"}
{"views":"1","paid_views":"1","date":"2014-05-05"}
{"views":"6","paid_views":"6","date":"2014-05-06"}
{"views":"1","paid_views":"1","date":"2014-05-10"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/14/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"11","name":null,"city_id":null,"latitude":null,"longitude":null}
{"views":"1","name":"Москва","city_id":23541,"latitude":"55.7522","longitude":"37.6156"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/14/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"11","name":null,"country_id":null,"percentage":92}
{"views":"1","name":"Российская Федерация","country_id":20,"percentage":8}
]
[200, body, {}]
mockDataResponseForFirstCampaign: ->
@http
.when('GET', '/api/campaigns/1/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"2","paid_views":"1","date":"2014-05-03"}
{"views":"2","paid_views":"0","date":"2014-05-04"}
{"views":"1","paid_views":"1","date":"2014-05-05"}
{"views":"6","paid_views":"2","date":"2014-05-06"}
{"views":"1","paid_views":"1","date":"2014-05-10"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"11","name":null,"city_id":null,"latitude":null,"longitude":null}
{"views":"10","name":"Москва","city_id":23541,"latitude":"55.7522","longitude":"37.6156"}
{"views":"4","name":"Санкт-Петербург","city_id":23540,"latitude":"55.7522","longitude":"37.6156"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"900","name":null,"country_id":null,"percentage":90}
{"views":"50","name":"<NAME>","country_id":20,"percentage":5}
{"views":"50","name":"<NAME>","country_id":1,"percentage":5}
]
[200, body, {}]
mockNoDataResponseForFirstCampaign: ->
@http
.when('GET', '/api/campaigns/1/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
mockOkResponse: ->
@http
.when('GET', '/api/campaigns/1/statistics/daily?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [{}, {}], {}]
@http
.when('GET', '/api/campaigns/999/statistics/daily?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/hourly/today')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/hourly/yesterday')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/geo?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/geo/countries?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/geo/countries/999?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/3/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/3/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/3/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
| true | class StatisticsMock
constructor: (httpBackend) -> @http = httpBackend
mockDataResponseForLastCampaign: ->
@http
.when('GET', '/api/campaigns/14/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"2","paid_views":"2","date":"2014-05-03"}
{"views":"2","paid_views":"1","date":"2014-05-04"}
{"views":"1","paid_views":"1","date":"2014-05-05"}
{"views":"6","paid_views":"6","date":"2014-05-06"}
{"views":"1","paid_views":"1","date":"2014-05-10"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/14/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"11","name":null,"city_id":null,"latitude":null,"longitude":null}
{"views":"1","name":"Москва","city_id":23541,"latitude":"55.7522","longitude":"37.6156"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/14/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"11","name":null,"country_id":null,"percentage":92}
{"views":"1","name":"Российская Федерация","country_id":20,"percentage":8}
]
[200, body, {}]
mockDataResponseForFirstCampaign: ->
@http
.when('GET', '/api/campaigns/1/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"2","paid_views":"1","date":"2014-05-03"}
{"views":"2","paid_views":"0","date":"2014-05-04"}
{"views":"1","paid_views":"1","date":"2014-05-05"}
{"views":"6","paid_views":"2","date":"2014-05-06"}
{"views":"1","paid_views":"1","date":"2014-05-10"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"11","name":null,"city_id":null,"latitude":null,"longitude":null}
{"views":"10","name":"Москва","city_id":23541,"latitude":"55.7522","longitude":"37.6156"}
{"views":"4","name":"Санкт-Петербург","city_id":23540,"latitude":"55.7522","longitude":"37.6156"}
]
[200, body, {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) ->
body = [
{"views":"900","name":null,"country_id":null,"percentage":90}
{"views":"50","name":"PI:NAME:<NAME>END_PI","country_id":20,"percentage":5}
{"views":"50","name":"PI:NAME:<NAME>END_PI","country_id":1,"percentage":5}
]
[200, body, {}]
mockNoDataResponseForFirstCampaign: ->
@http
.when('GET', '/api/campaigns/1/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/1/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
mockOkResponse: ->
@http
.when('GET', '/api/campaigns/1/statistics/daily?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [{}, {}], {}]
@http
.when('GET', '/api/campaigns/999/statistics/daily?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/hourly/today')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/hourly/yesterday')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/geo?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/geo/countries?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/999/statistics/geo/countries/999?date_from=2014-01-01&date_to=2014-01-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/3/statistics/daily?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/3/statistics/geo?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
@http
.when('GET', '/api/campaigns/3/statistics/geo/countries?date_from=2014-05-03&date_to=2014-05-10')
.respond (method, url, data, headers) -> [200, [], {}]
|
[
{
"context": "apan Meteorological Agency's image\n#\n# Author:\n# Jun Sato\n\nmoment = require('moment');\n\nmodule.exports = (r",
"end": 206,
"score": 0.9998767971992493,
"start": 198,
"tag": "NAME",
"value": "Jun Sato"
}
] | scripts/himawari8.coffee | jnst/hubot-himawari8 | 1 | # Description:
# Himawari 8 is Japanese weather satellite
#
# Dependencies:
# "moment": "2.10.3"
#
# Commands:
# hubot himawari8 - show the Japan Meteorological Agency's image
#
# Author:
# Jun Sato
moment = require('moment');
module.exports = (robot) ->
delimitBy30 = ->
m = moment()
min = +m.format('m')
switch
when min <= 5 then m.subtract(1, 'hours').minutes(30)
when min <= 35 then m.minutes(0)
else m.minutes(30)
robot.respond /himawari8$/i, (msg) ->
dateStr = delimitBy30().format('YYYYMMDDHHmm')
msg.send "http://www.jma.go.jp/jp/gms/imgs_c/0/visible/0/#{dateStr}-00.png"
| 75740 | # Description:
# Himawari 8 is Japanese weather satellite
#
# Dependencies:
# "moment": "2.10.3"
#
# Commands:
# hubot himawari8 - show the Japan Meteorological Agency's image
#
# Author:
# <NAME>
moment = require('moment');
module.exports = (robot) ->
delimitBy30 = ->
m = moment()
min = +m.format('m')
switch
when min <= 5 then m.subtract(1, 'hours').minutes(30)
when min <= 35 then m.minutes(0)
else m.minutes(30)
robot.respond /himawari8$/i, (msg) ->
dateStr = delimitBy30().format('YYYYMMDDHHmm')
msg.send "http://www.jma.go.jp/jp/gms/imgs_c/0/visible/0/#{dateStr}-00.png"
| true | # Description:
# Himawari 8 is Japanese weather satellite
#
# Dependencies:
# "moment": "2.10.3"
#
# Commands:
# hubot himawari8 - show the Japan Meteorological Agency's image
#
# Author:
# PI:NAME:<NAME>END_PI
moment = require('moment');
module.exports = (robot) ->
delimitBy30 = ->
m = moment()
min = +m.format('m')
switch
when min <= 5 then m.subtract(1, 'hours').minutes(30)
when min <= 35 then m.minutes(0)
else m.minutes(30)
robot.respond /himawari8$/i, (msg) ->
dateStr = delimitBy30().format('YYYYMMDDHHmm')
msg.send "http://www.jma.go.jp/jp/gms/imgs_c/0/visible/0/#{dateStr}-00.png"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.