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": "+9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAALlJREFUeNpi1F3xYAIDA4MBA35wgQWqyB5dRoaVmeHJ779", "end": 716, "score": 0.5451204180717468, "start": 715, "tag": "KEY", "value": "P" }, { "context": "AAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAALlJREFUeNpi1F3xY...
packages/server/test/unit/screenshots_spec.coffee
pedbarros/cypress
2
require("../spec_helper") _ = require("lodash") path = require("path") Jimp = require("jimp") Buffer = require("buffer").Buffer dataUriToBuffer = require("data-uri-to-buffer") sizeOf = require("image-size") Fixtures = require("../support/helpers/fixtures") config = require("#{root}lib/config") screenshots = require("#{root}lib/screenshots") fs = require("#{root}lib/util/fs") settings = require("#{root}lib/util/settings") plugins = require("#{root}lib/plugins") screenshotAutomation = require("#{root}lib/automation/screenshot") image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAALlJREFUeNpi1F3xYAIDA4MBA35wgQWqyB5dRoaVmeHJ779wPhOM0aQtyBAoyglmOwmwM6z1lWY44CMDFgcBFmRTGp3EGGJe/WIQ5mZm4GRlBGJmhlm3PqGaeODpNzCtKsbGIARUCALvvv6FWw9XeOvrH4bbQNOQwfabnzHdGK3AwyAjyAqX2HPzC0Pn7Y9wPtyNIMGlD74wmAqwMZz+8AvFxzATVZAFQIqwABWQiWtgAY5uCnKAAwQYAPr8OZysiz4PAAAAAElFTkSuQmCC" iso8601Regex = /^\d{4}\-\d{2}\-\d{2}T\d{2}\:\d{2}\:\d{2}\.?\d*Z?$/ describe "lib/screenshots", -> beforeEach -> ## make each test timeout after only 1 sec ## so that durations are handled correctly @currentTest.timeout(1000) Fixtures.scaffold() @todosPath = Fixtures.projectPath("todos") @appData = { capture: "viewport" clip: { x: 0, y: 0, width: 10, height: 10 } viewport: { width: 40, height: 40 } } @buffer = Buffer.from("image 1 data buffer") @jimpImage = { id: 1 bitmap: { width: 40 height: 40 data: @buffer } crop: sinon.stub().callsFake => @jimpImage getBuffer: sinon.stub().resolves(@buffer) getMIME: -> "image/png" hash: sinon.stub().returns("image hash") clone: => @jimpImage } Jimp.prototype.composite = sinon.stub() # Jimp.prototype.getBuffer = sinon.stub().resolves(@buffer) config.get(@todosPath).then (@config) => afterEach -> Fixtures.remove() context ".capture", -> beforeEach -> @getPixelColor = sinon.stub() @getPixelColor.withArgs(0, 0).returns("grey") @getPixelColor.withArgs(1, 0).returns("white") @getPixelColor.withArgs(0, 1).returns("white") @getPixelColor.withArgs(40, 0).returns("white") @getPixelColor.withArgs(0, 40).returns("white") @getPixelColor.withArgs(40, 40).returns("black") @jimpImage.getPixelColor = @getPixelColor sinon.stub(Jimp, "read").resolves(@jimpImage) intToRGBA = sinon.stub(Jimp, "intToRGBA") intToRGBA.withArgs("black").returns({ r: 0, g: 0, b: 0 }) intToRGBA.withArgs("grey").returns({ r: 127, g: 127, b: 127 }) intToRGBA.withArgs("white").returns({ r: 255, g: 255, b: 255 }) @automate = sinon.stub().resolves(image) @passPixelTest = => @getPixelColor.withArgs(0, 0).returns("white") it "captures screenshot with automation", -> data = { viewport: @jimpImage.bitmap } screenshots.capture(data, @automate).then => expect(@automate).to.be.calledOnce expect(@automate).to.be.calledWith(data) it "retries until helper pixels are no longer present for viewport capture", -> @getPixelColor.withArgs(0, 0).onCall(1).returns("white") screenshots.capture(@appData, @automate).then => expect(@automate).to.be.calledTwice it "retries until helper pixels are present for runner capture", -> @passPixelTest() @getPixelColor.withArgs(0, 0).onCall(1).returns("black") screenshots.capture({ viewport: @jimpImage.bitmap }, @automate) .then => expect(@automate).to.be.calledTwice it "adjusts cropping based on pixel ratio", -> @appData.viewport = { width: 20, height: 20 } @appData.clip = { x: 5, y: 5, width: 10, height: 10 } @passPixelTest() @getPixelColor.withArgs(2, 0).returns("white") @getPixelColor.withArgs(0, 2).returns("white") screenshots.capture(@appData, @automate) .then => expect(@jimpImage.crop).to.be.calledWith(10, 10, 20, 20) it "resolves details w/ image", -> @passPixelTest() screenshots.capture(@appData, @automate).then (details) => expect(details.image).to.equal(@jimpImage) expect(details.multipart).to.be.false expect(details.pixelRatio).to.equal(1) expect(details.takenAt).to.match(iso8601Regex) describe "simple capture", -> beforeEach -> @appData.simple = true it "skips pixel checking / reading into Jimp image", -> screenshots.capture(@appData, @automate).then -> expect(Jimp.read).not.to.be.called it "resolves details w/ buffer", -> screenshots.capture(@appData, @automate).then (details) -> expect(details.takenAt).to.match(iso8601Regex) expect(details.multipart).to.be.false expect(details.buffer).to.be.instanceOf(Buffer) describe "userClip", -> it "crops final image if userClip specified", -> @appData.userClip = { width: 5, height: 5, x: 2, y: 2 } @passPixelTest() screenshots.capture(@appData, @automate).then => expect(@jimpImage.crop).to.be.calledWith(2, 2, 5, 5) it "does not crop intermediary multi-part images", -> @appData.userClip = { width: 5, height: 5, x: 2, y: 2 } @appData.current = 1 @appData.total = 3 @passPixelTest() screenshots.capture(@appData, @automate).then => expect(@jimpImage.crop).not.to.be.called it "adjusts cropping based on pixel ratio", -> @appData.viewport = { width: 20, height: 20 } @appData.userClip = { x: 5, y: 5, width: 10, height: 10 } @passPixelTest() @getPixelColor.withArgs(2, 0).returns("white") @getPixelColor.withArgs(0, 2).returns("white") screenshots.capture(@appData, @automate).then => expect(@jimpImage.crop).to.be.calledWith(10, 10, 20, 20) describe "multi-part capture (fullPage or element)", -> beforeEach -> screenshots.clearMultipartState() @appData.current = 1 @appData.total = 3 @getPixelColor.withArgs(0, 0).onSecondCall().returns("white") clone = (img, props) -> _.defaultsDeep(props, img) @jimpImage2 = clone(@jimpImage, { id: 2 bitmap: { data: Buffer.from("image 2 data buffer") } }) @jimpImage3 = clone(@jimpImage, { id: 3 bitmap: { data: Buffer.from("image 3 data buffer") } }) @jimpImage4 = clone(@jimpImage, { id: 4 bitmap: { data: Buffer.from("image 4 data buffer") } }) it "retries until helper pixels are no longer present on first capture", -> screenshots.capture(@appData, @automate) .then => expect(@automate).to.be.calledTwice it "retries until images aren't the same on subsequent captures", -> screenshots.capture(@appData, @automate) .then => Jimp.read.onCall(3).resolves(@jimpImage2) @appData.current = 2 screenshots.capture(@appData, @automate) .then => expect(@automate.callCount).to.equal(4) it "resolves no image on non-last captures", -> screenshots.capture(@appData, @automate) .then (image) -> expect(image).to.be.null it "resolves details w/ image on last capture", -> screenshots.capture(@appData, @automate) .then => Jimp.read.onCall(3).resolves(@jimpImage2) @appData.current = 3 screenshots.capture(@appData, @automate) .then ({ image }) => expect(image).to.be.an.instanceOf(Jimp) it "composites images into one image", -> Jimp.read.onThirdCall().resolves(@jimpImage2) Jimp.read.onCall(3).resolves(@jimpImage3) screenshots.capture(@appData, @automate) .then => @appData.current = 2 screenshots.capture(@appData, @automate) .then => @appData.current = 3 screenshots.capture(@appData, @automate) .then => composite = Jimp.prototype.composite expect(composite).to.be.calledThrice expect(composite.getCall(0).args[0]).to.equal(@jimpImage) expect(composite.getCall(0).args[1]).to.equal(0) expect(composite.getCall(0).args[2]).to.equal(0) expect(composite.getCall(1).args[0]).to.equal(@jimpImage) expect(composite.getCall(1).args[2]).to.equal(40) expect(composite.getCall(2).args[0]).to.equal(@jimpImage) expect(composite.getCall(2).args[2]).to.equal(80) it "clears previous full page state once complete", -> @getPixelColor.withArgs(0, 0).returns("white") Jimp.read.onSecondCall().resolves(@jimpImage2) Jimp.read.onThirdCall().resolves(@jimpImage3) Jimp.read.onCall(3).resolves(@jimpImage4) @appData.total = 2 screenshots.capture(@appData, @automate) .then => @appData.current = 2 screenshots.capture(@appData, @automate) .then => @appData.current = 1 screenshots.capture(@appData, @automate) .then => @appData.current = 2 screenshots.capture(@appData, @automate) .then -> expect(Jimp.prototype.composite.callCount).to.equal(4) it "skips full page process if only one capture needed", -> @appData.total = 1 screenshots.capture(@appData, @automate) .then -> expect(Jimp.prototype.composite).not.to.be.called describe "integration", -> beforeEach -> screenshots.clearMultipartState() @currentTest.timeout(10000) sinon.restore() @data1 = { titles: [ 'cy.screenshot() - take a screenshot' ], testId: 'r2', name: 'app-screenshot', capture: 'fullPage', clip: { x: 0, y: 0, width: 1000, height: 646 }, viewport: { width: 1280, height: 646 }, current: 1, total: 3 } @data2 = { titles: [ 'cy.screenshot() - take a screenshot' ], testId: 'r2', name: 'app-screenshot', capture: 'fullPage', clip: { x: 0, y: 0, width: 1000, height: 646 }, viewport: { width: 1280, height: 646 }, current: 2, total: 3 } @data3 = { titles: [ 'cy.screenshot() - take a screenshot' ], testId: 'r2', name: 'app-screenshot', capture: 'fullPage', clip: { x: 0, y: 138, width: 1000, height: 508 }, viewport: { width: 1280, height: 646 }, current: 3, total: 3 } @dataUri = (img) -> return -> fs.readFileAsync(Fixtures.path("img/#{img}")) .then (buf) -> "data:image/png;base64," + buf.toString("base64") it "stiches together 1x DPI images", -> screenshots .capture(@data1, @dataUri("DPI-1x/1.png")) .then (img1) => expect(img1).to.be.null screenshots .capture(@data2, @dataUri("DPI-1x/2.png")) .then (img2) => expect(img2).to.be.null screenshots .capture(@data3, @dataUri("DPI-1x/3.png")) .then (img3) => Jimp.read(Fixtures.path("img/DPI-1x/stitched.png")) .then (img) => expect(screenshots.imagesMatch(img, img3.image)) it "stiches together 2x DPI images", -> screenshots .capture(@data1, @dataUri("DPI-2x/1.png")) .then (img1) => expect(img1).to.be.null screenshots .capture(@data2, @dataUri("DPI-2x/2.png")) .then (img2) => expect(img2).to.be.null screenshots .capture(@data3, @dataUri("DPI-2x/3.png")) .then (img3) => Jimp.read(Fixtures.path("img/DPI-2x/stitched.png")) .then (img) => expect(screenshots.imagesMatch(img, img3.image)) context ".crop", -> beforeEach -> @dimensions = (overrides) -> _.extend({ x: 0, y: 0, width: 10, height: 10 }, overrides) it "crops to dimension size if less than the image size", -> screenshots.crop(@jimpImage, @dimensions()) expect(@jimpImage.crop).to.be.calledWith(0, 0, 10, 10) it "crops to dimension size if less than the image size", -> screenshots.crop(@jimpImage, @dimensions()) expect(@jimpImage.crop).to.be.calledWith(0, 0, 10, 10) it "crops to one less than width if dimensions x is more than the image width", -> screenshots.crop(@jimpImage, @dimensions({ x: 50 })) expect(@jimpImage.crop).to.be.calledWith(39, 0, 1, 10) it "crops to one less than height if dimensions y is more than the image height", -> screenshots.crop(@jimpImage, @dimensions({ y: 50 })) expect(@jimpImage.crop).to.be.calledWith(0, 39, 10, 1) it "crops only width if dimensions height is more than the image height", -> screenshots.crop(@jimpImage, @dimensions({ height: 50 })) expect(@jimpImage.crop).to.be.calledWith(0, 0, 10, 40) it "crops only height if dimensions width is more than the image width", -> screenshots.crop(@jimpImage, @dimensions({ width: 50 })) expect(@jimpImage.crop).to.be.calledWith(0, 0, 40, 10) context ".save", -> it "outputs file and returns details", -> buf = dataUriToBuffer(image) Jimp.read(buf) .then (i) => details = { image: i multipart: false pixelRatio: 2 takenAt: "1234-date" } dimensions = sizeOf(buf) screenshots.save( { name: "foo bar\\baz/my-screenshot", specName: "foo.spec.js", testFailure: false }, details, @config.screenshotsFolder ) .then (result) => expectedPath = path.join( @config.screenshotsFolder, "foo.spec.js", "foo bar", "baz", "my-screenshot.png" ) actualPath = path.normalize(result.path) expect(result).to.deep.eq({ multipart: false pixelRatio: 2 path: path.normalize(result.path) size: 272 name: "foo bar\\baz/my-screenshot" specName: "foo.spec.js" testFailure: false takenAt: "1234-date" dimensions: _.pick(dimensions, "width", "height") }) expect(expectedPath).to.eq(actualPath) fs.statAsync(expectedPath) it "can handle saving buffer", -> details = { multipart: false pixelRatio: 1 buffer: dataUriToBuffer(image) takenAt: "1234-date" } dimensions = sizeOf(details.buffer) screenshots.save( { name: "with-buffer", specName: "foo.spec.js", testFailure: false }, details, @config.screenshotsFolder ) .then (result) => expectedPath = path.join( @config.screenshotsFolder, "foo.spec.js", "with-buffer.png" ) actualPath = path.normalize(result.path) expect(result).to.deep.eq({ name: "with-buffer" multipart: false pixelRatio: 1 path: path.normalize(result.path) size: 279 specName: "foo.spec.js" testFailure: false takenAt: "1234-date" dimensions: _.pick(dimensions, "width", "height") }) expect(expectedPath).to.eq(actualPath) fs.statAsync(expectedPath) context ".copy", -> it "doesnt yell over ENOENT errors", -> screenshots.copy("/does/not/exist", "/foo/bar/baz") it "copies src to des with {overwrite: true}", -> sinon.stub(fs, "copyAsync").withArgs("foo", "bar", {overwrite: true}).resolves() screenshots.copy("foo", "bar") context ".getPath", -> it "concats spec name, screenshotsFolder, and name", -> screenshots.getPath({ specName: "examples/user/list.js" titles: ["bar", "baz"] name: "quux/lorem" }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq( "path/to/screenshots/examples/user/list.js/quux/lorem.png" ) it "concats spec name, screenshotsFolder, and titles", -> screenshots.getPath({ specName: "examples/user/list.js" titles: ["bar", "baz"] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq( "path/to/screenshots/examples/user/list.js/bar -- baz (failed).png" ) it "sanitizes file paths", -> screenshots.getPath({ specName: "examples$/user/list.js" titles: ["bar*", "baz..", "語言"] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq( "path/to/screenshots/examples$/user/list.js/bar -- baz -- 語言 (failed).png" ) _.each [Infinity, 0 / 0, [], {}, 1, false], (value) -> it "doesn't err and stringifies non-string test title: #{value}", -> screenshots.getPath({ specName: "examples$/user/list.js" titles: ["bar*", "語言", value] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq("path/to/screenshots/examples$/user/list.js/bar -- 語言 -- #{value} (failed).png") _.each [null, undefined], (value) -> it "doesn't err and removes null/undefined test title: #{value}", -> screenshots.getPath({ specName: "examples$/user/list.js" titles: ["bar*", "語言", value] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq("path/to/screenshots/examples$/user/list.js/bar -- 語言 -- (failed).png") context ".afterScreenshot", -> beforeEach -> @data = { titles: ["the", "title"] testId: "r1" name: "my-screenshot" capture: "runner" clip: { x: 0, y: 0, width: 1000, height: 660 } viewport: { width: 1400, height: 700 } scaled: true blackout: [] startTime: "2018-06-27T20:17:19.537Z" specName: "integration/spec.coffee" } @details = { size: 100 takenAt: new Date().toISOString() dimensions: { width: 1000, height: 660 } multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/path/to/my-screenshot.png" } sinon.stub(plugins, "has") sinon.stub(plugins, "execute") it "resolves whitelisted details if no after:screenshot plugin registered", -> plugins.has.returns(false) screenshots.afterScreenshot(@data, @details).then (result) => expect(_.omit(result, "duration")).to.eql({ size: 100 takenAt: @details.takenAt dimensions: @details.dimensions multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/path/to/my-screenshot.png" scaled: true blackout: [] }) expect(result.duration).to.be.a("number") it "executes after:screenshot plugin and merges in size, dimensions, and/or path", -> plugins.has.returns(true) plugins.execute.resolves({ size: 200 dimensions: { width: 2000, height: 1320 } path: "/new/path/to/screenshot.png" pixelRatio: 2 takenAt: "1234" }) screenshots.afterScreenshot(@data, @details).then (result) => expect(_.omit(result, "duration")).to.eql({ size: 200 takenAt: @details.takenAt dimensions: { width: 2000, height: 1320 } multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/new/path/to/screenshot.png" scaled: true blackout: [] }) expect(result.duration).to.be.a("number") it "ignores updates that are not an object", -> plugins.execute.resolves("foo") screenshots.afterScreenshot(@data, @details).then (result) => expect(_.omit(result, "duration")).to.eql({ size: 100 takenAt: @details.takenAt dimensions: @details.dimensions multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/path/to/my-screenshot.png" scaled: true blackout: [] }) expect(result.duration).to.be.a("number") describe "lib/automation/screenshot", -> beforeEach -> @details = {} sinon.stub(screenshots, "capture").resolves(@details) @savedDetails = {} sinon.stub(screenshots, "save").resolves(@savedDetails) @updatedDetails = {} sinon.stub(screenshots, "afterScreenshot").resolves(@updatedDetails) @screenshot = screenshotAutomation("cypress/screenshots") it "captures screenshot", -> data = {} automation = -> @screenshot.capture(data, automation).then -> expect(screenshots.capture).to.be.calledWith(data, automation) it "saves screenshot if there's a buffer", -> data = {} @screenshot.capture(data, @automate).then => expect(screenshots.save).to.be.calledWith(data, @details, "cypress/screenshots") it "does not save screenshot if there's no buffer", -> screenshots.capture.resolves(null) @screenshot.capture({}, @automate).then => expect(screenshots.save).not.to.be.called it "calls afterScreenshot", -> data = {} @screenshot.capture(data, @automate).then => expect(screenshots.afterScreenshot).to.be.calledWith(data, @savedDetails) it "resolves with updated details", -> @screenshot.capture({}, @automate).then (details) => expect(details).to.equal(@updatedDetails)
1355
require("../spec_helper") _ = require("lodash") path = require("path") Jimp = require("jimp") Buffer = require("buffer").Buffer dataUriToBuffer = require("data-uri-to-buffer") sizeOf = require("image-size") Fixtures = require("../support/helpers/fixtures") config = require("#{root}lib/config") screenshots = require("#{root}lib/screenshots") fs = require("#{root}lib/util/fs") settings = require("#{root}lib/util/settings") plugins = require("#{root}lib/plugins") screenshotAutomation = require("#{root}lib/automation/screenshot") image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccll<KEY>AAA<KEY>lJ<KEY>UeN<KEY>wg<KEY>qy<KEY>" iso8601Regex = /^\d{4}\-\d{2}\-\d{2}T\d{2}\:\d{2}\:\d{2}\.?\d*Z?$/ describe "lib/screenshots", -> beforeEach -> ## make each test timeout after only 1 sec ## so that durations are handled correctly @currentTest.timeout(1000) Fixtures.scaffold() @todosPath = Fixtures.projectPath("todos") @appData = { capture: "viewport" clip: { x: 0, y: 0, width: 10, height: 10 } viewport: { width: 40, height: 40 } } @buffer = Buffer.from("image 1 data buffer") @jimpImage = { id: 1 bitmap: { width: 40 height: 40 data: @buffer } crop: sinon.stub().callsFake => @jimpImage getBuffer: sinon.stub().resolves(@buffer) getMIME: -> "image/png" hash: sinon.stub().returns("image hash") clone: => @jimpImage } Jimp.prototype.composite = sinon.stub() # Jimp.prototype.getBuffer = sinon.stub().resolves(@buffer) config.get(@todosPath).then (@config) => afterEach -> Fixtures.remove() context ".capture", -> beforeEach -> @getPixelColor = sinon.stub() @getPixelColor.withArgs(0, 0).returns("grey") @getPixelColor.withArgs(1, 0).returns("white") @getPixelColor.withArgs(0, 1).returns("white") @getPixelColor.withArgs(40, 0).returns("white") @getPixelColor.withArgs(0, 40).returns("white") @getPixelColor.withArgs(40, 40).returns("black") @jimpImage.getPixelColor = @getPixelColor sinon.stub(Jimp, "read").resolves(@jimpImage) intToRGBA = sinon.stub(Jimp, "intToRGBA") intToRGBA.withArgs("black").returns({ r: 0, g: 0, b: 0 }) intToRGBA.withArgs("grey").returns({ r: 127, g: 127, b: 127 }) intToRGBA.withArgs("white").returns({ r: 255, g: 255, b: 255 }) @automate = sinon.stub().resolves(image) @passPixelTest = => @getPixelColor.withArgs(0, 0).returns("white") it "captures screenshot with automation", -> data = { viewport: @jimpImage.bitmap } screenshots.capture(data, @automate).then => expect(@automate).to.be.calledOnce expect(@automate).to.be.calledWith(data) it "retries until helper pixels are no longer present for viewport capture", -> @getPixelColor.withArgs(0, 0).onCall(1).returns("white") screenshots.capture(@appData, @automate).then => expect(@automate).to.be.calledTwice it "retries until helper pixels are present for runner capture", -> @passPixelTest() @getPixelColor.withArgs(0, 0).onCall(1).returns("black") screenshots.capture({ viewport: @jimpImage.bitmap }, @automate) .then => expect(@automate).to.be.calledTwice it "adjusts cropping based on pixel ratio", -> @appData.viewport = { width: 20, height: 20 } @appData.clip = { x: 5, y: 5, width: 10, height: 10 } @passPixelTest() @getPixelColor.withArgs(2, 0).returns("white") @getPixelColor.withArgs(0, 2).returns("white") screenshots.capture(@appData, @automate) .then => expect(@jimpImage.crop).to.be.calledWith(10, 10, 20, 20) it "resolves details w/ image", -> @passPixelTest() screenshots.capture(@appData, @automate).then (details) => expect(details.image).to.equal(@jimpImage) expect(details.multipart).to.be.false expect(details.pixelRatio).to.equal(1) expect(details.takenAt).to.match(iso8601Regex) describe "simple capture", -> beforeEach -> @appData.simple = true it "skips pixel checking / reading into Jimp image", -> screenshots.capture(@appData, @automate).then -> expect(Jimp.read).not.to.be.called it "resolves details w/ buffer", -> screenshots.capture(@appData, @automate).then (details) -> expect(details.takenAt).to.match(iso8601Regex) expect(details.multipart).to.be.false expect(details.buffer).to.be.instanceOf(Buffer) describe "userClip", -> it "crops final image if userClip specified", -> @appData.userClip = { width: 5, height: 5, x: 2, y: 2 } @passPixelTest() screenshots.capture(@appData, @automate).then => expect(@jimpImage.crop).to.be.calledWith(2, 2, 5, 5) it "does not crop intermediary multi-part images", -> @appData.userClip = { width: 5, height: 5, x: 2, y: 2 } @appData.current = 1 @appData.total = 3 @passPixelTest() screenshots.capture(@appData, @automate).then => expect(@jimpImage.crop).not.to.be.called it "adjusts cropping based on pixel ratio", -> @appData.viewport = { width: 20, height: 20 } @appData.userClip = { x: 5, y: 5, width: 10, height: 10 } @passPixelTest() @getPixelColor.withArgs(2, 0).returns("white") @getPixelColor.withArgs(0, 2).returns("white") screenshots.capture(@appData, @automate).then => expect(@jimpImage.crop).to.be.calledWith(10, 10, 20, 20) describe "multi-part capture (fullPage or element)", -> beforeEach -> screenshots.clearMultipartState() @appData.current = 1 @appData.total = 3 @getPixelColor.withArgs(0, 0).onSecondCall().returns("white") clone = (img, props) -> _.defaultsDeep(props, img) @jimpImage2 = clone(@jimpImage, { id: 2 bitmap: { data: Buffer.from("image 2 data buffer") } }) @jimpImage3 = clone(@jimpImage, { id: 3 bitmap: { data: Buffer.from("image 3 data buffer") } }) @jimpImage4 = clone(@jimpImage, { id: 4 bitmap: { data: Buffer.from("image 4 data buffer") } }) it "retries until helper pixels are no longer present on first capture", -> screenshots.capture(@appData, @automate) .then => expect(@automate).to.be.calledTwice it "retries until images aren't the same on subsequent captures", -> screenshots.capture(@appData, @automate) .then => Jimp.read.onCall(3).resolves(@jimpImage2) @appData.current = 2 screenshots.capture(@appData, @automate) .then => expect(@automate.callCount).to.equal(4) it "resolves no image on non-last captures", -> screenshots.capture(@appData, @automate) .then (image) -> expect(image).to.be.null it "resolves details w/ image on last capture", -> screenshots.capture(@appData, @automate) .then => Jimp.read.onCall(3).resolves(@jimpImage2) @appData.current = 3 screenshots.capture(@appData, @automate) .then ({ image }) => expect(image).to.be.an.instanceOf(Jimp) it "composites images into one image", -> Jimp.read.onThirdCall().resolves(@jimpImage2) Jimp.read.onCall(3).resolves(@jimpImage3) screenshots.capture(@appData, @automate) .then => @appData.current = 2 screenshots.capture(@appData, @automate) .then => @appData.current = 3 screenshots.capture(@appData, @automate) .then => composite = Jimp.prototype.composite expect(composite).to.be.calledThrice expect(composite.getCall(0).args[0]).to.equal(@jimpImage) expect(composite.getCall(0).args[1]).to.equal(0) expect(composite.getCall(0).args[2]).to.equal(0) expect(composite.getCall(1).args[0]).to.equal(@jimpImage) expect(composite.getCall(1).args[2]).to.equal(40) expect(composite.getCall(2).args[0]).to.equal(@jimpImage) expect(composite.getCall(2).args[2]).to.equal(80) it "clears previous full page state once complete", -> @getPixelColor.withArgs(0, 0).returns("white") Jimp.read.onSecondCall().resolves(@jimpImage2) Jimp.read.onThirdCall().resolves(@jimpImage3) Jimp.read.onCall(3).resolves(@jimpImage4) @appData.total = 2 screenshots.capture(@appData, @automate) .then => @appData.current = 2 screenshots.capture(@appData, @automate) .then => @appData.current = 1 screenshots.capture(@appData, @automate) .then => @appData.current = 2 screenshots.capture(@appData, @automate) .then -> expect(Jimp.prototype.composite.callCount).to.equal(4) it "skips full page process if only one capture needed", -> @appData.total = 1 screenshots.capture(@appData, @automate) .then -> expect(Jimp.prototype.composite).not.to.be.called describe "integration", -> beforeEach -> screenshots.clearMultipartState() @currentTest.timeout(10000) sinon.restore() @data1 = { titles: [ 'cy.screenshot() - take a screenshot' ], testId: 'r2', name: 'app-screenshot', capture: 'fullPage', clip: { x: 0, y: 0, width: 1000, height: 646 }, viewport: { width: 1280, height: 646 }, current: 1, total: 3 } @data2 = { titles: [ 'cy.screenshot() - take a screenshot' ], testId: 'r2', name: 'app-screenshot', capture: 'fullPage', clip: { x: 0, y: 0, width: 1000, height: 646 }, viewport: { width: 1280, height: 646 }, current: 2, total: 3 } @data3 = { titles: [ 'cy.screenshot() - take a screenshot' ], testId: 'r2', name: 'app-screenshot', capture: 'fullPage', clip: { x: 0, y: 138, width: 1000, height: 508 }, viewport: { width: 1280, height: 646 }, current: 3, total: 3 } @dataUri = (img) -> return -> fs.readFileAsync(Fixtures.path("img/#{img}")) .then (buf) -> "data:image/png;base64," + buf.toString("base64") it "stiches together 1x DPI images", -> screenshots .capture(@data1, @dataUri("DPI-1x/1.png")) .then (img1) => expect(img1).to.be.null screenshots .capture(@data2, @dataUri("DPI-1x/2.png")) .then (img2) => expect(img2).to.be.null screenshots .capture(@data3, @dataUri("DPI-1x/3.png")) .then (img3) => Jimp.read(Fixtures.path("img/DPI-1x/stitched.png")) .then (img) => expect(screenshots.imagesMatch(img, img3.image)) it "stiches together 2x DPI images", -> screenshots .capture(@data1, @dataUri("DPI-2x/1.png")) .then (img1) => expect(img1).to.be.null screenshots .capture(@data2, @dataUri("DPI-2x/2.png")) .then (img2) => expect(img2).to.be.null screenshots .capture(@data3, @dataUri("DPI-2x/3.png")) .then (img3) => Jimp.read(Fixtures.path("img/DPI-2x/stitched.png")) .then (img) => expect(screenshots.imagesMatch(img, img3.image)) context ".crop", -> beforeEach -> @dimensions = (overrides) -> _.extend({ x: 0, y: 0, width: 10, height: 10 }, overrides) it "crops to dimension size if less than the image size", -> screenshots.crop(@jimpImage, @dimensions()) expect(@jimpImage.crop).to.be.calledWith(0, 0, 10, 10) it "crops to dimension size if less than the image size", -> screenshots.crop(@jimpImage, @dimensions()) expect(@jimpImage.crop).to.be.calledWith(0, 0, 10, 10) it "crops to one less than width if dimensions x is more than the image width", -> screenshots.crop(@jimpImage, @dimensions({ x: 50 })) expect(@jimpImage.crop).to.be.calledWith(39, 0, 1, 10) it "crops to one less than height if dimensions y is more than the image height", -> screenshots.crop(@jimpImage, @dimensions({ y: 50 })) expect(@jimpImage.crop).to.be.calledWith(0, 39, 10, 1) it "crops only width if dimensions height is more than the image height", -> screenshots.crop(@jimpImage, @dimensions({ height: 50 })) expect(@jimpImage.crop).to.be.calledWith(0, 0, 10, 40) it "crops only height if dimensions width is more than the image width", -> screenshots.crop(@jimpImage, @dimensions({ width: 50 })) expect(@jimpImage.crop).to.be.calledWith(0, 0, 40, 10) context ".save", -> it "outputs file and returns details", -> buf = dataUriToBuffer(image) Jimp.read(buf) .then (i) => details = { image: i multipart: false pixelRatio: 2 takenAt: "1234-date" } dimensions = sizeOf(buf) screenshots.save( { name: "foo bar\\baz/my-screenshot", specName: "foo.spec.js", testFailure: false }, details, @config.screenshotsFolder ) .then (result) => expectedPath = path.join( @config.screenshotsFolder, "foo.spec.js", "foo bar", "baz", "my-screenshot.png" ) actualPath = path.normalize(result.path) expect(result).to.deep.eq({ multipart: false pixelRatio: 2 path: path.normalize(result.path) size: 272 name: "foo bar\\baz/my-screenshot" specName: "foo.spec.js" testFailure: false takenAt: "1234-date" dimensions: _.pick(dimensions, "width", "height") }) expect(expectedPath).to.eq(actualPath) fs.statAsync(expectedPath) it "can handle saving buffer", -> details = { multipart: false pixelRatio: 1 buffer: dataUriToBuffer(image) takenAt: "1234-date" } dimensions = sizeOf(details.buffer) screenshots.save( { name: "with-buffer", specName: "foo.spec.js", testFailure: false }, details, @config.screenshotsFolder ) .then (result) => expectedPath = path.join( @config.screenshotsFolder, "foo.spec.js", "with-buffer.png" ) actualPath = path.normalize(result.path) expect(result).to.deep.eq({ name: "with-buffer" multipart: false pixelRatio: 1 path: path.normalize(result.path) size: 279 specName: "foo.spec.js" testFailure: false takenAt: "1234-date" dimensions: _.pick(dimensions, "width", "height") }) expect(expectedPath).to.eq(actualPath) fs.statAsync(expectedPath) context ".copy", -> it "doesnt yell over ENOENT errors", -> screenshots.copy("/does/not/exist", "/foo/bar/baz") it "copies src to des with {overwrite: true}", -> sinon.stub(fs, "copyAsync").withArgs("foo", "bar", {overwrite: true}).resolves() screenshots.copy("foo", "bar") context ".getPath", -> it "concats spec name, screenshotsFolder, and name", -> screenshots.getPath({ specName: "examples/user/list.js" titles: ["bar", "baz"] name: "quux/lorem" }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq( "path/to/screenshots/examples/user/list.js/quux/lorem.png" ) it "concats spec name, screenshotsFolder, and titles", -> screenshots.getPath({ specName: "examples/user/list.js" titles: ["bar", "baz"] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq( "path/to/screenshots/examples/user/list.js/bar -- baz (failed).png" ) it "sanitizes file paths", -> screenshots.getPath({ specName: "examples$/user/list.js" titles: ["bar*", "baz..", "語言"] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq( "path/to/screenshots/examples$/user/list.js/bar -- baz -- 語言 (failed).png" ) _.each [Infinity, 0 / 0, [], {}, 1, false], (value) -> it "doesn't err and stringifies non-string test title: #{value}", -> screenshots.getPath({ specName: "examples$/user/list.js" titles: ["bar*", "語言", value] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq("path/to/screenshots/examples$/user/list.js/bar -- 語言 -- #{value} (failed).png") _.each [null, undefined], (value) -> it "doesn't err and removes null/undefined test title: #{value}", -> screenshots.getPath({ specName: "examples$/user/list.js" titles: ["bar*", "語言", value] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq("path/to/screenshots/examples$/user/list.js/bar -- 語言 -- (failed).png") context ".afterScreenshot", -> beforeEach -> @data = { titles: ["the", "title"] testId: "r1" name: "<NAME>-screenshot" capture: "runner" clip: { x: 0, y: 0, width: 1000, height: 660 } viewport: { width: 1400, height: 700 } scaled: true blackout: [] startTime: "2018-06-27T20:17:19.537Z" specName: "integration/spec.coffee" } @details = { size: 100 takenAt: new Date().toISOString() dimensions: { width: 1000, height: 660 } multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/path/to/my-screenshot.png" } sinon.stub(plugins, "has") sinon.stub(plugins, "execute") it "resolves whitelisted details if no after:screenshot plugin registered", -> plugins.has.returns(false) screenshots.afterScreenshot(@data, @details).then (result) => expect(_.omit(result, "duration")).to.eql({ size: 100 takenAt: @details.takenAt dimensions: @details.dimensions multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/path/to/my-screenshot.png" scaled: true blackout: [] }) expect(result.duration).to.be.a("number") it "executes after:screenshot plugin and merges in size, dimensions, and/or path", -> plugins.has.returns(true) plugins.execute.resolves({ size: 200 dimensions: { width: 2000, height: 1320 } path: "/new/path/to/screenshot.png" pixelRatio: 2 takenAt: "1234" }) screenshots.afterScreenshot(@data, @details).then (result) => expect(_.omit(result, "duration")).to.eql({ size: 200 takenAt: @details.takenAt dimensions: { width: 2000, height: 1320 } multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/new/path/to/screenshot.png" scaled: true blackout: [] }) expect(result.duration).to.be.a("number") it "ignores updates that are not an object", -> plugins.execute.resolves("foo") screenshots.afterScreenshot(@data, @details).then (result) => expect(_.omit(result, "duration")).to.eql({ size: 100 takenAt: @details.takenAt dimensions: @details.dimensions multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/path/to/my-screenshot.png" scaled: true blackout: [] }) expect(result.duration).to.be.a("number") describe "lib/automation/screenshot", -> beforeEach -> @details = {} sinon.stub(screenshots, "capture").resolves(@details) @savedDetails = {} sinon.stub(screenshots, "save").resolves(@savedDetails) @updatedDetails = {} sinon.stub(screenshots, "afterScreenshot").resolves(@updatedDetails) @screenshot = screenshotAutomation("cypress/screenshots") it "captures screenshot", -> data = {} automation = -> @screenshot.capture(data, automation).then -> expect(screenshots.capture).to.be.calledWith(data, automation) it "saves screenshot if there's a buffer", -> data = {} @screenshot.capture(data, @automate).then => expect(screenshots.save).to.be.calledWith(data, @details, "cypress/screenshots") it "does not save screenshot if there's no buffer", -> screenshots.capture.resolves(null) @screenshot.capture({}, @automate).then => expect(screenshots.save).not.to.be.called it "calls afterScreenshot", -> data = {} @screenshot.capture(data, @automate).then => expect(screenshots.afterScreenshot).to.be.calledWith(data, @savedDetails) it "resolves with updated details", -> @screenshot.capture({}, @automate).then (details) => expect(details).to.equal(@updatedDetails)
true
require("../spec_helper") _ = require("lodash") path = require("path") Jimp = require("jimp") Buffer = require("buffer").Buffer dataUriToBuffer = require("data-uri-to-buffer") sizeOf = require("image-size") Fixtures = require("../support/helpers/fixtures") config = require("#{root}lib/config") screenshots = require("#{root}lib/screenshots") fs = require("#{root}lib/util/fs") settings = require("#{root}lib/util/settings") plugins = require("#{root}lib/plugins") screenshotAutomation = require("#{root}lib/automation/screenshot") image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPI:KEY:<KEY>END_PIAAAPI:KEY:<KEY>END_PIlJPI:KEY:<KEY>END_PIUeNPI:KEY:<KEY>END_PIwgPI:KEY:<KEY>END_PIqyPI:KEY:<KEY>END_PI" iso8601Regex = /^\d{4}\-\d{2}\-\d{2}T\d{2}\:\d{2}\:\d{2}\.?\d*Z?$/ describe "lib/screenshots", -> beforeEach -> ## make each test timeout after only 1 sec ## so that durations are handled correctly @currentTest.timeout(1000) Fixtures.scaffold() @todosPath = Fixtures.projectPath("todos") @appData = { capture: "viewport" clip: { x: 0, y: 0, width: 10, height: 10 } viewport: { width: 40, height: 40 } } @buffer = Buffer.from("image 1 data buffer") @jimpImage = { id: 1 bitmap: { width: 40 height: 40 data: @buffer } crop: sinon.stub().callsFake => @jimpImage getBuffer: sinon.stub().resolves(@buffer) getMIME: -> "image/png" hash: sinon.stub().returns("image hash") clone: => @jimpImage } Jimp.prototype.composite = sinon.stub() # Jimp.prototype.getBuffer = sinon.stub().resolves(@buffer) config.get(@todosPath).then (@config) => afterEach -> Fixtures.remove() context ".capture", -> beforeEach -> @getPixelColor = sinon.stub() @getPixelColor.withArgs(0, 0).returns("grey") @getPixelColor.withArgs(1, 0).returns("white") @getPixelColor.withArgs(0, 1).returns("white") @getPixelColor.withArgs(40, 0).returns("white") @getPixelColor.withArgs(0, 40).returns("white") @getPixelColor.withArgs(40, 40).returns("black") @jimpImage.getPixelColor = @getPixelColor sinon.stub(Jimp, "read").resolves(@jimpImage) intToRGBA = sinon.stub(Jimp, "intToRGBA") intToRGBA.withArgs("black").returns({ r: 0, g: 0, b: 0 }) intToRGBA.withArgs("grey").returns({ r: 127, g: 127, b: 127 }) intToRGBA.withArgs("white").returns({ r: 255, g: 255, b: 255 }) @automate = sinon.stub().resolves(image) @passPixelTest = => @getPixelColor.withArgs(0, 0).returns("white") it "captures screenshot with automation", -> data = { viewport: @jimpImage.bitmap } screenshots.capture(data, @automate).then => expect(@automate).to.be.calledOnce expect(@automate).to.be.calledWith(data) it "retries until helper pixels are no longer present for viewport capture", -> @getPixelColor.withArgs(0, 0).onCall(1).returns("white") screenshots.capture(@appData, @automate).then => expect(@automate).to.be.calledTwice it "retries until helper pixels are present for runner capture", -> @passPixelTest() @getPixelColor.withArgs(0, 0).onCall(1).returns("black") screenshots.capture({ viewport: @jimpImage.bitmap }, @automate) .then => expect(@automate).to.be.calledTwice it "adjusts cropping based on pixel ratio", -> @appData.viewport = { width: 20, height: 20 } @appData.clip = { x: 5, y: 5, width: 10, height: 10 } @passPixelTest() @getPixelColor.withArgs(2, 0).returns("white") @getPixelColor.withArgs(0, 2).returns("white") screenshots.capture(@appData, @automate) .then => expect(@jimpImage.crop).to.be.calledWith(10, 10, 20, 20) it "resolves details w/ image", -> @passPixelTest() screenshots.capture(@appData, @automate).then (details) => expect(details.image).to.equal(@jimpImage) expect(details.multipart).to.be.false expect(details.pixelRatio).to.equal(1) expect(details.takenAt).to.match(iso8601Regex) describe "simple capture", -> beforeEach -> @appData.simple = true it "skips pixel checking / reading into Jimp image", -> screenshots.capture(@appData, @automate).then -> expect(Jimp.read).not.to.be.called it "resolves details w/ buffer", -> screenshots.capture(@appData, @automate).then (details) -> expect(details.takenAt).to.match(iso8601Regex) expect(details.multipart).to.be.false expect(details.buffer).to.be.instanceOf(Buffer) describe "userClip", -> it "crops final image if userClip specified", -> @appData.userClip = { width: 5, height: 5, x: 2, y: 2 } @passPixelTest() screenshots.capture(@appData, @automate).then => expect(@jimpImage.crop).to.be.calledWith(2, 2, 5, 5) it "does not crop intermediary multi-part images", -> @appData.userClip = { width: 5, height: 5, x: 2, y: 2 } @appData.current = 1 @appData.total = 3 @passPixelTest() screenshots.capture(@appData, @automate).then => expect(@jimpImage.crop).not.to.be.called it "adjusts cropping based on pixel ratio", -> @appData.viewport = { width: 20, height: 20 } @appData.userClip = { x: 5, y: 5, width: 10, height: 10 } @passPixelTest() @getPixelColor.withArgs(2, 0).returns("white") @getPixelColor.withArgs(0, 2).returns("white") screenshots.capture(@appData, @automate).then => expect(@jimpImage.crop).to.be.calledWith(10, 10, 20, 20) describe "multi-part capture (fullPage or element)", -> beforeEach -> screenshots.clearMultipartState() @appData.current = 1 @appData.total = 3 @getPixelColor.withArgs(0, 0).onSecondCall().returns("white") clone = (img, props) -> _.defaultsDeep(props, img) @jimpImage2 = clone(@jimpImage, { id: 2 bitmap: { data: Buffer.from("image 2 data buffer") } }) @jimpImage3 = clone(@jimpImage, { id: 3 bitmap: { data: Buffer.from("image 3 data buffer") } }) @jimpImage4 = clone(@jimpImage, { id: 4 bitmap: { data: Buffer.from("image 4 data buffer") } }) it "retries until helper pixels are no longer present on first capture", -> screenshots.capture(@appData, @automate) .then => expect(@automate).to.be.calledTwice it "retries until images aren't the same on subsequent captures", -> screenshots.capture(@appData, @automate) .then => Jimp.read.onCall(3).resolves(@jimpImage2) @appData.current = 2 screenshots.capture(@appData, @automate) .then => expect(@automate.callCount).to.equal(4) it "resolves no image on non-last captures", -> screenshots.capture(@appData, @automate) .then (image) -> expect(image).to.be.null it "resolves details w/ image on last capture", -> screenshots.capture(@appData, @automate) .then => Jimp.read.onCall(3).resolves(@jimpImage2) @appData.current = 3 screenshots.capture(@appData, @automate) .then ({ image }) => expect(image).to.be.an.instanceOf(Jimp) it "composites images into one image", -> Jimp.read.onThirdCall().resolves(@jimpImage2) Jimp.read.onCall(3).resolves(@jimpImage3) screenshots.capture(@appData, @automate) .then => @appData.current = 2 screenshots.capture(@appData, @automate) .then => @appData.current = 3 screenshots.capture(@appData, @automate) .then => composite = Jimp.prototype.composite expect(composite).to.be.calledThrice expect(composite.getCall(0).args[0]).to.equal(@jimpImage) expect(composite.getCall(0).args[1]).to.equal(0) expect(composite.getCall(0).args[2]).to.equal(0) expect(composite.getCall(1).args[0]).to.equal(@jimpImage) expect(composite.getCall(1).args[2]).to.equal(40) expect(composite.getCall(2).args[0]).to.equal(@jimpImage) expect(composite.getCall(2).args[2]).to.equal(80) it "clears previous full page state once complete", -> @getPixelColor.withArgs(0, 0).returns("white") Jimp.read.onSecondCall().resolves(@jimpImage2) Jimp.read.onThirdCall().resolves(@jimpImage3) Jimp.read.onCall(3).resolves(@jimpImage4) @appData.total = 2 screenshots.capture(@appData, @automate) .then => @appData.current = 2 screenshots.capture(@appData, @automate) .then => @appData.current = 1 screenshots.capture(@appData, @automate) .then => @appData.current = 2 screenshots.capture(@appData, @automate) .then -> expect(Jimp.prototype.composite.callCount).to.equal(4) it "skips full page process if only one capture needed", -> @appData.total = 1 screenshots.capture(@appData, @automate) .then -> expect(Jimp.prototype.composite).not.to.be.called describe "integration", -> beforeEach -> screenshots.clearMultipartState() @currentTest.timeout(10000) sinon.restore() @data1 = { titles: [ 'cy.screenshot() - take a screenshot' ], testId: 'r2', name: 'app-screenshot', capture: 'fullPage', clip: { x: 0, y: 0, width: 1000, height: 646 }, viewport: { width: 1280, height: 646 }, current: 1, total: 3 } @data2 = { titles: [ 'cy.screenshot() - take a screenshot' ], testId: 'r2', name: 'app-screenshot', capture: 'fullPage', clip: { x: 0, y: 0, width: 1000, height: 646 }, viewport: { width: 1280, height: 646 }, current: 2, total: 3 } @data3 = { titles: [ 'cy.screenshot() - take a screenshot' ], testId: 'r2', name: 'app-screenshot', capture: 'fullPage', clip: { x: 0, y: 138, width: 1000, height: 508 }, viewport: { width: 1280, height: 646 }, current: 3, total: 3 } @dataUri = (img) -> return -> fs.readFileAsync(Fixtures.path("img/#{img}")) .then (buf) -> "data:image/png;base64," + buf.toString("base64") it "stiches together 1x DPI images", -> screenshots .capture(@data1, @dataUri("DPI-1x/1.png")) .then (img1) => expect(img1).to.be.null screenshots .capture(@data2, @dataUri("DPI-1x/2.png")) .then (img2) => expect(img2).to.be.null screenshots .capture(@data3, @dataUri("DPI-1x/3.png")) .then (img3) => Jimp.read(Fixtures.path("img/DPI-1x/stitched.png")) .then (img) => expect(screenshots.imagesMatch(img, img3.image)) it "stiches together 2x DPI images", -> screenshots .capture(@data1, @dataUri("DPI-2x/1.png")) .then (img1) => expect(img1).to.be.null screenshots .capture(@data2, @dataUri("DPI-2x/2.png")) .then (img2) => expect(img2).to.be.null screenshots .capture(@data3, @dataUri("DPI-2x/3.png")) .then (img3) => Jimp.read(Fixtures.path("img/DPI-2x/stitched.png")) .then (img) => expect(screenshots.imagesMatch(img, img3.image)) context ".crop", -> beforeEach -> @dimensions = (overrides) -> _.extend({ x: 0, y: 0, width: 10, height: 10 }, overrides) it "crops to dimension size if less than the image size", -> screenshots.crop(@jimpImage, @dimensions()) expect(@jimpImage.crop).to.be.calledWith(0, 0, 10, 10) it "crops to dimension size if less than the image size", -> screenshots.crop(@jimpImage, @dimensions()) expect(@jimpImage.crop).to.be.calledWith(0, 0, 10, 10) it "crops to one less than width if dimensions x is more than the image width", -> screenshots.crop(@jimpImage, @dimensions({ x: 50 })) expect(@jimpImage.crop).to.be.calledWith(39, 0, 1, 10) it "crops to one less than height if dimensions y is more than the image height", -> screenshots.crop(@jimpImage, @dimensions({ y: 50 })) expect(@jimpImage.crop).to.be.calledWith(0, 39, 10, 1) it "crops only width if dimensions height is more than the image height", -> screenshots.crop(@jimpImage, @dimensions({ height: 50 })) expect(@jimpImage.crop).to.be.calledWith(0, 0, 10, 40) it "crops only height if dimensions width is more than the image width", -> screenshots.crop(@jimpImage, @dimensions({ width: 50 })) expect(@jimpImage.crop).to.be.calledWith(0, 0, 40, 10) context ".save", -> it "outputs file and returns details", -> buf = dataUriToBuffer(image) Jimp.read(buf) .then (i) => details = { image: i multipart: false pixelRatio: 2 takenAt: "1234-date" } dimensions = sizeOf(buf) screenshots.save( { name: "foo bar\\baz/my-screenshot", specName: "foo.spec.js", testFailure: false }, details, @config.screenshotsFolder ) .then (result) => expectedPath = path.join( @config.screenshotsFolder, "foo.spec.js", "foo bar", "baz", "my-screenshot.png" ) actualPath = path.normalize(result.path) expect(result).to.deep.eq({ multipart: false pixelRatio: 2 path: path.normalize(result.path) size: 272 name: "foo bar\\baz/my-screenshot" specName: "foo.spec.js" testFailure: false takenAt: "1234-date" dimensions: _.pick(dimensions, "width", "height") }) expect(expectedPath).to.eq(actualPath) fs.statAsync(expectedPath) it "can handle saving buffer", -> details = { multipart: false pixelRatio: 1 buffer: dataUriToBuffer(image) takenAt: "1234-date" } dimensions = sizeOf(details.buffer) screenshots.save( { name: "with-buffer", specName: "foo.spec.js", testFailure: false }, details, @config.screenshotsFolder ) .then (result) => expectedPath = path.join( @config.screenshotsFolder, "foo.spec.js", "with-buffer.png" ) actualPath = path.normalize(result.path) expect(result).to.deep.eq({ name: "with-buffer" multipart: false pixelRatio: 1 path: path.normalize(result.path) size: 279 specName: "foo.spec.js" testFailure: false takenAt: "1234-date" dimensions: _.pick(dimensions, "width", "height") }) expect(expectedPath).to.eq(actualPath) fs.statAsync(expectedPath) context ".copy", -> it "doesnt yell over ENOENT errors", -> screenshots.copy("/does/not/exist", "/foo/bar/baz") it "copies src to des with {overwrite: true}", -> sinon.stub(fs, "copyAsync").withArgs("foo", "bar", {overwrite: true}).resolves() screenshots.copy("foo", "bar") context ".getPath", -> it "concats spec name, screenshotsFolder, and name", -> screenshots.getPath({ specName: "examples/user/list.js" titles: ["bar", "baz"] name: "quux/lorem" }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq( "path/to/screenshots/examples/user/list.js/quux/lorem.png" ) it "concats spec name, screenshotsFolder, and titles", -> screenshots.getPath({ specName: "examples/user/list.js" titles: ["bar", "baz"] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq( "path/to/screenshots/examples/user/list.js/bar -- baz (failed).png" ) it "sanitizes file paths", -> screenshots.getPath({ specName: "examples$/user/list.js" titles: ["bar*", "baz..", "語言"] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq( "path/to/screenshots/examples$/user/list.js/bar -- baz -- 語言 (failed).png" ) _.each [Infinity, 0 / 0, [], {}, 1, false], (value) -> it "doesn't err and stringifies non-string test title: #{value}", -> screenshots.getPath({ specName: "examples$/user/list.js" titles: ["bar*", "語言", value] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq("path/to/screenshots/examples$/user/list.js/bar -- 語言 -- #{value} (failed).png") _.each [null, undefined], (value) -> it "doesn't err and removes null/undefined test title: #{value}", -> screenshots.getPath({ specName: "examples$/user/list.js" titles: ["bar*", "語言", value] takenPaths: ["a"] testFailure: true }, "png", "path/to/screenshots") .then (p) -> expect(p).to.eq("path/to/screenshots/examples$/user/list.js/bar -- 語言 -- (failed).png") context ".afterScreenshot", -> beforeEach -> @data = { titles: ["the", "title"] testId: "r1" name: "PI:NAME:<NAME>END_PI-screenshot" capture: "runner" clip: { x: 0, y: 0, width: 1000, height: 660 } viewport: { width: 1400, height: 700 } scaled: true blackout: [] startTime: "2018-06-27T20:17:19.537Z" specName: "integration/spec.coffee" } @details = { size: 100 takenAt: new Date().toISOString() dimensions: { width: 1000, height: 660 } multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/path/to/my-screenshot.png" } sinon.stub(plugins, "has") sinon.stub(plugins, "execute") it "resolves whitelisted details if no after:screenshot plugin registered", -> plugins.has.returns(false) screenshots.afterScreenshot(@data, @details).then (result) => expect(_.omit(result, "duration")).to.eql({ size: 100 takenAt: @details.takenAt dimensions: @details.dimensions multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/path/to/my-screenshot.png" scaled: true blackout: [] }) expect(result.duration).to.be.a("number") it "executes after:screenshot plugin and merges in size, dimensions, and/or path", -> plugins.has.returns(true) plugins.execute.resolves({ size: 200 dimensions: { width: 2000, height: 1320 } path: "/new/path/to/screenshot.png" pixelRatio: 2 takenAt: "1234" }) screenshots.afterScreenshot(@data, @details).then (result) => expect(_.omit(result, "duration")).to.eql({ size: 200 takenAt: @details.takenAt dimensions: { width: 2000, height: 1320 } multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/new/path/to/screenshot.png" scaled: true blackout: [] }) expect(result.duration).to.be.a("number") it "ignores updates that are not an object", -> plugins.execute.resolves("foo") screenshots.afterScreenshot(@data, @details).then (result) => expect(_.omit(result, "duration")).to.eql({ size: 100 takenAt: @details.takenAt dimensions: @details.dimensions multipart: false pixelRatio: 1 name: "my-screenshot" specName: "integration/spec.coffee" testFailure: true path: "/path/to/my-screenshot.png" scaled: true blackout: [] }) expect(result.duration).to.be.a("number") describe "lib/automation/screenshot", -> beforeEach -> @details = {} sinon.stub(screenshots, "capture").resolves(@details) @savedDetails = {} sinon.stub(screenshots, "save").resolves(@savedDetails) @updatedDetails = {} sinon.stub(screenshots, "afterScreenshot").resolves(@updatedDetails) @screenshot = screenshotAutomation("cypress/screenshots") it "captures screenshot", -> data = {} automation = -> @screenshot.capture(data, automation).then -> expect(screenshots.capture).to.be.calledWith(data, automation) it "saves screenshot if there's a buffer", -> data = {} @screenshot.capture(data, @automate).then => expect(screenshots.save).to.be.calledWith(data, @details, "cypress/screenshots") it "does not save screenshot if there's no buffer", -> screenshots.capture.resolves(null) @screenshot.capture({}, @automate).then => expect(screenshots.save).not.to.be.called it "calls afterScreenshot", -> data = {} @screenshot.capture(data, @automate).then => expect(screenshots.afterScreenshot).to.be.calledWith(data, @savedDetails) it "resolves with updated details", -> @screenshot.capture({}, @automate).then (details) => expect(details).to.equal(@updatedDetails)
[ { "context": "image of lod curves linked to plot of lod curves\n# Karl W Broman\n\niplotMScanone_eff = (lod_data, eff_data, times, ", "end": 85, "score": 0.999846339225769, "start": 72, "tag": "NAME", "value": "Karl W Broman" } ]
inst/charts/iplotMScanone_eff.coffee
FourchettesDeInterActive/qtlcharts
0
# iplotMScanone_eff: image of lod curves linked to plot of lod curves # Karl W Broman iplotMScanone_eff = (lod_data, eff_data, times, chartOpts) -> # chartOpts start wleft = chartOpts?.wleft ? 650 # width of left panels in pixels wright = chartOpts?.wright ? 350 # width of right panel in pixels htop = chartOpts?.htop ? 350 # height of top panels in pixels hbot = chartOpts?.hbot ? 350 # height of bottom panel in pixels margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner) axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels chrGap = chartOpts?.chrGap ? 8 # gap between chromosomes in pixels darkrect = chartOpts?.darkrect ? "#C8C8C8" # color of darker background rectangle lightrect = chartOpts?.lightrect ? "#E6E6E6" # color of lighter background rectangle nullcolor = chartOpts?.nullcolor ? "#E6E6E6" # color for pixels with null values colors = chartOpts?.colors ? ["slateblue", "white", "crimson"] # heat map colors zlim = chartOpts?.zlim ? null # z-axis limits zthresh = chartOpts?.zthresh ? null # lower z-axis threshold for display in heat map lod_ylab = chartOpts?.lod_ylab ? "" # y-axis label for LOD heatmap (also used as x-axis label on effect plot) eff_ylim = chartOpts?.eff_ylim ? null # y-axis limits for effect plot (right panel) eff_ylab = chartOpts?.eff_ylab ? "" # y-axis label for effect plot (right panel) linecolor = chartOpts?.linecolor ? "darkslateblue" # line color for LOD curves (lower panel) eff_linecolor = chartOpts?.eff_linecolor ? null # line color for effect plot (right panel) linewidth = chartOpts?.linewidth ? 2 # line width for LOD curves (lower panel) eff_linewidth = chartOpts?.eff_linewidth ? 2 # width of line for effect plot (right panel) nxticks = chartOpts?.nxticks ? 5 # no. ticks in x-axis for effect plot (right panel), if quantitative scale xticks = chartOpts?.xticks ? null # tick positions in x-axis for effect plot (right panel), if quantitative scale lod_labels = chartOpts?.lod_labels ? null # optional vector of strings, for LOD column labels # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' totalh = htop + hbot + 2*(margin.top + margin.bottom) totalw = wleft + wright + 2*(margin.left + margin.right) # if quant scale, use times as labels; otherwise use lod_data.lodnames unless lod_labels? lod_labels = if times? then (formatAxis(times, extra_digits=1)(x) for x in times) else lod_data.lodnames mylodheatmap = lodheatmap().height(htop) .width(wleft) .margin(margin) .axispos(axispos) .titlepos(titlepos) .chrGap(chrGap) .rectcolor(lightrect) .colors(colors) .zlim(zlim) .zthresh(zthresh) .quantScale(times) .lod_labels(lod_labels) .ylab(lod_ylab) .nullcolor(nullcolor) svg = d3.select("div##{chartdivid}") .append("svg") .attr("height", totalh) .attr("width", totalw) g_heatmap = svg.append("g") .attr("id", "heatmap") .datum(lod_data) .call(mylodheatmap) mylodchart = lodchart().height(hbot) .width(wleft) .margin(margin) .axispos(axispos) .titlepos(titlepos) .chrGap(chrGap) .linecolor("none") .pad4heatmap(true) .darkrect(darkrect) .lightrect(lightrect) .ylim([0, d3.max(mylodheatmap.zlim())]) .pointsAtMarkers(false) g_lodchart = svg.append("g") .attr("transform", "translate(0,#{htop+margin.top+margin.bottom})") .attr("id", "lodchart") .datum(lod_data) .call(mylodchart) # function for lod curve path lodcurve = (chr, lodcolumn) -> d3.svg.line() .x((d) -> mylodchart.xscale()[chr](d)) .y((d,i) -> mylodchart.yscale()(Math.abs(lod_data.lodByChr[chr][i][lodcolumn]))) # plot lod curves for selected LOD column lodchart_curves = null plotLodCurve = (lodcolumn) -> lodchart_curves = g_lodchart.append("g").attr("id", "lodcurves") for chr in lod_data.chrnames lodchart_curves.append("path") .datum(lod_data.posByChr[chr]) .attr("d", lodcurve(chr, lodcolumn)) .attr("stroke", linecolor) .attr("fill", "none") .attr("stroke-width", linewidth) .style("pointer-events", "none") eff_ylim = eff_ylim ? matrixExtent(eff_data.map((d) -> matrixExtent(d.data))) eff_nlines = d3.max(eff_data.map((d) -> d.names.length)) eff_linecolor = eff_linecolor ? selectGroupColors(eff_nlines, "dark") mycurvechart = curvechart().height(htop) .width(wright) .margin(margin) .axispos(axispos) .titlepos(titlepos) .xlab(lod_ylab) .ylab(eff_ylab) .strokecolor("none") .rectcolor(lightrect) .xlim([-0.5, lod_data.lodnames.length-0.5]) .ylim(eff_ylim) .nxticks(0) .commonX(true) g_curvechart = svg.append("g") .attr("transform", "translate(#{wleft+margin.top+margin.bottom},0)") .attr("id", "curvechart") .datum(eff_data[0]) .call(mycurvechart) # function for eff curve path effcurve = (posindex, column) -> d3.svg.line() .x((d) -> mycurvechart.xscale()(d)) .y((d,i) -> mycurvechart.yscale()(eff_data[posindex].data[column][i])) # plot effect curves for a given position effchart_curves = null plotEffCurves = (posindex) -> effchart_curves = g_curvechart.append("g").attr("id", "curves") for curveindex of eff_data[posindex].names effchart_curves.append("path") .datum(eff_data[posindex].x) .attr("d", effcurve(posindex,curveindex)) .attr("fill", "none") .attr("stroke", eff_linecolor[curveindex]) .attr("stroke-width", eff_linewidth) effchart_curves.selectAll("empty") .data(eff_data[posindex].names) .enter() .append("text") .text((d) -> d) .attr("x", (d,i) -> margin.left + wright + axispos.ylabel) .attr("y", (d,i) -> z = eff_data[posindex].data[i] mycurvechart.yscale()(z[z.length-1])) .style("dominant-baseline", "middle") .style("text-anchor", "start") # add X axis if times? # use quantitative axis xscale = d3.scale.linear().range(mycurvechart.xscale().range()) xscale.domain([times[0], times[times.length-1]]) xticks = xticks ? xscale.ticks(nxticks) curvechart_xaxis = g_curvechart.select("g.x.axis") curvechart_xaxis.selectAll("empty") .data(xticks) .enter() .append("line") .attr("x1", (d) -> xscale(d)) .attr("x2", (d) -> xscale(d)) .attr("y1", margin.top) .attr("y2", margin.top+htop) .attr("fill", "none") .attr("stroke", "white") .attr("stroke-width", 1) .style("pointer-events", "none") curvechart_xaxis.selectAll("empty") .data(xticks) .enter() .append("text") .attr("x", (d) -> xscale(d)) .attr("y", margin.top+htop+axispos.xlabel) .text((d) -> formatAxis(xticks)(d)) else # qualitative axis curvechart_xaxis = g_curvechart.select("g.x.axis") .selectAll("empty") .data(lod_labels) .enter() .append("text") .attr("class", "y axis") .attr("id", (d,i) -> "xaxis#{i}") .attr("x", (d,i) -> mycurvechart.xscale()(i)) .attr("y", margin.top+htop+axispos.xlabel) .text((d) -> d) .attr("opacity", 0) # hash for [chr][pos] -> posindex posindex = {} curindex = 0 for chr in lod_data.chrnames posindex[chr] = {} for pos in lod_data.posByChr[chr] posindex[chr][pos] = curindex curindex += 1 mycurvechart.curvesSelect() .on("mouseover.panel", null) .on("mouseout.panel", null) mylodheatmap.cellSelect() .on "mouseover", (d) -> plotLodCurve(d.lodindex) g_lodchart.select("g.title text").text("#{lod_labels[d.lodindex]}") plotEffCurves(posindex[d.chr][d.pos]) p = d3.format(".1f")(d.pos) g_curvechart.select("g.title text").text("#{d.chr}@#{p}") g_curvechart.select("text#xaxis#{d.lodindex}").attr("opacity", 1) .on "mouseout", (d) -> lodchart_curves.remove() g_lodchart.select("g.title text").text("") effchart_curves.remove() g_curvechart.select("g.title text").text("") g_curvechart.select("text#xaxis#{d.lodindex}").attr("opacity", 0)
174749
# iplotMScanone_eff: image of lod curves linked to plot of lod curves # <NAME> iplotMScanone_eff = (lod_data, eff_data, times, chartOpts) -> # chartOpts start wleft = chartOpts?.wleft ? 650 # width of left panels in pixels wright = chartOpts?.wright ? 350 # width of right panel in pixels htop = chartOpts?.htop ? 350 # height of top panels in pixels hbot = chartOpts?.hbot ? 350 # height of bottom panel in pixels margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner) axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels chrGap = chartOpts?.chrGap ? 8 # gap between chromosomes in pixels darkrect = chartOpts?.darkrect ? "#C8C8C8" # color of darker background rectangle lightrect = chartOpts?.lightrect ? "#E6E6E6" # color of lighter background rectangle nullcolor = chartOpts?.nullcolor ? "#E6E6E6" # color for pixels with null values colors = chartOpts?.colors ? ["slateblue", "white", "crimson"] # heat map colors zlim = chartOpts?.zlim ? null # z-axis limits zthresh = chartOpts?.zthresh ? null # lower z-axis threshold for display in heat map lod_ylab = chartOpts?.lod_ylab ? "" # y-axis label for LOD heatmap (also used as x-axis label on effect plot) eff_ylim = chartOpts?.eff_ylim ? null # y-axis limits for effect plot (right panel) eff_ylab = chartOpts?.eff_ylab ? "" # y-axis label for effect plot (right panel) linecolor = chartOpts?.linecolor ? "darkslateblue" # line color for LOD curves (lower panel) eff_linecolor = chartOpts?.eff_linecolor ? null # line color for effect plot (right panel) linewidth = chartOpts?.linewidth ? 2 # line width for LOD curves (lower panel) eff_linewidth = chartOpts?.eff_linewidth ? 2 # width of line for effect plot (right panel) nxticks = chartOpts?.nxticks ? 5 # no. ticks in x-axis for effect plot (right panel), if quantitative scale xticks = chartOpts?.xticks ? null # tick positions in x-axis for effect plot (right panel), if quantitative scale lod_labels = chartOpts?.lod_labels ? null # optional vector of strings, for LOD column labels # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' totalh = htop + hbot + 2*(margin.top + margin.bottom) totalw = wleft + wright + 2*(margin.left + margin.right) # if quant scale, use times as labels; otherwise use lod_data.lodnames unless lod_labels? lod_labels = if times? then (formatAxis(times, extra_digits=1)(x) for x in times) else lod_data.lodnames mylodheatmap = lodheatmap().height(htop) .width(wleft) .margin(margin) .axispos(axispos) .titlepos(titlepos) .chrGap(chrGap) .rectcolor(lightrect) .colors(colors) .zlim(zlim) .zthresh(zthresh) .quantScale(times) .lod_labels(lod_labels) .ylab(lod_ylab) .nullcolor(nullcolor) svg = d3.select("div##{chartdivid}") .append("svg") .attr("height", totalh) .attr("width", totalw) g_heatmap = svg.append("g") .attr("id", "heatmap") .datum(lod_data) .call(mylodheatmap) mylodchart = lodchart().height(hbot) .width(wleft) .margin(margin) .axispos(axispos) .titlepos(titlepos) .chrGap(chrGap) .linecolor("none") .pad4heatmap(true) .darkrect(darkrect) .lightrect(lightrect) .ylim([0, d3.max(mylodheatmap.zlim())]) .pointsAtMarkers(false) g_lodchart = svg.append("g") .attr("transform", "translate(0,#{htop+margin.top+margin.bottom})") .attr("id", "lodchart") .datum(lod_data) .call(mylodchart) # function for lod curve path lodcurve = (chr, lodcolumn) -> d3.svg.line() .x((d) -> mylodchart.xscale()[chr](d)) .y((d,i) -> mylodchart.yscale()(Math.abs(lod_data.lodByChr[chr][i][lodcolumn]))) # plot lod curves for selected LOD column lodchart_curves = null plotLodCurve = (lodcolumn) -> lodchart_curves = g_lodchart.append("g").attr("id", "lodcurves") for chr in lod_data.chrnames lodchart_curves.append("path") .datum(lod_data.posByChr[chr]) .attr("d", lodcurve(chr, lodcolumn)) .attr("stroke", linecolor) .attr("fill", "none") .attr("stroke-width", linewidth) .style("pointer-events", "none") eff_ylim = eff_ylim ? matrixExtent(eff_data.map((d) -> matrixExtent(d.data))) eff_nlines = d3.max(eff_data.map((d) -> d.names.length)) eff_linecolor = eff_linecolor ? selectGroupColors(eff_nlines, "dark") mycurvechart = curvechart().height(htop) .width(wright) .margin(margin) .axispos(axispos) .titlepos(titlepos) .xlab(lod_ylab) .ylab(eff_ylab) .strokecolor("none") .rectcolor(lightrect) .xlim([-0.5, lod_data.lodnames.length-0.5]) .ylim(eff_ylim) .nxticks(0) .commonX(true) g_curvechart = svg.append("g") .attr("transform", "translate(#{wleft+margin.top+margin.bottom},0)") .attr("id", "curvechart") .datum(eff_data[0]) .call(mycurvechart) # function for eff curve path effcurve = (posindex, column) -> d3.svg.line() .x((d) -> mycurvechart.xscale()(d)) .y((d,i) -> mycurvechart.yscale()(eff_data[posindex].data[column][i])) # plot effect curves for a given position effchart_curves = null plotEffCurves = (posindex) -> effchart_curves = g_curvechart.append("g").attr("id", "curves") for curveindex of eff_data[posindex].names effchart_curves.append("path") .datum(eff_data[posindex].x) .attr("d", effcurve(posindex,curveindex)) .attr("fill", "none") .attr("stroke", eff_linecolor[curveindex]) .attr("stroke-width", eff_linewidth) effchart_curves.selectAll("empty") .data(eff_data[posindex].names) .enter() .append("text") .text((d) -> d) .attr("x", (d,i) -> margin.left + wright + axispos.ylabel) .attr("y", (d,i) -> z = eff_data[posindex].data[i] mycurvechart.yscale()(z[z.length-1])) .style("dominant-baseline", "middle") .style("text-anchor", "start") # add X axis if times? # use quantitative axis xscale = d3.scale.linear().range(mycurvechart.xscale().range()) xscale.domain([times[0], times[times.length-1]]) xticks = xticks ? xscale.ticks(nxticks) curvechart_xaxis = g_curvechart.select("g.x.axis") curvechart_xaxis.selectAll("empty") .data(xticks) .enter() .append("line") .attr("x1", (d) -> xscale(d)) .attr("x2", (d) -> xscale(d)) .attr("y1", margin.top) .attr("y2", margin.top+htop) .attr("fill", "none") .attr("stroke", "white") .attr("stroke-width", 1) .style("pointer-events", "none") curvechart_xaxis.selectAll("empty") .data(xticks) .enter() .append("text") .attr("x", (d) -> xscale(d)) .attr("y", margin.top+htop+axispos.xlabel) .text((d) -> formatAxis(xticks)(d)) else # qualitative axis curvechart_xaxis = g_curvechart.select("g.x.axis") .selectAll("empty") .data(lod_labels) .enter() .append("text") .attr("class", "y axis") .attr("id", (d,i) -> "xaxis#{i}") .attr("x", (d,i) -> mycurvechart.xscale()(i)) .attr("y", margin.top+htop+axispos.xlabel) .text((d) -> d) .attr("opacity", 0) # hash for [chr][pos] -> posindex posindex = {} curindex = 0 for chr in lod_data.chrnames posindex[chr] = {} for pos in lod_data.posByChr[chr] posindex[chr][pos] = curindex curindex += 1 mycurvechart.curvesSelect() .on("mouseover.panel", null) .on("mouseout.panel", null) mylodheatmap.cellSelect() .on "mouseover", (d) -> plotLodCurve(d.lodindex) g_lodchart.select("g.title text").text("#{lod_labels[d.lodindex]}") plotEffCurves(posindex[d.chr][d.pos]) p = d3.format(".1f")(d.pos) g_curvechart.select("g.title text").text("#{d.chr}@#{p}") g_curvechart.select("text#xaxis#{d.lodindex}").attr("opacity", 1) .on "mouseout", (d) -> lodchart_curves.remove() g_lodchart.select("g.title text").text("") effchart_curves.remove() g_curvechart.select("g.title text").text("") g_curvechart.select("text#xaxis#{d.lodindex}").attr("opacity", 0)
true
# iplotMScanone_eff: image of lod curves linked to plot of lod curves # PI:NAME:<NAME>END_PI iplotMScanone_eff = (lod_data, eff_data, times, chartOpts) -> # chartOpts start wleft = chartOpts?.wleft ? 650 # width of left panels in pixels wright = chartOpts?.wright ? 350 # width of right panel in pixels htop = chartOpts?.htop ? 350 # height of top panels in pixels hbot = chartOpts?.hbot ? 350 # height of bottom panel in pixels margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner) axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels chrGap = chartOpts?.chrGap ? 8 # gap between chromosomes in pixels darkrect = chartOpts?.darkrect ? "#C8C8C8" # color of darker background rectangle lightrect = chartOpts?.lightrect ? "#E6E6E6" # color of lighter background rectangle nullcolor = chartOpts?.nullcolor ? "#E6E6E6" # color for pixels with null values colors = chartOpts?.colors ? ["slateblue", "white", "crimson"] # heat map colors zlim = chartOpts?.zlim ? null # z-axis limits zthresh = chartOpts?.zthresh ? null # lower z-axis threshold for display in heat map lod_ylab = chartOpts?.lod_ylab ? "" # y-axis label for LOD heatmap (also used as x-axis label on effect plot) eff_ylim = chartOpts?.eff_ylim ? null # y-axis limits for effect plot (right panel) eff_ylab = chartOpts?.eff_ylab ? "" # y-axis label for effect plot (right panel) linecolor = chartOpts?.linecolor ? "darkslateblue" # line color for LOD curves (lower panel) eff_linecolor = chartOpts?.eff_linecolor ? null # line color for effect plot (right panel) linewidth = chartOpts?.linewidth ? 2 # line width for LOD curves (lower panel) eff_linewidth = chartOpts?.eff_linewidth ? 2 # width of line for effect plot (right panel) nxticks = chartOpts?.nxticks ? 5 # no. ticks in x-axis for effect plot (right panel), if quantitative scale xticks = chartOpts?.xticks ? null # tick positions in x-axis for effect plot (right panel), if quantitative scale lod_labels = chartOpts?.lod_labels ? null # optional vector of strings, for LOD column labels # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' totalh = htop + hbot + 2*(margin.top + margin.bottom) totalw = wleft + wright + 2*(margin.left + margin.right) # if quant scale, use times as labels; otherwise use lod_data.lodnames unless lod_labels? lod_labels = if times? then (formatAxis(times, extra_digits=1)(x) for x in times) else lod_data.lodnames mylodheatmap = lodheatmap().height(htop) .width(wleft) .margin(margin) .axispos(axispos) .titlepos(titlepos) .chrGap(chrGap) .rectcolor(lightrect) .colors(colors) .zlim(zlim) .zthresh(zthresh) .quantScale(times) .lod_labels(lod_labels) .ylab(lod_ylab) .nullcolor(nullcolor) svg = d3.select("div##{chartdivid}") .append("svg") .attr("height", totalh) .attr("width", totalw) g_heatmap = svg.append("g") .attr("id", "heatmap") .datum(lod_data) .call(mylodheatmap) mylodchart = lodchart().height(hbot) .width(wleft) .margin(margin) .axispos(axispos) .titlepos(titlepos) .chrGap(chrGap) .linecolor("none") .pad4heatmap(true) .darkrect(darkrect) .lightrect(lightrect) .ylim([0, d3.max(mylodheatmap.zlim())]) .pointsAtMarkers(false) g_lodchart = svg.append("g") .attr("transform", "translate(0,#{htop+margin.top+margin.bottom})") .attr("id", "lodchart") .datum(lod_data) .call(mylodchart) # function for lod curve path lodcurve = (chr, lodcolumn) -> d3.svg.line() .x((d) -> mylodchart.xscale()[chr](d)) .y((d,i) -> mylodchart.yscale()(Math.abs(lod_data.lodByChr[chr][i][lodcolumn]))) # plot lod curves for selected LOD column lodchart_curves = null plotLodCurve = (lodcolumn) -> lodchart_curves = g_lodchart.append("g").attr("id", "lodcurves") for chr in lod_data.chrnames lodchart_curves.append("path") .datum(lod_data.posByChr[chr]) .attr("d", lodcurve(chr, lodcolumn)) .attr("stroke", linecolor) .attr("fill", "none") .attr("stroke-width", linewidth) .style("pointer-events", "none") eff_ylim = eff_ylim ? matrixExtent(eff_data.map((d) -> matrixExtent(d.data))) eff_nlines = d3.max(eff_data.map((d) -> d.names.length)) eff_linecolor = eff_linecolor ? selectGroupColors(eff_nlines, "dark") mycurvechart = curvechart().height(htop) .width(wright) .margin(margin) .axispos(axispos) .titlepos(titlepos) .xlab(lod_ylab) .ylab(eff_ylab) .strokecolor("none") .rectcolor(lightrect) .xlim([-0.5, lod_data.lodnames.length-0.5]) .ylim(eff_ylim) .nxticks(0) .commonX(true) g_curvechart = svg.append("g") .attr("transform", "translate(#{wleft+margin.top+margin.bottom},0)") .attr("id", "curvechart") .datum(eff_data[0]) .call(mycurvechart) # function for eff curve path effcurve = (posindex, column) -> d3.svg.line() .x((d) -> mycurvechart.xscale()(d)) .y((d,i) -> mycurvechart.yscale()(eff_data[posindex].data[column][i])) # plot effect curves for a given position effchart_curves = null plotEffCurves = (posindex) -> effchart_curves = g_curvechart.append("g").attr("id", "curves") for curveindex of eff_data[posindex].names effchart_curves.append("path") .datum(eff_data[posindex].x) .attr("d", effcurve(posindex,curveindex)) .attr("fill", "none") .attr("stroke", eff_linecolor[curveindex]) .attr("stroke-width", eff_linewidth) effchart_curves.selectAll("empty") .data(eff_data[posindex].names) .enter() .append("text") .text((d) -> d) .attr("x", (d,i) -> margin.left + wright + axispos.ylabel) .attr("y", (d,i) -> z = eff_data[posindex].data[i] mycurvechart.yscale()(z[z.length-1])) .style("dominant-baseline", "middle") .style("text-anchor", "start") # add X axis if times? # use quantitative axis xscale = d3.scale.linear().range(mycurvechart.xscale().range()) xscale.domain([times[0], times[times.length-1]]) xticks = xticks ? xscale.ticks(nxticks) curvechart_xaxis = g_curvechart.select("g.x.axis") curvechart_xaxis.selectAll("empty") .data(xticks) .enter() .append("line") .attr("x1", (d) -> xscale(d)) .attr("x2", (d) -> xscale(d)) .attr("y1", margin.top) .attr("y2", margin.top+htop) .attr("fill", "none") .attr("stroke", "white") .attr("stroke-width", 1) .style("pointer-events", "none") curvechart_xaxis.selectAll("empty") .data(xticks) .enter() .append("text") .attr("x", (d) -> xscale(d)) .attr("y", margin.top+htop+axispos.xlabel) .text((d) -> formatAxis(xticks)(d)) else # qualitative axis curvechart_xaxis = g_curvechart.select("g.x.axis") .selectAll("empty") .data(lod_labels) .enter() .append("text") .attr("class", "y axis") .attr("id", (d,i) -> "xaxis#{i}") .attr("x", (d,i) -> mycurvechart.xscale()(i)) .attr("y", margin.top+htop+axispos.xlabel) .text((d) -> d) .attr("opacity", 0) # hash for [chr][pos] -> posindex posindex = {} curindex = 0 for chr in lod_data.chrnames posindex[chr] = {} for pos in lod_data.posByChr[chr] posindex[chr][pos] = curindex curindex += 1 mycurvechart.curvesSelect() .on("mouseover.panel", null) .on("mouseout.panel", null) mylodheatmap.cellSelect() .on "mouseover", (d) -> plotLodCurve(d.lodindex) g_lodchart.select("g.title text").text("#{lod_labels[d.lodindex]}") plotEffCurves(posindex[d.chr][d.pos]) p = d3.format(".1f")(d.pos) g_curvechart.select("g.title text").text("#{d.chr}@#{p}") g_curvechart.select("text#xaxis#{d.lodindex}").attr("opacity", 1) .on "mouseout", (d) -> lodchart_curves.remove() g_lodchart.select("g.title text").text("") effchart_curves.remove() g_curvechart.select("g.title text").text("") g_curvechart.select("text#xaxis#{d.lodindex}").attr("opacity", 0)
[ { "context": "\n firstName: 'Test'\n lastName: 'User'\n email: 'test@user.com'\n\ndescribe 'User Model', ->\n it 'should be able ", "end": 173, "score": 0.9999263882637024, "start": 160, "tag": "EMAIL", "value": "test@user.com" }, { "context": ".equal 'User'\n testuser.email.s...
test/models/user.coffee
t3mpus/tempus-api
3
User = require '../../models/user' should = require 'should' uuid = require 'uuid' makeTestUser = -> new User firstName: 'Test' lastName: 'User' email: 'test@user.com' describe 'User Model', -> it 'should be able to construct a new user', -> testUser = new User testUser.should.not.be.equal undefined it 'should be able to construct a new user with params', -> testuser = makeTestUser() testuser.firstName.should.be.equal 'Test' testuser.lastName.should.be.equal 'User' testuser.email.should.be.equal 'test@user.com' it 'should be able to add login credentials', -> testuser = makeTestUser() testuser.makeCredentials 'password!@#$' testuser.should.have.property 'hash' testuser.should.not.have.property 'password' testuser.validate().should.be.true it 'if password is intially password is initally passed to constructor make credential', -> testuser = new User firstName: 'hi' lastName: 'bye' email: 'test@user.com' password: 'fakepassword' testuser.should.have.property 'hash' testuser.should.not.have.property 'password' testuser.validate().should.be.true
144971
User = require '../../models/user' should = require 'should' uuid = require 'uuid' makeTestUser = -> new User firstName: 'Test' lastName: 'User' email: '<EMAIL>' describe 'User Model', -> it 'should be able to construct a new user', -> testUser = new User testUser.should.not.be.equal undefined it 'should be able to construct a new user with params', -> testuser = makeTestUser() testuser.firstName.should.be.equal 'Test' testuser.lastName.should.be.equal 'User' testuser.email.should.be.equal '<EMAIL>' it 'should be able to add login credentials', -> testuser = makeTestUser() testuser.makeCredentials 'password!@#$' testuser.should.have.property 'hash' testuser.should.not.have.property 'password' testuser.validate().should.be.true it 'if password is intially password is initally passed to constructor make credential', -> testuser = new User firstName: 'hi' lastName: 'bye' email: '<EMAIL>' password: '<PASSWORD>' testuser.should.have.property 'hash' testuser.should.not.have.property 'password' testuser.validate().should.be.true
true
User = require '../../models/user' should = require 'should' uuid = require 'uuid' makeTestUser = -> new User firstName: 'Test' lastName: 'User' email: 'PI:EMAIL:<EMAIL>END_PI' describe 'User Model', -> it 'should be able to construct a new user', -> testUser = new User testUser.should.not.be.equal undefined it 'should be able to construct a new user with params', -> testuser = makeTestUser() testuser.firstName.should.be.equal 'Test' testuser.lastName.should.be.equal 'User' testuser.email.should.be.equal 'PI:EMAIL:<EMAIL>END_PI' it 'should be able to add login credentials', -> testuser = makeTestUser() testuser.makeCredentials 'password!@#$' testuser.should.have.property 'hash' testuser.should.not.have.property 'password' testuser.validate().should.be.true it 'if password is intially password is initally passed to constructor make credential', -> testuser = new User firstName: 'hi' lastName: 'bye' email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' testuser.should.have.property 'hash' testuser.should.not.have.property 'password' testuser.validate().should.be.true
[ { "context": "###\n *\n * jQuery ResponsiveTables by Gary Hepting - https://github.com/ghepting/responsiveTables\n *", "end": 50, "score": 0.9998961687088013, "start": 38, "tag": "NAME", "value": "Gary Hepting" }, { "context": "onsiveTables by Gary Hepting - https://github.com/ghept...
js/plugins/coffee/jquery.responsiveTables.coffee
storagebot/groundwork
1
### * * jQuery ResponsiveTables by Gary Hepting - https://github.com/ghepting/responsiveTables * * Open source under the BSD License. * * Copyright © 2013 Gary Hepting. All rights reserved. * ### (($) -> elems = [] $.fn.responsiveTable = (options) -> settings = compressor: options.compressor or 10 minSize: options.minSize or Number.NEGATIVE_INFINITY maxSize: options.maxSize or Number.POSITIVE_INFINITY padding: 2 height: "auto" # '100%' will fit tables (and containers) to viewport height as well adjust_parents: true # if height specified, force parent elements to be height 100% @each -> elem = $(this) elem.attr('data-compression',settings.compressor) elem.attr('data-min',settings.minSize) elem.attr('data-max',settings.maxSize) elem.attr('data-padding',settings.padding) # count columns columns = $("tr", elem).first().children("th, td").length # count rows rows = $("tr", elem).length unless settings.height is "auto" # set height of table $this.css "height", settings.height # set height of each parent of table if settings.adjust_parents $this.parents().each -> $(this).css "height", "100%" # set column widths $("tr th, tr td", elem).css "width", Math.floor(100 / columns) + "%" # set row heights $("tr th, tr td", elem).css "height", Math.floor(100 / rows) + "%" # set cell font sizes fontSize = Math.floor(Math.max(Math.min((elem.width() / (settings.compressor)), parseFloat(settings.maxSize)), parseFloat(settings.minSize))) $("tr th, tr td", elem).css "font-size", fontSize + "px" # elems.push elem $(window).on "resize", -> $(elems).each -> elem = $(this) # set cell font sizes fontSize = Math.floor(Math.max(Math.min((elem.width() / (elem.attr('data-compression'))), parseFloat(elem.attr('data-max'))), parseFloat(elem.attr('data-min')))) $("tr th, tr td", elem).css "font-size", fontSize + "px" ) jQuery
201085
### * * jQuery ResponsiveTables by <NAME> - https://github.com/ghepting/responsiveTables * * Open source under the BSD License. * * Copyright © 2013 <NAME>. All rights reserved. * ### (($) -> elems = [] $.fn.responsiveTable = (options) -> settings = compressor: options.compressor or 10 minSize: options.minSize or Number.NEGATIVE_INFINITY maxSize: options.maxSize or Number.POSITIVE_INFINITY padding: 2 height: "auto" # '100%' will fit tables (and containers) to viewport height as well adjust_parents: true # if height specified, force parent elements to be height 100% @each -> elem = $(this) elem.attr('data-compression',settings.compressor) elem.attr('data-min',settings.minSize) elem.attr('data-max',settings.maxSize) elem.attr('data-padding',settings.padding) # count columns columns = $("tr", elem).first().children("th, td").length # count rows rows = $("tr", elem).length unless settings.height is "auto" # set height of table $this.css "height", settings.height # set height of each parent of table if settings.adjust_parents $this.parents().each -> $(this).css "height", "100%" # set column widths $("tr th, tr td", elem).css "width", Math.floor(100 / columns) + "%" # set row heights $("tr th, tr td", elem).css "height", Math.floor(100 / rows) + "%" # set cell font sizes fontSize = Math.floor(Math.max(Math.min((elem.width() / (settings.compressor)), parseFloat(settings.maxSize)), parseFloat(settings.minSize))) $("tr th, tr td", elem).css "font-size", fontSize + "px" # elems.push elem $(window).on "resize", -> $(elems).each -> elem = $(this) # set cell font sizes fontSize = Math.floor(Math.max(Math.min((elem.width() / (elem.attr('data-compression'))), parseFloat(elem.attr('data-max'))), parseFloat(elem.attr('data-min')))) $("tr th, tr td", elem).css "font-size", fontSize + "px" ) jQuery
true
### * * jQuery ResponsiveTables by PI:NAME:<NAME>END_PI - https://github.com/ghepting/responsiveTables * * Open source under the BSD License. * * Copyright © 2013 PI:NAME:<NAME>END_PI. All rights reserved. * ### (($) -> elems = [] $.fn.responsiveTable = (options) -> settings = compressor: options.compressor or 10 minSize: options.minSize or Number.NEGATIVE_INFINITY maxSize: options.maxSize or Number.POSITIVE_INFINITY padding: 2 height: "auto" # '100%' will fit tables (and containers) to viewport height as well adjust_parents: true # if height specified, force parent elements to be height 100% @each -> elem = $(this) elem.attr('data-compression',settings.compressor) elem.attr('data-min',settings.minSize) elem.attr('data-max',settings.maxSize) elem.attr('data-padding',settings.padding) # count columns columns = $("tr", elem).first().children("th, td").length # count rows rows = $("tr", elem).length unless settings.height is "auto" # set height of table $this.css "height", settings.height # set height of each parent of table if settings.adjust_parents $this.parents().each -> $(this).css "height", "100%" # set column widths $("tr th, tr td", elem).css "width", Math.floor(100 / columns) + "%" # set row heights $("tr th, tr td", elem).css "height", Math.floor(100 / rows) + "%" # set cell font sizes fontSize = Math.floor(Math.max(Math.min((elem.width() / (settings.compressor)), parseFloat(settings.maxSize)), parseFloat(settings.minSize))) $("tr th, tr td", elem).css "font-size", fontSize + "px" # elems.push elem $(window).on "resize", -> $(elems).each -> elem = $(this) # set cell font sizes fontSize = Math.floor(Math.max(Math.min((elem.width() / (elem.attr('data-compression'))), parseFloat(elem.attr('data-max'))), parseFloat(elem.attr('data-min')))) $("tr th, tr td", elem).css "font-size", fontSize + "px" ) jQuery
[ { "context": "ags\", type: [\"Array\"], default: []\n \n @scope \"byBaldwin\", firstName: \"=~\": \"Baldwin\"\n @scope \"thisWeek\",", "end": 255, "score": 0.9790275692939758, "start": 248, "tag": "USERNAME", "value": "Baldwin" }, { "context": "lt: []\n \n @scope \"byBaldwin\", ...
test/test-app/app/models/user.coffee
ludicast/tower
1
class App.User extends Tower.Model @field "id", type: "Id" @field "firstName" @field "createdAt", type: "Time", default: -> new Date() @field "likes", type: "Integer", default: 0 @field "tags", type: ["Array"], default: [] @scope "byBaldwin", firstName: "=~": "Baldwin" @scope "thisWeek", @where createdAt: ">=": -> require('moment')().subtract('days', 7) @hasMany "posts", type: "Page", cache: true # postIds @hasMany "comments", source: "commenter" @validates "firstName", presence: true @timestamps()
156444
class App.User extends Tower.Model @field "id", type: "Id" @field "firstName" @field "createdAt", type: "Time", default: -> new Date() @field "likes", type: "Integer", default: 0 @field "tags", type: ["Array"], default: [] @scope "byBaldwin", firstName: "=~": "<NAME>" @scope "thisWeek", @where createdAt: ">=": -> require('moment')().subtract('days', 7) @hasMany "posts", type: "Page", cache: true # postIds @hasMany "comments", source: "commenter" @validates "firstName", presence: true @timestamps()
true
class App.User extends Tower.Model @field "id", type: "Id" @field "firstName" @field "createdAt", type: "Time", default: -> new Date() @field "likes", type: "Integer", default: 0 @field "tags", type: ["Array"], default: [] @scope "byBaldwin", firstName: "=~": "PI:NAME:<NAME>END_PI" @scope "thisWeek", @where createdAt: ">=": -> require('moment')().subtract('days', 7) @hasMany "posts", type: "Page", cache: true # postIds @hasMany "comments", source: "commenter" @validates "firstName", presence: true @timestamps()
[ { "context": "e) ->\n handle = Util.formatNameAsUnixHandle \"Fahad Ibnay Heylaal\"\n expect(handle).to.deep.equal \"FIH\"\n\n ", "end": 496, "score": 0.9998142719268799, "start": 477, "tag": "NAME", "value": "Fahad Ibnay Heylaal" }, { "context": "FIH\"\n\n handle ...
test/test-util.coffee
kvz/baseamp
4
should = require("chai").should() debug = require("debug")("Baseamp:test-util") util = require "util" fs = require "fs" expect = require("chai").expect fixture_dir = "#{__dirname}/fixtures" Util = require "../src/Util" describe "todo", -> @timeout 10000 # <-- This is the Mocha timeout, allowing tests to run longer describe "_formatName", -> it "should be a unix handle", (done) -> handle = Util.formatNameAsUnixHandle "Fahad Ibnay Heylaal" expect(handle).to.deep.equal "FIH" handle = Util.formatNameAsUnixHandle "Kevin van Zonneveld" expect(handle).to.deep.equal "KVZ" handle = Util.formatNameAsUnixHandle "Tim Koschützki" expect(handle).to.deep.equal "TIK" handle = Util.formatNameAsUnixHandle "Joe Danziger" expect(handle).to.deep.equal "JOD" handle = Util.formatNameAsUnixHandle "JAW van Hocks" expect(handle).to.deep.equal "JVH" handle = Util.formatNameAsUnixHandle "K.M. van Schagen" expect(handle).to.deep.equal "KVS" handle = Util.formatNameAsUnixHandle "K.M. Schagen" expect(handle).to.deep.equal "KMS" done()
160879
should = require("chai").should() debug = require("debug")("Baseamp:test-util") util = require "util" fs = require "fs" expect = require("chai").expect fixture_dir = "#{__dirname}/fixtures" Util = require "../src/Util" describe "todo", -> @timeout 10000 # <-- This is the Mocha timeout, allowing tests to run longer describe "_formatName", -> it "should be a unix handle", (done) -> handle = Util.formatNameAsUnixHandle "<NAME>" expect(handle).to.deep.equal "FIH" handle = Util.formatNameAsUnixHandle "<NAME>" expect(handle).to.deep.equal "KVZ" handle = Util.formatNameAsUnixHandle "<NAME>" expect(handle).to.deep.equal "TIK" handle = Util.formatNameAsUnixHandle "<NAME>" expect(handle).to.deep.equal "JOD" handle = Util.formatNameAsUnixHandle "<NAME>" expect(handle).to.deep.equal "JVH" handle = Util.formatNameAsUnixHandle "<NAME>" expect(handle).to.deep.equal "KVS" handle = Util.formatNameAsUnixHandle "<NAME>" expect(handle).to.deep.equal "KMS" done()
true
should = require("chai").should() debug = require("debug")("Baseamp:test-util") util = require "util" fs = require "fs" expect = require("chai").expect fixture_dir = "#{__dirname}/fixtures" Util = require "../src/Util" describe "todo", -> @timeout 10000 # <-- This is the Mocha timeout, allowing tests to run longer describe "_formatName", -> it "should be a unix handle", (done) -> handle = Util.formatNameAsUnixHandle "PI:NAME:<NAME>END_PI" expect(handle).to.deep.equal "FIH" handle = Util.formatNameAsUnixHandle "PI:NAME:<NAME>END_PI" expect(handle).to.deep.equal "KVZ" handle = Util.formatNameAsUnixHandle "PI:NAME:<NAME>END_PI" expect(handle).to.deep.equal "TIK" handle = Util.formatNameAsUnixHandle "PI:NAME:<NAME>END_PI" expect(handle).to.deep.equal "JOD" handle = Util.formatNameAsUnixHandle "PI:NAME:<NAME>END_PI" expect(handle).to.deep.equal "JVH" handle = Util.formatNameAsUnixHandle "PI:NAME:<NAME>END_PI" expect(handle).to.deep.equal "KVS" handle = Util.formatNameAsUnixHandle "PI:NAME:<NAME>END_PI" expect(handle).to.deep.equal "KMS" done()
[ { "context": " mail_tel : user\n password : password\n .then (res) ->\n return Promise", "end": 2178, "score": 0.9972511529922485, "start": 2170, "tag": "PASSWORD", "value": "password" }, { "context": "ookie = new ToughCookie.Cookie\n ...
src/NicoSession.coffee
taku-o/node-nicovideo-api
28
{Emitter} = require "event-kit" cheerio = require "cheerio" Request = require "request-promise" ToughCookie = require "tough-cookie" {SerializeCookieStore} = require "tough-cookie-serialize" Deferred = require "promise-native-deferred" NicoUrl = require "./NicoURL" NicoException = require "./NicoException" NicoLiveAPI = require "./live/NicoLiveApi" NicoVideoAPI = require "./video/NicoVideoApi" NicoMyListAPI = require "./mylist/NicoMyListApi" NicoUserAPI = require "./user/NicoUserAPI" class NicoSession @services : new WeakMap ###* # @property live # @type NicoLive ### ###* # @property video # @type NicoVideo ### ###* # @property mylist # @type NicoMyList ### ###* # @property sessionId # @type String ### ###* # @property cookie # @type request.CookieJar ### constructor : -> Object.defineProperties @, live : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.live ?= new NicoLiveAPI @ video : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.video ?= new NicoVideoAPI @ mylist : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.mylist ?= new NicoMyListAPI @ user : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.user ?= new NicoUserAPI @ ###* # 再ログインします。 # @return {Promise} ### relogin : (user, password) -> Request.post resolveWithFullResponse : true followAllRedirects : true url : NicoUrl.Auth.LOGIN jar : @cookie form : mail_tel : user password : password .then (res) -> return Promise.reject("Nicovideo has in maintenance.") if res.statusCode is 503 ###* # ログアウトします。 # @method logout # @return {Promise} ### logout : -> Request.post resolveWithFullResponse : true url : NicoUrl.Auth.LOGOUT jar : @cookie .then (res) => return Promise.reject("Nicovideo has in maintenance.") if res.statusCode is 503 ###* # セッションが有効であるか調べます。 # @method isActive # @return {Promise} # ネットワークエラー時にrejectされます # - Resolve: (state: Boolean) ### isActive : -> # ログインしてないと使えないAPIを叩く Request.get resolveWithFullResponse : true url : NicoUrl.Auth.LOGINTEST jar : @cookie .then (res) -> $res = cheerio res.body $err = $res.find "error code" Promise.resolve($err.length is 0) toJSON : -> JSON.parse @cookie._jar.store.toString() ###* # このインスタンスを破棄します。 # @method dispose ### module.exports = ###* # @return {Promise} ### fromJSON : (object, user = null, password = null) -> defer = new Deferred store = new SerializeCookieStore() store.fromString(JSON.stringify(object)) cookie = Request.jar(store) session = new NicoSession password? and Store.set(session, password) user? and Object.defineProperty session, "_user", {value : user} Object.defineProperty session, "cookie", {value : cookie} store.findCookie "nicovideo.jp", "/", "user_session", (err, cookie) -> return if err? or (not cookie?) defer.reject new NicoException message : "Cookie 'user_session' not found." session._sessionId = cookie.value defer.resolve session defer.promise ###* # @method restoreFromSessionId # @param {String} sessionId ### fromSessionId : (sessionId) -> defer = new Deferred session = new NicoSession store = new SerializeCookieStore cookieJar = Request.jar store nicoCookie = new ToughCookie.Cookie key : "user_session" value : sessionId domain : "nicovideo.jp" path : "/" httpOnly : false store.putCookie nicoCookie, -> session.sessionId = sessionId Object.defineProperties session, _user : value : null cookie : value : cookieJar sessionId : configurable : true value : sessionId defer.resolve session defer.promise ###* # ニコニコ動画のログインセッションを確立します。 # @param {String} user ログインユーザーID # @param {String} password ログインパスワード # @return {Promise} ### login : (user, password) -> cookie = Request.jar(new SerializeCookieStore) Request.post resolveWithFullResponse : true followAllRedirects : true url : NicoUrl.Auth.LOGIN jar : cookie form : mail_tel : user password : password .then (res) => defer = new Deferred if res.statusCode is 503 defer.reject "Nicovideo has in maintenance." return # try get cookie # console.log self._cookie cookie._jar.store .findCookie "nicovideo.jp", "/", "user_session", (err, cookie) -> if cookie? defer.resolve cookie.value else if err? defer.reject "Authorize failed" else defer.reject "Authorize failed (reason unknown)" return defer.promise .then (sessionId) -> session = new NicoSession session.sessionId = sessionId Object.defineProperties session, cookie : value : cookie sessionId : configurable : true value : sessionId Promise.resolve(session)
4144
{Emitter} = require "event-kit" cheerio = require "cheerio" Request = require "request-promise" ToughCookie = require "tough-cookie" {SerializeCookieStore} = require "tough-cookie-serialize" Deferred = require "promise-native-deferred" NicoUrl = require "./NicoURL" NicoException = require "./NicoException" NicoLiveAPI = require "./live/NicoLiveApi" NicoVideoAPI = require "./video/NicoVideoApi" NicoMyListAPI = require "./mylist/NicoMyListApi" NicoUserAPI = require "./user/NicoUserAPI" class NicoSession @services : new WeakMap ###* # @property live # @type NicoLive ### ###* # @property video # @type NicoVideo ### ###* # @property mylist # @type NicoMyList ### ###* # @property sessionId # @type String ### ###* # @property cookie # @type request.CookieJar ### constructor : -> Object.defineProperties @, live : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.live ?= new NicoLiveAPI @ video : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.video ?= new NicoVideoAPI @ mylist : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.mylist ?= new NicoMyListAPI @ user : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.user ?= new NicoUserAPI @ ###* # 再ログインします。 # @return {Promise} ### relogin : (user, password) -> Request.post resolveWithFullResponse : true followAllRedirects : true url : NicoUrl.Auth.LOGIN jar : @cookie form : mail_tel : user password : <PASSWORD> .then (res) -> return Promise.reject("Nicovideo has in maintenance.") if res.statusCode is 503 ###* # ログアウトします。 # @method logout # @return {Promise} ### logout : -> Request.post resolveWithFullResponse : true url : NicoUrl.Auth.LOGOUT jar : @cookie .then (res) => return Promise.reject("Nicovideo has in maintenance.") if res.statusCode is 503 ###* # セッションが有効であるか調べます。 # @method isActive # @return {Promise} # ネットワークエラー時にrejectされます # - Resolve: (state: Boolean) ### isActive : -> # ログインしてないと使えないAPIを叩く Request.get resolveWithFullResponse : true url : NicoUrl.Auth.LOGINTEST jar : @cookie .then (res) -> $res = cheerio res.body $err = $res.find "error code" Promise.resolve($err.length is 0) toJSON : -> JSON.parse @cookie._jar.store.toString() ###* # このインスタンスを破棄します。 # @method dispose ### module.exports = ###* # @return {Promise} ### fromJSON : (object, user = null, password = null) -> defer = new Deferred store = new SerializeCookieStore() store.fromString(JSON.stringify(object)) cookie = Request.jar(store) session = new NicoSession password? and Store.set(session, password) user? and Object.defineProperty session, "_user", {value : user} Object.defineProperty session, "cookie", {value : cookie} store.findCookie "nicovideo.jp", "/", "user_session", (err, cookie) -> return if err? or (not cookie?) defer.reject new NicoException message : "Cookie 'user_session' not found." session._sessionId = cookie.value defer.resolve session defer.promise ###* # @method restoreFromSessionId # @param {String} sessionId ### fromSessionId : (sessionId) -> defer = new Deferred session = new NicoSession store = new SerializeCookieStore cookieJar = Request.jar store nicoCookie = new ToughCookie.Cookie key : "<KEY>" value : sessionId domain : "nicovideo.jp" path : "/" httpOnly : false store.putCookie nicoCookie, -> session.sessionId = sessionId Object.defineProperties session, _user : value : null cookie : value : cookieJar sessionId : configurable : true value : sessionId defer.resolve session defer.promise ###* # ニコニコ動画のログインセッションを確立します。 # @param {String} user ログインユーザーID # @param {String} password <PASSWORD> # @return {Promise} ### login : (user, password) -> cookie = Request.jar(new SerializeCookieStore) Request.post resolveWithFullResponse : true followAllRedirects : true url : NicoUrl.Auth.LOGIN jar : cookie form : mail_tel : user password : <PASSWORD> .then (res) => defer = new Deferred if res.statusCode is 503 defer.reject "Nicovideo has in maintenance." return # try get cookie # console.log self._cookie cookie._jar.store .findCookie "nicovideo.jp", "/", "user_session", (err, cookie) -> if cookie? defer.resolve cookie.value else if err? defer.reject "Authorize failed" else defer.reject "Authorize failed (reason unknown)" return defer.promise .then (sessionId) -> session = new NicoSession session.sessionId = sessionId Object.defineProperties session, cookie : value : cookie sessionId : configurable : true value : sessionId Promise.resolve(session)
true
{Emitter} = require "event-kit" cheerio = require "cheerio" Request = require "request-promise" ToughCookie = require "tough-cookie" {SerializeCookieStore} = require "tough-cookie-serialize" Deferred = require "promise-native-deferred" NicoUrl = require "./NicoURL" NicoException = require "./NicoException" NicoLiveAPI = require "./live/NicoLiveApi" NicoVideoAPI = require "./video/NicoVideoApi" NicoMyListAPI = require "./mylist/NicoMyListApi" NicoUserAPI = require "./user/NicoUserAPI" class NicoSession @services : new WeakMap ###* # @property live # @type NicoLive ### ###* # @property video # @type NicoVideo ### ###* # @property mylist # @type NicoMyList ### ###* # @property sessionId # @type String ### ###* # @property cookie # @type request.CookieJar ### constructor : -> Object.defineProperties @, live : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.live ?= new NicoLiveAPI @ video : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.video ?= new NicoVideoAPI @ mylist : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.mylist ?= new NicoMyListAPI @ user : get : -> store = NicoSession.services.get(@) store or NicoSession.services.set(@, store = {}) store.user ?= new NicoUserAPI @ ###* # 再ログインします。 # @return {Promise} ### relogin : (user, password) -> Request.post resolveWithFullResponse : true followAllRedirects : true url : NicoUrl.Auth.LOGIN jar : @cookie form : mail_tel : user password : PI:PASSWORD:<PASSWORD>END_PI .then (res) -> return Promise.reject("Nicovideo has in maintenance.") if res.statusCode is 503 ###* # ログアウトします。 # @method logout # @return {Promise} ### logout : -> Request.post resolveWithFullResponse : true url : NicoUrl.Auth.LOGOUT jar : @cookie .then (res) => return Promise.reject("Nicovideo has in maintenance.") if res.statusCode is 503 ###* # セッションが有効であるか調べます。 # @method isActive # @return {Promise} # ネットワークエラー時にrejectされます # - Resolve: (state: Boolean) ### isActive : -> # ログインしてないと使えないAPIを叩く Request.get resolveWithFullResponse : true url : NicoUrl.Auth.LOGINTEST jar : @cookie .then (res) -> $res = cheerio res.body $err = $res.find "error code" Promise.resolve($err.length is 0) toJSON : -> JSON.parse @cookie._jar.store.toString() ###* # このインスタンスを破棄します。 # @method dispose ### module.exports = ###* # @return {Promise} ### fromJSON : (object, user = null, password = null) -> defer = new Deferred store = new SerializeCookieStore() store.fromString(JSON.stringify(object)) cookie = Request.jar(store) session = new NicoSession password? and Store.set(session, password) user? and Object.defineProperty session, "_user", {value : user} Object.defineProperty session, "cookie", {value : cookie} store.findCookie "nicovideo.jp", "/", "user_session", (err, cookie) -> return if err? or (not cookie?) defer.reject new NicoException message : "Cookie 'user_session' not found." session._sessionId = cookie.value defer.resolve session defer.promise ###* # @method restoreFromSessionId # @param {String} sessionId ### fromSessionId : (sessionId) -> defer = new Deferred session = new NicoSession store = new SerializeCookieStore cookieJar = Request.jar store nicoCookie = new ToughCookie.Cookie key : "PI:KEY:<KEY>END_PI" value : sessionId domain : "nicovideo.jp" path : "/" httpOnly : false store.putCookie nicoCookie, -> session.sessionId = sessionId Object.defineProperties session, _user : value : null cookie : value : cookieJar sessionId : configurable : true value : sessionId defer.resolve session defer.promise ###* # ニコニコ動画のログインセッションを確立します。 # @param {String} user ログインユーザーID # @param {String} password PI:PASSWORD:<PASSWORD>END_PI # @return {Promise} ### login : (user, password) -> cookie = Request.jar(new SerializeCookieStore) Request.post resolveWithFullResponse : true followAllRedirects : true url : NicoUrl.Auth.LOGIN jar : cookie form : mail_tel : user password : PI:PASSWORD:<PASSWORD>END_PI .then (res) => defer = new Deferred if res.statusCode is 503 defer.reject "Nicovideo has in maintenance." return # try get cookie # console.log self._cookie cookie._jar.store .findCookie "nicovideo.jp", "/", "user_session", (err, cookie) -> if cookie? defer.resolve cookie.value else if err? defer.reject "Authorize failed" else defer.reject "Authorize failed (reason unknown)" return defer.promise .then (sessionId) -> session = new NicoSession session.sessionId = sessionId Object.defineProperties session, cookie : value : cookie sessionId : configurable : true value : sessionId Promise.resolve(session)
[ { "context": "mailgun.org:9bad59febb44cf256ff0766960922980@smtp.mailgun.org:587'\n process.env.MAIL_URL = 'smtp://not", "end": 255, "score": 0.6061450242996216, "start": 248, "tag": "EMAIL", "value": "mailgun" }, { "context": "env.MAIL_URL = 'smtp://notify%40mail.tiegushi.com:Ac...
PushServer/server/test_email_url.coffee
Ritesh1991/mobile_app_server
0
if Meteor.isServer Meteor.startup ()-> if (not process.env.MAIL_URL) or process.env.MAIL_URL is '' #process.env.MAIL_URL = 'smtp://postmaster%40sandboxb40d25ffd9474e8b88a566924d4167bb.mailgun.org:9bad59febb44cf256ff0766960922980@smtp.mailgun.org:587' process.env.MAIL_URL = 'smtp://notify%40mail.tiegushi.com:Actiontec753951@smtpdm.aliyun.com:465'
83604
if Meteor.isServer Meteor.startup ()-> if (not process.env.MAIL_URL) or process.env.MAIL_URL is '' #process.env.MAIL_URL = 'smtp://postmaster%40sandboxb40d25ffd9474e8b88a566924d4167bb.mailgun.org:9bad59febb44cf256ff0766960922980@smtp.<EMAIL>.org:587' process.env.MAIL_URL = 'smtp://notify%40mail.tiegushi.com:<EMAIL>:465'
true
if Meteor.isServer Meteor.startup ()-> if (not process.env.MAIL_URL) or process.env.MAIL_URL is '' #process.env.MAIL_URL = 'smtp://postmaster%40sandboxb40d25ffd9474e8b88a566924d4167bb.mailgun.org:9bad59febb44cf256ff0766960922980@smtp.PI:EMAIL:<EMAIL>END_PI.org:587' process.env.MAIL_URL = 'smtp://notify%40mail.tiegushi.com:PI:EMAIL:<EMAIL>END_PI:465'
[ { "context": "t or force\n util.log \"Sending 'teams_new' to '#{@email}'\".yellow\n team = @parentArray._parent\n pos", "end": 498, "score": 0.6377660036087036, "start": 492, "tag": "USERNAME", "value": "@email" }, { "context": " postageapp.apiCall @email, 'teams_new', nul...
models/invite.coffee
sabman/website
4
mongoose = require 'mongoose' rbytes = require 'rbytes' util = require 'util' env = require '../config/env' postageapp = require('postageapp')(env.secrets.postageapp) qs = require 'querystring' InviteSchema = module.exports = new mongoose.Schema email: String sent: type: Boolean default: no code: type: String default: -> rbytes.randomBytes(12).toString('base64') InviteSchema.method 'send', (force) -> if not @sent or force util.log "Sending 'teams_new' to '#{@email}'".yellow team = @parentArray._parent postageapp.apiCall @email, 'teams_new', null, 'all@nodeknockout.com', team_id: team.id team_name: team.name invite_code: qs.escape @code @sent = yes mongoose.model 'Invite', InviteSchema
168032
mongoose = require 'mongoose' rbytes = require 'rbytes' util = require 'util' env = require '../config/env' postageapp = require('postageapp')(env.secrets.postageapp) qs = require 'querystring' InviteSchema = module.exports = new mongoose.Schema email: String sent: type: Boolean default: no code: type: String default: -> rbytes.randomBytes(12).toString('base64') InviteSchema.method 'send', (force) -> if not @sent or force util.log "Sending 'teams_new' to '#{@email}'".yellow team = @parentArray._parent postageapp.apiCall @email, 'teams_new', null, '<EMAIL>', team_id: team.id team_name: team.name invite_code: qs.escape @code @sent = yes mongoose.model 'Invite', InviteSchema
true
mongoose = require 'mongoose' rbytes = require 'rbytes' util = require 'util' env = require '../config/env' postageapp = require('postageapp')(env.secrets.postageapp) qs = require 'querystring' InviteSchema = module.exports = new mongoose.Schema email: String sent: type: Boolean default: no code: type: String default: -> rbytes.randomBytes(12).toString('base64') InviteSchema.method 'send', (force) -> if not @sent or force util.log "Sending 'teams_new' to '#{@email}'".yellow team = @parentArray._parent postageapp.apiCall @email, 'teams_new', null, 'PI:EMAIL:<EMAIL>END_PI', team_id: team.id team_name: team.name invite_code: qs.escape @code @sent = yes mongoose.model 'Invite', InviteSchema
[ { "context": "e timeouts.\n#\n# MIT License\n#\n# Copyright (c) 2016 Dennis Raymondo van der Sluis\n#\n# Permission is hereby granted, free of charge,", "end": 148, "score": 0.9998842477798462, "start": 119, "tag": "NAME", "value": "Dennis Raymondo van der Sluis" } ]
control-timeout.coffee
phazelift/control-timeout
1
# # control-timeout - A timeout class for controlling one or multiple timeouts. # # MIT License # # Copyright (c) 2016 Dennis Raymondo van der Sluis # # 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. # types= require 'types.js' moduleName= 'control-timeout' class Timeout @setLog = ( log ) -> Timeout.log= types.forceFunction log @log = Timeout.setLog console?.log @delay = 0 constructor: ( delay ) -> @timeouts = {} @running = {} @delay = (Math.abs delay) or Timeout.delay exists: ( id ) -> @timeouts.hasOwnProperty id isRunning: ( id ) -> @running.hasOwnProperty id _stopOne: ( id ) -> if @isRunning id clearTimeout @running[ id ] delete @running[ id ] return @ stop: ( ids... ) -> if not ids.length then for id of @running @_stopOne id else for id in ids @_stopOne id return @ setDelay: ( id, delay ) -> if @exists id @timeouts[ id ].delay= types.forceNumber delay, @timeouts[ id ].delay getTimeout: ( id ) -> @running[ id ] _setTimeout: ( id, action, delay ) -> return @running[ id ]= setTimeout => delete @running[ id ] action() , delay run: ( id, args... ) -> timeouts= [] if not id then for id, timeout of @timeouts if not @isRunning id timeouts.push @_setTimeout id, timeout.action.bind(null, args...), timeout.delay else if @exists id timeouts.push @_setTimeout id, @timeouts[id].action.bind(null, args...), @timeouts[id].delay else Timeout.log moduleName+ ': timeout with id: "'+ id+ '" was not found' switch timeouts.length when 0 then return null when 1 then return timeouts[0] else return timeouts removeAll: () -> @stop() @timeouts= {} return @ remove: ( ids... ) -> if ids.length then for id in ids @_stopOne id delete @timeouts[ id ] else Timeout.log moduleName+ ': cannot remove, invalid or non-existing timeout!' return @ _add: ( id, action, delay ) -> if types.notString(id) or not id.length Timeout.log moduleName+ ': cannot add timeout, invalid or missing id!' else if @exists id Timeout.log moduleName+ ': cannot add timeout, id: '+ id+ ' exists already!' else @timeouts[ id ]= action : types.forceFunction action delay : Math.abs types.forceNumber( delay, @delay ) return @ add: ( id, action, delay ) -> if types.isObject id return @_add id.id, id.action, id.delay else return @_add id, action, delay module.exports= Timeout
19383
# # control-timeout - A timeout class for controlling one or multiple timeouts. # # MIT License # # Copyright (c) 2016 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # types= require 'types.js' moduleName= 'control-timeout' class Timeout @setLog = ( log ) -> Timeout.log= types.forceFunction log @log = Timeout.setLog console?.log @delay = 0 constructor: ( delay ) -> @timeouts = {} @running = {} @delay = (Math.abs delay) or Timeout.delay exists: ( id ) -> @timeouts.hasOwnProperty id isRunning: ( id ) -> @running.hasOwnProperty id _stopOne: ( id ) -> if @isRunning id clearTimeout @running[ id ] delete @running[ id ] return @ stop: ( ids... ) -> if not ids.length then for id of @running @_stopOne id else for id in ids @_stopOne id return @ setDelay: ( id, delay ) -> if @exists id @timeouts[ id ].delay= types.forceNumber delay, @timeouts[ id ].delay getTimeout: ( id ) -> @running[ id ] _setTimeout: ( id, action, delay ) -> return @running[ id ]= setTimeout => delete @running[ id ] action() , delay run: ( id, args... ) -> timeouts= [] if not id then for id, timeout of @timeouts if not @isRunning id timeouts.push @_setTimeout id, timeout.action.bind(null, args...), timeout.delay else if @exists id timeouts.push @_setTimeout id, @timeouts[id].action.bind(null, args...), @timeouts[id].delay else Timeout.log moduleName+ ': timeout with id: "'+ id+ '" was not found' switch timeouts.length when 0 then return null when 1 then return timeouts[0] else return timeouts removeAll: () -> @stop() @timeouts= {} return @ remove: ( ids... ) -> if ids.length then for id in ids @_stopOne id delete @timeouts[ id ] else Timeout.log moduleName+ ': cannot remove, invalid or non-existing timeout!' return @ _add: ( id, action, delay ) -> if types.notString(id) or not id.length Timeout.log moduleName+ ': cannot add timeout, invalid or missing id!' else if @exists id Timeout.log moduleName+ ': cannot add timeout, id: '+ id+ ' exists already!' else @timeouts[ id ]= action : types.forceFunction action delay : Math.abs types.forceNumber( delay, @delay ) return @ add: ( id, action, delay ) -> if types.isObject id return @_add id.id, id.action, id.delay else return @_add id, action, delay module.exports= Timeout
true
# # control-timeout - A timeout class for controlling one or multiple timeouts. # # MIT License # # Copyright (c) 2016 PI:NAME:<NAME>END_PI # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # types= require 'types.js' moduleName= 'control-timeout' class Timeout @setLog = ( log ) -> Timeout.log= types.forceFunction log @log = Timeout.setLog console?.log @delay = 0 constructor: ( delay ) -> @timeouts = {} @running = {} @delay = (Math.abs delay) or Timeout.delay exists: ( id ) -> @timeouts.hasOwnProperty id isRunning: ( id ) -> @running.hasOwnProperty id _stopOne: ( id ) -> if @isRunning id clearTimeout @running[ id ] delete @running[ id ] return @ stop: ( ids... ) -> if not ids.length then for id of @running @_stopOne id else for id in ids @_stopOne id return @ setDelay: ( id, delay ) -> if @exists id @timeouts[ id ].delay= types.forceNumber delay, @timeouts[ id ].delay getTimeout: ( id ) -> @running[ id ] _setTimeout: ( id, action, delay ) -> return @running[ id ]= setTimeout => delete @running[ id ] action() , delay run: ( id, args... ) -> timeouts= [] if not id then for id, timeout of @timeouts if not @isRunning id timeouts.push @_setTimeout id, timeout.action.bind(null, args...), timeout.delay else if @exists id timeouts.push @_setTimeout id, @timeouts[id].action.bind(null, args...), @timeouts[id].delay else Timeout.log moduleName+ ': timeout with id: "'+ id+ '" was not found' switch timeouts.length when 0 then return null when 1 then return timeouts[0] else return timeouts removeAll: () -> @stop() @timeouts= {} return @ remove: ( ids... ) -> if ids.length then for id in ids @_stopOne id delete @timeouts[ id ] else Timeout.log moduleName+ ': cannot remove, invalid or non-existing timeout!' return @ _add: ( id, action, delay ) -> if types.notString(id) or not id.length Timeout.log moduleName+ ': cannot add timeout, invalid or missing id!' else if @exists id Timeout.log moduleName+ ': cannot add timeout, id: '+ id+ ' exists already!' else @timeouts[ id ]= action : types.forceFunction action delay : Math.abs types.forceNumber( delay, @delay ) return @ add: ( id, action, delay ) -> if types.isObject id return @_add id.id, id.action, id.delay else return @_add id, action, delay module.exports= Timeout
[ { "context": "A commonjs, coffeescript FDF generator inspired by Justin Koivisto's \"KOIVI HTML Form to FDF Parser for PHP (C) 2004", "end": 68, "score": 0.9998984336853027, "start": 53, "tag": "NAME", "value": "Justin Koivisto" }, { "context": "i.com/fill-pdf-form-fields/tutorial.ph...
packages/npm-container/.npm/package/node_modules/fdf/index.coffee
18F/iaa-mvp
3
# A commonjs, coffeescript FDF generator inspired by Justin Koivisto's "KOIVI HTML Form to FDF Parser for PHP (C) 2004" # http://koivi.com/fill-pdf-form-fields/tutorial.php # @author Clark Van Oyen md5 = require "MD5" fs = require "fs" # fdf.generate # --------- # Generates an FDF (Form Data File) from a provided input map from field name to field value. # # @param form The input map from field name to field value. ie) {name: 'Clark', type: 'superhero'} # @param file The url or file path of the PDF file which this data is for. # @result FDF representation of the form. You will usually write this to a file. module.exports.generate = (form, file) -> header = (String.fromCharCode 226) + (String.fromCharCode 227) + (String.fromCharCode 207) + (String.fromCharCode 211) data = """%FDF-1.2 %#{header} 1 0 obj << /FDF << /Fields [ """ for field, val of form if typeof val is "array" data += """<< /V(#{val}) /T[""" for opt in val data += "(" + opt + ")" data += "]>>" else data += """<< /V(#{val}) /T(#{field}) >> """ #time_hash = md5 (new Date()).valueOf() data += """] >> >> endobj trailer << /Root 1 0 R >> %%EOF """ data
42429
# A commonjs, coffeescript FDF generator inspired by <NAME>'s "KOIVI HTML Form to FDF Parser for PHP (C) 2004" # http://koivi.com/fill-pdf-form-fields/tutorial.php # @author <NAME> md5 = require "MD5" fs = require "fs" # fdf.generate # --------- # Generates an FDF (Form Data File) from a provided input map from field name to field value. # # @param form The input map from field name to field value. ie) {name: '<NAME>', type: 'superhero'} # @param file The url or file path of the PDF file which this data is for. # @result FDF representation of the form. You will usually write this to a file. module.exports.generate = (form, file) -> header = (String.fromCharCode 226) + (String.fromCharCode 227) + (String.fromCharCode 207) + (String.fromCharCode 211) data = """%FDF-1.2 %#{header} 1 0 obj << /FDF << /Fields [ """ for field, val of form if typeof val is "array" data += """<< /V(#{val}) /T[""" for opt in val data += "(" + opt + ")" data += "]>>" else data += """<< /V(#{val}) /T(#{field}) >> """ #time_hash = md5 (new Date()).valueOf() data += """] >> >> endobj trailer << /Root 1 0 R >> %%EOF """ data
true
# A commonjs, coffeescript FDF generator inspired by PI:NAME:<NAME>END_PI's "KOIVI HTML Form to FDF Parser for PHP (C) 2004" # http://koivi.com/fill-pdf-form-fields/tutorial.php # @author PI:NAME:<NAME>END_PI md5 = require "MD5" fs = require "fs" # fdf.generate # --------- # Generates an FDF (Form Data File) from a provided input map from field name to field value. # # @param form The input map from field name to field value. ie) {name: 'PI:NAME:<NAME>END_PI', type: 'superhero'} # @param file The url or file path of the PDF file which this data is for. # @result FDF representation of the form. You will usually write this to a file. module.exports.generate = (form, file) -> header = (String.fromCharCode 226) + (String.fromCharCode 227) + (String.fromCharCode 207) + (String.fromCharCode 211) data = """%FDF-1.2 %#{header} 1 0 obj << /FDF << /Fields [ """ for field, val of form if typeof val is "array" data += """<< /V(#{val}) /T[""" for opt in val data += "(" + opt + ")" data += "]>>" else data += """<< /V(#{val}) /T(#{field}) >> """ #time_hash = md5 (new Date()).valueOf() data += """] >> >> endobj trailer << /Root 1 0 R >> %%EOF """ data
[ { "context": "erview Tests for constructor-super rule.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------", "end": 79, "score": 0.9998633861541748, "start": 65, "tag": "NAME", "value": "Toru Nagashima" }, { "context": " return a\n '''\n\n # h...
src/tests/rules/constructor-super.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for constructor-super rule. # @author Toru Nagashima ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/constructor-super' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'constructor-super', rule, valid: [ # non derived classes. ''' class A ''' ''' class A constructor: -> ''' ### # inherit from non constructors. # those are valid if we don't define the constructor. ### ''' class A extends null ''' # derived classes. ''' class A extends B ''' ''' class A extends B constructor: -> super() ''' ''' class A extends B constructor: -> if true super() else super() ''' ''' class A extends (class B) constructor: -> super() ''' ''' class A extends (B = C) constructor: -> super() ''' ''' class A extends (B or C) constructor: -> super() ''' ''' class A extends (if a then B else C) constructor: -> super() ''' ''' class A extends (B; C) constructor: -> super() ''' # nested. ''' class A constructor: -> class B extends C constructor: -> super() ''' ''' class A extends B constructor: -> super() class C extends D constructor: -> super() ''' ''' class A extends B constructor: -> super() class C constructor: -> ''' # ignores out of constructors. ''' class A b: -> super() ''' # multi code path. ''' class A extends B constructor: -> if a then super() else super() ''' ''' class A extends B constructor: -> if a super() else super() ''' ''' class A extends B constructor: -> switch a when 0, 1 super() else super() ''' ''' class A extends B constructor: -> try finally super() ''' ''' class A extends B constructor: -> if a throw Error() super() ''' # returning value is a substitute of 'super()'. ''' class A extends B constructor: -> return a if yes super() ''' ''' class A extends null constructor: -> return a ''' ''' class A constructor: -> return a ''' # https://github.com/eslint/eslint/issues/5261 ''' class A extends B constructor: (a) -> super() for b from a @a() ''' # https://github.com/eslint/eslint/issues/5319 ''' class Foo extends Object constructor: (method) -> super() @method = method or -> ''' # # https://github.com/eslint/eslint/issues/5894 # ''' # class A # constructor: -> # return # super() # ''' # https://github.com/eslint/eslint/issues/8848 ''' class A extends B constructor: (props) -> super props try arr = [] for a from arr ; catch err ''' ] invalid: [ # # non derived classes. # code: ''' # class A # constructor: -> super() # ''' # errors: [messageId: 'unexpected', type: 'CallExpression'] # , # inherit from non constructors. code: ''' class A extends null constructor: -> super() ''' errors: [messageId: 'badSuper', type: 'CallExpression'] , code: ''' class A extends null constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends 100 constructor: -> super() ''' errors: [messageId: 'badSuper', type: 'CallExpression'] , code: ''' class A extends 'test' constructor: -> super() ''' errors: [messageId: 'badSuper', type: 'CallExpression'] , # derived classes. code: ''' class A extends B constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> for a from b super.foo() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , # nested execution scope. code: ''' class A extends B constructor: -> c = -> super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> c = => super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> class C extends D constructor: -> super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 2] , code: ''' class A extends B constructor: -> C = class extends D constructor: -> super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 2] , code: ''' class A extends B constructor: -> super() class C extends D constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 5] , code: ''' class A extends B constructor: -> super() C = class extends D constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 5] , # lacked in some code path. code: ''' class A extends B constructor: -> if a super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> if a ; else super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> a and super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> switch a when 0 super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> switch a when 0 ; else super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> try super() catch err ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> try a catch err super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> return if a super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , # duplicate. code: ''' class A extends B constructor: -> super() super() ''' errors: [messageId: 'duplicate', type: 'CallExpression', line: 4] , code: ''' class A extends B constructor: -> super() or super() ''' errors: [ messageId: 'duplicate', type: 'CallExpression', line: 3, column: 16 ] , code: ''' class A extends B constructor: -> super() ? super() ''' errors: [ messageId: 'duplicate', type: 'CallExpression', line: 3, column: 15 ] , code: ''' class A extends B constructor: -> super() if a super() ''' errors: [messageId: 'duplicate', type: 'CallExpression', line: 4] , code: ''' class A extends B constructor: (a) -> while a super() ''' errors: [ messageId: 'missingSome', type: 'MethodDefinition' , messageId: 'duplicate', type: 'CallExpression', line: 4 ] , # ignores `super()` on unreachable paths. code: ''' class A extends B constructor: -> return super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , # https://github.com/eslint/eslint/issues/8248 code: ''' class Foo extends Bar constructor: -> for a of b for c of d ; ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] ]
199542
###* # @fileoverview Tests for constructor-super rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/constructor-super' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'constructor-super', rule, valid: [ # non derived classes. ''' class A ''' ''' class A constructor: -> ''' ### # inherit from non constructors. # those are valid if we don't define the constructor. ### ''' class A extends null ''' # derived classes. ''' class A extends B ''' ''' class A extends B constructor: -> super() ''' ''' class A extends B constructor: -> if true super() else super() ''' ''' class A extends (class B) constructor: -> super() ''' ''' class A extends (B = C) constructor: -> super() ''' ''' class A extends (B or C) constructor: -> super() ''' ''' class A extends (if a then B else C) constructor: -> super() ''' ''' class A extends (B; C) constructor: -> super() ''' # nested. ''' class A constructor: -> class B extends C constructor: -> super() ''' ''' class A extends B constructor: -> super() class C extends D constructor: -> super() ''' ''' class A extends B constructor: -> super() class C constructor: -> ''' # ignores out of constructors. ''' class A b: -> super() ''' # multi code path. ''' class A extends B constructor: -> if a then super() else super() ''' ''' class A extends B constructor: -> if a super() else super() ''' ''' class A extends B constructor: -> switch a when 0, 1 super() else super() ''' ''' class A extends B constructor: -> try finally super() ''' ''' class A extends B constructor: -> if a throw Error() super() ''' # returning value is a substitute of 'super()'. ''' class A extends B constructor: -> return a if yes super() ''' ''' class A extends null constructor: -> return a ''' ''' class A constructor: -> return a ''' # https://github.com/eslint/eslint/issues/5261 ''' class A extends B constructor: (a) -> super() for b from a @a() ''' # https://github.com/eslint/eslint/issues/5319 ''' class Foo extends Object constructor: (method) -> super() @method = method or -> ''' # # https://github.com/eslint/eslint/issues/5894 # ''' # class A # constructor: -> # return # super() # ''' # https://github.com/eslint/eslint/issues/8848 ''' class A extends B constructor: (props) -> super props try arr = [] for a from arr ; catch err ''' ] invalid: [ # # non derived classes. # code: ''' # class A # constructor: -> super() # ''' # errors: [messageId: 'unexpected', type: 'CallExpression'] # , # inherit from non constructors. code: ''' class A extends null constructor: -> super() ''' errors: [messageId: 'badSuper', type: 'CallExpression'] , code: ''' class A extends null constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends 100 constructor: -> super() ''' errors: [messageId: 'badSuper', type: 'CallExpression'] , code: ''' class A extends 'test' constructor: -> super() ''' errors: [messageId: 'badSuper', type: 'CallExpression'] , # derived classes. code: ''' class A extends B constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> for a from b super.foo() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , # nested execution scope. code: ''' class A extends B constructor: -> c = -> super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> c = => super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> class C extends D constructor: -> super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 2] , code: ''' class A extends B constructor: -> C = class extends D constructor: -> super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 2] , code: ''' class A extends B constructor: -> super() class C extends D constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 5] , code: ''' class A extends B constructor: -> super() C = class extends D constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 5] , # lacked in some code path. code: ''' class A extends B constructor: -> if a super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> if a ; else super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> a and super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> switch a when 0 super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> switch a when 0 ; else super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> try super() catch err ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> try a catch err super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> return if a super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , # duplicate. code: ''' class A extends B constructor: -> super() super() ''' errors: [messageId: 'duplicate', type: 'CallExpression', line: 4] , code: ''' class A extends B constructor: -> super() or super() ''' errors: [ messageId: 'duplicate', type: 'CallExpression', line: 3, column: 16 ] , code: ''' class A extends B constructor: -> super() ? super() ''' errors: [ messageId: 'duplicate', type: 'CallExpression', line: 3, column: 15 ] , code: ''' class A extends B constructor: -> super() if a super() ''' errors: [messageId: 'duplicate', type: 'CallExpression', line: 4] , code: ''' class A extends B constructor: (a) -> while a super() ''' errors: [ messageId: 'missingSome', type: 'MethodDefinition' , messageId: 'duplicate', type: 'CallExpression', line: 4 ] , # ignores `super()` on unreachable paths. code: ''' class A extends B constructor: -> return super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , # https://github.com/eslint/eslint/issues/8248 code: ''' class Foo extends Bar constructor: -> for a of b for c of d ; ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] ]
true
###* # @fileoverview Tests for constructor-super rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/constructor-super' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'constructor-super', rule, valid: [ # non derived classes. ''' class A ''' ''' class A constructor: -> ''' ### # inherit from non constructors. # those are valid if we don't define the constructor. ### ''' class A extends null ''' # derived classes. ''' class A extends B ''' ''' class A extends B constructor: -> super() ''' ''' class A extends B constructor: -> if true super() else super() ''' ''' class A extends (class B) constructor: -> super() ''' ''' class A extends (B = C) constructor: -> super() ''' ''' class A extends (B or C) constructor: -> super() ''' ''' class A extends (if a then B else C) constructor: -> super() ''' ''' class A extends (B; C) constructor: -> super() ''' # nested. ''' class A constructor: -> class B extends C constructor: -> super() ''' ''' class A extends B constructor: -> super() class C extends D constructor: -> super() ''' ''' class A extends B constructor: -> super() class C constructor: -> ''' # ignores out of constructors. ''' class A b: -> super() ''' # multi code path. ''' class A extends B constructor: -> if a then super() else super() ''' ''' class A extends B constructor: -> if a super() else super() ''' ''' class A extends B constructor: -> switch a when 0, 1 super() else super() ''' ''' class A extends B constructor: -> try finally super() ''' ''' class A extends B constructor: -> if a throw Error() super() ''' # returning value is a substitute of 'super()'. ''' class A extends B constructor: -> return a if yes super() ''' ''' class A extends null constructor: -> return a ''' ''' class A constructor: -> return a ''' # https://github.com/eslint/eslint/issues/5261 ''' class A extends B constructor: (a) -> super() for b from a @a() ''' # https://github.com/eslint/eslint/issues/5319 ''' class Foo extends Object constructor: (method) -> super() @method = method or -> ''' # # https://github.com/eslint/eslint/issues/5894 # ''' # class A # constructor: -> # return # super() # ''' # https://github.com/eslint/eslint/issues/8848 ''' class A extends B constructor: (props) -> super props try arr = [] for a from arr ; catch err ''' ] invalid: [ # # non derived classes. # code: ''' # class A # constructor: -> super() # ''' # errors: [messageId: 'unexpected', type: 'CallExpression'] # , # inherit from non constructors. code: ''' class A extends null constructor: -> super() ''' errors: [messageId: 'badSuper', type: 'CallExpression'] , code: ''' class A extends null constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends 100 constructor: -> super() ''' errors: [messageId: 'badSuper', type: 'CallExpression'] , code: ''' class A extends 'test' constructor: -> super() ''' errors: [messageId: 'badSuper', type: 'CallExpression'] , # derived classes. code: ''' class A extends B constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> for a from b super.foo() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , # nested execution scope. code: ''' class A extends B constructor: -> c = -> super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> c = => super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> class C extends D constructor: -> super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 2] , code: ''' class A extends B constructor: -> C = class extends D constructor: -> super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 2] , code: ''' class A extends B constructor: -> super() class C extends D constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 5] , code: ''' class A extends B constructor: -> super() C = class extends D constructor: -> ''' errors: [messageId: 'missingAll', type: 'MethodDefinition', line: 5] , # lacked in some code path. code: ''' class A extends B constructor: -> if a super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> if a ; else super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> a and super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> switch a when 0 super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> switch a when 0 ; else super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> try super() catch err ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> try a catch err super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , code: ''' class A extends B constructor: -> return if a super() ''' errors: [messageId: 'missingSome', type: 'MethodDefinition'] , # duplicate. code: ''' class A extends B constructor: -> super() super() ''' errors: [messageId: 'duplicate', type: 'CallExpression', line: 4] , code: ''' class A extends B constructor: -> super() or super() ''' errors: [ messageId: 'duplicate', type: 'CallExpression', line: 3, column: 16 ] , code: ''' class A extends B constructor: -> super() ? super() ''' errors: [ messageId: 'duplicate', type: 'CallExpression', line: 3, column: 15 ] , code: ''' class A extends B constructor: -> super() if a super() ''' errors: [messageId: 'duplicate', type: 'CallExpression', line: 4] , code: ''' class A extends B constructor: (a) -> while a super() ''' errors: [ messageId: 'missingSome', type: 'MethodDefinition' , messageId: 'duplicate', type: 'CallExpression', line: 4 ] , # ignores `super()` on unreachable paths. code: ''' class A extends B constructor: -> return super() ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] , # https://github.com/eslint/eslint/issues/8248 code: ''' class Foo extends Bar constructor: -> for a of b for c of d ; ''' errors: [messageId: 'missingAll', type: 'MethodDefinition'] ]
[ { "context": "se login'\n browser.setValue '.x-input-email', 'patrick@purpleapp.com'\n browser.setValue '.x-input-password', 'patri", "end": 500, "score": 0.99992835521698, "start": 479, "tag": "EMAIL", "value": "patrick@purpleapp.com" }, { "context": "p.com'\n browser.setVa...
src/test/test/specs/Accounts.coffee
Purple-Services/app
2
Utils = require('./test_utils.js') assert = require('assert') sinon = require('sinon') describe 'webdriver.io page', -> it 'should have the right title', -> console.log 'should have the right title' browser.url Utils.clientUrl title = browser.getTitle() assert.equal title, 'Purple' return it 'should login', -> console.log 'should login line#16' Utils.getMenu 'div=Login' console.log 'choose login' browser.setValue '.x-input-email', 'patrick@purpleapp.com' browser.setValue '.x-input-password', 'patrick' console.log 'login info' browser.click '#loginButtonContainer' console.log 'login' Utils.waitUntil 'visible', '#requestGasButton' return it 'should test accounts', -> console.log 'should test accounts' Utils.getMenu 'div=Account' console.log 'go to account' name = browser.getValue '[name="name"]' console.log 'Name: ' + name[1] assert.equal name[1], 'Patrick Tan' phone = browser.getValue '[name="phone_number"]' console.log 'Phone: ' + phone[1] assert.equal phone[1], '(714) 864 9041' return it 'should register a credit card', -> this.timeout(30000) console.log 'should register a credit card' Utils.getMenu 'div=Account' console.log 'go to account' browser.click 'div=Payment' console.log 'click on credit card' browser.waitUntil 'visible', 'span=Add Card' browser.click 'span=Add Card' console.log 'click add card' browser.setValue '[name="card_number"]', '4242424242424242' browser.setValue '[name="card_cvc"]', '123' browser.setValue '[name="card_billing_zip"]', '90024' console.log 'fill in text' browser.click 'div=Exp. Month' browser.click 'span=6 (June)' console.log 'month set to 6 (June)' Utils.waitUntil 'value', '[name="card_exp_month"]' browser.click 'div=Exp. Year' browser.click 'span=2020' console.log 'year set to 2020' Utils.waitUntil 'value', '[name="card_exp_year"]' browser.click 'span=Save Changes' Utils.waitUntil 'visible', '[name="payment_method"]', 30000 return it 'should delete a credit card', -> console.log 'should delete a credit card' Utils.getMenu 'div=Account' console.log 'go to account' browser.click 'div=Payment' console.log 'click on credit card' browser.waitUntil 'visible', 'div=Visa*4242' browser.click 'div=Visa *4242' Utils.waitForAlert(true) Utils.waitForAlert(true) console.log 'alerts clicked' Utils.hitBack() console.log 'back clicked' return return
174664
Utils = require('./test_utils.js') assert = require('assert') sinon = require('sinon') describe 'webdriver.io page', -> it 'should have the right title', -> console.log 'should have the right title' browser.url Utils.clientUrl title = browser.getTitle() assert.equal title, 'Purple' return it 'should login', -> console.log 'should login line#16' Utils.getMenu 'div=Login' console.log 'choose login' browser.setValue '.x-input-email', '<EMAIL>' browser.setValue '.x-input-password', '<PASSWORD>' console.log 'login info' browser.click '#loginButtonContainer' console.log 'login' Utils.waitUntil 'visible', '#requestGasButton' return it 'should test accounts', -> console.log 'should test accounts' Utils.getMenu 'div=Account' console.log 'go to account' name = browser.getValue '[name="name"]' console.log 'Name: ' + name[1] assert.equal name[1], '<NAME>' phone = browser.getValue '[name="phone_number"]' console.log 'Phone: ' + phone[1] assert.equal phone[1], '(714) 864 9041' return it 'should register a credit card', -> this.timeout(30000) console.log 'should register a credit card' Utils.getMenu 'div=Account' console.log 'go to account' browser.click 'div=Payment' console.log 'click on credit card' browser.waitUntil 'visible', 'span=Add Card' browser.click 'span=Add Card' console.log 'click add card' browser.setValue '[name="card_number"]', '4242424242424242' browser.setValue '[name="card_cvc"]', '123' browser.setValue '[name="card_billing_zip"]', '90024' console.log 'fill in text' browser.click 'div=Exp. Month' browser.click 'span=6 (June)' console.log 'month set to 6 (June)' Utils.waitUntil 'value', '[name="card_exp_month"]' browser.click 'div=Exp. Year' browser.click 'span=2020' console.log 'year set to 2020' Utils.waitUntil 'value', '[name="card_exp_year"]' browser.click 'span=Save Changes' Utils.waitUntil 'visible', '[name="payment_method"]', 30000 return it 'should delete a credit card', -> console.log 'should delete a credit card' Utils.getMenu 'div=Account' console.log 'go to account' browser.click 'div=Payment' console.log 'click on credit card' browser.waitUntil 'visible', 'div=Visa*4242' browser.click 'div=Visa *4242' Utils.waitForAlert(true) Utils.waitForAlert(true) console.log 'alerts clicked' Utils.hitBack() console.log 'back clicked' return return
true
Utils = require('./test_utils.js') assert = require('assert') sinon = require('sinon') describe 'webdriver.io page', -> it 'should have the right title', -> console.log 'should have the right title' browser.url Utils.clientUrl title = browser.getTitle() assert.equal title, 'Purple' return it 'should login', -> console.log 'should login line#16' Utils.getMenu 'div=Login' console.log 'choose login' browser.setValue '.x-input-email', 'PI:EMAIL:<EMAIL>END_PI' browser.setValue '.x-input-password', 'PI:PASSWORD:<PASSWORD>END_PI' console.log 'login info' browser.click '#loginButtonContainer' console.log 'login' Utils.waitUntil 'visible', '#requestGasButton' return it 'should test accounts', -> console.log 'should test accounts' Utils.getMenu 'div=Account' console.log 'go to account' name = browser.getValue '[name="name"]' console.log 'Name: ' + name[1] assert.equal name[1], 'PI:NAME:<NAME>END_PI' phone = browser.getValue '[name="phone_number"]' console.log 'Phone: ' + phone[1] assert.equal phone[1], '(714) 864 9041' return it 'should register a credit card', -> this.timeout(30000) console.log 'should register a credit card' Utils.getMenu 'div=Account' console.log 'go to account' browser.click 'div=Payment' console.log 'click on credit card' browser.waitUntil 'visible', 'span=Add Card' browser.click 'span=Add Card' console.log 'click add card' browser.setValue '[name="card_number"]', '4242424242424242' browser.setValue '[name="card_cvc"]', '123' browser.setValue '[name="card_billing_zip"]', '90024' console.log 'fill in text' browser.click 'div=Exp. Month' browser.click 'span=6 (June)' console.log 'month set to 6 (June)' Utils.waitUntil 'value', '[name="card_exp_month"]' browser.click 'div=Exp. Year' browser.click 'span=2020' console.log 'year set to 2020' Utils.waitUntil 'value', '[name="card_exp_year"]' browser.click 'span=Save Changes' Utils.waitUntil 'visible', '[name="payment_method"]', 30000 return it 'should delete a credit card', -> console.log 'should delete a credit card' Utils.getMenu 'div=Account' console.log 'go to account' browser.click 'div=Payment' console.log 'click on credit card' browser.waitUntil 'visible', 'div=Visa*4242' browser.click 'div=Visa *4242' Utils.waitForAlert(true) Utils.waitForAlert(true) console.log 'alerts clicked' Utils.hitBack() console.log 'back clicked' return return
[ { "context": "ld say hello to person', ->\n expect(hello 'Bob').toBe 'hello Bob'\n\n it 'should say \"hello wor", "end": 86, "score": 0.9156580567359924, "start": 83, "tag": "NAME", "value": "Bob" }, { "context": "erson', ->\n expect(hello 'Bob').toBe 'hello Bob'\n\n...
examples/coffeescript/tests.coffee
Turbo87/testem
1,004
describe 'hello', -> it 'should say hello to person', -> expect(hello 'Bob').toBe 'hello Bob' it 'should say "hello world" if no provided', -> expect(hello()).toBe 'hello world'
28596
describe 'hello', -> it 'should say hello to person', -> expect(hello '<NAME>').toBe 'hello <NAME>' it 'should say "hello world" if no provided', -> expect(hello()).toBe 'hello world'
true
describe 'hello', -> it 'should say hello to person', -> expect(hello 'PI:NAME:<NAME>END_PI').toBe 'hello PI:NAME:<NAME>END_PI' it 'should say "hello world" if no provided', -> expect(hello()).toBe 'hello world'
[ { "context": "#\n# Commands:\n# hubot hi - Hi! 🤖\n#\n# Author:\n# Zach Whaley (zachwhaley) <zachbwhaley@gmail.com>\n\n\nmodule.exp", "end": 91, "score": 0.9998670816421509, "start": 80, "tag": "NAME", "value": "Zach Whaley" }, { "context": "# hubot hi - Hi! 🤖\n#\n# Author:\n#...
scripts/hi.coffee
galtx-centex/roobot
3
# Description: # Say Hi! 🤖 # # Commands: # hubot hi - Hi! 🤖 # # Author: # Zach Whaley (zachwhaley) <zachbwhaley@gmail.com> module.exports = (robot) -> robot.respond /hi/i, (res) -> res.reply "Hi! 🤖"
210677
# Description: # Say Hi! 🤖 # # Commands: # hubot hi - Hi! 🤖 # # Author: # <NAME> (zachwhaley) <<EMAIL>> module.exports = (robot) -> robot.respond /hi/i, (res) -> res.reply "Hi! 🤖"
true
# Description: # Say Hi! 🤖 # # Commands: # hubot hi - Hi! 🤖 # # Author: # PI:NAME:<NAME>END_PI (zachwhaley) <PI:EMAIL:<EMAIL>END_PI> module.exports = (robot) -> robot.respond /hi/i, (res) -> res.reply "Hi! 🤖"
[ { "context": "example =\n Created: 1371157430\n Id: '511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158'\n ParentId: ''\n RepoTags: [\n '<none>:<none>'", "end": 103, "score": 0.9887920618057251, "start": 39, "tag": "KEY", "value": "511136ea3c5a64f264b78b5433614aec563103b...
src/groupimages.coffee
metocean/ducke
2
example = Created: 1371157430 Id: '511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158' ParentId: '' RepoTags: [ '<none>:<none>' ] Size: 0 VirtualSize: 0 module.exports = (images) -> root = {} byid = {} bytag = {} for image in images node = image: image children: [] byid[image.Id] = node root[image.Id] = node if image.ParentId is '' for tag in image.RepoTags continue if tag is '<none>:<none>' bytag[tag] = node for _, node of byid if node.image.ParentId isnt '' byid[node.image.ParentId].children.push node result = images: [] graph: [] tags: bytag ids: byid for _, value of byid result.images.push value for _, value of root result.graph.push value result
13041
example = Created: 1371157430 Id: '<KEY>' ParentId: '' RepoTags: [ '<none>:<none>' ] Size: 0 VirtualSize: 0 module.exports = (images) -> root = {} byid = {} bytag = {} for image in images node = image: image children: [] byid[image.Id] = node root[image.Id] = node if image.ParentId is '' for tag in image.RepoTags continue if tag is '<none>:<none>' bytag[tag] = node for _, node of byid if node.image.ParentId isnt '' byid[node.image.ParentId].children.push node result = images: [] graph: [] tags: bytag ids: byid for _, value of byid result.images.push value for _, value of root result.graph.push value result
true
example = Created: 1371157430 Id: 'PI:KEY:<KEY>END_PI' ParentId: '' RepoTags: [ '<none>:<none>' ] Size: 0 VirtualSize: 0 module.exports = (images) -> root = {} byid = {} bytag = {} for image in images node = image: image children: [] byid[image.Id] = node root[image.Id] = node if image.ParentId is '' for tag in image.RepoTags continue if tag is '<none>:<none>' bytag[tag] = node for _, node of byid if node.image.ParentId isnt '' byid[node.image.ParentId].children.push node result = images: [] graph: [] tags: bytag ids: byid for _, value of byid result.images.push value for _, value of root result.graph.push value result
[ { "context": "ndom element from the array', ->\n names = [ 'Alice', 'Bob', 'Carol', 'Dave' ]\n for i in [1..NUM", "end": 514, "score": 0.999843418598175, "start": 509, "tag": "NAME", "value": "Alice" }, { "context": "ent from the array', ->\n names = [ 'Alice', 'Bob', ...
_old/node/test/js/arrayTest.coffee
lagdotcom/rot.js
1,653
# arrayTest.coffee #---------------------------------------------------------------------------- should = require 'should' ROT = require '../../lib/rot' NUM_RANDOM_CALLS = 100 describe 'array', -> it 'should have added methods to the Array prototype', -> [].should.have.properties ['random', 'randomize'] describe 'random', -> it 'should return null when the array is empty', -> should([].random()).equal null it 'should return a random element from the array', -> names = [ 'Alice', 'Bob', 'Carol', 'Dave' ] for i in [1..NUM_RANDOM_CALLS] randomName = names.random() (randomName in names).should.equal true describe 'randomize', -> it 'should return an empty array if provided an empty array', -> ([].randomize()).should.eql [] it 'should return an randomized array when provided with an array', -> names = [ 'Alice', 'Bob', 'Carol', 'Dave' ] numNames = names.length randomizedNames = names.randomize() randomizedNames.length.should.equal numNames names.length.should.equal 0 #---------------------------------------------------------------------------- # end of arrayTest.coffee
9289
# arrayTest.coffee #---------------------------------------------------------------------------- should = require 'should' ROT = require '../../lib/rot' NUM_RANDOM_CALLS = 100 describe 'array', -> it 'should have added methods to the Array prototype', -> [].should.have.properties ['random', 'randomize'] describe 'random', -> it 'should return null when the array is empty', -> should([].random()).equal null it 'should return a random element from the array', -> names = [ '<NAME>', '<NAME>', '<NAME>', '<NAME>' ] for i in [1..NUM_RANDOM_CALLS] randomName = names.random() (randomName in names).should.equal true describe 'randomize', -> it 'should return an empty array if provided an empty array', -> ([].randomize()).should.eql [] it 'should return an randomized array when provided with an array', -> names = [ '<NAME>', '<NAME>', '<NAME>', '<NAME>' ] numNames = names.length randomizedNames = names.randomize() randomizedNames.length.should.equal numNames names.length.should.equal 0 #---------------------------------------------------------------------------- # end of arrayTest.coffee
true
# arrayTest.coffee #---------------------------------------------------------------------------- should = require 'should' ROT = require '../../lib/rot' NUM_RANDOM_CALLS = 100 describe 'array', -> it 'should have added methods to the Array prototype', -> [].should.have.properties ['random', 'randomize'] describe 'random', -> it 'should return null when the array is empty', -> should([].random()).equal null it 'should return a random element from the array', -> names = [ 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI' ] for i in [1..NUM_RANDOM_CALLS] randomName = names.random() (randomName in names).should.equal true describe 'randomize', -> it 'should return an empty array if provided an empty array', -> ([].randomize()).should.eql [] it 'should return an randomized array when provided with an array', -> names = [ 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI' ] numNames = names.length randomizedNames = names.randomize() randomizedNames.length.should.equal numNames names.length.should.equal 0 #---------------------------------------------------------------------------- # end of arrayTest.coffee
[ { "context": "nd with an image\n#\n# Notes\n# None\n#\n# Author:\n# Julianoe <ju.gasba+npm@gmail.com> (https://github.com/juli", "end": 272, "score": 0.8843636512756348, "start": 264, "tag": "NAME", "value": "Julianoe" }, { "context": "image\n#\n# Notes\n# None\n#\n# Author:\n# ...
src/melenshack.coffee
Julianoe/hubot-melenshack
0
# Description: # Hubot supports Melenchon with a set of images ! Can't Stench the Meluch ! # # Dependencies: # None # # Configuration: # None # # Commands: # Say : "Mélenchon en images", the bot will respond with an image # # Notes # None # # Author: # Julianoe <ju.gasba+npm@gmail.com> (https://github.com/julianoe) module.exports = (robot) -> robot.hear regex, (msg) -> msg.send msg.random images images = require './data/images.json' memel = [ 'Insoumis en images', '(((M|m)(é|e)l|mel)(e|a)nchon) en images' ] regex = new RegExp memel.join('|'), 'ig'
82671
# Description: # Hubot supports Melenchon with a set of images ! Can't Stench the Meluch ! # # Dependencies: # None # # Configuration: # None # # Commands: # Say : "Mélenchon en images", the bot will respond with an image # # Notes # None # # Author: # <NAME> <<EMAIL>> (https://github.com/julianoe) module.exports = (robot) -> robot.hear regex, (msg) -> msg.send msg.random images images = require './data/images.json' memel = [ 'Insoumis en images', '(((M|m)(é|e)l|mel)(e|a)nchon) en images' ] regex = new RegExp memel.join('|'), 'ig'
true
# Description: # Hubot supports Melenchon with a set of images ! Can't Stench the Meluch ! # # Dependencies: # None # # Configuration: # None # # Commands: # Say : "Mélenchon en images", the bot will respond with an image # # Notes # None # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (https://github.com/julianoe) module.exports = (robot) -> robot.hear regex, (msg) -> msg.send msg.random images images = require './data/images.json' memel = [ 'Insoumis en images', '(((M|m)(é|e)l|mel)(e|a)nchon) en images' ] regex = new RegExp memel.join('|'), 'ig'
[ { "context": " 1.0.0\n@file MultipleFields.js\n@author Elison de Campos\n@contact http://jokerjs.zaez.net/contato\n\n@co", "end": 146, "score": 0.999874472618103, "start": 130, "tag": "NAME", "value": "Elison de Campos" } ]
vendor/assets/javascripts/joker/MultipleFields.coffee
zaeznet/joker-rails
0
### @summary Joker @description Framework of RIAs applications @version 1.0.0 @file MultipleFields.js @author Elison de Campos @contact http://jokerjs.zaez.net/contato @copyright Copyright 2013 Zaez Solucoes em Tecnologia, all rights reserved. This source file is free software, under the license MIT, available at: http://jokerjs.zaez.net/license This source file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. For details please refer to: http://jokerjs.zaez.net ### ### ### class Joker.MultipleFields extends Joker.Core constructor: -> super @setEvents() addNewField: (template, target) -> uniqID = JokerUtils.uniqid() uniqReference = JokerUtils.uniqid() template = template.replace(/[A-z]*value/g, 'value').replace(/value="{entry.[A-z]*}"/g,'').replace(/{entry.id}/g, uniqID).replace(/{uniq_id}/g, uniqID).replace(/{uniq_reference}/g, uniqReference) template = template.replace(/{remove_tag\[(...*)\]}/g, @accessor("patterns").link.assign({ icon: target.data("removeIcon"), ref: uniqReference })) target.append template setEvents: -> @libSupport(document).on "ajaxComplete", @libSupport.proxy(@verifyMultipleFields, @) @libSupport(document).on "click", '.multiple-fields-wrapper a.remove-item i', @libSupport.proxy(@removeField, @) setUpMultipleFields: (el) -> template = el.dataset.template target = @libSupport ".#{el.dataset.wrapper}" callbacks = target.data "callbacks" if callbacks.after_button_press @libSupport(".#{callbacks.after_button_press.trigger}").on 'click', => @addNewField template, target el.dataset.multiplefields = true removeField: (e) -> console.log e caller = @libSupport(e.target) @libSupport("##{caller.data('target')}").remove() verifyMultipleFields: (e) -> @libSupport(".multiple-fields-wrapper:not([data-multiplefields])").each (index, el) => @setUpMultipleFields el @debugPrefix: "Joker_MultipleFields" @className : "Joker_MultipleFields" ### @type [Joker.MultipleFields] ### @instance : undefined @patterns: link: """<a href="#" class="remove-item"><i class="{icon}" data-target="{ref}"></i></a>""" ### Retorna a variavel unica para a instacia do objeto @return [Joker.MultipleFields] ### @getInstance: -> Joker.MultipleFields.instance = new Joker.MultipleFields() unless Joker.MultipleFields.instance? Joker.MultipleFields.instance
42881
### @summary Joker @description Framework of RIAs applications @version 1.0.0 @file MultipleFields.js @author <NAME> @contact http://jokerjs.zaez.net/contato @copyright Copyright 2013 Zaez Solucoes em Tecnologia, all rights reserved. This source file is free software, under the license MIT, available at: http://jokerjs.zaez.net/license This source file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. For details please refer to: http://jokerjs.zaez.net ### ### ### class Joker.MultipleFields extends Joker.Core constructor: -> super @setEvents() addNewField: (template, target) -> uniqID = JokerUtils.uniqid() uniqReference = JokerUtils.uniqid() template = template.replace(/[A-z]*value/g, 'value').replace(/value="{entry.[A-z]*}"/g,'').replace(/{entry.id}/g, uniqID).replace(/{uniq_id}/g, uniqID).replace(/{uniq_reference}/g, uniqReference) template = template.replace(/{remove_tag\[(...*)\]}/g, @accessor("patterns").link.assign({ icon: target.data("removeIcon"), ref: uniqReference })) target.append template setEvents: -> @libSupport(document).on "ajaxComplete", @libSupport.proxy(@verifyMultipleFields, @) @libSupport(document).on "click", '.multiple-fields-wrapper a.remove-item i', @libSupport.proxy(@removeField, @) setUpMultipleFields: (el) -> template = el.dataset.template target = @libSupport ".#{el.dataset.wrapper}" callbacks = target.data "callbacks" if callbacks.after_button_press @libSupport(".#{callbacks.after_button_press.trigger}").on 'click', => @addNewField template, target el.dataset.multiplefields = true removeField: (e) -> console.log e caller = @libSupport(e.target) @libSupport("##{caller.data('target')}").remove() verifyMultipleFields: (e) -> @libSupport(".multiple-fields-wrapper:not([data-multiplefields])").each (index, el) => @setUpMultipleFields el @debugPrefix: "Joker_MultipleFields" @className : "Joker_MultipleFields" ### @type [Joker.MultipleFields] ### @instance : undefined @patterns: link: """<a href="#" class="remove-item"><i class="{icon}" data-target="{ref}"></i></a>""" ### Retorna a variavel unica para a instacia do objeto @return [Joker.MultipleFields] ### @getInstance: -> Joker.MultipleFields.instance = new Joker.MultipleFields() unless Joker.MultipleFields.instance? Joker.MultipleFields.instance
true
### @summary Joker @description Framework of RIAs applications @version 1.0.0 @file MultipleFields.js @author PI:NAME:<NAME>END_PI @contact http://jokerjs.zaez.net/contato @copyright Copyright 2013 Zaez Solucoes em Tecnologia, all rights reserved. This source file is free software, under the license MIT, available at: http://jokerjs.zaez.net/license This source file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. For details please refer to: http://jokerjs.zaez.net ### ### ### class Joker.MultipleFields extends Joker.Core constructor: -> super @setEvents() addNewField: (template, target) -> uniqID = JokerUtils.uniqid() uniqReference = JokerUtils.uniqid() template = template.replace(/[A-z]*value/g, 'value').replace(/value="{entry.[A-z]*}"/g,'').replace(/{entry.id}/g, uniqID).replace(/{uniq_id}/g, uniqID).replace(/{uniq_reference}/g, uniqReference) template = template.replace(/{remove_tag\[(...*)\]}/g, @accessor("patterns").link.assign({ icon: target.data("removeIcon"), ref: uniqReference })) target.append template setEvents: -> @libSupport(document).on "ajaxComplete", @libSupport.proxy(@verifyMultipleFields, @) @libSupport(document).on "click", '.multiple-fields-wrapper a.remove-item i', @libSupport.proxy(@removeField, @) setUpMultipleFields: (el) -> template = el.dataset.template target = @libSupport ".#{el.dataset.wrapper}" callbacks = target.data "callbacks" if callbacks.after_button_press @libSupport(".#{callbacks.after_button_press.trigger}").on 'click', => @addNewField template, target el.dataset.multiplefields = true removeField: (e) -> console.log e caller = @libSupport(e.target) @libSupport("##{caller.data('target')}").remove() verifyMultipleFields: (e) -> @libSupport(".multiple-fields-wrapper:not([data-multiplefields])").each (index, el) => @setUpMultipleFields el @debugPrefix: "Joker_MultipleFields" @className : "Joker_MultipleFields" ### @type [Joker.MultipleFields] ### @instance : undefined @patterns: link: """<a href="#" class="remove-item"><i class="{icon}" data-target="{ref}"></i></a>""" ### Retorna a variavel unica para a instacia do objeto @return [Joker.MultipleFields] ### @getInstance: -> Joker.MultipleFields.instance = new Joker.MultipleFields() unless Joker.MultipleFields.instance? Joker.MultipleFields.instance
[ { "context": "ithArgs('userId').returns(\n name: 'name'\n email: 'email'\n a", "end": 786, "score": 0.9988589882850647, "start": 782, "tag": "NAME", "value": "name" }, { "context": " test.deepEqual(user,\n name: 'name',...
src/tests/server/export/test_wave.coffee
LaPingvino/rizzoma
88
testCase = require('nodeunit').testCase sinon = require('sinon') WaveExportMarkupBuilder = require('../../../server/export/wave').WaveExportMarkupBuilder module.exports = WaveExportMarkupBuilderTest: testCase setUp: (callback) -> @_builder = new WaveExportMarkupBuilder() callback() testGetUserInfoByIdIfNotFound: sinon.test (test) -> sinon.stub(@_builder, '_getUserById').withArgs('userId').returns(null) user = @_builder._getUserInfoById('userId', true) test.deepEqual(user, {name: '(unknown)', email: '(unknown)'}) test.done() testGetUserInfoById: sinon.test (test) -> sinon.stub(@_builder, '_getUserById').withArgs('userId').returns( name: 'name' email: 'email' avatar: 'avatar' ) user = @_builder._getUserInfoById('userId', true) test.deepEqual(user, name: 'name', email: 'email', avatar: 'avatar' ) test.done() testGetWaveTitleIfNoRootBlipFound: sinon.test (test) -> sinon.stub(@_builder, '_getBlipById').withArgs('blipId').returns(null) @_builder._wave = {rootBlipId: 'blipId'} title = @_builder._getWaveTitle() test.equal(title, null) test.done() testGetRootNodeIfNoContainerBlip: sinon.test (test) -> sinon.stub(@_builder, '_getWaveUrl').returns('') sinon.stub(@_builder, '_getWaveTitle').returns('') sinon.stub(@_builder, '_getContainerBlip').returns(null) root = @_builder._getRootNode() test.equal(root.nodes.length, 0) test.done() testInjectReplyIfNoBlipFound: sinon.test (test) -> sinon.stub(@_builder, '_getBlipById').withArgs('blipId').returns(null) @_builder._injectReply({id: 'blipId'}) test.done()
46400
testCase = require('nodeunit').testCase sinon = require('sinon') WaveExportMarkupBuilder = require('../../../server/export/wave').WaveExportMarkupBuilder module.exports = WaveExportMarkupBuilderTest: testCase setUp: (callback) -> @_builder = new WaveExportMarkupBuilder() callback() testGetUserInfoByIdIfNotFound: sinon.test (test) -> sinon.stub(@_builder, '_getUserById').withArgs('userId').returns(null) user = @_builder._getUserInfoById('userId', true) test.deepEqual(user, {name: '(unknown)', email: '(unknown)'}) test.done() testGetUserInfoById: sinon.test (test) -> sinon.stub(@_builder, '_getUserById').withArgs('userId').returns( name: '<NAME>' email: 'email' avatar: 'avatar' ) user = @_builder._getUserInfoById('userId', true) test.deepEqual(user, name: '<NAME>', email: 'email', avatar: 'avatar' ) test.done() testGetWaveTitleIfNoRootBlipFound: sinon.test (test) -> sinon.stub(@_builder, '_getBlipById').withArgs('blipId').returns(null) @_builder._wave = {rootBlipId: 'blipId'} title = @_builder._getWaveTitle() test.equal(title, null) test.done() testGetRootNodeIfNoContainerBlip: sinon.test (test) -> sinon.stub(@_builder, '_getWaveUrl').returns('') sinon.stub(@_builder, '_getWaveTitle').returns('') sinon.stub(@_builder, '_getContainerBlip').returns(null) root = @_builder._getRootNode() test.equal(root.nodes.length, 0) test.done() testInjectReplyIfNoBlipFound: sinon.test (test) -> sinon.stub(@_builder, '_getBlipById').withArgs('blipId').returns(null) @_builder._injectReply({id: 'blipId'}) test.done()
true
testCase = require('nodeunit').testCase sinon = require('sinon') WaveExportMarkupBuilder = require('../../../server/export/wave').WaveExportMarkupBuilder module.exports = WaveExportMarkupBuilderTest: testCase setUp: (callback) -> @_builder = new WaveExportMarkupBuilder() callback() testGetUserInfoByIdIfNotFound: sinon.test (test) -> sinon.stub(@_builder, '_getUserById').withArgs('userId').returns(null) user = @_builder._getUserInfoById('userId', true) test.deepEqual(user, {name: '(unknown)', email: '(unknown)'}) test.done() testGetUserInfoById: sinon.test (test) -> sinon.stub(@_builder, '_getUserById').withArgs('userId').returns( name: 'PI:NAME:<NAME>END_PI' email: 'email' avatar: 'avatar' ) user = @_builder._getUserInfoById('userId', true) test.deepEqual(user, name: 'PI:NAME:<NAME>END_PI', email: 'email', avatar: 'avatar' ) test.done() testGetWaveTitleIfNoRootBlipFound: sinon.test (test) -> sinon.stub(@_builder, '_getBlipById').withArgs('blipId').returns(null) @_builder._wave = {rootBlipId: 'blipId'} title = @_builder._getWaveTitle() test.equal(title, null) test.done() testGetRootNodeIfNoContainerBlip: sinon.test (test) -> sinon.stub(@_builder, '_getWaveUrl').returns('') sinon.stub(@_builder, '_getWaveTitle').returns('') sinon.stub(@_builder, '_getContainerBlip').returns(null) root = @_builder._getRootNode() test.equal(root.nodes.length, 0) test.done() testInjectReplyIfNoBlipFound: sinon.test (test) -> sinon.stub(@_builder, '_getBlipById').withArgs('blipId').returns(null) @_builder._injectReply({id: 'blipId'}) test.done()
[ { "context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib", "end": 79, "score": 0.9998531341552734, "start": 66, "tag": "NAME", "value": "Henri Bergius" } ]
src/plugins/publicationselector.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 # This plugin handles the selection from a list of previously associated publications ((jQuery) -> jQuery.widget 'IKS.hallopublicationselector', widget: null selectables: '' citeproc: new ICiteProc() list_toolbar: null options: editable: null range: null toolbar: null uuid: '' element: null tip_element: null data: null loid: null has_changed: false toolbar_actions: 'Filter': null default_css: 'width': '100%' 'height': '100%' 'top': 0 'left': 0 'position': 'fixed' 'z-index': 999999 _init: -> #debug.log('publicationselector initialized',@options) @widget = jQuery('<div id="publication_selector"></div>') @widget.addClass('form_display'); jQuery('body').css({'overflow':'hidden'}) jQuery('body').append(@widget) @widget.append('<div id="publication_list" style="background-color:white; margin-bottom: 4px"></div>'); @widget.append('<button class="publication_selector_back action_button">' + utils.tr('back') + '</button>'); @widget.append('<button class="publication_selector_apply action_button">' + utils.tr('apply') + '</button>'); @widget.css @options.default_css @widget.find('.publication_selector_back').bind 'click', => @back() @widget.find('.publication_selector_apply').bind 'click', => @apply() @wigtet.css('width', jQuery('body').width()) if !@options.default_css.width @widget.css('height', jQuery(window).height()) if !@options.default_css.height @list = new List(); @list.setupItemActions({ 'node_dblclick': (node) => @select(node) @apply() 'node_select': (node) => @select(node) }) @list.init($('#publication_list'),omc.PublicationList).done () => @list_toolbar = new ToolBarBase(); @options.toolbar_actions['Filter'] = @list_toolbar.default_actions.Filter; @options.toolbar_actions['FilterUnreferenced'] = @list_toolbar.default_actions.FilterUnreferenced; @options.toolbar_actions['FilterSystem'] = @list_toolbar.default_actions.FilterSystem; @options.toolbar_actions['SortAlpha'] = @list_toolbar.default_actions.SortAlpha; @options.toolbar_actions['SortTime'] = @list_toolbar.default_actions.SortTime; @options.toolbar_actions['SortType'] = @list_toolbar.default_actions.SortType; @options.toolbar_actions['_filter'] = @list_toolbar.default_actions._filter; # for sort @options.toolbar_actions['_removeFilter'] = @list_toolbar.default_actions._removeFilter; @list_toolbar.displayBase('body','publicationselector',@options.toolbar_actions,true,jQuery('#publication_list')) @list_toolbar.toolbar.stop(true,true); # otherwise z-index is cleared when animation finishes @list_toolbar.toolbar.css({'z-index':@options.default_css['z-index'] + 1}) @options.toolbar_actions['Filter'](null,null,null,@list_toolbar.action_context) window.setTimeout () => @list_toolbar.action_context.find('#filter_input').focus() # deferred, otherwise editable grabs back @list_toolbar.action_context.css({'padding-top':'2em'}) , 500 jQuery(window).resize() apply: -> if ( typeof @current_node == 'undefined' ) utils.error(utils.tr('nothing selected')) return jQuery('#basepublicationselectortoolbar').remove() publication_loid = @current_node.replace(/node_/,'') target_loid = @options.editable.element.closest('.Text').attr('id').replace(/node/,'') dfo = omc.AssociatePublication(target_loid,publication_loid) dfo.fail (error) => @back() #tmp_id is used to identify new sourcedescription after it has been inserted for further editing tmp_id = 'tmp_' + (new Date()).getTime() dfo.done (result) => data = result.loid element = @current_node_label @options.editable.restoreContentPosition() @options.editable.getSelectionNode (selection_common) => selection_html = @options.editable.getSelectionHtml() if selection_html == "" replacement = "" else replacement = "<span class=\"citation\">" + selection_html + "</span>" replacement+= "<span class=\"cite\" contenteditable=\"false\" id=\"#{tmp_id}\"><span class=\"csl\">#{element}</span><span class=\"Z3988\" data-sourcedescriptionloid=\"#{data}\"><span style=\"display:none;\">&#160;</span></span>" replacement_node = jQuery('<span></span>').append(replacement) z3988 = new Z3988(); nugget = new DOMNugget(); z3988_node = jQuery('.Z3988',replacement_node)[0]; co = new Z3988ContextObject(); co.sourcedescription = {data:result}; nugget.addDerivedSourceDescriptionAttributes(z3988_node,co.sourcedescription); co.referent.setByValueMetadata(co.referent.fromCSL(nugget.getSourceDescriptionCSL(co.sourcedescription))); co.referent.setPrivateData((new Z3988SourceDescription()).toPrivateData(co.sourcedescription)); delete co.sourcedescription; z3988.setFormat(new Z3988KEV()); z3988.attach(z3988_node,co); selection = rangy.getSelection() if ( selection.rangeCount > 0 ) range = selection.getRangeAt(0) range.deleteContents() else range = rangy.createRange() range.selectNode(@options.editable.element[0]) range.collapse(false) # toEnd if ( selection_html == '' ) if ( selection_common.attr('contenteditable') == 'true' && !selection_common.hasClass('rangySelectionBoundary')) selection_common.append(replacement_node.contents()) else replacement_node.insertAfter(selection_common) # avoid inserting _in_ hyperlinks else range.insertNode(replacement_node[0]) nugget = new DOMNugget() @options.editable.element.closest('.nugget').find('.auto-cite').remove() occ.UpdateNuggetSourceDescriptions({loid:target_loid}) # launch sourcedescription editor with newly created sourcedescription new_sd_node = jQuery('#' + tmp_id); new_sd_node.removeAttr('id') #console.log(new_sd_node) nugget.commitSourceDescriptionChanges(@options.editable.element).done => #console.log(new_sd_node) @openSourceDescriptionEditor(nugget,target_loid,new_sd_node) @back() openSourceDescriptionEditor: (nugget,target_loid,new_sd_node) -> nugget.getSourceDescriptionData(new_sd_node).done (citation_data) => jQuery('body').hallosourcedescriptioneditor 'loid': citation_data.loid 'element': new_sd_node 'back': false 'nugget_loid': target_loid back: -> @widget.remove() jQuery('#basepublicationselectortoolbar').remove() jQuery('body').css({'overflow':'auto'}) @options.editable.restoreContentPosition() @options.editable.activate() select: (node) -> @current_node = jQuery(node).attr('id') @current_node_label = jQuery(node).text() @widget.find(".citation_data_processed").slideUp 'slow', () -> jQuery(this).remove() omc_settings.getSettings().done (settings) => @citeproc.init().done => loid = jQuery(node).attr('id').replace(/node_/,'') omc.getPublicationCitationData(loid).done (citation_data) => if ( jQuery(node).find(".citation_data_processed").length == 0 ) jQuery(node).append('<div class="citation_data_processed"></div>') jQuery.each citation_data, (key,value) => jQuery(node).find('.citation_data_processed').append('<span class="cite"><span class="csl" id="' + key + '"></span></span></div>') @citeproc.resetCitationData() @citeproc.appendCitationData(citation_data) @citeproc.citation_style = settings['default_citation_style'] @citeproc.process('#node_' + loid + ' .citation_data_processed', settings.iso_language) endnotes = @citeproc.endnotes() endnotes = endnotes.replace(/\[1\]/,'') jQuery(node).find('.citation_data_processed').html(endnotes).slideDown() _createInput: (identifier, label, value) -> input = jQuery('<div><label for="' + identifier + '">' + label + '</label><input id="' + identifier + '" type="text" value="<!--user-data-->"/></div>') input.find('input').bind 'blur', (event) => @_formChanged(event,@options) input.find('input').val(value) input _formChanged: (event, options) -> target = jQuery(event.target) #debug.log('form changed' + target.html()) path = target.attr('id') data = target.val() if omc && options.loid omc.storePublicationDescriptionAttribute(options.loid,path,data) #debug.log('stored',options.loid,path,data) _create: -> #debug.log('created'); @ )(jQuery)
188458
# Hallo - a rich text editing jQuery UI widget # (c) 2011 <NAME>, IKS Consortium # Hallo may be freely distributed under the MIT license # This plugin handles the selection from a list of previously associated publications ((jQuery) -> jQuery.widget 'IKS.hallopublicationselector', widget: null selectables: '' citeproc: new ICiteProc() list_toolbar: null options: editable: null range: null toolbar: null uuid: '' element: null tip_element: null data: null loid: null has_changed: false toolbar_actions: 'Filter': null default_css: 'width': '100%' 'height': '100%' 'top': 0 'left': 0 'position': 'fixed' 'z-index': 999999 _init: -> #debug.log('publicationselector initialized',@options) @widget = jQuery('<div id="publication_selector"></div>') @widget.addClass('form_display'); jQuery('body').css({'overflow':'hidden'}) jQuery('body').append(@widget) @widget.append('<div id="publication_list" style="background-color:white; margin-bottom: 4px"></div>'); @widget.append('<button class="publication_selector_back action_button">' + utils.tr('back') + '</button>'); @widget.append('<button class="publication_selector_apply action_button">' + utils.tr('apply') + '</button>'); @widget.css @options.default_css @widget.find('.publication_selector_back').bind 'click', => @back() @widget.find('.publication_selector_apply').bind 'click', => @apply() @wigtet.css('width', jQuery('body').width()) if !@options.default_css.width @widget.css('height', jQuery(window).height()) if !@options.default_css.height @list = new List(); @list.setupItemActions({ 'node_dblclick': (node) => @select(node) @apply() 'node_select': (node) => @select(node) }) @list.init($('#publication_list'),omc.PublicationList).done () => @list_toolbar = new ToolBarBase(); @options.toolbar_actions['Filter'] = @list_toolbar.default_actions.Filter; @options.toolbar_actions['FilterUnreferenced'] = @list_toolbar.default_actions.FilterUnreferenced; @options.toolbar_actions['FilterSystem'] = @list_toolbar.default_actions.FilterSystem; @options.toolbar_actions['SortAlpha'] = @list_toolbar.default_actions.SortAlpha; @options.toolbar_actions['SortTime'] = @list_toolbar.default_actions.SortTime; @options.toolbar_actions['SortType'] = @list_toolbar.default_actions.SortType; @options.toolbar_actions['_filter'] = @list_toolbar.default_actions._filter; # for sort @options.toolbar_actions['_removeFilter'] = @list_toolbar.default_actions._removeFilter; @list_toolbar.displayBase('body','publicationselector',@options.toolbar_actions,true,jQuery('#publication_list')) @list_toolbar.toolbar.stop(true,true); # otherwise z-index is cleared when animation finishes @list_toolbar.toolbar.css({'z-index':@options.default_css['z-index'] + 1}) @options.toolbar_actions['Filter'](null,null,null,@list_toolbar.action_context) window.setTimeout () => @list_toolbar.action_context.find('#filter_input').focus() # deferred, otherwise editable grabs back @list_toolbar.action_context.css({'padding-top':'2em'}) , 500 jQuery(window).resize() apply: -> if ( typeof @current_node == 'undefined' ) utils.error(utils.tr('nothing selected')) return jQuery('#basepublicationselectortoolbar').remove() publication_loid = @current_node.replace(/node_/,'') target_loid = @options.editable.element.closest('.Text').attr('id').replace(/node/,'') dfo = omc.AssociatePublication(target_loid,publication_loid) dfo.fail (error) => @back() #tmp_id is used to identify new sourcedescription after it has been inserted for further editing tmp_id = 'tmp_' + (new Date()).getTime() dfo.done (result) => data = result.loid element = @current_node_label @options.editable.restoreContentPosition() @options.editable.getSelectionNode (selection_common) => selection_html = @options.editable.getSelectionHtml() if selection_html == "" replacement = "" else replacement = "<span class=\"citation\">" + selection_html + "</span>" replacement+= "<span class=\"cite\" contenteditable=\"false\" id=\"#{tmp_id}\"><span class=\"csl\">#{element}</span><span class=\"Z3988\" data-sourcedescriptionloid=\"#{data}\"><span style=\"display:none;\">&#160;</span></span>" replacement_node = jQuery('<span></span>').append(replacement) z3988 = new Z3988(); nugget = new DOMNugget(); z3988_node = jQuery('.Z3988',replacement_node)[0]; co = new Z3988ContextObject(); co.sourcedescription = {data:result}; nugget.addDerivedSourceDescriptionAttributes(z3988_node,co.sourcedescription); co.referent.setByValueMetadata(co.referent.fromCSL(nugget.getSourceDescriptionCSL(co.sourcedescription))); co.referent.setPrivateData((new Z3988SourceDescription()).toPrivateData(co.sourcedescription)); delete co.sourcedescription; z3988.setFormat(new Z3988KEV()); z3988.attach(z3988_node,co); selection = rangy.getSelection() if ( selection.rangeCount > 0 ) range = selection.getRangeAt(0) range.deleteContents() else range = rangy.createRange() range.selectNode(@options.editable.element[0]) range.collapse(false) # toEnd if ( selection_html == '' ) if ( selection_common.attr('contenteditable') == 'true' && !selection_common.hasClass('rangySelectionBoundary')) selection_common.append(replacement_node.contents()) else replacement_node.insertAfter(selection_common) # avoid inserting _in_ hyperlinks else range.insertNode(replacement_node[0]) nugget = new DOMNugget() @options.editable.element.closest('.nugget').find('.auto-cite').remove() occ.UpdateNuggetSourceDescriptions({loid:target_loid}) # launch sourcedescription editor with newly created sourcedescription new_sd_node = jQuery('#' + tmp_id); new_sd_node.removeAttr('id') #console.log(new_sd_node) nugget.commitSourceDescriptionChanges(@options.editable.element).done => #console.log(new_sd_node) @openSourceDescriptionEditor(nugget,target_loid,new_sd_node) @back() openSourceDescriptionEditor: (nugget,target_loid,new_sd_node) -> nugget.getSourceDescriptionData(new_sd_node).done (citation_data) => jQuery('body').hallosourcedescriptioneditor 'loid': citation_data.loid 'element': new_sd_node 'back': false 'nugget_loid': target_loid back: -> @widget.remove() jQuery('#basepublicationselectortoolbar').remove() jQuery('body').css({'overflow':'auto'}) @options.editable.restoreContentPosition() @options.editable.activate() select: (node) -> @current_node = jQuery(node).attr('id') @current_node_label = jQuery(node).text() @widget.find(".citation_data_processed").slideUp 'slow', () -> jQuery(this).remove() omc_settings.getSettings().done (settings) => @citeproc.init().done => loid = jQuery(node).attr('id').replace(/node_/,'') omc.getPublicationCitationData(loid).done (citation_data) => if ( jQuery(node).find(".citation_data_processed").length == 0 ) jQuery(node).append('<div class="citation_data_processed"></div>') jQuery.each citation_data, (key,value) => jQuery(node).find('.citation_data_processed').append('<span class="cite"><span class="csl" id="' + key + '"></span></span></div>') @citeproc.resetCitationData() @citeproc.appendCitationData(citation_data) @citeproc.citation_style = settings['default_citation_style'] @citeproc.process('#node_' + loid + ' .citation_data_processed', settings.iso_language) endnotes = @citeproc.endnotes() endnotes = endnotes.replace(/\[1\]/,'') jQuery(node).find('.citation_data_processed').html(endnotes).slideDown() _createInput: (identifier, label, value) -> input = jQuery('<div><label for="' + identifier + '">' + label + '</label><input id="' + identifier + '" type="text" value="<!--user-data-->"/></div>') input.find('input').bind 'blur', (event) => @_formChanged(event,@options) input.find('input').val(value) input _formChanged: (event, options) -> target = jQuery(event.target) #debug.log('form changed' + target.html()) path = target.attr('id') data = target.val() if omc && options.loid omc.storePublicationDescriptionAttribute(options.loid,path,data) #debug.log('stored',options.loid,path,data) _create: -> #debug.log('created'); @ )(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 # This plugin handles the selection from a list of previously associated publications ((jQuery) -> jQuery.widget 'IKS.hallopublicationselector', widget: null selectables: '' citeproc: new ICiteProc() list_toolbar: null options: editable: null range: null toolbar: null uuid: '' element: null tip_element: null data: null loid: null has_changed: false toolbar_actions: 'Filter': null default_css: 'width': '100%' 'height': '100%' 'top': 0 'left': 0 'position': 'fixed' 'z-index': 999999 _init: -> #debug.log('publicationselector initialized',@options) @widget = jQuery('<div id="publication_selector"></div>') @widget.addClass('form_display'); jQuery('body').css({'overflow':'hidden'}) jQuery('body').append(@widget) @widget.append('<div id="publication_list" style="background-color:white; margin-bottom: 4px"></div>'); @widget.append('<button class="publication_selector_back action_button">' + utils.tr('back') + '</button>'); @widget.append('<button class="publication_selector_apply action_button">' + utils.tr('apply') + '</button>'); @widget.css @options.default_css @widget.find('.publication_selector_back').bind 'click', => @back() @widget.find('.publication_selector_apply').bind 'click', => @apply() @wigtet.css('width', jQuery('body').width()) if !@options.default_css.width @widget.css('height', jQuery(window).height()) if !@options.default_css.height @list = new List(); @list.setupItemActions({ 'node_dblclick': (node) => @select(node) @apply() 'node_select': (node) => @select(node) }) @list.init($('#publication_list'),omc.PublicationList).done () => @list_toolbar = new ToolBarBase(); @options.toolbar_actions['Filter'] = @list_toolbar.default_actions.Filter; @options.toolbar_actions['FilterUnreferenced'] = @list_toolbar.default_actions.FilterUnreferenced; @options.toolbar_actions['FilterSystem'] = @list_toolbar.default_actions.FilterSystem; @options.toolbar_actions['SortAlpha'] = @list_toolbar.default_actions.SortAlpha; @options.toolbar_actions['SortTime'] = @list_toolbar.default_actions.SortTime; @options.toolbar_actions['SortType'] = @list_toolbar.default_actions.SortType; @options.toolbar_actions['_filter'] = @list_toolbar.default_actions._filter; # for sort @options.toolbar_actions['_removeFilter'] = @list_toolbar.default_actions._removeFilter; @list_toolbar.displayBase('body','publicationselector',@options.toolbar_actions,true,jQuery('#publication_list')) @list_toolbar.toolbar.stop(true,true); # otherwise z-index is cleared when animation finishes @list_toolbar.toolbar.css({'z-index':@options.default_css['z-index'] + 1}) @options.toolbar_actions['Filter'](null,null,null,@list_toolbar.action_context) window.setTimeout () => @list_toolbar.action_context.find('#filter_input').focus() # deferred, otherwise editable grabs back @list_toolbar.action_context.css({'padding-top':'2em'}) , 500 jQuery(window).resize() apply: -> if ( typeof @current_node == 'undefined' ) utils.error(utils.tr('nothing selected')) return jQuery('#basepublicationselectortoolbar').remove() publication_loid = @current_node.replace(/node_/,'') target_loid = @options.editable.element.closest('.Text').attr('id').replace(/node/,'') dfo = omc.AssociatePublication(target_loid,publication_loid) dfo.fail (error) => @back() #tmp_id is used to identify new sourcedescription after it has been inserted for further editing tmp_id = 'tmp_' + (new Date()).getTime() dfo.done (result) => data = result.loid element = @current_node_label @options.editable.restoreContentPosition() @options.editable.getSelectionNode (selection_common) => selection_html = @options.editable.getSelectionHtml() if selection_html == "" replacement = "" else replacement = "<span class=\"citation\">" + selection_html + "</span>" replacement+= "<span class=\"cite\" contenteditable=\"false\" id=\"#{tmp_id}\"><span class=\"csl\">#{element}</span><span class=\"Z3988\" data-sourcedescriptionloid=\"#{data}\"><span style=\"display:none;\">&#160;</span></span>" replacement_node = jQuery('<span></span>').append(replacement) z3988 = new Z3988(); nugget = new DOMNugget(); z3988_node = jQuery('.Z3988',replacement_node)[0]; co = new Z3988ContextObject(); co.sourcedescription = {data:result}; nugget.addDerivedSourceDescriptionAttributes(z3988_node,co.sourcedescription); co.referent.setByValueMetadata(co.referent.fromCSL(nugget.getSourceDescriptionCSL(co.sourcedescription))); co.referent.setPrivateData((new Z3988SourceDescription()).toPrivateData(co.sourcedescription)); delete co.sourcedescription; z3988.setFormat(new Z3988KEV()); z3988.attach(z3988_node,co); selection = rangy.getSelection() if ( selection.rangeCount > 0 ) range = selection.getRangeAt(0) range.deleteContents() else range = rangy.createRange() range.selectNode(@options.editable.element[0]) range.collapse(false) # toEnd if ( selection_html == '' ) if ( selection_common.attr('contenteditable') == 'true' && !selection_common.hasClass('rangySelectionBoundary')) selection_common.append(replacement_node.contents()) else replacement_node.insertAfter(selection_common) # avoid inserting _in_ hyperlinks else range.insertNode(replacement_node[0]) nugget = new DOMNugget() @options.editable.element.closest('.nugget').find('.auto-cite').remove() occ.UpdateNuggetSourceDescriptions({loid:target_loid}) # launch sourcedescription editor with newly created sourcedescription new_sd_node = jQuery('#' + tmp_id); new_sd_node.removeAttr('id') #console.log(new_sd_node) nugget.commitSourceDescriptionChanges(@options.editable.element).done => #console.log(new_sd_node) @openSourceDescriptionEditor(nugget,target_loid,new_sd_node) @back() openSourceDescriptionEditor: (nugget,target_loid,new_sd_node) -> nugget.getSourceDescriptionData(new_sd_node).done (citation_data) => jQuery('body').hallosourcedescriptioneditor 'loid': citation_data.loid 'element': new_sd_node 'back': false 'nugget_loid': target_loid back: -> @widget.remove() jQuery('#basepublicationselectortoolbar').remove() jQuery('body').css({'overflow':'auto'}) @options.editable.restoreContentPosition() @options.editable.activate() select: (node) -> @current_node = jQuery(node).attr('id') @current_node_label = jQuery(node).text() @widget.find(".citation_data_processed").slideUp 'slow', () -> jQuery(this).remove() omc_settings.getSettings().done (settings) => @citeproc.init().done => loid = jQuery(node).attr('id').replace(/node_/,'') omc.getPublicationCitationData(loid).done (citation_data) => if ( jQuery(node).find(".citation_data_processed").length == 0 ) jQuery(node).append('<div class="citation_data_processed"></div>') jQuery.each citation_data, (key,value) => jQuery(node).find('.citation_data_processed').append('<span class="cite"><span class="csl" id="' + key + '"></span></span></div>') @citeproc.resetCitationData() @citeproc.appendCitationData(citation_data) @citeproc.citation_style = settings['default_citation_style'] @citeproc.process('#node_' + loid + ' .citation_data_processed', settings.iso_language) endnotes = @citeproc.endnotes() endnotes = endnotes.replace(/\[1\]/,'') jQuery(node).find('.citation_data_processed').html(endnotes).slideDown() _createInput: (identifier, label, value) -> input = jQuery('<div><label for="' + identifier + '">' + label + '</label><input id="' + identifier + '" type="text" value="<!--user-data-->"/></div>') input.find('input').bind 'blur', (event) => @_formChanged(event,@options) input.find('input').val(value) input _formChanged: (event, options) -> target = jQuery(event.target) #debug.log('form changed' + target.html()) path = target.attr('id') data = target.val() if omc && options.loid omc.storePublicationDescriptionAttribute(options.loid,path,data) #debug.log('stored',options.loid,path,data) _create: -> #debug.log('created'); @ )(jQuery)
[ { "context": "module.exports =\n 'purisima-creek':\n name: 'Purisima Creek'\n picture: '/pictures/purisima.jpg'\n area: ", "end": 62, "score": 0.9872609376907349, "start": 48, "tag": "NAME", "value": "Purisima Creek" }, { "context": "g', '/purisima/4.jpg']\n 'mori-point':\...
src/models/hikes.coffee
rachelmcquirk/hiking
0
module.exports = 'purisima-creek': name: 'Purisima Creek' picture: '/pictures/purisima.jpg' area: 'Penninsula Area' path: '/hikes/san-francisco-bay/purisima-creek' length: '3.3 miles' location: 'Purisima Creek Redwoods' elevation: 'x feet' latitude: 37.44963 longitude: -122.33882 difficulty: 'Moderate' parking: 'No fees. The directions will take you to the main entrance which allows for at least 20 cars.' highlights: ['Restrooms', 'Redwoods', 'Multiple Trails', 'Free Parking'] negatives: ['no dogs', 'no water fountains'] photos: ['/purisima/1.jpg', '/purisima/2.jpg', '/purisima/3.jpg', '/purisima/4.jpg'] 'mori-point': name: 'Mori Point' picture: '/pictures/moripoint.jpg' area: 'Penninsula Area' path: '/hikes/san-francisco-bay/mori-point' length: '2.1 miles' location: '' elevation: 'x feet' latitude: 37.608988 longitude: -122.48602 difficulty: 'Moderate' parking: 'The directions take you to a neighborhood where the trail is located. Park on the side and continue on straight to the trail.' highlights: ['Coastal', 'Restrooms', 'Dogs allowed', 'Spring flowers', 'Free Parking'] negatives: ['No water fountains'] photos: ['/mori/1.jpg', '/mori/2.jpg', '/mori/3.jpg', '/mori/4.jpg'] 'san-pedro-valley': name: 'Montara Mountain Trail' picture: '/pictures/sanpedro.jpg' area: 'Penninsula Area' path: '/hikes/san-francisco-bay/san-pedro-valley' length: '2.1 miles' location: 'San Pedro Valley' elevation: '1174 feet' latitude: 37.57659 longitude: -122.47997 difficulty: 'Strenuous' parking: '$6 parking fee.' highlights: ['Equestrian', 'Beach/Bay views'] negatives: ['No dogs', ] photos: ['/sanpedro/1.jpg', '/sanpedro/2.jpg', '/sanpedro/3.jpg', '/sanpedro/4.jpg']
173208
module.exports = 'purisima-creek': name: '<NAME>' picture: '/pictures/purisima.jpg' area: 'Penninsula Area' path: '/hikes/san-francisco-bay/purisima-creek' length: '3.3 miles' location: 'Purisima Creek Redwoods' elevation: 'x feet' latitude: 37.44963 longitude: -122.33882 difficulty: 'Moderate' parking: 'No fees. The directions will take you to the main entrance which allows for at least 20 cars.' highlights: ['Restrooms', 'Redwoods', 'Multiple Trails', 'Free Parking'] negatives: ['no dogs', 'no water fountains'] photos: ['/purisima/1.jpg', '/purisima/2.jpg', '/purisima/3.jpg', '/purisima/4.jpg'] 'mori-point': name: '<NAME>' picture: '/pictures/moripoint.jpg' area: 'Penninsula Area' path: '/hikes/san-francisco-bay/mori-point' length: '2.1 miles' location: '' elevation: 'x feet' latitude: 37.608988 longitude: -122.48602 difficulty: 'Moderate' parking: 'The directions take you to a neighborhood where the trail is located. Park on the side and continue on straight to the trail.' highlights: ['Coastal', 'Restrooms', 'Dogs allowed', 'Spring flowers', 'Free Parking'] negatives: ['No water fountains'] photos: ['/mori/1.jpg', '/mori/2.jpg', '/mori/3.jpg', '/mori/4.jpg'] 'san-pedro-valley': name: 'Montara Mountain Trail' picture: '/pictures/sanpedro.jpg' area: 'Penninsula Area' path: '/hikes/san-francisco-bay/san-pedro-valley' length: '2.1 miles' location: 'San Pedro Valley' elevation: '1174 feet' latitude: 37.57659 longitude: -122.47997 difficulty: 'Strenuous' parking: '$6 parking fee.' highlights: ['Equestrian', 'Beach/Bay views'] negatives: ['No dogs', ] photos: ['/sanpedro/1.jpg', '/sanpedro/2.jpg', '/sanpedro/3.jpg', '/sanpedro/4.jpg']
true
module.exports = 'purisima-creek': name: 'PI:NAME:<NAME>END_PI' picture: '/pictures/purisima.jpg' area: 'Penninsula Area' path: '/hikes/san-francisco-bay/purisima-creek' length: '3.3 miles' location: 'Purisima Creek Redwoods' elevation: 'x feet' latitude: 37.44963 longitude: -122.33882 difficulty: 'Moderate' parking: 'No fees. The directions will take you to the main entrance which allows for at least 20 cars.' highlights: ['Restrooms', 'Redwoods', 'Multiple Trails', 'Free Parking'] negatives: ['no dogs', 'no water fountains'] photos: ['/purisima/1.jpg', '/purisima/2.jpg', '/purisima/3.jpg', '/purisima/4.jpg'] 'mori-point': name: 'PI:NAME:<NAME>END_PI' picture: '/pictures/moripoint.jpg' area: 'Penninsula Area' path: '/hikes/san-francisco-bay/mori-point' length: '2.1 miles' location: '' elevation: 'x feet' latitude: 37.608988 longitude: -122.48602 difficulty: 'Moderate' parking: 'The directions take you to a neighborhood where the trail is located. Park on the side and continue on straight to the trail.' highlights: ['Coastal', 'Restrooms', 'Dogs allowed', 'Spring flowers', 'Free Parking'] negatives: ['No water fountains'] photos: ['/mori/1.jpg', '/mori/2.jpg', '/mori/3.jpg', '/mori/4.jpg'] 'san-pedro-valley': name: 'Montara Mountain Trail' picture: '/pictures/sanpedro.jpg' area: 'Penninsula Area' path: '/hikes/san-francisco-bay/san-pedro-valley' length: '2.1 miles' location: 'San Pedro Valley' elevation: '1174 feet' latitude: 37.57659 longitude: -122.47997 difficulty: 'Strenuous' parking: '$6 parking fee.' highlights: ['Equestrian', 'Beach/Bay views'] negatives: ['No dogs', ] photos: ['/sanpedro/1.jpg', '/sanpedro/2.jpg', '/sanpedro/3.jpg', '/sanpedro/4.jpg']
[ { "context": "n \"{your answer} who?\", then \"lol\"\n#\n# Author:\n# Tim Kinnane\n#\n\nmodule.exports = (robot) ->\n require '../../l", "end": 464, "score": 0.9998759031295776, "start": 453, "tag": "NAME", "value": "Tim Kinnane" } ]
integration/scripts/knock-knock-direct-reply.coffee
PropertyUX/nubot-playbook
0
# Description: # Tell Hubot a knock knock joke - it is guaranteed to laugh # Uses inline path declarations, with branches separate (is a little cleaner) # # Dependencies: # hubot-playbook # # Configuration: # Playbook direct scene responds to a single user and room # sendReplies: ture (false by default) - Hubot will reply to the user # # Commands: # knock - it will say "Who's there", then "{your answer} who?", then "lol" # # Author: # Tim Kinnane # module.exports = (robot) -> require '../../lib' .use robot .sceneHear /knock/, scope: 'direct', sendReplies: true, (res) -> res.dialogue.addPath "Who's there?" res.dialogue.addBranch /.*/, (res) -> res.dialogue.addPath "#{ res.match[0] } who?" res.dialogue.addBranch /.*/, "lol"
198546
# Description: # Tell Hubot a knock knock joke - it is guaranteed to laugh # Uses inline path declarations, with branches separate (is a little cleaner) # # Dependencies: # hubot-playbook # # Configuration: # Playbook direct scene responds to a single user and room # sendReplies: ture (false by default) - Hubot will reply to the user # # Commands: # knock - it will say "Who's there", then "{your answer} who?", then "lol" # # Author: # <NAME> # module.exports = (robot) -> require '../../lib' .use robot .sceneHear /knock/, scope: 'direct', sendReplies: true, (res) -> res.dialogue.addPath "Who's there?" res.dialogue.addBranch /.*/, (res) -> res.dialogue.addPath "#{ res.match[0] } who?" res.dialogue.addBranch /.*/, "lol"
true
# Description: # Tell Hubot a knock knock joke - it is guaranteed to laugh # Uses inline path declarations, with branches separate (is a little cleaner) # # Dependencies: # hubot-playbook # # Configuration: # Playbook direct scene responds to a single user and room # sendReplies: ture (false by default) - Hubot will reply to the user # # Commands: # knock - it will say "Who's there", then "{your answer} who?", then "lol" # # Author: # PI:NAME:<NAME>END_PI # module.exports = (robot) -> require '../../lib' .use robot .sceneHear /knock/, scope: 'direct', sendReplies: true, (res) -> res.dialogue.addPath "Who's there?" res.dialogue.addBranch /.*/, (res) -> res.dialogue.addPath "#{ res.match[0] } who?" res.dialogue.addBranch /.*/, "lol"
[ { "context": " enable=max_line_length\n done()\n \n it 'john due',(done)->\n npmFetchAvatar 'john due',(error,re", "end": 448, "score": 0.9805943965911865, "start": 440, "tag": "NAME", "value": "john due" }, { "context": " \n it 'john due',(done)->\n npmFetchAvat...
index.spec.coffee
59naga/npm-fetch-avatar
0
# Dependencies npmFetchAvatar= require './' # Environment jasmine.DEFAULT_TIMEOUT_INTERVAL= 5000 # Specs describe 'npmFetchAvatar',-> it 'substack',(done)-> npmFetchAvatar 'substack',(error,result)-> # coffeelint: disable=max_line_length expect(result).toBe 'https://secure.gravatar.com/avatar/d4a2f12ceae3b7f211b661576d22bfb9?size=496&default=retro' # coffeelint: enable=max_line_length done() it 'john due',(done)-> npmFetchAvatar 'john due',(error,result)-> expect(error).toBe null expect(result).toBe undefined done()
8169
# Dependencies npmFetchAvatar= require './' # Environment jasmine.DEFAULT_TIMEOUT_INTERVAL= 5000 # Specs describe 'npmFetchAvatar',-> it 'substack',(done)-> npmFetchAvatar 'substack',(error,result)-> # coffeelint: disable=max_line_length expect(result).toBe 'https://secure.gravatar.com/avatar/d4a2f12ceae3b7f211b661576d22bfb9?size=496&default=retro' # coffeelint: enable=max_line_length done() it '<NAME>',(done)-> npmFetchAvatar '<NAME>',(error,result)-> expect(error).toBe null expect(result).toBe undefined done()
true
# Dependencies npmFetchAvatar= require './' # Environment jasmine.DEFAULT_TIMEOUT_INTERVAL= 5000 # Specs describe 'npmFetchAvatar',-> it 'substack',(done)-> npmFetchAvatar 'substack',(error,result)-> # coffeelint: disable=max_line_length expect(result).toBe 'https://secure.gravatar.com/avatar/d4a2f12ceae3b7f211b661576d22bfb9?size=496&default=retro' # coffeelint: enable=max_line_length done() it 'PI:NAME:<NAME>END_PI',(done)-> npmFetchAvatar 'PI:NAME:<NAME>END_PI',(error,result)-> expect(error).toBe null expect(result).toBe undefined done()
[ { "context": "rr, docs) ->\n items.concat([{cognome: 'Petrucci', 'Fabio'}])\n\n items\n # .when '/regis", "end": 683, "score": 0.9997749328613281, "start": 675, "tag": "NAME", "value": "Petrucci" }, { "context": "\n items.concat([{cognome: 'Petrucci'...
app/app.coffee
biospank/brunch-nw-angular-seed
3
'use strict' # Declare app level module which depends on filters, and services angular.module('app', [ 'ngCookies' 'ngResource' 'ngRoute' 'app.controllers' 'app.directives' 'app.filters' 'app.services' ]) .config([ '$routeProvider' '$locationProvider' ($routeProvider, $locationProvider, config) -> $routeProvider .when '/todo', templateUrl: 'partials/todo.html' controller: 'TodoCtrl' .when '/registry/new', templateUrl: 'partials/registry/new.html' controller: 'RegistryCtrl' resolve: actors: (store) -> items = [] store.find {}, (err, docs) -> items.concat([{cognome: 'Petrucci', 'Fabio'}]) items # .when '/registry/edit/:regid', # templateUrl: '/partials/registry/edit.html' # controller: 'RegistryCtrl' .when('/view1', {templateUrl: 'partials/partial1.html'}) .when('/view2', {templateUrl: 'partials/partial2.html'}) # Catch all .otherwise({redirectTo: '/todo'}) # Without server side support html5 must be disabled. $locationProvider.html5Mode(false) ])
39399
'use strict' # Declare app level module which depends on filters, and services angular.module('app', [ 'ngCookies' 'ngResource' 'ngRoute' 'app.controllers' 'app.directives' 'app.filters' 'app.services' ]) .config([ '$routeProvider' '$locationProvider' ($routeProvider, $locationProvider, config) -> $routeProvider .when '/todo', templateUrl: 'partials/todo.html' controller: 'TodoCtrl' .when '/registry/new', templateUrl: 'partials/registry/new.html' controller: 'RegistryCtrl' resolve: actors: (store) -> items = [] store.find {}, (err, docs) -> items.concat([{cognome: '<NAME>', '<NAME>'}]) items # .when '/registry/edit/:regid', # templateUrl: '/partials/registry/edit.html' # controller: 'RegistryCtrl' .when('/view1', {templateUrl: 'partials/partial1.html'}) .when('/view2', {templateUrl: 'partials/partial2.html'}) # Catch all .otherwise({redirectTo: '/todo'}) # Without server side support html5 must be disabled. $locationProvider.html5Mode(false) ])
true
'use strict' # Declare app level module which depends on filters, and services angular.module('app', [ 'ngCookies' 'ngResource' 'ngRoute' 'app.controllers' 'app.directives' 'app.filters' 'app.services' ]) .config([ '$routeProvider' '$locationProvider' ($routeProvider, $locationProvider, config) -> $routeProvider .when '/todo', templateUrl: 'partials/todo.html' controller: 'TodoCtrl' .when '/registry/new', templateUrl: 'partials/registry/new.html' controller: 'RegistryCtrl' resolve: actors: (store) -> items = [] store.find {}, (err, docs) -> items.concat([{cognome: 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'}]) items # .when '/registry/edit/:regid', # templateUrl: '/partials/registry/edit.html' # controller: 'RegistryCtrl' .when('/view1', {templateUrl: 'partials/partial1.html'}) .when('/view2', {templateUrl: 'partials/partial2.html'}) # Catch all .otherwise({redirectTo: '/todo'}) # Without server side support html5 must be disabled. $locationProvider.html5Mode(false) ])
[ { "context": "debug文件push到生产目录,并将引用到的背景图片自动添加hash后缀\n* \n* @author pjg <iampjg@gmail.com>\n* @link http://pjg.pw\n* @versi", "end": 80, "score": 0.9996275901794434, "start": 77, "tag": "USERNAME", "value": "pjg" }, { "context": "件push到生产目录,并将引用到的背景图片自动添加hash后缀\n* \n* @author pjg <iam...
node_modules/vbuilder/lib/cssCtl/index.coffee
duolaimi/v.builder.site
0
###* * @fileOverview 将CSS的debug文件push到生产目录,并将引用到的背景图片自动添加hash后缀 * * @author pjg <iampjg@gmail.com> * @link http://pjg.pw * @version $Id$ ### fs = require 'fs' path = require 'path' _ = require 'lodash' crypto = require 'crypto' vfs = require 'vinyl-fs' gutil = require 'gulp-util' less = require 'gulp-less' mincss = require 'gulp-minify-css' # sourcemaps = require 'gulp-sourcemaps' autoprefixer = require 'gulp-autoprefixer' plumber = require 'gulp-plumber' color = gutil.colors Utils = require '../utils' ImgCtl = require '../imgCtl' class CssCtl # 参数初始化 constructor:(@opts)-> @root = @opts.root @hashLen = @opts.hashLen @srcPath = @opts.srcPath @debugPath = @opts.debugPath @distPath = @opts.distPath @lessPath = @srcPath + 'less' @cssDebugPath = @debugPath + 'css' @imgDistPath = @distPath + 'img' @cssDistPath = @distPath + 'css' @env = @opts.env @isDebug = @opts.isDebug # 替换背景图片,带上md5版本戳 _replaceImgPaths: (source)-> _this = @ Utils.getMap('imgMap') if _.has(global.Cache,'imgMap') _cssBgMap = global.Cache['imgMap'] # console.log _cssBgMap _sPath = source.path _sPath = Utils.tranFilePath _sPath _type = if _sPath.indexOf('/less/') isnt -1 then 'less' else 'css' _sPath = _sPath.split("/#{_type}/")[1] .replace(/\\/g,'/') # 计算CSS文件的目录深度 _pathDeeps = '' _temArr = _sPath.split('/') for i,k in _temArr _pathDeeps += '../' # 文件相对路径的对象 _nameObj = path.parse(_sPath) _nameObj.hash = Utils.md5(source.contents) # 替换CSS中的背景图片,加上md5版本戳 _cssBgReg = /url\s*\(([^\)]+)\)/g _source = String(source.contents).replace _cssBgReg, (str,map)-> # 过滤一些标签 if map.indexOf('fonts/') isnt -1 or map.indexOf('font/') isnt -1 or map.indexOf('#') isnt -1 or map.indexOf('//:') isnt -1 or map.indexOf('about:') isnt -1 or map.indexOf('data:') isnt -1 return str else key = map.split('/img/')[1] .replace(/(^\'|\")|(\'|\"$)/g, '') val = _pathDeeps + "img/" if _type is 'less' val += key else val += if _.has(_cssBgMap,key) then _cssBgMap[key].distname else key + '?t=' + String(new Date().getTime()).substr(0,8) # console.log str.replace(map, val) return str.replace(map, val) return _source # 替换css的背景图片,加上hash _stream: (files,cb,cb2)-> _this = @ vfs.src files .pipe plumber({errorHandler: Utils.errrHandler}) .pipe mincss({ keepBreaks:false compatibility: properties: iePrefixHack:true ieSuffixHack:true }) .on 'data',(source)-> _path = Utils.tranFilePath source.path _path = _path.split('/css/')[1] .replace(/\\/g,'/') # 文件相对路径的对象 _nameObj = path.parse(_path) _nameObj.hash = Utils.md5(source.contents) # 替换CSS背景图片,带上版本 _source = _this._replaceImgPaths(source) cb(_nameObj,_source ) .on 'end',cb2 ###* * 从less生成css源码 ### less2css: (cb,offLog)-> _this = @ _cb = cb or -> _files = [ path.join(@lessPath, '*.less') path.join(@lessPath, '**/*.less') "!#{path.join(@lessPath, '_*.less')}" "!#{path.join(@lessPath, '_**/*.less')}" "!#{path.join(@lessPath, '_**/**/*.less')}" "!#{path.join(@lessPath, '_**/**/**/*.less')}" ] _offLog = offLog or true _lessPath = _this.lessPath _cssDistPath = _this.cssDebugPath vfs.src(_files) .pipe plumber({errorHandler: Utils.errrHandler}) .pipe less compress: false paths: [_lessPath] .pipe autoprefixer() .on 'data',(res)-> # console.log res.path _path = Utils.tranFilePath res.path _fileName = _path.split('/less/')[1] .replace(/\\/g,'/') _filePath = path.join _cssDistPath,_fileName _LessName = _fileName.replace('.css','.less') _source = _this._replaceImgPaths(res) Utils.writeFile(_filePath,_source,!0) !_offLog and gutil.log '\'' + color.cyan(_LessName) + '\'','build success.' .on 'end',-> _cb() ### # css生产文件构建函数 # @param {string} file 同gulp.src接口所接收的参数,默认是css源文件的所有css文件 # @param {function} done 回调函数 ### css2dist: (file,done)-> _this = @ if not file _done = -> _file = [_this.cssDebugPath + '/*.css',_this.cssDebugPath + '/**/*.css'] else if typeof file is 'function' _done = file _file = [_this.cssDebugPath + '/*.css',_this.cssDebugPath + '/**/*.css'] else _file = file _done = done # 读取缓存 Utils.getMap("cssMap") if not _.has(global.Cache,'cssMap') cssMap = global.Cache['cssMap'] _hashLen = _this.hashLen # console.log _file _this._stream( _file (obj,source)-> _source = source _distPath = obj.dir + '/' + obj.name + '.' + obj.hash.substr(0,_hashLen) + obj.ext _distPath2 = obj.dir + '/' + obj.name + obj.ext cssMap[_distPath2.replace(/^\//,'')] = hash : obj.hash distname : _distPath.replace(/^\//,'') _filePath = path.join(_this.root, _this.cssDistPath, _distPath) _filePath2 = path.join(_this.root, _this.cssDistPath, _distPath2) if not fs.existsSync(_filePath) Utils.writeFile(_filePath,_source) Utils.writeFile(_filePath2,_source,!0) -> Utils.updateMap(cssMap,'cssMap') Utils.saveMapFile('cssMap') _done() ) init: (cb)-> gutil.log 'Starting','\'' + color.cyan('LESS-->CSS') + '\'...' _this = @ _this.less2css -> gutil.log '\'' + color.cyan('LESS') + '\'','build success.' if _this.env isnt 'local' and _this.env isnt 'dev' _this.css2dist -> gutil.log '\'' + color.cyan('CSS') + '\'','build success.' cb and cb() else if _this.isDebug and _this.env is 'local' _this.css2dist -> gutil.log '\'' + color.cyan('CSS') + '\'','build success.' cb and cb() else cb and cb() module.exports = CssCtl
75923
###* * @fileOverview 将CSS的debug文件push到生产目录,并将引用到的背景图片自动添加hash后缀 * * @author pjg <<EMAIL>> * @link http://pjg.pw * @version $Id$ ### fs = require 'fs' path = require 'path' _ = require 'lodash' crypto = require 'crypto' vfs = require 'vinyl-fs' gutil = require 'gulp-util' less = require 'gulp-less' mincss = require 'gulp-minify-css' # sourcemaps = require 'gulp-sourcemaps' autoprefixer = require 'gulp-autoprefixer' plumber = require 'gulp-plumber' color = gutil.colors Utils = require '../utils' ImgCtl = require '../imgCtl' class CssCtl # 参数初始化 constructor:(@opts)-> @root = @opts.root @hashLen = @opts.hashLen @srcPath = @opts.srcPath @debugPath = @opts.debugPath @distPath = @opts.distPath @lessPath = @srcPath + 'less' @cssDebugPath = @debugPath + 'css' @imgDistPath = @distPath + 'img' @cssDistPath = @distPath + 'css' @env = @opts.env @isDebug = @opts.isDebug # 替换背景图片,带上md5版本戳 _replaceImgPaths: (source)-> _this = @ Utils.getMap('imgMap') if _.has(global.Cache,'imgMap') _cssBgMap = global.Cache['imgMap'] # console.log _cssBgMap _sPath = source.path _sPath = Utils.tranFilePath _sPath _type = if _sPath.indexOf('/less/') isnt -1 then 'less' else 'css' _sPath = _sPath.split("/#{_type}/")[1] .replace(/\\/g,'/') # 计算CSS文件的目录深度 _pathDeeps = '' _temArr = _sPath.split('/') for i,k in _temArr _pathDeeps += '../' # 文件相对路径的对象 _nameObj = path.parse(_sPath) _nameObj.hash = Utils.md5(source.contents) # 替换CSS中的背景图片,加上md5版本戳 _cssBgReg = /url\s*\(([^\)]+)\)/g _source = String(source.contents).replace _cssBgReg, (str,map)-> # 过滤一些标签 if map.indexOf('fonts/') isnt -1 or map.indexOf('font/') isnt -1 or map.indexOf('#') isnt -1 or map.indexOf('//:') isnt -1 or map.indexOf('about:') isnt -1 or map.indexOf('data:') isnt -1 return str else key = map.split('/img/')[1] .replace(/(^\'|\")|(\'|\"$)/g, '') val = _pathDeeps + "img/" if _type is 'less' val += key else val += if _.has(_cssBgMap,key) then _cssBgMap[key].distname else key + '?t=' + String(new Date().getTime()).substr(0,8) # console.log str.replace(map, val) return str.replace(map, val) return _source # 替换css的背景图片,加上hash _stream: (files,cb,cb2)-> _this = @ vfs.src files .pipe plumber({errorHandler: Utils.errrHandler}) .pipe mincss({ keepBreaks:false compatibility: properties: iePrefixHack:true ieSuffixHack:true }) .on 'data',(source)-> _path = Utils.tranFilePath source.path _path = _path.split('/css/')[1] .replace(/\\/g,'/') # 文件相对路径的对象 _nameObj = path.parse(_path) _nameObj.hash = Utils.md5(source.contents) # 替换CSS背景图片,带上版本 _source = _this._replaceImgPaths(source) cb(_nameObj,_source ) .on 'end',cb2 ###* * 从less生成css源码 ### less2css: (cb,offLog)-> _this = @ _cb = cb or -> _files = [ path.join(@lessPath, '*.less') path.join(@lessPath, '**/*.less') "!#{path.join(@lessPath, '_*.less')}" "!#{path.join(@lessPath, '_**/*.less')}" "!#{path.join(@lessPath, '_**/**/*.less')}" "!#{path.join(@lessPath, '_**/**/**/*.less')}" ] _offLog = offLog or true _lessPath = _this.lessPath _cssDistPath = _this.cssDebugPath vfs.src(_files) .pipe plumber({errorHandler: Utils.errrHandler}) .pipe less compress: false paths: [_lessPath] .pipe autoprefixer() .on 'data',(res)-> # console.log res.path _path = Utils.tranFilePath res.path _fileName = _path.split('/less/')[1] .replace(/\\/g,'/') _filePath = path.join _cssDistPath,_fileName _LessName = _fileName.replace('.css','.less') _source = _this._replaceImgPaths(res) Utils.writeFile(_filePath,_source,!0) !_offLog and gutil.log '\'' + color.cyan(_LessName) + '\'','build success.' .on 'end',-> _cb() ### # css生产文件构建函数 # @param {string} file 同gulp.src接口所接收的参数,默认是css源文件的所有css文件 # @param {function} done 回调函数 ### css2dist: (file,done)-> _this = @ if not file _done = -> _file = [_this.cssDebugPath + '/*.css',_this.cssDebugPath + '/**/*.css'] else if typeof file is 'function' _done = file _file = [_this.cssDebugPath + '/*.css',_this.cssDebugPath + '/**/*.css'] else _file = file _done = done # 读取缓存 Utils.getMap("cssMap") if not _.has(global.Cache,'cssMap') cssMap = global.Cache['cssMap'] _hashLen = _this.hashLen # console.log _file _this._stream( _file (obj,source)-> _source = source _distPath = obj.dir + '/' + obj.name + '.' + obj.hash.substr(0,_hashLen) + obj.ext _distPath2 = obj.dir + '/' + obj.name + obj.ext cssMap[_distPath2.replace(/^\//,'')] = hash : obj.hash distname : _distPath.replace(/^\//,'') _filePath = path.join(_this.root, _this.cssDistPath, _distPath) _filePath2 = path.join(_this.root, _this.cssDistPath, _distPath2) if not fs.existsSync(_filePath) Utils.writeFile(_filePath,_source) Utils.writeFile(_filePath2,_source,!0) -> Utils.updateMap(cssMap,'cssMap') Utils.saveMapFile('cssMap') _done() ) init: (cb)-> gutil.log 'Starting','\'' + color.cyan('LESS-->CSS') + '\'...' _this = @ _this.less2css -> gutil.log '\'' + color.cyan('LESS') + '\'','build success.' if _this.env isnt 'local' and _this.env isnt 'dev' _this.css2dist -> gutil.log '\'' + color.cyan('CSS') + '\'','build success.' cb and cb() else if _this.isDebug and _this.env is 'local' _this.css2dist -> gutil.log '\'' + color.cyan('CSS') + '\'','build success.' cb and cb() else cb and cb() module.exports = CssCtl
true
###* * @fileOverview 将CSS的debug文件push到生产目录,并将引用到的背景图片自动添加hash后缀 * * @author pjg <PI:EMAIL:<EMAIL>END_PI> * @link http://pjg.pw * @version $Id$ ### fs = require 'fs' path = require 'path' _ = require 'lodash' crypto = require 'crypto' vfs = require 'vinyl-fs' gutil = require 'gulp-util' less = require 'gulp-less' mincss = require 'gulp-minify-css' # sourcemaps = require 'gulp-sourcemaps' autoprefixer = require 'gulp-autoprefixer' plumber = require 'gulp-plumber' color = gutil.colors Utils = require '../utils' ImgCtl = require '../imgCtl' class CssCtl # 参数初始化 constructor:(@opts)-> @root = @opts.root @hashLen = @opts.hashLen @srcPath = @opts.srcPath @debugPath = @opts.debugPath @distPath = @opts.distPath @lessPath = @srcPath + 'less' @cssDebugPath = @debugPath + 'css' @imgDistPath = @distPath + 'img' @cssDistPath = @distPath + 'css' @env = @opts.env @isDebug = @opts.isDebug # 替换背景图片,带上md5版本戳 _replaceImgPaths: (source)-> _this = @ Utils.getMap('imgMap') if _.has(global.Cache,'imgMap') _cssBgMap = global.Cache['imgMap'] # console.log _cssBgMap _sPath = source.path _sPath = Utils.tranFilePath _sPath _type = if _sPath.indexOf('/less/') isnt -1 then 'less' else 'css' _sPath = _sPath.split("/#{_type}/")[1] .replace(/\\/g,'/') # 计算CSS文件的目录深度 _pathDeeps = '' _temArr = _sPath.split('/') for i,k in _temArr _pathDeeps += '../' # 文件相对路径的对象 _nameObj = path.parse(_sPath) _nameObj.hash = Utils.md5(source.contents) # 替换CSS中的背景图片,加上md5版本戳 _cssBgReg = /url\s*\(([^\)]+)\)/g _source = String(source.contents).replace _cssBgReg, (str,map)-> # 过滤一些标签 if map.indexOf('fonts/') isnt -1 or map.indexOf('font/') isnt -1 or map.indexOf('#') isnt -1 or map.indexOf('//:') isnt -1 or map.indexOf('about:') isnt -1 or map.indexOf('data:') isnt -1 return str else key = map.split('/img/')[1] .replace(/(^\'|\")|(\'|\"$)/g, '') val = _pathDeeps + "img/" if _type is 'less' val += key else val += if _.has(_cssBgMap,key) then _cssBgMap[key].distname else key + '?t=' + String(new Date().getTime()).substr(0,8) # console.log str.replace(map, val) return str.replace(map, val) return _source # 替换css的背景图片,加上hash _stream: (files,cb,cb2)-> _this = @ vfs.src files .pipe plumber({errorHandler: Utils.errrHandler}) .pipe mincss({ keepBreaks:false compatibility: properties: iePrefixHack:true ieSuffixHack:true }) .on 'data',(source)-> _path = Utils.tranFilePath source.path _path = _path.split('/css/')[1] .replace(/\\/g,'/') # 文件相对路径的对象 _nameObj = path.parse(_path) _nameObj.hash = Utils.md5(source.contents) # 替换CSS背景图片,带上版本 _source = _this._replaceImgPaths(source) cb(_nameObj,_source ) .on 'end',cb2 ###* * 从less生成css源码 ### less2css: (cb,offLog)-> _this = @ _cb = cb or -> _files = [ path.join(@lessPath, '*.less') path.join(@lessPath, '**/*.less') "!#{path.join(@lessPath, '_*.less')}" "!#{path.join(@lessPath, '_**/*.less')}" "!#{path.join(@lessPath, '_**/**/*.less')}" "!#{path.join(@lessPath, '_**/**/**/*.less')}" ] _offLog = offLog or true _lessPath = _this.lessPath _cssDistPath = _this.cssDebugPath vfs.src(_files) .pipe plumber({errorHandler: Utils.errrHandler}) .pipe less compress: false paths: [_lessPath] .pipe autoprefixer() .on 'data',(res)-> # console.log res.path _path = Utils.tranFilePath res.path _fileName = _path.split('/less/')[1] .replace(/\\/g,'/') _filePath = path.join _cssDistPath,_fileName _LessName = _fileName.replace('.css','.less') _source = _this._replaceImgPaths(res) Utils.writeFile(_filePath,_source,!0) !_offLog and gutil.log '\'' + color.cyan(_LessName) + '\'','build success.' .on 'end',-> _cb() ### # css生产文件构建函数 # @param {string} file 同gulp.src接口所接收的参数,默认是css源文件的所有css文件 # @param {function} done 回调函数 ### css2dist: (file,done)-> _this = @ if not file _done = -> _file = [_this.cssDebugPath + '/*.css',_this.cssDebugPath + '/**/*.css'] else if typeof file is 'function' _done = file _file = [_this.cssDebugPath + '/*.css',_this.cssDebugPath + '/**/*.css'] else _file = file _done = done # 读取缓存 Utils.getMap("cssMap") if not _.has(global.Cache,'cssMap') cssMap = global.Cache['cssMap'] _hashLen = _this.hashLen # console.log _file _this._stream( _file (obj,source)-> _source = source _distPath = obj.dir + '/' + obj.name + '.' + obj.hash.substr(0,_hashLen) + obj.ext _distPath2 = obj.dir + '/' + obj.name + obj.ext cssMap[_distPath2.replace(/^\//,'')] = hash : obj.hash distname : _distPath.replace(/^\//,'') _filePath = path.join(_this.root, _this.cssDistPath, _distPath) _filePath2 = path.join(_this.root, _this.cssDistPath, _distPath2) if not fs.existsSync(_filePath) Utils.writeFile(_filePath,_source) Utils.writeFile(_filePath2,_source,!0) -> Utils.updateMap(cssMap,'cssMap') Utils.saveMapFile('cssMap') _done() ) init: (cb)-> gutil.log 'Starting','\'' + color.cyan('LESS-->CSS') + '\'...' _this = @ _this.less2css -> gutil.log '\'' + color.cyan('LESS') + '\'','build success.' if _this.env isnt 'local' and _this.env isnt 'dev' _this.css2dist -> gutil.log '\'' + color.cyan('CSS') + '\'','build success.' cb and cb() else if _this.isDebug and _this.env is 'local' _this.css2dist -> gutil.log '\'' + color.cyan('CSS') + '\'','build success.' cb and cb() else cb and cb() module.exports = CssCtl
[ { "context": ".js --preamble \"// Sequenced v<%= pkg.version %> | arielyang@github | MIT Licensed\"'\n\t\t\t\tcwd: '.'\n\n\t\tconcat:\n\t\t\tdist:", "end": 385, "score": 0.9753665924072266, "start": 369, "tag": "EMAIL", "value": "arielyang@github" } ]
Gruntfile.coffee
arielyang/sequenced
0
module.exports = (grunt) -> # Project configuration. grunt.initConfig pkg: grunt.file.readJSON('package.json') # Task configuration. exec: compile: command: 'coffee -c -b dest/sequenced.coffee' cwd: '.' compress: command: 'uglifyjs dest/sequenced.js --compress --mangle -o dest/sequenced.min.js --preamble "// Sequenced v<%= pkg.version %> | arielyang@github | MIT Licensed"' cwd: '.' concat: dist: src: [ 'lib/sequenced.coffee' 'lib/canvasHelper.coffee' 'lib/definationParser.coffee' ] dest: 'dest/sequenced.coffee' uglify: target: options: mangle: true target: files: 'dest/sequenced.min.js': 'dest/sequenced.js' cwd: '.' watch: build: options: spawn: false livereload: true files: [ 'lib/*' 'test/*' ] tasks: [ 'concat:dist' 'exec:compile' ] connect: server: options: keepalive: true port: 8081 base: '.' # These plugins provide necessary tasks. grunt.loadNpmTasks 'grunt-contrib-concat' grunt.loadNpmTasks 'grunt-contrib-connect' grunt.loadNpmTasks 'grunt-contrib-uglify' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-exec' # Serve a static HTTP server. grunt.registerTask 'server', [ 'connect:server' ] # Build coffee file to js file. grunt.registerTask 'monitor', [ 'concat:dist' 'exec:compile' 'watch:build' ] # Uglify and compress dest js file. grunt.registerTask 'compress', [ 'uglify:target' ]
130940
module.exports = (grunt) -> # Project configuration. grunt.initConfig pkg: grunt.file.readJSON('package.json') # Task configuration. exec: compile: command: 'coffee -c -b dest/sequenced.coffee' cwd: '.' compress: command: 'uglifyjs dest/sequenced.js --compress --mangle -o dest/sequenced.min.js --preamble "// Sequenced v<%= pkg.version %> | <EMAIL> | MIT Licensed"' cwd: '.' concat: dist: src: [ 'lib/sequenced.coffee' 'lib/canvasHelper.coffee' 'lib/definationParser.coffee' ] dest: 'dest/sequenced.coffee' uglify: target: options: mangle: true target: files: 'dest/sequenced.min.js': 'dest/sequenced.js' cwd: '.' watch: build: options: spawn: false livereload: true files: [ 'lib/*' 'test/*' ] tasks: [ 'concat:dist' 'exec:compile' ] connect: server: options: keepalive: true port: 8081 base: '.' # These plugins provide necessary tasks. grunt.loadNpmTasks 'grunt-contrib-concat' grunt.loadNpmTasks 'grunt-contrib-connect' grunt.loadNpmTasks 'grunt-contrib-uglify' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-exec' # Serve a static HTTP server. grunt.registerTask 'server', [ 'connect:server' ] # Build coffee file to js file. grunt.registerTask 'monitor', [ 'concat:dist' 'exec:compile' 'watch:build' ] # Uglify and compress dest js file. grunt.registerTask 'compress', [ 'uglify:target' ]
true
module.exports = (grunt) -> # Project configuration. grunt.initConfig pkg: grunt.file.readJSON('package.json') # Task configuration. exec: compile: command: 'coffee -c -b dest/sequenced.coffee' cwd: '.' compress: command: 'uglifyjs dest/sequenced.js --compress --mangle -o dest/sequenced.min.js --preamble "// Sequenced v<%= pkg.version %> | PI:EMAIL:<EMAIL>END_PI | MIT Licensed"' cwd: '.' concat: dist: src: [ 'lib/sequenced.coffee' 'lib/canvasHelper.coffee' 'lib/definationParser.coffee' ] dest: 'dest/sequenced.coffee' uglify: target: options: mangle: true target: files: 'dest/sequenced.min.js': 'dest/sequenced.js' cwd: '.' watch: build: options: spawn: false livereload: true files: [ 'lib/*' 'test/*' ] tasks: [ 'concat:dist' 'exec:compile' ] connect: server: options: keepalive: true port: 8081 base: '.' # These plugins provide necessary tasks. grunt.loadNpmTasks 'grunt-contrib-concat' grunt.loadNpmTasks 'grunt-contrib-connect' grunt.loadNpmTasks 'grunt-contrib-uglify' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-exec' # Serve a static HTTP server. grunt.registerTask 'server', [ 'connect:server' ] # Build coffee file to js file. grunt.registerTask 'monitor', [ 'concat:dist' 'exec:compile' 'watch:build' ] # Uglify and compress dest js file. grunt.registerTask 'compress', [ 'uglify:target' ]
[ { "context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.", "end": 197, "score": 0.9998764991760254, "start": 180, "tag": "NAME", "value": "Benjamin Blundell" }, { "context": " PXL.js\n ...
examples/lights.coffee
OniDaito/pxljs
1
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js Benjamin Blundell - ben@pxljs.com http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> # Get a couple of colours white = new PXL.Colour.RGBA.WHITE() magnolia = new PXL.Colour.RGBA.MAGNOLIA() # Create some geometry plane = new PXL.Geometry.Plane 10,10 shadowed_node = new PXL.Node plane q = new PXL.Geometry.Quad() # Cameras we need c = new PXL.Camera.MousePerspCamera() cp = new PXL.Camera.PerspCamera() # Materials and lights for the main scene uniformMaterial = new PXL.Material.PhongMaterial white, magnolia, white, 2 shadowed_node.add uniformMaterial sphere = new PXL.Geometry.Sphere 0.2,10 basicMaterial = new PXL.Material.BasicColourMaterial white @light_node = new PXL.Node sphere @light_node.matrix.translate new PXL.Math.Vec3(0,2,0) @light_node.add basicMaterial cube_node = new PXL.Node new PXL.Geometry.Cuboid(new PXL.Math.Vec3(0.5,0.5,0.5)) cube_node.add new PXL.Material.BasicColourMaterial new PXL.Colour.RGB(1,0,0) cube_node.matrix.translate new PXL.Math.Vec3(0.25,0.25,0) shadowed_node.add cube_node ambientlight = new PXL.Light.AmbientLight new PXL.Colour.RGB(0.01,0.01,0.01) @spotlight = new PXL.Light.SpotLight new PXL.Math.Vec3(-2,2,0), white, new PXL.Math.Vec3(1,-1,0), PXL.Math.degToRad(45.0), true shadowed_node.add @spotlight @pointLight = new PXL.Light.PointLight new PXL.Math.Vec3(0,3,0), new PXL.Colour.RGB(0.1,0.12,0.24) @light_node.add @pointLight # our quad node for showing the lights view @quad_node = new PXL.Node q @quad_node.add cp @quad_node.add new PXL.Material.ViewDepthMaterial @spotlight.shadowmap_fbo.texture, 0.01, 10.0 @quad_node.matrix.translate(new PXL.Math.Vec3(1,-1,0)) # Now add the nodes and cameras for the main objects @topnode = new PXL.Node @topnode.add shadowed_node @topnode.add @light_node @topnode.add c uber0 = new PXL.GL.UberShader @topnode uber1 = new PXL.GL.UberShader @quad_node @topnode.add uber0 @quad_node.add uber1 @step = 0 draw = (dt) -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) GL.enable(GL.DEPTH_TEST) # Draw out nodes @topnode.draw() GL.disable(GL.DEPTH_TEST) @quad_node.draw() # Move the light around @step += 0.01 newpos = new PXL.Math.Vec3(Math.sin(@step),2.0 + Math.sin(@step),Math.cos(@step)) newdir = newpos.clone().multScalar(-1).normalize() # Keep the spotlight always pointing at the origin @spotlight.pos.copy newpos @spotlight.dir.copy newdir @light_node.matrix.translatePart newpos params = canvas : 'webgl-canvas' context : @ init : init debug : true draw : draw cgl = new PXL.App params
22287
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js <NAME> - <EMAIL> http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> # Get a couple of colours white = new PXL.Colour.RGBA.WHITE() magnolia = new PXL.Colour.RGBA.MAGNOLIA() # Create some geometry plane = new PXL.Geometry.Plane 10,10 shadowed_node = new PXL.Node plane q = new PXL.Geometry.Quad() # Cameras we need c = new PXL.Camera.MousePerspCamera() cp = new PXL.Camera.PerspCamera() # Materials and lights for the main scene uniformMaterial = new PXL.Material.PhongMaterial white, magnolia, white, 2 shadowed_node.add uniformMaterial sphere = new PXL.Geometry.Sphere 0.2,10 basicMaterial = new PXL.Material.BasicColourMaterial white @light_node = new PXL.Node sphere @light_node.matrix.translate new PXL.Math.Vec3(0,2,0) @light_node.add basicMaterial cube_node = new PXL.Node new PXL.Geometry.Cuboid(new PXL.Math.Vec3(0.5,0.5,0.5)) cube_node.add new PXL.Material.BasicColourMaterial new PXL.Colour.RGB(1,0,0) cube_node.matrix.translate new PXL.Math.Vec3(0.25,0.25,0) shadowed_node.add cube_node ambientlight = new PXL.Light.AmbientLight new PXL.Colour.RGB(0.01,0.01,0.01) @spotlight = new PXL.Light.SpotLight new PXL.Math.Vec3(-2,2,0), white, new PXL.Math.Vec3(1,-1,0), PXL.Math.degToRad(45.0), true shadowed_node.add @spotlight @pointLight = new PXL.Light.PointLight new PXL.Math.Vec3(0,3,0), new PXL.Colour.RGB(0.1,0.12,0.24) @light_node.add @pointLight # our quad node for showing the lights view @quad_node = new PXL.Node q @quad_node.add cp @quad_node.add new PXL.Material.ViewDepthMaterial @spotlight.shadowmap_fbo.texture, 0.01, 10.0 @quad_node.matrix.translate(new PXL.Math.Vec3(1,-1,0)) # Now add the nodes and cameras for the main objects @topnode = new PXL.Node @topnode.add shadowed_node @topnode.add @light_node @topnode.add c uber0 = new PXL.GL.UberShader @topnode uber1 = new PXL.GL.UberShader @quad_node @topnode.add uber0 @quad_node.add uber1 @step = 0 draw = (dt) -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) GL.enable(GL.DEPTH_TEST) # Draw out nodes @topnode.draw() GL.disable(GL.DEPTH_TEST) @quad_node.draw() # Move the light around @step += 0.01 newpos = new PXL.Math.Vec3(Math.sin(@step),2.0 + Math.sin(@step),Math.cos(@step)) newdir = newpos.clone().multScalar(-1).normalize() # Keep the spotlight always pointing at the origin @spotlight.pos.copy newpos @spotlight.dir.copy newdir @light_node.matrix.translatePart newpos params = canvas : 'webgl-canvas' context : @ init : init debug : true draw : draw cgl = new PXL.App params
true
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> # Get a couple of colours white = new PXL.Colour.RGBA.WHITE() magnolia = new PXL.Colour.RGBA.MAGNOLIA() # Create some geometry plane = new PXL.Geometry.Plane 10,10 shadowed_node = new PXL.Node plane q = new PXL.Geometry.Quad() # Cameras we need c = new PXL.Camera.MousePerspCamera() cp = new PXL.Camera.PerspCamera() # Materials and lights for the main scene uniformMaterial = new PXL.Material.PhongMaterial white, magnolia, white, 2 shadowed_node.add uniformMaterial sphere = new PXL.Geometry.Sphere 0.2,10 basicMaterial = new PXL.Material.BasicColourMaterial white @light_node = new PXL.Node sphere @light_node.matrix.translate new PXL.Math.Vec3(0,2,0) @light_node.add basicMaterial cube_node = new PXL.Node new PXL.Geometry.Cuboid(new PXL.Math.Vec3(0.5,0.5,0.5)) cube_node.add new PXL.Material.BasicColourMaterial new PXL.Colour.RGB(1,0,0) cube_node.matrix.translate new PXL.Math.Vec3(0.25,0.25,0) shadowed_node.add cube_node ambientlight = new PXL.Light.AmbientLight new PXL.Colour.RGB(0.01,0.01,0.01) @spotlight = new PXL.Light.SpotLight new PXL.Math.Vec3(-2,2,0), white, new PXL.Math.Vec3(1,-1,0), PXL.Math.degToRad(45.0), true shadowed_node.add @spotlight @pointLight = new PXL.Light.PointLight new PXL.Math.Vec3(0,3,0), new PXL.Colour.RGB(0.1,0.12,0.24) @light_node.add @pointLight # our quad node for showing the lights view @quad_node = new PXL.Node q @quad_node.add cp @quad_node.add new PXL.Material.ViewDepthMaterial @spotlight.shadowmap_fbo.texture, 0.01, 10.0 @quad_node.matrix.translate(new PXL.Math.Vec3(1,-1,0)) # Now add the nodes and cameras for the main objects @topnode = new PXL.Node @topnode.add shadowed_node @topnode.add @light_node @topnode.add c uber0 = new PXL.GL.UberShader @topnode uber1 = new PXL.GL.UberShader @quad_node @topnode.add uber0 @quad_node.add uber1 @step = 0 draw = (dt) -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) GL.enable(GL.DEPTH_TEST) # Draw out nodes @topnode.draw() GL.disable(GL.DEPTH_TEST) @quad_node.draw() # Move the light around @step += 0.01 newpos = new PXL.Math.Vec3(Math.sin(@step),2.0 + Math.sin(@step),Math.cos(@step)) newdir = newpos.clone().multScalar(-1).normalize() # Keep the spotlight always pointing at the origin @spotlight.pos.copy newpos @spotlight.dir.copy newdir @light_node.matrix.translatePart newpos params = canvas : 'webgl-canvas' context : @ init : init debug : true draw : draw cgl = new PXL.App params
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999106526374817, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" }, { "context": "comments.isShowDeleted\n\n el Comment,\n key: comment....
resources/assets/coffee/react/_components/comments.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Comment } from 'comment' import { CommentEditor } from 'comment-editor' import { CommentShowMore } from 'comment-show-more' import { CommentsSort } from 'comments-sort' import DeletedCommentsCount from 'deleted-comments-count' import { Observer } from 'mobx-react' import core from 'osu-core-singleton' import * as React from 'react' import { button, div, h2, span } from 'react-dom-factories' import { Spinner } from 'spinner' el = React.createElement store = core.dataStore.commentStore uiState = core.dataStore.uiState export class Comments extends React.PureComponent render: => el Observer, null, () => # TODO: comments should be passed in as props? comments = uiState.comments.topLevelCommentIds.map (id) -> store.comments.get(id) pinnedComments = uiState.comments.pinnedCommentIds.map (id) -> store.comments.get(id) div className: osu.classWithModifiers('comments', @props.modifiers), div className: 'u-has-anchor u-has-anchor--no-event', div(className: 'fragment-target', id: 'comments') h2 className: 'comments__title', osu.trans('comments.title') span className: 'comments__count', osu.formatNumber(uiState.comments.total) if pinnedComments.length > 0 div className: "comments__items comments__items--pinned", @renderComments pinnedComments, true div className: 'comments__new', el CommentEditor, commentableType: @props.commentableType commentableId: @props.commentableId focus: false modifiers: @props.modifiers div className: 'comments__items comments__items--toolbar', el CommentsSort, modifiers: @props.modifiers div className: osu.classWithModifiers('sort', @props.modifiers), div className: 'sort__items', @renderFollowToggle() @renderShowDeletedToggle() if comments.length > 0 div className: "comments__items #{if uiState.comments.loadingSort? then 'comments__items--loading' else ''}", @renderComments comments, false el DeletedCommentsCount, { comments, showDeleted: uiState.comments.isShowDeleted, modifiers: ['top'] } el CommentShowMore, commentableType: @props.commentableType commentableId: @props.commentableId comments: comments total: uiState.comments.topLevelCount sort: uiState.comments.currentSort modifiers: _.concat 'top', @props.modifiers else div className: 'comments__items comments__items--empty' osu.trans('comments.empty') renderComment: (comment, pinned = false) => return null if comment.isDeleted && !uiState.comments.isShowDeleted el Comment, key: comment.id comment: comment depth: 0 modifiers: @props.modifiers showDeleted: uiState.comments.isShowDeleted expandReplies: if pinned then false else null renderComments: (comments, pinned) => @renderComment(comment, pinned) for comment in comments when comment.pinned == pinned renderShowDeletedToggle: => button type: 'button' className: 'sort__item sort__item--button' onClick: @toggleShowDeleted span className: 'sort__item-icon', span className: if uiState.comments.isShowDeleted then 'fas fa-check-square' else 'far fa-square' osu.trans('common.buttons.show_deleted') renderFollowToggle: => if uiState.comments.userFollow icon = 'fas fa-eye-slash' label = osu.trans('common.buttons.watch.to_0') else icon = 'fas fa-eye' label = osu.trans('common.buttons.watch.to_1') iconEl = if @props.loadingFollow el Spinner, modifiers: ['center-inline'] else span className: icon button type: 'button' className: 'sort__item sort__item--button' onClick: @toggleFollow disabled: @props.loadingFollow span className: 'sort__item-icon', iconEl label toggleShowDeleted: -> $.publish 'comments:toggle-show-deleted' toggleFollow: -> $.publish 'comments:toggle-follow'
59477
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Comment } from 'comment' import { CommentEditor } from 'comment-editor' import { CommentShowMore } from 'comment-show-more' import { CommentsSort } from 'comments-sort' import DeletedCommentsCount from 'deleted-comments-count' import { Observer } from 'mobx-react' import core from 'osu-core-singleton' import * as React from 'react' import { button, div, h2, span } from 'react-dom-factories' import { Spinner } from 'spinner' el = React.createElement store = core.dataStore.commentStore uiState = core.dataStore.uiState export class Comments extends React.PureComponent render: => el Observer, null, () => # TODO: comments should be passed in as props? comments = uiState.comments.topLevelCommentIds.map (id) -> store.comments.get(id) pinnedComments = uiState.comments.pinnedCommentIds.map (id) -> store.comments.get(id) div className: osu.classWithModifiers('comments', @props.modifiers), div className: 'u-has-anchor u-has-anchor--no-event', div(className: 'fragment-target', id: 'comments') h2 className: 'comments__title', osu.trans('comments.title') span className: 'comments__count', osu.formatNumber(uiState.comments.total) if pinnedComments.length > 0 div className: "comments__items comments__items--pinned", @renderComments pinnedComments, true div className: 'comments__new', el CommentEditor, commentableType: @props.commentableType commentableId: @props.commentableId focus: false modifiers: @props.modifiers div className: 'comments__items comments__items--toolbar', el CommentsSort, modifiers: @props.modifiers div className: osu.classWithModifiers('sort', @props.modifiers), div className: 'sort__items', @renderFollowToggle() @renderShowDeletedToggle() if comments.length > 0 div className: "comments__items #{if uiState.comments.loadingSort? then 'comments__items--loading' else ''}", @renderComments comments, false el DeletedCommentsCount, { comments, showDeleted: uiState.comments.isShowDeleted, modifiers: ['top'] } el CommentShowMore, commentableType: @props.commentableType commentableId: @props.commentableId comments: comments total: uiState.comments.topLevelCount sort: uiState.comments.currentSort modifiers: _.concat 'top', @props.modifiers else div className: 'comments__items comments__items--empty' osu.trans('comments.empty') renderComment: (comment, pinned = false) => return null if comment.isDeleted && !uiState.comments.isShowDeleted el Comment, key: <KEY> comment: comment depth: 0 modifiers: @props.modifiers showDeleted: uiState.comments.isShowDeleted expandReplies: if pinned then false else null renderComments: (comments, pinned) => @renderComment(comment, pinned) for comment in comments when comment.pinned == pinned renderShowDeletedToggle: => button type: 'button' className: 'sort__item sort__item--button' onClick: @toggleShowDeleted span className: 'sort__item-icon', span className: if uiState.comments.isShowDeleted then 'fas fa-check-square' else 'far fa-square' osu.trans('common.buttons.show_deleted') renderFollowToggle: => if uiState.comments.userFollow icon = 'fas fa-eye-slash' label = osu.trans('common.buttons.watch.to_0') else icon = 'fas fa-eye' label = osu.trans('common.buttons.watch.to_1') iconEl = if @props.loadingFollow el Spinner, modifiers: ['center-inline'] else span className: icon button type: 'button' className: 'sort__item sort__item--button' onClick: @toggleFollow disabled: @props.loadingFollow span className: 'sort__item-icon', iconEl label toggleShowDeleted: -> $.publish 'comments:toggle-show-deleted' toggleFollow: -> $.publish 'comments:toggle-follow'
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Comment } from 'comment' import { CommentEditor } from 'comment-editor' import { CommentShowMore } from 'comment-show-more' import { CommentsSort } from 'comments-sort' import DeletedCommentsCount from 'deleted-comments-count' import { Observer } from 'mobx-react' import core from 'osu-core-singleton' import * as React from 'react' import { button, div, h2, span } from 'react-dom-factories' import { Spinner } from 'spinner' el = React.createElement store = core.dataStore.commentStore uiState = core.dataStore.uiState export class Comments extends React.PureComponent render: => el Observer, null, () => # TODO: comments should be passed in as props? comments = uiState.comments.topLevelCommentIds.map (id) -> store.comments.get(id) pinnedComments = uiState.comments.pinnedCommentIds.map (id) -> store.comments.get(id) div className: osu.classWithModifiers('comments', @props.modifiers), div className: 'u-has-anchor u-has-anchor--no-event', div(className: 'fragment-target', id: 'comments') h2 className: 'comments__title', osu.trans('comments.title') span className: 'comments__count', osu.formatNumber(uiState.comments.total) if pinnedComments.length > 0 div className: "comments__items comments__items--pinned", @renderComments pinnedComments, true div className: 'comments__new', el CommentEditor, commentableType: @props.commentableType commentableId: @props.commentableId focus: false modifiers: @props.modifiers div className: 'comments__items comments__items--toolbar', el CommentsSort, modifiers: @props.modifiers div className: osu.classWithModifiers('sort', @props.modifiers), div className: 'sort__items', @renderFollowToggle() @renderShowDeletedToggle() if comments.length > 0 div className: "comments__items #{if uiState.comments.loadingSort? then 'comments__items--loading' else ''}", @renderComments comments, false el DeletedCommentsCount, { comments, showDeleted: uiState.comments.isShowDeleted, modifiers: ['top'] } el CommentShowMore, commentableType: @props.commentableType commentableId: @props.commentableId comments: comments total: uiState.comments.topLevelCount sort: uiState.comments.currentSort modifiers: _.concat 'top', @props.modifiers else div className: 'comments__items comments__items--empty' osu.trans('comments.empty') renderComment: (comment, pinned = false) => return null if comment.isDeleted && !uiState.comments.isShowDeleted el Comment, key: PI:KEY:<KEY>END_PI comment: comment depth: 0 modifiers: @props.modifiers showDeleted: uiState.comments.isShowDeleted expandReplies: if pinned then false else null renderComments: (comments, pinned) => @renderComment(comment, pinned) for comment in comments when comment.pinned == pinned renderShowDeletedToggle: => button type: 'button' className: 'sort__item sort__item--button' onClick: @toggleShowDeleted span className: 'sort__item-icon', span className: if uiState.comments.isShowDeleted then 'fas fa-check-square' else 'far fa-square' osu.trans('common.buttons.show_deleted') renderFollowToggle: => if uiState.comments.userFollow icon = 'fas fa-eye-slash' label = osu.trans('common.buttons.watch.to_0') else icon = 'fas fa-eye' label = osu.trans('common.buttons.watch.to_1') iconEl = if @props.loadingFollow el Spinner, modifiers: ['center-inline'] else span className: icon button type: 'button' className: 'sort__item sort__item--button' onClick: @toggleFollow disabled: @props.loadingFollow span className: 'sort__item-icon', iconEl label toggleShowDeleted: -> $.publish 'comments:toggle-show-deleted' toggleFollow: -> $.publish 'comments:toggle-follow'
[ { "context": " email: $scope.email_input,\n password: $scope.password_input\n }\n request = $http {\n url: ajaxurl,", "end": 492, "score": 0.8724168539047241, "start": 472, "tag": "PASSWORD", "value": "scope.password_input" }, { "context": " email: $scope.em...
plugin-assets/custom/base.coffee
wp-plugins/anybackup
0
window.app = angular.module('BitsAnyBackup', ['ui.bootstrap']) app.filter 'html', ($sce) -> (input) -> $sce.trustAsHtml(input) app.controller "LoginModalController", ($scope, $http, $modalInstance, $rootScope) -> $scope.backups = [] $scope.dismiss = -> $modalInstance.dismiss('cancel') $scope.loginAccount = -> $scope.loginFormSubmitting=true data = { action: "bits_login_account", email: $scope.email_input, password: $scope.password_input } request = $http { url: ajaxurl, method: "POST", params: data } request.success (data, status, headers, config) => $scope.status = data.status $scope.loginFormSubmitting=false if(data.status == 200) $rootScope.$broadcast("user-login") $modalInstance.dismiss('complete') request.error (data, status, headers, config) => $scope.loginFormSubmitting=false $scope.status = 500 false app.controller "RegistrationModalController", ($scope, $modalInstance, $http, $rootScope) -> $scope.dismiss = -> $modalInstance.dismiss('cancel') $scope.registerUser = -> $scope.registerFormSubmitting=true data = { action: "bits_register_account", email: $scope.email_input, password: $scope.password_input } request = $http { url: ajaxurl, method: "POST", params: data } request.success (data, status, headers, config) => if(data.status == 200) if(data.error) $scope.registerFormSubmitting=false $scope.error = data.error else $rootScope.$broadcast("user-registered") $modalInstance.dismiss('complete') request.error (data, status, headers, config) => $scope.registerFormSubmitting=false $scope.error = "Error communicating with server" app.controller "BaseController", ($scope, $http, backupFactory, accountFactory) -> $scope.backups = [] $scope.parseUrl = ( url = location.href ) -> params = {} ( ( parts = part.split( "=" ) ) && params[ parts[0] ] = parts[1] for part in ( url.split "?" ).pop().split "&" if url.indexOf( "?" ) != -1 ) && params || {} $scope.urlParams = $scope.parseUrl() $scope.selectedBackupId = $scope.urlParams.backup_id $scope.list = (siteId) -> backupFactory.list siteId, (data) -> $scope.backups = data.backups $scope.loading = false $scope.selectBackup = () -> unless $scope.selectedBackupId $scope.selectedBackup = null return request = $http { url: ajaxurl, method: "GET", params: { action: "bits_backup_get_backup", id: $scope.selectedBackupId } } request.success (data, status, headers, config) => $scope.selectedBackup = data $scope.openLogin = -> accountFactory.loginModal() $scope.openRegister = -> accountFactory.registerModal() $scope.readableDate = (backup) -> localTimeZone = new Date().getTimezoneOffset() if(backup && backup.committed_at) moment.parseZone(backup.committed_at).zone(localTimeZone/60).calendar().toLowerCase() else if(backup && backup.created_at) moment.parseZone(backup.created_at).zone(localTimeZone/60).calendar().toLowerCase() else "" #Warning this sets up a timeout event $scope.updateStatus = (callback)-> request = accountFactory.getStatus (data) -> $scope.status = data callback(data) if callback request.finally -> clearTimeout($scope.updateStatusTimeout) if $scope.updateStatusTimeout $scope.updateStatusTimeout = setTimeout($scope.updateStatus, 7000) $scope.statusUpdated() if $scope.statusUpdated $scope.cancel = () -> data = { action: "bits_force_cancel" } request = $http { url: ajaxurl, method: "POST", params: data } request.success -> $scope.backup_cancelled = $scope.status.backup_running $scope.restore_cancelled = $scope.status.restore_running $scope.status.backup_running = false $scope.status.restore_running = false $scope.status.step_description = "Cancelled." $scope.updateStatus() $scope.status.step_description = "Cancelling..." if($scope.selectedBackupId) $scope.selectBackup()
190987
window.app = angular.module('BitsAnyBackup', ['ui.bootstrap']) app.filter 'html', ($sce) -> (input) -> $sce.trustAsHtml(input) app.controller "LoginModalController", ($scope, $http, $modalInstance, $rootScope) -> $scope.backups = [] $scope.dismiss = -> $modalInstance.dismiss('cancel') $scope.loginAccount = -> $scope.loginFormSubmitting=true data = { action: "bits_login_account", email: $scope.email_input, password: $<PASSWORD> } request = $http { url: ajaxurl, method: "POST", params: data } request.success (data, status, headers, config) => $scope.status = data.status $scope.loginFormSubmitting=false if(data.status == 200) $rootScope.$broadcast("user-login") $modalInstance.dismiss('complete') request.error (data, status, headers, config) => $scope.loginFormSubmitting=false $scope.status = 500 false app.controller "RegistrationModalController", ($scope, $modalInstance, $http, $rootScope) -> $scope.dismiss = -> $modalInstance.dismiss('cancel') $scope.registerUser = -> $scope.registerFormSubmitting=true data = { action: "bits_register_account", email: $scope.email_input, password: $<PASSWORD> } request = $http { url: ajaxurl, method: "POST", params: data } request.success (data, status, headers, config) => if(data.status == 200) if(data.error) $scope.registerFormSubmitting=false $scope.error = data.error else $rootScope.$broadcast("user-registered") $modalInstance.dismiss('complete') request.error (data, status, headers, config) => $scope.registerFormSubmitting=false $scope.error = "Error communicating with server" app.controller "BaseController", ($scope, $http, backupFactory, accountFactory) -> $scope.backups = [] $scope.parseUrl = ( url = location.href ) -> params = {} ( ( parts = part.split( "=" ) ) && params[ parts[0] ] = parts[1] for part in ( url.split "?" ).pop().split "&" if url.indexOf( "?" ) != -1 ) && params || {} $scope.urlParams = $scope.parseUrl() $scope.selectedBackupId = $scope.urlParams.backup_id $scope.list = (siteId) -> backupFactory.list siteId, (data) -> $scope.backups = data.backups $scope.loading = false $scope.selectBackup = () -> unless $scope.selectedBackupId $scope.selectedBackup = null return request = $http { url: ajaxurl, method: "GET", params: { action: "bits_backup_get_backup", id: $scope.selectedBackupId } } request.success (data, status, headers, config) => $scope.selectedBackup = data $scope.openLogin = -> accountFactory.loginModal() $scope.openRegister = -> accountFactory.registerModal() $scope.readableDate = (backup) -> localTimeZone = new Date().getTimezoneOffset() if(backup && backup.committed_at) moment.parseZone(backup.committed_at).zone(localTimeZone/60).calendar().toLowerCase() else if(backup && backup.created_at) moment.parseZone(backup.created_at).zone(localTimeZone/60).calendar().toLowerCase() else "" #Warning this sets up a timeout event $scope.updateStatus = (callback)-> request = accountFactory.getStatus (data) -> $scope.status = data callback(data) if callback request.finally -> clearTimeout($scope.updateStatusTimeout) if $scope.updateStatusTimeout $scope.updateStatusTimeout = setTimeout($scope.updateStatus, 7000) $scope.statusUpdated() if $scope.statusUpdated $scope.cancel = () -> data = { action: "bits_force_cancel" } request = $http { url: ajaxurl, method: "POST", params: data } request.success -> $scope.backup_cancelled = $scope.status.backup_running $scope.restore_cancelled = $scope.status.restore_running $scope.status.backup_running = false $scope.status.restore_running = false $scope.status.step_description = "Cancelled." $scope.updateStatus() $scope.status.step_description = "Cancelling..." if($scope.selectedBackupId) $scope.selectBackup()
true
window.app = angular.module('BitsAnyBackup', ['ui.bootstrap']) app.filter 'html', ($sce) -> (input) -> $sce.trustAsHtml(input) app.controller "LoginModalController", ($scope, $http, $modalInstance, $rootScope) -> $scope.backups = [] $scope.dismiss = -> $modalInstance.dismiss('cancel') $scope.loginAccount = -> $scope.loginFormSubmitting=true data = { action: "bits_login_account", email: $scope.email_input, password: $PI:PASSWORD:<PASSWORD>END_PI } request = $http { url: ajaxurl, method: "POST", params: data } request.success (data, status, headers, config) => $scope.status = data.status $scope.loginFormSubmitting=false if(data.status == 200) $rootScope.$broadcast("user-login") $modalInstance.dismiss('complete') request.error (data, status, headers, config) => $scope.loginFormSubmitting=false $scope.status = 500 false app.controller "RegistrationModalController", ($scope, $modalInstance, $http, $rootScope) -> $scope.dismiss = -> $modalInstance.dismiss('cancel') $scope.registerUser = -> $scope.registerFormSubmitting=true data = { action: "bits_register_account", email: $scope.email_input, password: $PI:PASSWORD:<PASSWORD>END_PI } request = $http { url: ajaxurl, method: "POST", params: data } request.success (data, status, headers, config) => if(data.status == 200) if(data.error) $scope.registerFormSubmitting=false $scope.error = data.error else $rootScope.$broadcast("user-registered") $modalInstance.dismiss('complete') request.error (data, status, headers, config) => $scope.registerFormSubmitting=false $scope.error = "Error communicating with server" app.controller "BaseController", ($scope, $http, backupFactory, accountFactory) -> $scope.backups = [] $scope.parseUrl = ( url = location.href ) -> params = {} ( ( parts = part.split( "=" ) ) && params[ parts[0] ] = parts[1] for part in ( url.split "?" ).pop().split "&" if url.indexOf( "?" ) != -1 ) && params || {} $scope.urlParams = $scope.parseUrl() $scope.selectedBackupId = $scope.urlParams.backup_id $scope.list = (siteId) -> backupFactory.list siteId, (data) -> $scope.backups = data.backups $scope.loading = false $scope.selectBackup = () -> unless $scope.selectedBackupId $scope.selectedBackup = null return request = $http { url: ajaxurl, method: "GET", params: { action: "bits_backup_get_backup", id: $scope.selectedBackupId } } request.success (data, status, headers, config) => $scope.selectedBackup = data $scope.openLogin = -> accountFactory.loginModal() $scope.openRegister = -> accountFactory.registerModal() $scope.readableDate = (backup) -> localTimeZone = new Date().getTimezoneOffset() if(backup && backup.committed_at) moment.parseZone(backup.committed_at).zone(localTimeZone/60).calendar().toLowerCase() else if(backup && backup.created_at) moment.parseZone(backup.created_at).zone(localTimeZone/60).calendar().toLowerCase() else "" #Warning this sets up a timeout event $scope.updateStatus = (callback)-> request = accountFactory.getStatus (data) -> $scope.status = data callback(data) if callback request.finally -> clearTimeout($scope.updateStatusTimeout) if $scope.updateStatusTimeout $scope.updateStatusTimeout = setTimeout($scope.updateStatus, 7000) $scope.statusUpdated() if $scope.statusUpdated $scope.cancel = () -> data = { action: "bits_force_cancel" } request = $http { url: ajaxurl, method: "POST", params: data } request.success -> $scope.backup_cancelled = $scope.status.backup_running $scope.restore_cancelled = $scope.status.restore_running $scope.status.backup_running = false $scope.status.restore_running = false $scope.status.step_description = "Cancelled." $scope.updateStatus() $scope.status.step_description = "Cancelling..." if($scope.selectedBackupId) $scope.selectBackup()
[ { "context": "name: 'Tablatal'\nscopeName: 'tablatal'\nfileTypes: ['tbtl', 't", "end": 11, "score": 0.7857733964920044, "start": 7, "tag": "NAME", "value": "Tabl" } ]
grammars/tree-sitter-tablatal.cson
jakofranko/language-tablatal
0
name: 'Tablatal' scopeName: 'tablatal' fileTypes: ['tbtl', 'tome', 'ma'] type: 'tree-sitter' parser: 'tree-sitter-tablatal' scopes: 'header_definition': 'language.constant.tablatal.header' 'row_definition': 'entity.string.tablatal.row' 'comment_definition': 'comment.block.tablatal' comments: start: '~ '
224484
name: '<NAME>atal' scopeName: 'tablatal' fileTypes: ['tbtl', 'tome', 'ma'] type: 'tree-sitter' parser: 'tree-sitter-tablatal' scopes: 'header_definition': 'language.constant.tablatal.header' 'row_definition': 'entity.string.tablatal.row' 'comment_definition': 'comment.block.tablatal' comments: start: '~ '
true
name: 'PI:NAME:<NAME>END_PIatal' scopeName: 'tablatal' fileTypes: ['tbtl', 'tome', 'ma'] type: 'tree-sitter' parser: 'tree-sitter-tablatal' scopes: 'header_definition': 'language.constant.tablatal.header' 'row_definition': 'entity.string.tablatal.row' 'comment_definition': 'comment.block.tablatal' comments: start: '~ '
[ { "context": "# Copyright (c) 2008-2013 Michael Dvorkin and contributors.\n#\n# Eatech CRM is freely distri", "end": 41, "score": 0.999862551689148, "start": 26, "tag": "NAME", "value": "Michael Dvorkin" } ]
app/assets/javascripts/crm_classes.js.coffee
amiteatech/fat_free_crm
0
# Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Eatech CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> window.crm ||= {} class crm.Popup #---------------------------------------------------------------------------- constructor: (options = {}) -> @options = $.extend( trigger: "#trigger" # #id of the element that triggers on_mouseover popup. target: "#popup" # #id of the popup div that is shown or hidden. appear: 0 # duration of EffectAppear or 0 for show(). fade: 0 # duration of EffectFade or 0 for hide(). under: false # true to show popup right under the trigger div. zindex: 100 # zIndex value for the popup. before_show: $.noop # before show callback. before_hide: $.noop # before hide callback. after_show: $.noop # after show callback. after_hide: $.noop # after hide callback. , options) @popup = $(@options.target) # actual popup div. @setup_toggle_observer() @setup_hide_observer() #---------------------------------------------------------------------------- setup_toggle_observer: -> $(@options.trigger).on "click", (e) => @toggle_popup e #---------------------------------------------------------------------------- setup_hide_observer: -> $(document).on "click", (e) => if @popup and @popup.css('display') isnt 'none' clicked_on = $(e.target).closest("div") @hide_popup e if clicked_on.length is 0 or ('#' + clicked_on.attr('id')) isnt @options.target #---------------------------------------------------------------------------- show_popup: (e) -> e.preventDefault() e.stopPropagation() @popup.css zIndex: @options.zindex # Add custom "trigger" attribute to the popup div so we could check who has triggered it. @popup.attr trigger: @options.trigger @options.before_show e unless @options.appear @popup.show() @set_position e @options.after_show e else @set_position e @popup.fadeIn( @options.appear @options.after_show ) #---------------------------------------------------------------------------- toggle_popup: (e) -> if @popup.filter(':visible').length unless @options.trigger is @popup.attr("trigger") # Currently shown popup was opened by some other trigger: hide it immediately # without any fancy callbacks, then show this popup. @popup.hide() @show_popup e else @hide_popup e else @show_popup e #---------------------------------------------------------------------------- hide_popup: (e) -> e.preventDefault() if e @options.before_hide e unless @options.fade @popup.hide() @options.after_hide e else @popup.fadeOut( @options.fade @options.after_hide ) set_position: (e) -> if @options.under under = $(@options.under) popup = $(@popup) offset = under.offset() x = (offset.left + under.width() - popup.width()) + "px" y = (offset.top + under.height()) + "px" @popup.css left: x top: y class crm.Menu #---------------------------------------------------------------------------- constructor: (options = {}) -> @options = $.extend( trigger: "#menu" # #id of the element clicking on which triggers dropdown menu. align: "left" # align the menu left or right appear: 0 # duration of EffectAppear or 0 for show(). fade: 0 # duration of EffectFade or 0 for hide(). width: 0 # explicit menu width if set to non-zero zindex: 100 # zIndex value for the popup. before_show: $.noop # before show callback. before_hide: $.noop # before hide callback. after_show: $.noop # after show callback. after_hide: $.noop # after hide callback. , options) @build_menu() @setup_show_observer() @setup_hide_observer() #---------------------------------------------------------------------------- build_menu: -> @menu = $("<div>", class: "menu" style: "display:none;"; on: click: (e) -> e.preventDefault() ) @menu.css width: @options.width + "px" if @options.width @menu.appendTo(document.body) ul = $("<ul>") ul.appendTo(@menu) for item in @options.menu_items li = $("<li>") li.appendTo(ul) a = $("<a>", href: "#" title: item.name on: click: @select_menu.bind(this) ).html(item.name) a.data(on_select: item.on_select) if item.on_select a.appendTo(li) #---------------------------------------------------------------------------- setup_hide_observer: -> $(document).on "click", (e) => @hide_menu(e) if @menu and @menu.css('display') isnt 'none' #---------------------------------------------------------------------------- setup_show_observer: -> $(@options.trigger).on "click", (e) => @show_menu(e) if @menu and @menu.css('display') is 'none' #---------------------------------------------------------------------------- hide_menu: (e) -> @options.before_hide e unless @options.fade @menu.hide() @options.after_hide e else @menu.fadeOut( @options.fade @options.after_hide ) #---------------------------------------------------------------------------- show_menu: (e) -> e.preventDefault() e.stopPropagation() $el = $(e.target) offset = $el.offset() x = offset.left + "px" y = offset.top + $el.height() + "px" x = (offset.left - (@options.width - $el.width() + 1)) + "px" if @options.align is "right" @menu.css left: x top: y zIndex: @options.zindex @options.before_show e unless @options.appear @menu.show() @options.after_show e else @menu.fadeIn( @options.appear @options.after_show ) @event = e #---------------------------------------------------------------------------- select_menu: (e) -> e.preventDefault() $el = $(e.target) if on_select = $el.data('on_select') @hide_menu() on_select @event ) jQuery
80103
# Copyright (c) 2008-2013 <NAME> and contributors. # # Eatech CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> window.crm ||= {} class crm.Popup #---------------------------------------------------------------------------- constructor: (options = {}) -> @options = $.extend( trigger: "#trigger" # #id of the element that triggers on_mouseover popup. target: "#popup" # #id of the popup div that is shown or hidden. appear: 0 # duration of EffectAppear or 0 for show(). fade: 0 # duration of EffectFade or 0 for hide(). under: false # true to show popup right under the trigger div. zindex: 100 # zIndex value for the popup. before_show: $.noop # before show callback. before_hide: $.noop # before hide callback. after_show: $.noop # after show callback. after_hide: $.noop # after hide callback. , options) @popup = $(@options.target) # actual popup div. @setup_toggle_observer() @setup_hide_observer() #---------------------------------------------------------------------------- setup_toggle_observer: -> $(@options.trigger).on "click", (e) => @toggle_popup e #---------------------------------------------------------------------------- setup_hide_observer: -> $(document).on "click", (e) => if @popup and @popup.css('display') isnt 'none' clicked_on = $(e.target).closest("div") @hide_popup e if clicked_on.length is 0 or ('#' + clicked_on.attr('id')) isnt @options.target #---------------------------------------------------------------------------- show_popup: (e) -> e.preventDefault() e.stopPropagation() @popup.css zIndex: @options.zindex # Add custom "trigger" attribute to the popup div so we could check who has triggered it. @popup.attr trigger: @options.trigger @options.before_show e unless @options.appear @popup.show() @set_position e @options.after_show e else @set_position e @popup.fadeIn( @options.appear @options.after_show ) #---------------------------------------------------------------------------- toggle_popup: (e) -> if @popup.filter(':visible').length unless @options.trigger is @popup.attr("trigger") # Currently shown popup was opened by some other trigger: hide it immediately # without any fancy callbacks, then show this popup. @popup.hide() @show_popup e else @hide_popup e else @show_popup e #---------------------------------------------------------------------------- hide_popup: (e) -> e.preventDefault() if e @options.before_hide e unless @options.fade @popup.hide() @options.after_hide e else @popup.fadeOut( @options.fade @options.after_hide ) set_position: (e) -> if @options.under under = $(@options.under) popup = $(@popup) offset = under.offset() x = (offset.left + under.width() - popup.width()) + "px" y = (offset.top + under.height()) + "px" @popup.css left: x top: y class crm.Menu #---------------------------------------------------------------------------- constructor: (options = {}) -> @options = $.extend( trigger: "#menu" # #id of the element clicking on which triggers dropdown menu. align: "left" # align the menu left or right appear: 0 # duration of EffectAppear or 0 for show(). fade: 0 # duration of EffectFade or 0 for hide(). width: 0 # explicit menu width if set to non-zero zindex: 100 # zIndex value for the popup. before_show: $.noop # before show callback. before_hide: $.noop # before hide callback. after_show: $.noop # after show callback. after_hide: $.noop # after hide callback. , options) @build_menu() @setup_show_observer() @setup_hide_observer() #---------------------------------------------------------------------------- build_menu: -> @menu = $("<div>", class: "menu" style: "display:none;"; on: click: (e) -> e.preventDefault() ) @menu.css width: @options.width + "px" if @options.width @menu.appendTo(document.body) ul = $("<ul>") ul.appendTo(@menu) for item in @options.menu_items li = $("<li>") li.appendTo(ul) a = $("<a>", href: "#" title: item.name on: click: @select_menu.bind(this) ).html(item.name) a.data(on_select: item.on_select) if item.on_select a.appendTo(li) #---------------------------------------------------------------------------- setup_hide_observer: -> $(document).on "click", (e) => @hide_menu(e) if @menu and @menu.css('display') isnt 'none' #---------------------------------------------------------------------------- setup_show_observer: -> $(@options.trigger).on "click", (e) => @show_menu(e) if @menu and @menu.css('display') is 'none' #---------------------------------------------------------------------------- hide_menu: (e) -> @options.before_hide e unless @options.fade @menu.hide() @options.after_hide e else @menu.fadeOut( @options.fade @options.after_hide ) #---------------------------------------------------------------------------- show_menu: (e) -> e.preventDefault() e.stopPropagation() $el = $(e.target) offset = $el.offset() x = offset.left + "px" y = offset.top + $el.height() + "px" x = (offset.left - (@options.width - $el.width() + 1)) + "px" if @options.align is "right" @menu.css left: x top: y zIndex: @options.zindex @options.before_show e unless @options.appear @menu.show() @options.after_show e else @menu.fadeIn( @options.appear @options.after_show ) @event = e #---------------------------------------------------------------------------- select_menu: (e) -> e.preventDefault() $el = $(e.target) if on_select = $el.data('on_select') @hide_menu() on_select @event ) jQuery
true
# Copyright (c) 2008-2013 PI:NAME:<NAME>END_PI and contributors. # # Eatech CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> window.crm ||= {} class crm.Popup #---------------------------------------------------------------------------- constructor: (options = {}) -> @options = $.extend( trigger: "#trigger" # #id of the element that triggers on_mouseover popup. target: "#popup" # #id of the popup div that is shown or hidden. appear: 0 # duration of EffectAppear or 0 for show(). fade: 0 # duration of EffectFade or 0 for hide(). under: false # true to show popup right under the trigger div. zindex: 100 # zIndex value for the popup. before_show: $.noop # before show callback. before_hide: $.noop # before hide callback. after_show: $.noop # after show callback. after_hide: $.noop # after hide callback. , options) @popup = $(@options.target) # actual popup div. @setup_toggle_observer() @setup_hide_observer() #---------------------------------------------------------------------------- setup_toggle_observer: -> $(@options.trigger).on "click", (e) => @toggle_popup e #---------------------------------------------------------------------------- setup_hide_observer: -> $(document).on "click", (e) => if @popup and @popup.css('display') isnt 'none' clicked_on = $(e.target).closest("div") @hide_popup e if clicked_on.length is 0 or ('#' + clicked_on.attr('id')) isnt @options.target #---------------------------------------------------------------------------- show_popup: (e) -> e.preventDefault() e.stopPropagation() @popup.css zIndex: @options.zindex # Add custom "trigger" attribute to the popup div so we could check who has triggered it. @popup.attr trigger: @options.trigger @options.before_show e unless @options.appear @popup.show() @set_position e @options.after_show e else @set_position e @popup.fadeIn( @options.appear @options.after_show ) #---------------------------------------------------------------------------- toggle_popup: (e) -> if @popup.filter(':visible').length unless @options.trigger is @popup.attr("trigger") # Currently shown popup was opened by some other trigger: hide it immediately # without any fancy callbacks, then show this popup. @popup.hide() @show_popup e else @hide_popup e else @show_popup e #---------------------------------------------------------------------------- hide_popup: (e) -> e.preventDefault() if e @options.before_hide e unless @options.fade @popup.hide() @options.after_hide e else @popup.fadeOut( @options.fade @options.after_hide ) set_position: (e) -> if @options.under under = $(@options.under) popup = $(@popup) offset = under.offset() x = (offset.left + under.width() - popup.width()) + "px" y = (offset.top + under.height()) + "px" @popup.css left: x top: y class crm.Menu #---------------------------------------------------------------------------- constructor: (options = {}) -> @options = $.extend( trigger: "#menu" # #id of the element clicking on which triggers dropdown menu. align: "left" # align the menu left or right appear: 0 # duration of EffectAppear or 0 for show(). fade: 0 # duration of EffectFade or 0 for hide(). width: 0 # explicit menu width if set to non-zero zindex: 100 # zIndex value for the popup. before_show: $.noop # before show callback. before_hide: $.noop # before hide callback. after_show: $.noop # after show callback. after_hide: $.noop # after hide callback. , options) @build_menu() @setup_show_observer() @setup_hide_observer() #---------------------------------------------------------------------------- build_menu: -> @menu = $("<div>", class: "menu" style: "display:none;"; on: click: (e) -> e.preventDefault() ) @menu.css width: @options.width + "px" if @options.width @menu.appendTo(document.body) ul = $("<ul>") ul.appendTo(@menu) for item in @options.menu_items li = $("<li>") li.appendTo(ul) a = $("<a>", href: "#" title: item.name on: click: @select_menu.bind(this) ).html(item.name) a.data(on_select: item.on_select) if item.on_select a.appendTo(li) #---------------------------------------------------------------------------- setup_hide_observer: -> $(document).on "click", (e) => @hide_menu(e) if @menu and @menu.css('display') isnt 'none' #---------------------------------------------------------------------------- setup_show_observer: -> $(@options.trigger).on "click", (e) => @show_menu(e) if @menu and @menu.css('display') is 'none' #---------------------------------------------------------------------------- hide_menu: (e) -> @options.before_hide e unless @options.fade @menu.hide() @options.after_hide e else @menu.fadeOut( @options.fade @options.after_hide ) #---------------------------------------------------------------------------- show_menu: (e) -> e.preventDefault() e.stopPropagation() $el = $(e.target) offset = $el.offset() x = offset.left + "px" y = offset.top + $el.height() + "px" x = (offset.left - (@options.width - $el.width() + 1)) + "px" if @options.align is "right" @menu.css left: x top: y zIndex: @options.zindex @options.before_show e unless @options.appear @menu.show() @options.after_show e else @menu.fadeIn( @options.appear @options.after_show ) @event = e #---------------------------------------------------------------------------- select_menu: (e) -> e.preventDefault() $el = $(e.target) if on_select = $el.data('on_select') @hide_menu() on_select @event ) jQuery
[ { "context": "ns.port ?= 9090\n @options.host ?= '127.0.0.1'\n @options.user ?= 'xbmc'\n @options.p", "end": 287, "score": 0.9997637271881104, "start": 278, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " ?= '127.0.0.1'\n @options.user ...
home/pi/Documents/NodeFrame/node_modules/xbmc/src/TCPConnection.coffee
srmooney/PiFrame
0
debug = require('debug') 'xbmc:TCPConnection' pubsub = require './PubSub' {defer} = require 'node-promise' net = require 'net' class Connection constructor: (@options = {}) -> debug 'constructor', @options @options.port ?= 9090 @options.host ?= '127.0.0.1' @options.user ?= 'xbmc' @options.password ?= false @options.verbose ?= false @options.connectNow ?= true @readRaw = '' @sendQueue = [] @deferreds = {} if @options.connectNow do @create create: => debug 'create' @socket = net.connect host: @options.host port: @options.port @socket.on 'connect', @onOpen @socket.on 'data', @onMessage @socket.on 'error', @onError @socket.on 'disconnect', @onClose @socket.on 'close', @onClose @_id: 0 @generateId: -> "__id#{++Connection._id}" isActive: => debug 'isActive' return @socket?._connecting is false send: (data = null) => debug 'send', JSON.stringify data throw new Error 'Connection: Unknown arguments' if not data data.id ?= do Connection.generateId dfd = @deferreds[data.id] ?= defer() unless @isActive() @sendQueue.push data else data.jsonrpc = '2.0' data = JSON.stringify data @publish 'send', data @socket.write data return dfd.promise close: (fn = null) => debug 'close' try do @socket.end do @socket.destroy do fn if fn catch err @publish 'error', err fn err if fn publish: (topic, data = {}) => #data.connection = @ dataVerbose = if typeof(data) is 'object' then JSON.stringify data else data debug 'publish', topic, dataVerbose pubsub.emit "connection:#{topic}", data onOpen: => debug 'onOpen' @publish 'open' setTimeout (=> for item in @sendQueue @send item @sendQueue = [] ), 500 onError: (evt) => debug 'onError', JSON.stringify evt @publish 'error', evt onClose: (evt) => debug 'onClose', evt @publish 'close', evt parseBuffer: (buffer) => debug 'parseBuffer' @readRaw = buffer.toString() lines = [] try line = JSON.parse @readRaw lines.push line @readRaw = '' catch err # Hack: sometimes json are concat splitStr = '{"jsonrpc":"2.0"' rawlines = @readRaw.split splitStr lines = [] for rawline in rawlines continue unless rawline.length str = splitStr + rawline try @readRaw.replace(/}{/g, '}%%%%{').split(/%%%%/).forEach (part) -> lines.push JSON.parse part return lines onMessage: (buffer) => debug 'onMessage' lines = @parseBuffer buffer for line in lines evt = {} evt.data = line id = evt.data?.id dfd = @deferreds[id] delete @deferreds[id] if evt.data.error @onError evt dfd.reject evt.data if dfd continue @publish 'data', evt.data if evt.data.method?.indexOf '.On' > 1 @publish 'notification', evt.data dfd.resolve evt.data if dfd module.exports = Connection
226113
debug = require('debug') 'xbmc:TCPConnection' pubsub = require './PubSub' {defer} = require 'node-promise' net = require 'net' class Connection constructor: (@options = {}) -> debug 'constructor', @options @options.port ?= 9090 @options.host ?= '127.0.0.1' @options.user ?= 'xbmc' @options.password ?= <PASSWORD> @options.verbose ?= false @options.connectNow ?= true @readRaw = '' @sendQueue = [] @deferreds = {} if @options.connectNow do @create create: => debug 'create' @socket = net.connect host: @options.host port: @options.port @socket.on 'connect', @onOpen @socket.on 'data', @onMessage @socket.on 'error', @onError @socket.on 'disconnect', @onClose @socket.on 'close', @onClose @_id: 0 @generateId: -> "__id#{++Connection._id}" isActive: => debug 'isActive' return @socket?._connecting is false send: (data = null) => debug 'send', JSON.stringify data throw new Error 'Connection: Unknown arguments' if not data data.id ?= do Connection.generateId dfd = @deferreds[data.id] ?= defer() unless @isActive() @sendQueue.push data else data.jsonrpc = '2.0' data = JSON.stringify data @publish 'send', data @socket.write data return dfd.promise close: (fn = null) => debug 'close' try do @socket.end do @socket.destroy do fn if fn catch err @publish 'error', err fn err if fn publish: (topic, data = {}) => #data.connection = @ dataVerbose = if typeof(data) is 'object' then JSON.stringify data else data debug 'publish', topic, dataVerbose pubsub.emit "connection:#{topic}", data onOpen: => debug 'onOpen' @publish 'open' setTimeout (=> for item in @sendQueue @send item @sendQueue = [] ), 500 onError: (evt) => debug 'onError', JSON.stringify evt @publish 'error', evt onClose: (evt) => debug 'onClose', evt @publish 'close', evt parseBuffer: (buffer) => debug 'parseBuffer' @readRaw = buffer.toString() lines = [] try line = JSON.parse @readRaw lines.push line @readRaw = '' catch err # Hack: sometimes json are concat splitStr = '{"jsonrpc":"2.0"' rawlines = @readRaw.split splitStr lines = [] for rawline in rawlines continue unless rawline.length str = splitStr + rawline try @readRaw.replace(/}{/g, '}%%%%{').split(/%%%%/).forEach (part) -> lines.push JSON.parse part return lines onMessage: (buffer) => debug 'onMessage' lines = @parseBuffer buffer for line in lines evt = {} evt.data = line id = evt.data?.id dfd = @deferreds[id] delete @deferreds[id] if evt.data.error @onError evt dfd.reject evt.data if dfd continue @publish 'data', evt.data if evt.data.method?.indexOf '.On' > 1 @publish 'notification', evt.data dfd.resolve evt.data if dfd module.exports = Connection
true
debug = require('debug') 'xbmc:TCPConnection' pubsub = require './PubSub' {defer} = require 'node-promise' net = require 'net' class Connection constructor: (@options = {}) -> debug 'constructor', @options @options.port ?= 9090 @options.host ?= '127.0.0.1' @options.user ?= 'xbmc' @options.password ?= PI:PASSWORD:<PASSWORD>END_PI @options.verbose ?= false @options.connectNow ?= true @readRaw = '' @sendQueue = [] @deferreds = {} if @options.connectNow do @create create: => debug 'create' @socket = net.connect host: @options.host port: @options.port @socket.on 'connect', @onOpen @socket.on 'data', @onMessage @socket.on 'error', @onError @socket.on 'disconnect', @onClose @socket.on 'close', @onClose @_id: 0 @generateId: -> "__id#{++Connection._id}" isActive: => debug 'isActive' return @socket?._connecting is false send: (data = null) => debug 'send', JSON.stringify data throw new Error 'Connection: Unknown arguments' if not data data.id ?= do Connection.generateId dfd = @deferreds[data.id] ?= defer() unless @isActive() @sendQueue.push data else data.jsonrpc = '2.0' data = JSON.stringify data @publish 'send', data @socket.write data return dfd.promise close: (fn = null) => debug 'close' try do @socket.end do @socket.destroy do fn if fn catch err @publish 'error', err fn err if fn publish: (topic, data = {}) => #data.connection = @ dataVerbose = if typeof(data) is 'object' then JSON.stringify data else data debug 'publish', topic, dataVerbose pubsub.emit "connection:#{topic}", data onOpen: => debug 'onOpen' @publish 'open' setTimeout (=> for item in @sendQueue @send item @sendQueue = [] ), 500 onError: (evt) => debug 'onError', JSON.stringify evt @publish 'error', evt onClose: (evt) => debug 'onClose', evt @publish 'close', evt parseBuffer: (buffer) => debug 'parseBuffer' @readRaw = buffer.toString() lines = [] try line = JSON.parse @readRaw lines.push line @readRaw = '' catch err # Hack: sometimes json are concat splitStr = '{"jsonrpc":"2.0"' rawlines = @readRaw.split splitStr lines = [] for rawline in rawlines continue unless rawline.length str = splitStr + rawline try @readRaw.replace(/}{/g, '}%%%%{').split(/%%%%/).forEach (part) -> lines.push JSON.parse part return lines onMessage: (buffer) => debug 'onMessage' lines = @parseBuffer buffer for line in lines evt = {} evt.data = line id = evt.data?.id dfd = @deferreds[id] delete @deferreds[id] if evt.data.error @onError evt dfd.reject evt.data if dfd continue @publish 'data', evt.data if evt.data.method?.indexOf '.On' > 1 @publish 'notification', evt.data dfd.resolve evt.data if dfd module.exports = Connection
[ { "context": "te <user> with a humorous greeting\n#\n# Author:\n# sopel\n\nmodule.exports = (robot) ->\n\n robot.respond /(b", "end": 432, "score": 0.9996979832649231, "start": 427, "tag": "USERNAME", "value": "sopel" }, { "context": "irthdays are feathers in the broad wing of tim...
scripts/birthday.coffee
sagasu/doc
1
# Description: # Delegate your birthday greetings, celebrations and quotes to Hubot. # # Dependencies: # None # # Configuration: # None # # Commands: # hubot birthday quote for <user> -- congratulate <user> with a random birthday quote # hubot celebrate me <user> -- congratulate <user> with an inspirational greeting # hubot happy birthday me <user> -- congratulate <user> with a humorous greeting # # Author: # sopel module.exports = (robot) -> robot.respond /(birthday quote)( for )?(.*)/i, (msg)-> name = msg.match[3].trim() if name.length == 0 msg.send(quote()) else msg.send(name + " - here's a quote for you: ") msg.send(quote(name)) robot.respond /(happy birthday)( me )?(.*)/i, (msg)-> name = msg.match[3].trim() if name.length == 0 msg.send(quote()) else msg.send(greeting(name)) robot.respond /(celebrate)( me )?(.*)/i, (msg)-> name = msg.match[3].trim() if name.length == 0 msg.send("You must be kidding.") else msg.send(celebrate(name)) celebrate = (name) -> celebrates[(Math.random() * celebrates.length) >> 0].replace(/{name}/, name); celebrates = [ "{name} - Hoping that your day will be as special as you are.", "{name} - Count your life by smiles, not tears. Count your age by friends, not years.", "May the years continue to be good to you. Happy Birthday {name}!", "{name} - You're not getting older, you're getting better.", "{name} - May this year bring with it all the success and fulfillment your heart desires.", "{name} - Wishing you all the great things in life, hope this day will bring you an extra share of all that makes you happiest.", "Happy Birthday {name}, and may all the wishes and dreams you dream today turn to reality.", "May this day bring to you all things that make you smile. Happy Birthday {name}!", "{name} - Your best years are still ahead of you.", "{name} - Birthdays are filled with yesterday's memories, today's joys, and tomorrow's dreams.", "{name} - Hoping that your day will be as special as you are.", "{name} - You'll always be forever young." ] greeting = (name) -> greetings[(Math.random() * greetings.length) >> 0].replace(/{name}/, name); greetings = [ "Happy Birthday {name}, you're not getting older, you're just a little closer to death.", "Birthdays are good for you {name}. Statistics show that people who have the most live the longest!", "{name} - I'm so glad you were born, because you brighten my life and fill it with joy.", "{name} - Always remember: growing old is mandatory, growing up is optional.", "{name} - Better to be over the hill than burried under it.", "You always have such fun birthdays {name}, you should have one every year.", "Happy birthday to {name}, a person who is smart, good looking, and funny and reminds me a lot of myself.", "{name} - We know we're getting old when the only thing we want for our birthday is not to be reminded of it.", "Happy Birthday on your very special day {name}, I hope that you don't die before you eat your cake." ] quote = () -> quotes[(Math.random() * quotes.length) >> 0]; quotes = [ "Our birthdays are feathers in the broad wing of time. - Jean Paul Richter", "Inside every older person is a younger person wondering what happened. - Jennifer Yane", "Wisdom doesn't necessarily come with age. Sometimes age just shows up all by itself. - Tom Wilson", "May you stay forever young. - Bob Dylan", "The old believe everything; the middle-aged suspect everything; the young know everything. - Oscar Wilde", "Old age is like everything else. To make a success of it, you've got to start young. - Fred Astaire", "Age is a number and mine is unlisted. - Unknown", "When I was younger, I could remember anything, whether it happened or not.- Mark Twain", "Whatever with the past has gone, The best is always yet to come. - Lucy Larcom", "It takes a long time to grow young. - Pablo Picasso", "Few women admit their age. Few men act theirs. - Unkown", "The best way to remember your wife's birthday is to forget it once. - H. V. Prochnow" ]
52694
# Description: # Delegate your birthday greetings, celebrations and quotes to Hubot. # # Dependencies: # None # # Configuration: # None # # Commands: # hubot birthday quote for <user> -- congratulate <user> with a random birthday quote # hubot celebrate me <user> -- congratulate <user> with an inspirational greeting # hubot happy birthday me <user> -- congratulate <user> with a humorous greeting # # Author: # sopel module.exports = (robot) -> robot.respond /(birthday quote)( for )?(.*)/i, (msg)-> name = msg.match[3].trim() if name.length == 0 msg.send(quote()) else msg.send(name + " - here's a quote for you: ") msg.send(quote(name)) robot.respond /(happy birthday)( me )?(.*)/i, (msg)-> name = msg.match[3].trim() if name.length == 0 msg.send(quote()) else msg.send(greeting(name)) robot.respond /(celebrate)( me )?(.*)/i, (msg)-> name = msg.match[3].trim() if name.length == 0 msg.send("You must be kidding.") else msg.send(celebrate(name)) celebrate = (name) -> celebrates[(Math.random() * celebrates.length) >> 0].replace(/{name}/, name); celebrates = [ "{name} - Hoping that your day will be as special as you are.", "{name} - Count your life by smiles, not tears. Count your age by friends, not years.", "May the years continue to be good to you. Happy Birthday {name}!", "{name} - You're not getting older, you're getting better.", "{name} - May this year bring with it all the success and fulfillment your heart desires.", "{name} - Wishing you all the great things in life, hope this day will bring you an extra share of all that makes you happiest.", "Happy Birthday {name}, and may all the wishes and dreams you dream today turn to reality.", "May this day bring to you all things that make you smile. Happy Birthday {name}!", "{name} - Your best years are still ahead of you.", "{name} - Birthdays are filled with yesterday's memories, today's joys, and tomorrow's dreams.", "{name} - Hoping that your day will be as special as you are.", "{name} - You'll always be forever young." ] greeting = (name) -> greetings[(Math.random() * greetings.length) >> 0].replace(/{name}/, name); greetings = [ "Happy Birthday {name}, you're not getting older, you're just a little closer to death.", "Birthdays are good for you {name}. Statistics show that people who have the most live the longest!", "{name} - I'm so glad you were born, because you brighten my life and fill it with joy.", "{name} - Always remember: growing old is mandatory, growing up is optional.", "{name} - Better to be over the hill than burried under it.", "You always have such fun birthdays {name}, you should have one every year.", "Happy birthday to {name}, a person who is smart, good looking, and funny and reminds me a lot of myself.", "{name} - We know we're getting old when the only thing we want for our birthday is not to be reminded of it.", "Happy Birthday on your very special day {name}, I hope that you don't die before you eat your cake." ] quote = () -> quotes[(Math.random() * quotes.length) >> 0]; quotes = [ "Our birthdays are feathers in the broad wing of time. - <NAME>", "Inside every older person is a younger person wondering what happened. - <NAME>", "Wisdom doesn't necessarily come with age. Sometimes age just shows up all by itself. - <NAME>", "May you stay forever young. - <NAME>", "The old believe everything; the middle-aged suspect everything; the young know everything. - <NAME>", "Old age is like everything else. To make a success of it, you've got to start young. - <NAME>", "Age is a number and mine is unlisted. - Unknown", "When I was younger, I could remember anything, whether it happened or not.- <NAME>", "Whatever with the past has gone, The best is always yet to come. - <NAME>", "It takes a long time to grow young. - <NAME>", "Few women admit their age. Few men act theirs. - Unkown", "The best way to remember your wife's birthday is to forget it once. - <NAME>" ]
true
# Description: # Delegate your birthday greetings, celebrations and quotes to Hubot. # # Dependencies: # None # # Configuration: # None # # Commands: # hubot birthday quote for <user> -- congratulate <user> with a random birthday quote # hubot celebrate me <user> -- congratulate <user> with an inspirational greeting # hubot happy birthday me <user> -- congratulate <user> with a humorous greeting # # Author: # sopel module.exports = (robot) -> robot.respond /(birthday quote)( for )?(.*)/i, (msg)-> name = msg.match[3].trim() if name.length == 0 msg.send(quote()) else msg.send(name + " - here's a quote for you: ") msg.send(quote(name)) robot.respond /(happy birthday)( me )?(.*)/i, (msg)-> name = msg.match[3].trim() if name.length == 0 msg.send(quote()) else msg.send(greeting(name)) robot.respond /(celebrate)( me )?(.*)/i, (msg)-> name = msg.match[3].trim() if name.length == 0 msg.send("You must be kidding.") else msg.send(celebrate(name)) celebrate = (name) -> celebrates[(Math.random() * celebrates.length) >> 0].replace(/{name}/, name); celebrates = [ "{name} - Hoping that your day will be as special as you are.", "{name} - Count your life by smiles, not tears. Count your age by friends, not years.", "May the years continue to be good to you. Happy Birthday {name}!", "{name} - You're not getting older, you're getting better.", "{name} - May this year bring with it all the success and fulfillment your heart desires.", "{name} - Wishing you all the great things in life, hope this day will bring you an extra share of all that makes you happiest.", "Happy Birthday {name}, and may all the wishes and dreams you dream today turn to reality.", "May this day bring to you all things that make you smile. Happy Birthday {name}!", "{name} - Your best years are still ahead of you.", "{name} - Birthdays are filled with yesterday's memories, today's joys, and tomorrow's dreams.", "{name} - Hoping that your day will be as special as you are.", "{name} - You'll always be forever young." ] greeting = (name) -> greetings[(Math.random() * greetings.length) >> 0].replace(/{name}/, name); greetings = [ "Happy Birthday {name}, you're not getting older, you're just a little closer to death.", "Birthdays are good for you {name}. Statistics show that people who have the most live the longest!", "{name} - I'm so glad you were born, because you brighten my life and fill it with joy.", "{name} - Always remember: growing old is mandatory, growing up is optional.", "{name} - Better to be over the hill than burried under it.", "You always have such fun birthdays {name}, you should have one every year.", "Happy birthday to {name}, a person who is smart, good looking, and funny and reminds me a lot of myself.", "{name} - We know we're getting old when the only thing we want for our birthday is not to be reminded of it.", "Happy Birthday on your very special day {name}, I hope that you don't die before you eat your cake." ] quote = () -> quotes[(Math.random() * quotes.length) >> 0]; quotes = [ "Our birthdays are feathers in the broad wing of time. - PI:NAME:<NAME>END_PI", "Inside every older person is a younger person wondering what happened. - PI:NAME:<NAME>END_PI", "Wisdom doesn't necessarily come with age. Sometimes age just shows up all by itself. - PI:NAME:<NAME>END_PI", "May you stay forever young. - PI:NAME:<NAME>END_PI", "The old believe everything; the middle-aged suspect everything; the young know everything. - PI:NAME:<NAME>END_PI", "Old age is like everything else. To make a success of it, you've got to start young. - PI:NAME:<NAME>END_PI", "Age is a number and mine is unlisted. - Unknown", "When I was younger, I could remember anything, whether it happened or not.- PI:NAME:<NAME>END_PI", "Whatever with the past has gone, The best is always yet to come. - PI:NAME:<NAME>END_PI", "It takes a long time to grow young. - PI:NAME:<NAME>END_PI", "Few women admit their age. Few men act theirs. - Unkown", "The best way to remember your wife's birthday is to forget it once. - PI:NAME:<NAME>END_PI" ]
[ { "context": "ngJS - Engine Core\n# Copyright (c) 2014,2015 Queue Sakura-Shiki\n# Released under the MIT license\n# \n\n# Page switc", "end": 117, "score": 0.9995989799499512, "start": 105, "tag": "NAME", "value": "Sakura-Shiki" } ]
leaping.coffee
qkwkw/WonderWallJS
0
############################################## # LeapingJS - Engine Core # Copyright (c) 2014,2015 Queue Sakura-Shiki # Released under the MIT license # # Page switching time PAGE_DELAY = 60 # Polyfills for AnimationFrame API nextFrame = # window.requestAnimationFrame || # window.mozRequestAnimationFrame || # window.msRequestAnimationFrame || # window.webkitRequestAnimationFrame || (fn) -> setTimeout fn,1000/60 # chacking mobile or not isMobile = (navigator.userAgent.indexOf('iPhone') > 0 && navigator.userAgent.indexOf('iPad') == -1) || navigator.userAgent.indexOf('iPod') > 0 || navigator.userAgent.indexOf('Android') > 0 # page swiching or not isWorking = false # use pushState or not for Single-page Applicaito spaPush = false; # frame count until this web page started frameCount = 0 # frame count until the virtual page started pageFrameCount = 0 # mutated visual state elements on the virtual pages speedElems = [] # cached section elements. sections = [] # Current page Number( ONLY using lp-touch="back"/"next", it working.) pageCount = 0 # Max page counts. maxPageCount = 0 # Next section element, when switching virtual page. after = null # Last section element, when switching virtual page. before = null # for plugins window.LEAPING = { actions : {}, PAGE_CHANGE_TIME : PAGE_DELAY }; ####################################### # Set default CSS Values setDefaultCSS = () -> style = document.createElement "style" style.textContent = """ html,body { margin : 0; padding : 0; background-color : black; color : white; overflow : hidden; width : 100%; height: 100%; } html { touch-action : none; } section { display : none; position : fixed; top : 0%; left : 0%; width : 100%; height : 100%; background-repeat : no-repeat; background-position : center center; background-size : cover; text-align : center; } .lpBlock { position : fixed; dipslay : block; width : 100%; left : 0%; top : 0%; text-align : center; margin : 0; padding : 0; } .nowloading { display : block; position : fixed; top : 0%; left : 0%; width : 100%; height : 100%; background-color: black; } .nowloading>.progress { position : absolute; bottom : 2%; right : 2%; width :100%; text-align : right; } .nowloading>.progress>.logo { display : inline-block; width : 16px; height : 16px; } """ (document.querySelector "head").appendChild style return ####################################### # Show Loading View. showLoadView = () -> nowLoading = document.createElement "div" nowLoading.setAttribute "class","nowloading" nowLoading.innerHTML = """ <div class='progress'>Now Loading (<span class='percent'>0</span>%)</div> """ (document.querySelector "body").appendChild nowLoading return ####################################### # Move Loading View.(Actially show the progress for loading resources.) moveProgressView = () -> images = document.querySelectorAll "img" loadView = document.querySelector ".nowloading" percent = loadView.querySelector ".percent" imageList = [] allElems = document.getElementsByTagName "*" for image in images imageList.push (image.getAttribute "src") for elem in allElems convertParams elem bg = elem.getAttribute "lp-bg" if bg imageList.push bg cnt = 0 for url in imageList img = document.createElement "img" img.onload = () -> cnt++ percent.textContent = parseInt((cnt*100)/imageList.length) if imageList.length <= cnt fadeOut loadView showFirstSection() img.onerror = () -> alert "Can't load resource -> " + url img.src = url return ####################################### # Fade out the element fadeOut = (elem) -> beginFrame = 0 maxFrame = 120.0 work = () -> beginFrame++ if maxFrame < beginFrame clearInterval timer elem.style.opacity = 0.0 elem.style.display = "none" else elem.style.opacity = (maxFrame-beginFrame)/maxFrame timer = setInterval work, 1000/60 return ####################################### # Convert lp-* params and set Data convertParams = (elem) -> classStr = elem.getAttribute "class" if ! classStr classStr = "" bg = elem.getAttribute "lp-bg" if bg elem.style.backgroundImage = "url("+bg+")" x = elem.getAttribute "lp-x" if x elem.setAttribute "class", classStr+" lpBlock" elem.style.left = x+"%" y = elem.getAttribute "lp-y" if y elem.setAttribute "class", classStr+" lpBlock" elem.style.top = y+"%" if elem.getAttribute "lp-speed" elem.setAttribute "lp-text", elem.textContent touch = elem.getAttribute "lp-touch" if touch if touch == "next" elem.addEventListener "click",gotoNextSection else if touch == "back" elem.addEventListener "click",goBackToLastSection else lst = touch.split(":") if lst[0] == "goto" elem.addEventListener "click",gotoTargetId return ####################################### # Move for frame moveFrame = () -> frameCount++ pageFrameCount++ for elem in speedElems count = (pageFrameCount-PAGE_DELAY)*parseInt(elem.getAttribute "lp-speed")*0.02 elem.textContent = (elem.getAttribute "lp-text").substring(0,count) if pageFrameCount <= PAGE_DELAY isWorking = true action = null action = after.getAttribute "lp-action" if action if window.LEAPING.actions[action] window.LEAPING.actions[action](before, after, pageFrameCount) else before.style.opacity = 1.0 before.style.display = "none" after.style.opacity = 1.0 after.style.display = "block" pageFrameCount = PAGE_DELAY else if pageFrameCount < PAGE_DELAY/2 maxTime = PAGE_DELAY/2 before.style.transform = "scale("+(2.0+Math.cos(Math.PI/(1.0+(pageFrameCount/maxTime))))+")" before.style.opacity = ((maxTime-pageFrameCount)/(maxTime*1.0)) else if before before.style.display = "none" maxTime = PAGE_DELAY/2 currentFrame = pageFrameCount-maxTime after.style.display = "block" after.style.transform = "scale("+(Math.sin(Math.PI/(1.0+(currentFrame/maxTime))))+")" after.style.opacity = 1.0-((maxTime-currentFrame)/(maxTime*1.0)) else isWorking = false nextFrame moveFrame return ####################################### # Get the elements which have lp-speed attribute getSpeedElement = (elem) -> list = [] elems = elem.getElementsByTagName "*" for d in elems speed = d.getAttribute "lp-speed" if speed list.push d return list ####################################### # change video tag's playing state switchVideoState = () -> if isMobile return if before video = before.querySelector "video" if video video.pause() if after video = after.querySelector "video" if video video.play() return ####################################### # Show first <section> showFirstSection = () -> pageFrameCount = PAGE_DELAY/2 pageCount = 0 sections = document.querySelectorAll "section" maxPageCount = sections.length after = sections[pageCount] speedElems = getSpeedElement after after.style.display = "block" moveFrame() switchVideoState() if spaPush && afterId history.pushState({id:afterId}, null, "#"+afterId); return ####################################### # Go to next <section> gotoNextSection = () -> if isWorking return pageFrameCount = 0 before = sections[pageCount] pageCount++ if maxPageCount <= pageCount pageCount = 0 after = sections[pageCount] speedElems = getSpeedElement after switchVideoState() afterId = after.getAttribute "id" return ####################################### # Go back to last <section> goBackToLastSection = () -> if isWorking return pageFrameCount = 0 before = sections[pageCount] pageCount-- if pageCount < 0 pageCount = maxPageCount-1 after = sections[pageCount] speedElems = getSpeedElement after switchVideoState() return ####################################### # Go to target <section> by id gotoTargetId = () -> if isWorking return lst = (this.getAttribute "lp-touch").split(":") afterId = lst[1] switchPage afterId if spaPush history.pushState({id:afterId}, null, "#"+afterId); return ####################################### # Switch Page by Element ID switchPage = (afterId) -> before = after after = document.querySelector "#"+afterId pageFrameCount = 0 speedElems = getSpeedElement after switchVideoState() return ####################################### # set styles for each elements. setCSS = (elems,styleName,value) -> for elem in elems elem.style[styleName] = value return ####################################### # Initialize before all of the elements are loaded. delayInit = () -> if document.querySelector("body").getAttribute("lp-push") && window.history.pushState spaPush = true window.addEventListener 'popstate', popEvent showLoadView() moveProgressView() return ####################################### # for popState events. popEvent = (evt) -> state = evt.state if state.id switchPage state.id return ####################################### # execute this program. init = () -> setDefaultCSS(); return init() document.addEventListener "DOMContentLoaded", delayInit
59205
############################################## # LeapingJS - Engine Core # Copyright (c) 2014,2015 Queue <NAME> # Released under the MIT license # # Page switching time PAGE_DELAY = 60 # Polyfills for AnimationFrame API nextFrame = # window.requestAnimationFrame || # window.mozRequestAnimationFrame || # window.msRequestAnimationFrame || # window.webkitRequestAnimationFrame || (fn) -> setTimeout fn,1000/60 # chacking mobile or not isMobile = (navigator.userAgent.indexOf('iPhone') > 0 && navigator.userAgent.indexOf('iPad') == -1) || navigator.userAgent.indexOf('iPod') > 0 || navigator.userAgent.indexOf('Android') > 0 # page swiching or not isWorking = false # use pushState or not for Single-page Applicaito spaPush = false; # frame count until this web page started frameCount = 0 # frame count until the virtual page started pageFrameCount = 0 # mutated visual state elements on the virtual pages speedElems = [] # cached section elements. sections = [] # Current page Number( ONLY using lp-touch="back"/"next", it working.) pageCount = 0 # Max page counts. maxPageCount = 0 # Next section element, when switching virtual page. after = null # Last section element, when switching virtual page. before = null # for plugins window.LEAPING = { actions : {}, PAGE_CHANGE_TIME : PAGE_DELAY }; ####################################### # Set default CSS Values setDefaultCSS = () -> style = document.createElement "style" style.textContent = """ html,body { margin : 0; padding : 0; background-color : black; color : white; overflow : hidden; width : 100%; height: 100%; } html { touch-action : none; } section { display : none; position : fixed; top : 0%; left : 0%; width : 100%; height : 100%; background-repeat : no-repeat; background-position : center center; background-size : cover; text-align : center; } .lpBlock { position : fixed; dipslay : block; width : 100%; left : 0%; top : 0%; text-align : center; margin : 0; padding : 0; } .nowloading { display : block; position : fixed; top : 0%; left : 0%; width : 100%; height : 100%; background-color: black; } .nowloading>.progress { position : absolute; bottom : 2%; right : 2%; width :100%; text-align : right; } .nowloading>.progress>.logo { display : inline-block; width : 16px; height : 16px; } """ (document.querySelector "head").appendChild style return ####################################### # Show Loading View. showLoadView = () -> nowLoading = document.createElement "div" nowLoading.setAttribute "class","nowloading" nowLoading.innerHTML = """ <div class='progress'>Now Loading (<span class='percent'>0</span>%)</div> """ (document.querySelector "body").appendChild nowLoading return ####################################### # Move Loading View.(Actially show the progress for loading resources.) moveProgressView = () -> images = document.querySelectorAll "img" loadView = document.querySelector ".nowloading" percent = loadView.querySelector ".percent" imageList = [] allElems = document.getElementsByTagName "*" for image in images imageList.push (image.getAttribute "src") for elem in allElems convertParams elem bg = elem.getAttribute "lp-bg" if bg imageList.push bg cnt = 0 for url in imageList img = document.createElement "img" img.onload = () -> cnt++ percent.textContent = parseInt((cnt*100)/imageList.length) if imageList.length <= cnt fadeOut loadView showFirstSection() img.onerror = () -> alert "Can't load resource -> " + url img.src = url return ####################################### # Fade out the element fadeOut = (elem) -> beginFrame = 0 maxFrame = 120.0 work = () -> beginFrame++ if maxFrame < beginFrame clearInterval timer elem.style.opacity = 0.0 elem.style.display = "none" else elem.style.opacity = (maxFrame-beginFrame)/maxFrame timer = setInterval work, 1000/60 return ####################################### # Convert lp-* params and set Data convertParams = (elem) -> classStr = elem.getAttribute "class" if ! classStr classStr = "" bg = elem.getAttribute "lp-bg" if bg elem.style.backgroundImage = "url("+bg+")" x = elem.getAttribute "lp-x" if x elem.setAttribute "class", classStr+" lpBlock" elem.style.left = x+"%" y = elem.getAttribute "lp-y" if y elem.setAttribute "class", classStr+" lpBlock" elem.style.top = y+"%" if elem.getAttribute "lp-speed" elem.setAttribute "lp-text", elem.textContent touch = elem.getAttribute "lp-touch" if touch if touch == "next" elem.addEventListener "click",gotoNextSection else if touch == "back" elem.addEventListener "click",goBackToLastSection else lst = touch.split(":") if lst[0] == "goto" elem.addEventListener "click",gotoTargetId return ####################################### # Move for frame moveFrame = () -> frameCount++ pageFrameCount++ for elem in speedElems count = (pageFrameCount-PAGE_DELAY)*parseInt(elem.getAttribute "lp-speed")*0.02 elem.textContent = (elem.getAttribute "lp-text").substring(0,count) if pageFrameCount <= PAGE_DELAY isWorking = true action = null action = after.getAttribute "lp-action" if action if window.LEAPING.actions[action] window.LEAPING.actions[action](before, after, pageFrameCount) else before.style.opacity = 1.0 before.style.display = "none" after.style.opacity = 1.0 after.style.display = "block" pageFrameCount = PAGE_DELAY else if pageFrameCount < PAGE_DELAY/2 maxTime = PAGE_DELAY/2 before.style.transform = "scale("+(2.0+Math.cos(Math.PI/(1.0+(pageFrameCount/maxTime))))+")" before.style.opacity = ((maxTime-pageFrameCount)/(maxTime*1.0)) else if before before.style.display = "none" maxTime = PAGE_DELAY/2 currentFrame = pageFrameCount-maxTime after.style.display = "block" after.style.transform = "scale("+(Math.sin(Math.PI/(1.0+(currentFrame/maxTime))))+")" after.style.opacity = 1.0-((maxTime-currentFrame)/(maxTime*1.0)) else isWorking = false nextFrame moveFrame return ####################################### # Get the elements which have lp-speed attribute getSpeedElement = (elem) -> list = [] elems = elem.getElementsByTagName "*" for d in elems speed = d.getAttribute "lp-speed" if speed list.push d return list ####################################### # change video tag's playing state switchVideoState = () -> if isMobile return if before video = before.querySelector "video" if video video.pause() if after video = after.querySelector "video" if video video.play() return ####################################### # Show first <section> showFirstSection = () -> pageFrameCount = PAGE_DELAY/2 pageCount = 0 sections = document.querySelectorAll "section" maxPageCount = sections.length after = sections[pageCount] speedElems = getSpeedElement after after.style.display = "block" moveFrame() switchVideoState() if spaPush && afterId history.pushState({id:afterId}, null, "#"+afterId); return ####################################### # Go to next <section> gotoNextSection = () -> if isWorking return pageFrameCount = 0 before = sections[pageCount] pageCount++ if maxPageCount <= pageCount pageCount = 0 after = sections[pageCount] speedElems = getSpeedElement after switchVideoState() afterId = after.getAttribute "id" return ####################################### # Go back to last <section> goBackToLastSection = () -> if isWorking return pageFrameCount = 0 before = sections[pageCount] pageCount-- if pageCount < 0 pageCount = maxPageCount-1 after = sections[pageCount] speedElems = getSpeedElement after switchVideoState() return ####################################### # Go to target <section> by id gotoTargetId = () -> if isWorking return lst = (this.getAttribute "lp-touch").split(":") afterId = lst[1] switchPage afterId if spaPush history.pushState({id:afterId}, null, "#"+afterId); return ####################################### # Switch Page by Element ID switchPage = (afterId) -> before = after after = document.querySelector "#"+afterId pageFrameCount = 0 speedElems = getSpeedElement after switchVideoState() return ####################################### # set styles for each elements. setCSS = (elems,styleName,value) -> for elem in elems elem.style[styleName] = value return ####################################### # Initialize before all of the elements are loaded. delayInit = () -> if document.querySelector("body").getAttribute("lp-push") && window.history.pushState spaPush = true window.addEventListener 'popstate', popEvent showLoadView() moveProgressView() return ####################################### # for popState events. popEvent = (evt) -> state = evt.state if state.id switchPage state.id return ####################################### # execute this program. init = () -> setDefaultCSS(); return init() document.addEventListener "DOMContentLoaded", delayInit
true
############################################## # LeapingJS - Engine Core # Copyright (c) 2014,2015 Queue PI:NAME:<NAME>END_PI # Released under the MIT license # # Page switching time PAGE_DELAY = 60 # Polyfills for AnimationFrame API nextFrame = # window.requestAnimationFrame || # window.mozRequestAnimationFrame || # window.msRequestAnimationFrame || # window.webkitRequestAnimationFrame || (fn) -> setTimeout fn,1000/60 # chacking mobile or not isMobile = (navigator.userAgent.indexOf('iPhone') > 0 && navigator.userAgent.indexOf('iPad') == -1) || navigator.userAgent.indexOf('iPod') > 0 || navigator.userAgent.indexOf('Android') > 0 # page swiching or not isWorking = false # use pushState or not for Single-page Applicaito spaPush = false; # frame count until this web page started frameCount = 0 # frame count until the virtual page started pageFrameCount = 0 # mutated visual state elements on the virtual pages speedElems = [] # cached section elements. sections = [] # Current page Number( ONLY using lp-touch="back"/"next", it working.) pageCount = 0 # Max page counts. maxPageCount = 0 # Next section element, when switching virtual page. after = null # Last section element, when switching virtual page. before = null # for plugins window.LEAPING = { actions : {}, PAGE_CHANGE_TIME : PAGE_DELAY }; ####################################### # Set default CSS Values setDefaultCSS = () -> style = document.createElement "style" style.textContent = """ html,body { margin : 0; padding : 0; background-color : black; color : white; overflow : hidden; width : 100%; height: 100%; } html { touch-action : none; } section { display : none; position : fixed; top : 0%; left : 0%; width : 100%; height : 100%; background-repeat : no-repeat; background-position : center center; background-size : cover; text-align : center; } .lpBlock { position : fixed; dipslay : block; width : 100%; left : 0%; top : 0%; text-align : center; margin : 0; padding : 0; } .nowloading { display : block; position : fixed; top : 0%; left : 0%; width : 100%; height : 100%; background-color: black; } .nowloading>.progress { position : absolute; bottom : 2%; right : 2%; width :100%; text-align : right; } .nowloading>.progress>.logo { display : inline-block; width : 16px; height : 16px; } """ (document.querySelector "head").appendChild style return ####################################### # Show Loading View. showLoadView = () -> nowLoading = document.createElement "div" nowLoading.setAttribute "class","nowloading" nowLoading.innerHTML = """ <div class='progress'>Now Loading (<span class='percent'>0</span>%)</div> """ (document.querySelector "body").appendChild nowLoading return ####################################### # Move Loading View.(Actially show the progress for loading resources.) moveProgressView = () -> images = document.querySelectorAll "img" loadView = document.querySelector ".nowloading" percent = loadView.querySelector ".percent" imageList = [] allElems = document.getElementsByTagName "*" for image in images imageList.push (image.getAttribute "src") for elem in allElems convertParams elem bg = elem.getAttribute "lp-bg" if bg imageList.push bg cnt = 0 for url in imageList img = document.createElement "img" img.onload = () -> cnt++ percent.textContent = parseInt((cnt*100)/imageList.length) if imageList.length <= cnt fadeOut loadView showFirstSection() img.onerror = () -> alert "Can't load resource -> " + url img.src = url return ####################################### # Fade out the element fadeOut = (elem) -> beginFrame = 0 maxFrame = 120.0 work = () -> beginFrame++ if maxFrame < beginFrame clearInterval timer elem.style.opacity = 0.0 elem.style.display = "none" else elem.style.opacity = (maxFrame-beginFrame)/maxFrame timer = setInterval work, 1000/60 return ####################################### # Convert lp-* params and set Data convertParams = (elem) -> classStr = elem.getAttribute "class" if ! classStr classStr = "" bg = elem.getAttribute "lp-bg" if bg elem.style.backgroundImage = "url("+bg+")" x = elem.getAttribute "lp-x" if x elem.setAttribute "class", classStr+" lpBlock" elem.style.left = x+"%" y = elem.getAttribute "lp-y" if y elem.setAttribute "class", classStr+" lpBlock" elem.style.top = y+"%" if elem.getAttribute "lp-speed" elem.setAttribute "lp-text", elem.textContent touch = elem.getAttribute "lp-touch" if touch if touch == "next" elem.addEventListener "click",gotoNextSection else if touch == "back" elem.addEventListener "click",goBackToLastSection else lst = touch.split(":") if lst[0] == "goto" elem.addEventListener "click",gotoTargetId return ####################################### # Move for frame moveFrame = () -> frameCount++ pageFrameCount++ for elem in speedElems count = (pageFrameCount-PAGE_DELAY)*parseInt(elem.getAttribute "lp-speed")*0.02 elem.textContent = (elem.getAttribute "lp-text").substring(0,count) if pageFrameCount <= PAGE_DELAY isWorking = true action = null action = after.getAttribute "lp-action" if action if window.LEAPING.actions[action] window.LEAPING.actions[action](before, after, pageFrameCount) else before.style.opacity = 1.0 before.style.display = "none" after.style.opacity = 1.0 after.style.display = "block" pageFrameCount = PAGE_DELAY else if pageFrameCount < PAGE_DELAY/2 maxTime = PAGE_DELAY/2 before.style.transform = "scale("+(2.0+Math.cos(Math.PI/(1.0+(pageFrameCount/maxTime))))+")" before.style.opacity = ((maxTime-pageFrameCount)/(maxTime*1.0)) else if before before.style.display = "none" maxTime = PAGE_DELAY/2 currentFrame = pageFrameCount-maxTime after.style.display = "block" after.style.transform = "scale("+(Math.sin(Math.PI/(1.0+(currentFrame/maxTime))))+")" after.style.opacity = 1.0-((maxTime-currentFrame)/(maxTime*1.0)) else isWorking = false nextFrame moveFrame return ####################################### # Get the elements which have lp-speed attribute getSpeedElement = (elem) -> list = [] elems = elem.getElementsByTagName "*" for d in elems speed = d.getAttribute "lp-speed" if speed list.push d return list ####################################### # change video tag's playing state switchVideoState = () -> if isMobile return if before video = before.querySelector "video" if video video.pause() if after video = after.querySelector "video" if video video.play() return ####################################### # Show first <section> showFirstSection = () -> pageFrameCount = PAGE_DELAY/2 pageCount = 0 sections = document.querySelectorAll "section" maxPageCount = sections.length after = sections[pageCount] speedElems = getSpeedElement after after.style.display = "block" moveFrame() switchVideoState() if spaPush && afterId history.pushState({id:afterId}, null, "#"+afterId); return ####################################### # Go to next <section> gotoNextSection = () -> if isWorking return pageFrameCount = 0 before = sections[pageCount] pageCount++ if maxPageCount <= pageCount pageCount = 0 after = sections[pageCount] speedElems = getSpeedElement after switchVideoState() afterId = after.getAttribute "id" return ####################################### # Go back to last <section> goBackToLastSection = () -> if isWorking return pageFrameCount = 0 before = sections[pageCount] pageCount-- if pageCount < 0 pageCount = maxPageCount-1 after = sections[pageCount] speedElems = getSpeedElement after switchVideoState() return ####################################### # Go to target <section> by id gotoTargetId = () -> if isWorking return lst = (this.getAttribute "lp-touch").split(":") afterId = lst[1] switchPage afterId if spaPush history.pushState({id:afterId}, null, "#"+afterId); return ####################################### # Switch Page by Element ID switchPage = (afterId) -> before = after after = document.querySelector "#"+afterId pageFrameCount = 0 speedElems = getSpeedElement after switchVideoState() return ####################################### # set styles for each elements. setCSS = (elems,styleName,value) -> for elem in elems elem.style[styleName] = value return ####################################### # Initialize before all of the elements are loaded. delayInit = () -> if document.querySelector("body").getAttribute("lp-push") && window.history.pushState spaPush = true window.addEventListener 'popstate', popEvent showLoadView() moveProgressView() return ####################################### # for popState events. popEvent = (evt) -> state = evt.state if state.id switchPage state.id return ####################################### # execute this program. init = () -> setDefaultCSS(); return init() document.addEventListener "DOMContentLoaded", delayInit
[ { "context": "# Droplet C mode\n#\n# Copyright (c) 2015 Anthony Bau\n# MIT License\n\nhelper = require '../helper.coffee", "end": 51, "score": 0.9998594522476196, "start": 40, "tag": "NAME", "value": "Anthony Bau" } ]
src/languages/c.coffee
takeratta/droplet
145
# Droplet C mode # # Copyright (c) 2015 Anthony Bau # MIT License helper = require '../helper.coffee' parser = require '../parser.coffee' antlrHelper = require '../antlr.coffee' {fixQuotedString, looseCUnescape, quoteAndCEscape} = helper RULES = { # Indents 'compoundStatement': { 'type': 'indent', 'indentContext': 'blockItem', }, 'structDeclarationsBlock': { 'type': 'indent', 'indentContext': 'structDeclaration' }, # Parens 'expressionStatement': 'parens', 'primaryExpression': 'parens', 'structDeclaration': 'parens', # Skips 'blockItemList': 'skip', 'macroParamList': 'skip', 'compilationUnit': 'skip', 'translationUnit': 'skip', 'declarationSpecifiers': 'skip', 'declarationSpecifier': 'skip', 'typeSpecifier': 'skip', 'structOrUnionSpecifier': 'skip', 'structDeclarationList': 'skip', 'declarator': 'skip', 'directDeclarator': 'skip', 'rootDeclarator': 'skip', 'parameterTypeList': 'skip', 'parameterList': 'skip', 'argumentExpressionList': 'skip', 'initializerList': 'skip', 'initDeclaratorList': 'skip', # Sockets 'Identifier': 'socket', 'StringLiteral': 'socket', 'SharedIncludeLiteral': 'socket', 'Constant': 'socket' } COLOR_RULES = [ ['jumpStatement', 'return'] # e.g. `return 0;` ['declaration', 'control'], # e.g. `int a;` ['specialMethodCall', 'command'], # e.g. `a(b);` ['equalityExpression', 'value'] # e.g. `a == b` ['additiveExpression', 'value'], # e.g. `a + b` ['multiplicativeExpression', 'value'], # e.g. `a * b` ['postfixExpression', 'command'], # e.g. `a(b, c);` OR `a++` ['iterationStatement', 'control'], # e.g. `for (int i = 0; i < 10; i++) { }` ['selectionStatement', 'control'], # e.g. if `(a) { } else { }` OR `switch (a) { }` ['assignmentExpression', 'command'], # e.g. `a = b;` OR `a = b` ['relationalExpression', 'value'], # e.g. `a < b` ['initDeclarator', 'command'], # e.g. `a = b` when inside `int a = b;` ['blockItemList', 'control'], # List of commands ['compoundStatement', 'control'], # List of commands inside braces ['externalDeclaration', 'control'], # e.g. `int a = b` when global ['structDeclaration', 'command'], # e.g. `struct a { }` ['declarationSpecifier', 'control'], # e.g. `int` when in `int a = b;` ['statement', 'command'], # Any statement, like `return 0;` ['functionDefinition', 'control'], # e.g. `int myMethod() { }` ['expressionStatement', 'command'], # Statement that consists of an expression, like `a = b;` ['expression', 'value'], # Any expression, like `a + b` ['parameterDeclaration', 'command'], # e.g. `int a` when in `int myMethod(int a) { }` ['unaryExpression', 'value'], # e.g. `sizeof(a)` ['typeName', 'value'], # e.g. `int` ['initializer', 'value'], # e.g. `{a, b, c}` when in `int x[] = {a, b, c};` ['castExpression', 'value'] # e.g. `(b)a` ] SHAPE_RULES = [ ['blockItem', 'block-only'], # Any statement, like `return 0;` ['expression', 'value-only'], # Any expression, like `a + b` ['postfixExpression', 'block-only'], # e.g. `a(b, c);` OR `a++` ['equalityExpression', 'value-only'], # e.g. `a == b` ['logicalAndExpression', 'value-only'], # e.g. `a && b` ['logicalOrExpression', 'value-only'], # e.g. `a || b` ['iterationStatement', 'block-only'], # e.g. `for (int i = 0; i < 10; i++) { }` ['selectionStatement', 'block-only'], # e.g. if `(a) { } else { }` OR `switch (a) { }` ['assignmentExpression', 'block-only'], # e.g. `a = b;` OR `a = b` ['relationalExpression', 'value-only'], # e.g. `a < b` ['initDeclarator', 'block-only'], # e.g. `a = b` when inside `int a = b;` ['externalDeclaration', 'block-only'], # e.g. `int a = b` when global ['structDeclaration', 'block-only'], # e.g. `struct a { }` ['declarationSpecifier', 'block-only'], # e.g. `int` when in `int a = b;` ['statement', 'block-only'], # Any statement, like `return 0;` ['functionDefinition', 'block-only'], # e.g. `int myMethod() { }` ['expressionStatement', 'block-only'], # Statement that consists of an expression, like `a = b;` ['additiveExpression', 'value-only'], # e.g. `a + b` ['multiplicativeExpression', 'value-only'], # e.g. `a * b` ['declaration', 'block-only'], # e.g. `int a;` ['parameterDeclaration', 'block-only'], # e.g. `int a` when in `int myMethod(int a) { }` ['unaryExpression', 'value-only'], # e.g. `sizeof(a)` ['typeName', 'value-only'], # e.g. `int` ['initializer', 'value-only'], # e.g. `{a, b, c}` when in `int x[] = {a, b, c};` ['castExpression', 'value-only'] # e.g. `(b)a` ] config = { RULES, COLOR_RULES, SHAPE_RULES } ADD_PARENS = (leading, trailing, node, context) -> leading '(' + leading() trailing trailing() + ')' STATEMENT_TO_EXPRESSION = (leading, trailing, node, context) -> matching = false for c in node.classes when c[...'__parse__'.length] is '__parse__' if c in context.classes matching = true break if matching leading '(' + leading() trailing trailing().replace(/\s*;\s*$/, '') + ')' else trailing trailing().replace(/\s*;\s*$/, '') EXPRESSION_TO_STATEMENT = (leading, trailing, node, context) -> while true if leading().match(/^\s*\(/)? and trailing().match(/\)\s*/)? leading leading().replace(/^\s*\(\s*/, '') trailing trailing().replace(/\s*\)\s*$/, '') else break trailing trailing() + ';' config.PAREN_RULES = { 'primaryExpression': { 'expression': ADD_PARENS 'additiveExpression': ADD_PARENS 'multiplicativeExpression': ADD_PARENS 'assignmentExpression': ADD_PARENS 'postfixExpression': ADD_PARENS 'expressionStatement': STATEMENT_TO_EXPRESSION 'specialMethodCall': STATEMENT_TO_EXPRESSION } 'blockItem': { 'expression': EXPRESSION_TO_STATEMENT 'additiveExpression': EXPRESSION_TO_STATEMENT 'multiplicativeExpression': EXPRESSION_TO_STATEMENT 'assignmentExpression': EXPRESSION_TO_STATEMENT 'postfixExpression': EXPRESSION_TO_STATEMENT } } # Test to see if a node is a method call getMethodName = (node) -> if node.type is 'postfixExpression' and # The children of a method call are either # `(method) '(' (paramlist) ')'` OR `(method) '(' ')'` node.children.length in [3, 4] and # Check to make sure that the correct children are parentheses node.children[1].type is 'LeftParen' and (node.children[2].type is 'RightParen' or node.children[3]?.type is 'RightParen') and # Check to see whether the called method is a single identifier, like `puts` in # `getc()`, rather than `getFunctionPointer()()` or `a.b()` node.children[0].children[0].type is 'primaryExpression' and node.children[0].children[0].children[0].type is 'Identifier' # If all of these are true, we have a function name to give return node.children[0].children[0].children[0].data.text # Alternatively, we could have the special `a(b)` node. else if node.type is 'specialMethodCall' return node.children[0].data.text return null config.SHOULD_SOCKET = (opts, node) -> # We will not socket if we are the identifier # in a single-identifier function call like `a(b, c)` # and `a` is in the known functions list. # # We can only be such an identifier if we have the appropriate number of parents; # check. unless opts.knownFunctions? and ((node.parent? and node.parent.parent? and node.parent.parent.parent?) or node.parent?.type is 'specialMethodCall') return true # Check to see whether the thing we are in is a function if (node.parent?.type is 'specialMethodCall' or getMethodName(node.parent.parent.parent)? and # Check to see whether we are the first child node.parent.parent is node.parent.parent.parent.children[0] and node.parent is node.parent.parent.children[0] and node is node.parent.children[0]) and # Finally, check to see if our name is a known function name node.data.text of opts.knownFunctions # If the checks pass, do not socket. return false return true # Color and shape callbacks look up the method name # in the known functions list if available. config.COLOR_CALLBACK = (opts, node) -> return null unless opts.knownFunctions? name = getMethodName node if name? and name of opts.knownFunctions return opts.knownFunctions[name].color else return null config.SHAPE_CALLBACK = (opts, node) -> return null unless opts.knownFunctions? name = getMethodName node if name? and name of opts.knownFunctions return opts.knownFunctions[name].shape else return null config.isComment = (text) -> text.match(/^(\s*\/\/.*)|(#.*)$/)? config.parseComment = (text) -> # Try standard comment comment = text.match(/^(\s*\/\/)(.*)$/) if comment? sockets = [ [comment[1].length, comment[1].length + comment[2].length] ] color = 'comment' return {sockets, color} if text.match(/^#\s*((?:else)|(?:endif))$/) sockets = [] color = 'purple' return {sockets, color} # Try #define directive binary = text.match(/^(#\s*(?:(?:define))\s*)([a-zA-Z_][0-9a-zA-Z_]*)(\s+)(.*)$/) if binary? sockets = [ [binary[1].length, binary[1].length + binary[2].length] [binary[1].length + binary[2].length + binary[3].length, binary[1].length + binary[2].length + binary[3].length + binary[4].length] ] color = 'purple' return {sockets, color} # Try functional #define directive. binary = text.match(/^(#\s*define\s*)([a-zA-Z_][0-9a-zA-Z_]*\s*\((?:[a-zA-Z_][0-9a-zA-Z_]*,\s)*[a-zA-Z_][0-9a-zA-Z_]*\s*\))(\s+)(.*)$/) if binary? sockets = [ [binary[1].length, binary[1].length + binary[2].length] [binary[1].length + binary[2].length + binary[3].length, binary[1].length + binary[2].length + binary[3].length + binary[4].length] ] color = 'purple' return {sockets, color} # Try any of the unary directives: #define, #if, #ifdef, #ifndef, #undef, #pragma unary = text.match(/^(#\s*(?:(?:define)|(?:ifdef)|(?:if)|(?:ifndef)|(?:undef)|(?:pragma))\s*)(.*)$/) if unary? sockets = [ [unary[1].length, unary[1].length + unary[2].length] ] color = 'purple' return {sockets, color} # Try #include, which must include the quotations unary = text.match(/^(#\s*include\s*<)(.*)>\s*$/) if unary? sockets = [ [unary[1].length, unary[1].length + unary[2].length] ] color = 'purple' return {sockets, color} unary = text.match(/^(#\s*include\s*")(.*)"\s*$/) if unary? sockets = [ [unary[1].length, unary[1].length + unary[2].length] ] color = 'purple' return {sockets, color} config.getDefaultSelectionRange = (string) -> start = 0; end = string.length if string.length > 1 and string[0] is string[string.length - 1] and string[0] is '"' start += 1; end -= 1 if string.length > 1 and string[0] is '<' and string[string.length - 1] is '>' start += 1; end -= 1 if string.length is 3 and string[0] is string[string.length - 1] is '\'' start += 1; end -= 1 return {start, end} config.stringFixer = (string) -> if /^['"]|['"]$/.test string return fixQuotedString [string] else return string config.empty = '__0_droplet__' config.emptyIndent = '' # TODO Implement removing parentheses at some point #config.unParenWrap = (leading, trailing, node, context) -> # while true # if leading().match(/^\s*\(/)? and trailing().match(/\)\s*/)? # leading leading().replace(/^\s*\(\s*/, '') # trailing trailing().replace(/\s*\)\s*$/, '') # else # break # DEBUG config.unParenWrap = null module.exports = parser.wrapParser antlrHelper.createANTLRParser 'C', config
84702
# Droplet C mode # # Copyright (c) 2015 <NAME> # MIT License helper = require '../helper.coffee' parser = require '../parser.coffee' antlrHelper = require '../antlr.coffee' {fixQuotedString, looseCUnescape, quoteAndCEscape} = helper RULES = { # Indents 'compoundStatement': { 'type': 'indent', 'indentContext': 'blockItem', }, 'structDeclarationsBlock': { 'type': 'indent', 'indentContext': 'structDeclaration' }, # Parens 'expressionStatement': 'parens', 'primaryExpression': 'parens', 'structDeclaration': 'parens', # Skips 'blockItemList': 'skip', 'macroParamList': 'skip', 'compilationUnit': 'skip', 'translationUnit': 'skip', 'declarationSpecifiers': 'skip', 'declarationSpecifier': 'skip', 'typeSpecifier': 'skip', 'structOrUnionSpecifier': 'skip', 'structDeclarationList': 'skip', 'declarator': 'skip', 'directDeclarator': 'skip', 'rootDeclarator': 'skip', 'parameterTypeList': 'skip', 'parameterList': 'skip', 'argumentExpressionList': 'skip', 'initializerList': 'skip', 'initDeclaratorList': 'skip', # Sockets 'Identifier': 'socket', 'StringLiteral': 'socket', 'SharedIncludeLiteral': 'socket', 'Constant': 'socket' } COLOR_RULES = [ ['jumpStatement', 'return'] # e.g. `return 0;` ['declaration', 'control'], # e.g. `int a;` ['specialMethodCall', 'command'], # e.g. `a(b);` ['equalityExpression', 'value'] # e.g. `a == b` ['additiveExpression', 'value'], # e.g. `a + b` ['multiplicativeExpression', 'value'], # e.g. `a * b` ['postfixExpression', 'command'], # e.g. `a(b, c);` OR `a++` ['iterationStatement', 'control'], # e.g. `for (int i = 0; i < 10; i++) { }` ['selectionStatement', 'control'], # e.g. if `(a) { } else { }` OR `switch (a) { }` ['assignmentExpression', 'command'], # e.g. `a = b;` OR `a = b` ['relationalExpression', 'value'], # e.g. `a < b` ['initDeclarator', 'command'], # e.g. `a = b` when inside `int a = b;` ['blockItemList', 'control'], # List of commands ['compoundStatement', 'control'], # List of commands inside braces ['externalDeclaration', 'control'], # e.g. `int a = b` when global ['structDeclaration', 'command'], # e.g. `struct a { }` ['declarationSpecifier', 'control'], # e.g. `int` when in `int a = b;` ['statement', 'command'], # Any statement, like `return 0;` ['functionDefinition', 'control'], # e.g. `int myMethod() { }` ['expressionStatement', 'command'], # Statement that consists of an expression, like `a = b;` ['expression', 'value'], # Any expression, like `a + b` ['parameterDeclaration', 'command'], # e.g. `int a` when in `int myMethod(int a) { }` ['unaryExpression', 'value'], # e.g. `sizeof(a)` ['typeName', 'value'], # e.g. `int` ['initializer', 'value'], # e.g. `{a, b, c}` when in `int x[] = {a, b, c};` ['castExpression', 'value'] # e.g. `(b)a` ] SHAPE_RULES = [ ['blockItem', 'block-only'], # Any statement, like `return 0;` ['expression', 'value-only'], # Any expression, like `a + b` ['postfixExpression', 'block-only'], # e.g. `a(b, c);` OR `a++` ['equalityExpression', 'value-only'], # e.g. `a == b` ['logicalAndExpression', 'value-only'], # e.g. `a && b` ['logicalOrExpression', 'value-only'], # e.g. `a || b` ['iterationStatement', 'block-only'], # e.g. `for (int i = 0; i < 10; i++) { }` ['selectionStatement', 'block-only'], # e.g. if `(a) { } else { }` OR `switch (a) { }` ['assignmentExpression', 'block-only'], # e.g. `a = b;` OR `a = b` ['relationalExpression', 'value-only'], # e.g. `a < b` ['initDeclarator', 'block-only'], # e.g. `a = b` when inside `int a = b;` ['externalDeclaration', 'block-only'], # e.g. `int a = b` when global ['structDeclaration', 'block-only'], # e.g. `struct a { }` ['declarationSpecifier', 'block-only'], # e.g. `int` when in `int a = b;` ['statement', 'block-only'], # Any statement, like `return 0;` ['functionDefinition', 'block-only'], # e.g. `int myMethod() { }` ['expressionStatement', 'block-only'], # Statement that consists of an expression, like `a = b;` ['additiveExpression', 'value-only'], # e.g. `a + b` ['multiplicativeExpression', 'value-only'], # e.g. `a * b` ['declaration', 'block-only'], # e.g. `int a;` ['parameterDeclaration', 'block-only'], # e.g. `int a` when in `int myMethod(int a) { }` ['unaryExpression', 'value-only'], # e.g. `sizeof(a)` ['typeName', 'value-only'], # e.g. `int` ['initializer', 'value-only'], # e.g. `{a, b, c}` when in `int x[] = {a, b, c};` ['castExpression', 'value-only'] # e.g. `(b)a` ] config = { RULES, COLOR_RULES, SHAPE_RULES } ADD_PARENS = (leading, trailing, node, context) -> leading '(' + leading() trailing trailing() + ')' STATEMENT_TO_EXPRESSION = (leading, trailing, node, context) -> matching = false for c in node.classes when c[...'__parse__'.length] is '__parse__' if c in context.classes matching = true break if matching leading '(' + leading() trailing trailing().replace(/\s*;\s*$/, '') + ')' else trailing trailing().replace(/\s*;\s*$/, '') EXPRESSION_TO_STATEMENT = (leading, trailing, node, context) -> while true if leading().match(/^\s*\(/)? and trailing().match(/\)\s*/)? leading leading().replace(/^\s*\(\s*/, '') trailing trailing().replace(/\s*\)\s*$/, '') else break trailing trailing() + ';' config.PAREN_RULES = { 'primaryExpression': { 'expression': ADD_PARENS 'additiveExpression': ADD_PARENS 'multiplicativeExpression': ADD_PARENS 'assignmentExpression': ADD_PARENS 'postfixExpression': ADD_PARENS 'expressionStatement': STATEMENT_TO_EXPRESSION 'specialMethodCall': STATEMENT_TO_EXPRESSION } 'blockItem': { 'expression': EXPRESSION_TO_STATEMENT 'additiveExpression': EXPRESSION_TO_STATEMENT 'multiplicativeExpression': EXPRESSION_TO_STATEMENT 'assignmentExpression': EXPRESSION_TO_STATEMENT 'postfixExpression': EXPRESSION_TO_STATEMENT } } # Test to see if a node is a method call getMethodName = (node) -> if node.type is 'postfixExpression' and # The children of a method call are either # `(method) '(' (paramlist) ')'` OR `(method) '(' ')'` node.children.length in [3, 4] and # Check to make sure that the correct children are parentheses node.children[1].type is 'LeftParen' and (node.children[2].type is 'RightParen' or node.children[3]?.type is 'RightParen') and # Check to see whether the called method is a single identifier, like `puts` in # `getc()`, rather than `getFunctionPointer()()` or `a.b()` node.children[0].children[0].type is 'primaryExpression' and node.children[0].children[0].children[0].type is 'Identifier' # If all of these are true, we have a function name to give return node.children[0].children[0].children[0].data.text # Alternatively, we could have the special `a(b)` node. else if node.type is 'specialMethodCall' return node.children[0].data.text return null config.SHOULD_SOCKET = (opts, node) -> # We will not socket if we are the identifier # in a single-identifier function call like `a(b, c)` # and `a` is in the known functions list. # # We can only be such an identifier if we have the appropriate number of parents; # check. unless opts.knownFunctions? and ((node.parent? and node.parent.parent? and node.parent.parent.parent?) or node.parent?.type is 'specialMethodCall') return true # Check to see whether the thing we are in is a function if (node.parent?.type is 'specialMethodCall' or getMethodName(node.parent.parent.parent)? and # Check to see whether we are the first child node.parent.parent is node.parent.parent.parent.children[0] and node.parent is node.parent.parent.children[0] and node is node.parent.children[0]) and # Finally, check to see if our name is a known function name node.data.text of opts.knownFunctions # If the checks pass, do not socket. return false return true # Color and shape callbacks look up the method name # in the known functions list if available. config.COLOR_CALLBACK = (opts, node) -> return null unless opts.knownFunctions? name = getMethodName node if name? and name of opts.knownFunctions return opts.knownFunctions[name].color else return null config.SHAPE_CALLBACK = (opts, node) -> return null unless opts.knownFunctions? name = getMethodName node if name? and name of opts.knownFunctions return opts.knownFunctions[name].shape else return null config.isComment = (text) -> text.match(/^(\s*\/\/.*)|(#.*)$/)? config.parseComment = (text) -> # Try standard comment comment = text.match(/^(\s*\/\/)(.*)$/) if comment? sockets = [ [comment[1].length, comment[1].length + comment[2].length] ] color = 'comment' return {sockets, color} if text.match(/^#\s*((?:else)|(?:endif))$/) sockets = [] color = 'purple' return {sockets, color} # Try #define directive binary = text.match(/^(#\s*(?:(?:define))\s*)([a-zA-Z_][0-9a-zA-Z_]*)(\s+)(.*)$/) if binary? sockets = [ [binary[1].length, binary[1].length + binary[2].length] [binary[1].length + binary[2].length + binary[3].length, binary[1].length + binary[2].length + binary[3].length + binary[4].length] ] color = 'purple' return {sockets, color} # Try functional #define directive. binary = text.match(/^(#\s*define\s*)([a-zA-Z_][0-9a-zA-Z_]*\s*\((?:[a-zA-Z_][0-9a-zA-Z_]*,\s)*[a-zA-Z_][0-9a-zA-Z_]*\s*\))(\s+)(.*)$/) if binary? sockets = [ [binary[1].length, binary[1].length + binary[2].length] [binary[1].length + binary[2].length + binary[3].length, binary[1].length + binary[2].length + binary[3].length + binary[4].length] ] color = 'purple' return {sockets, color} # Try any of the unary directives: #define, #if, #ifdef, #ifndef, #undef, #pragma unary = text.match(/^(#\s*(?:(?:define)|(?:ifdef)|(?:if)|(?:ifndef)|(?:undef)|(?:pragma))\s*)(.*)$/) if unary? sockets = [ [unary[1].length, unary[1].length + unary[2].length] ] color = 'purple' return {sockets, color} # Try #include, which must include the quotations unary = text.match(/^(#\s*include\s*<)(.*)>\s*$/) if unary? sockets = [ [unary[1].length, unary[1].length + unary[2].length] ] color = 'purple' return {sockets, color} unary = text.match(/^(#\s*include\s*")(.*)"\s*$/) if unary? sockets = [ [unary[1].length, unary[1].length + unary[2].length] ] color = 'purple' return {sockets, color} config.getDefaultSelectionRange = (string) -> start = 0; end = string.length if string.length > 1 and string[0] is string[string.length - 1] and string[0] is '"' start += 1; end -= 1 if string.length > 1 and string[0] is '<' and string[string.length - 1] is '>' start += 1; end -= 1 if string.length is 3 and string[0] is string[string.length - 1] is '\'' start += 1; end -= 1 return {start, end} config.stringFixer = (string) -> if /^['"]|['"]$/.test string return fixQuotedString [string] else return string config.empty = '__0_droplet__' config.emptyIndent = '' # TODO Implement removing parentheses at some point #config.unParenWrap = (leading, trailing, node, context) -> # while true # if leading().match(/^\s*\(/)? and trailing().match(/\)\s*/)? # leading leading().replace(/^\s*\(\s*/, '') # trailing trailing().replace(/\s*\)\s*$/, '') # else # break # DEBUG config.unParenWrap = null module.exports = parser.wrapParser antlrHelper.createANTLRParser 'C', config
true
# Droplet C mode # # Copyright (c) 2015 PI:NAME:<NAME>END_PI # MIT License helper = require '../helper.coffee' parser = require '../parser.coffee' antlrHelper = require '../antlr.coffee' {fixQuotedString, looseCUnescape, quoteAndCEscape} = helper RULES = { # Indents 'compoundStatement': { 'type': 'indent', 'indentContext': 'blockItem', }, 'structDeclarationsBlock': { 'type': 'indent', 'indentContext': 'structDeclaration' }, # Parens 'expressionStatement': 'parens', 'primaryExpression': 'parens', 'structDeclaration': 'parens', # Skips 'blockItemList': 'skip', 'macroParamList': 'skip', 'compilationUnit': 'skip', 'translationUnit': 'skip', 'declarationSpecifiers': 'skip', 'declarationSpecifier': 'skip', 'typeSpecifier': 'skip', 'structOrUnionSpecifier': 'skip', 'structDeclarationList': 'skip', 'declarator': 'skip', 'directDeclarator': 'skip', 'rootDeclarator': 'skip', 'parameterTypeList': 'skip', 'parameterList': 'skip', 'argumentExpressionList': 'skip', 'initializerList': 'skip', 'initDeclaratorList': 'skip', # Sockets 'Identifier': 'socket', 'StringLiteral': 'socket', 'SharedIncludeLiteral': 'socket', 'Constant': 'socket' } COLOR_RULES = [ ['jumpStatement', 'return'] # e.g. `return 0;` ['declaration', 'control'], # e.g. `int a;` ['specialMethodCall', 'command'], # e.g. `a(b);` ['equalityExpression', 'value'] # e.g. `a == b` ['additiveExpression', 'value'], # e.g. `a + b` ['multiplicativeExpression', 'value'], # e.g. `a * b` ['postfixExpression', 'command'], # e.g. `a(b, c);` OR `a++` ['iterationStatement', 'control'], # e.g. `for (int i = 0; i < 10; i++) { }` ['selectionStatement', 'control'], # e.g. if `(a) { } else { }` OR `switch (a) { }` ['assignmentExpression', 'command'], # e.g. `a = b;` OR `a = b` ['relationalExpression', 'value'], # e.g. `a < b` ['initDeclarator', 'command'], # e.g. `a = b` when inside `int a = b;` ['blockItemList', 'control'], # List of commands ['compoundStatement', 'control'], # List of commands inside braces ['externalDeclaration', 'control'], # e.g. `int a = b` when global ['structDeclaration', 'command'], # e.g. `struct a { }` ['declarationSpecifier', 'control'], # e.g. `int` when in `int a = b;` ['statement', 'command'], # Any statement, like `return 0;` ['functionDefinition', 'control'], # e.g. `int myMethod() { }` ['expressionStatement', 'command'], # Statement that consists of an expression, like `a = b;` ['expression', 'value'], # Any expression, like `a + b` ['parameterDeclaration', 'command'], # e.g. `int a` when in `int myMethod(int a) { }` ['unaryExpression', 'value'], # e.g. `sizeof(a)` ['typeName', 'value'], # e.g. `int` ['initializer', 'value'], # e.g. `{a, b, c}` when in `int x[] = {a, b, c};` ['castExpression', 'value'] # e.g. `(b)a` ] SHAPE_RULES = [ ['blockItem', 'block-only'], # Any statement, like `return 0;` ['expression', 'value-only'], # Any expression, like `a + b` ['postfixExpression', 'block-only'], # e.g. `a(b, c);` OR `a++` ['equalityExpression', 'value-only'], # e.g. `a == b` ['logicalAndExpression', 'value-only'], # e.g. `a && b` ['logicalOrExpression', 'value-only'], # e.g. `a || b` ['iterationStatement', 'block-only'], # e.g. `for (int i = 0; i < 10; i++) { }` ['selectionStatement', 'block-only'], # e.g. if `(a) { } else { }` OR `switch (a) { }` ['assignmentExpression', 'block-only'], # e.g. `a = b;` OR `a = b` ['relationalExpression', 'value-only'], # e.g. `a < b` ['initDeclarator', 'block-only'], # e.g. `a = b` when inside `int a = b;` ['externalDeclaration', 'block-only'], # e.g. `int a = b` when global ['structDeclaration', 'block-only'], # e.g. `struct a { }` ['declarationSpecifier', 'block-only'], # e.g. `int` when in `int a = b;` ['statement', 'block-only'], # Any statement, like `return 0;` ['functionDefinition', 'block-only'], # e.g. `int myMethod() { }` ['expressionStatement', 'block-only'], # Statement that consists of an expression, like `a = b;` ['additiveExpression', 'value-only'], # e.g. `a + b` ['multiplicativeExpression', 'value-only'], # e.g. `a * b` ['declaration', 'block-only'], # e.g. `int a;` ['parameterDeclaration', 'block-only'], # e.g. `int a` when in `int myMethod(int a) { }` ['unaryExpression', 'value-only'], # e.g. `sizeof(a)` ['typeName', 'value-only'], # e.g. `int` ['initializer', 'value-only'], # e.g. `{a, b, c}` when in `int x[] = {a, b, c};` ['castExpression', 'value-only'] # e.g. `(b)a` ] config = { RULES, COLOR_RULES, SHAPE_RULES } ADD_PARENS = (leading, trailing, node, context) -> leading '(' + leading() trailing trailing() + ')' STATEMENT_TO_EXPRESSION = (leading, trailing, node, context) -> matching = false for c in node.classes when c[...'__parse__'.length] is '__parse__' if c in context.classes matching = true break if matching leading '(' + leading() trailing trailing().replace(/\s*;\s*$/, '') + ')' else trailing trailing().replace(/\s*;\s*$/, '') EXPRESSION_TO_STATEMENT = (leading, trailing, node, context) -> while true if leading().match(/^\s*\(/)? and trailing().match(/\)\s*/)? leading leading().replace(/^\s*\(\s*/, '') trailing trailing().replace(/\s*\)\s*$/, '') else break trailing trailing() + ';' config.PAREN_RULES = { 'primaryExpression': { 'expression': ADD_PARENS 'additiveExpression': ADD_PARENS 'multiplicativeExpression': ADD_PARENS 'assignmentExpression': ADD_PARENS 'postfixExpression': ADD_PARENS 'expressionStatement': STATEMENT_TO_EXPRESSION 'specialMethodCall': STATEMENT_TO_EXPRESSION } 'blockItem': { 'expression': EXPRESSION_TO_STATEMENT 'additiveExpression': EXPRESSION_TO_STATEMENT 'multiplicativeExpression': EXPRESSION_TO_STATEMENT 'assignmentExpression': EXPRESSION_TO_STATEMENT 'postfixExpression': EXPRESSION_TO_STATEMENT } } # Test to see if a node is a method call getMethodName = (node) -> if node.type is 'postfixExpression' and # The children of a method call are either # `(method) '(' (paramlist) ')'` OR `(method) '(' ')'` node.children.length in [3, 4] and # Check to make sure that the correct children are parentheses node.children[1].type is 'LeftParen' and (node.children[2].type is 'RightParen' or node.children[3]?.type is 'RightParen') and # Check to see whether the called method is a single identifier, like `puts` in # `getc()`, rather than `getFunctionPointer()()` or `a.b()` node.children[0].children[0].type is 'primaryExpression' and node.children[0].children[0].children[0].type is 'Identifier' # If all of these are true, we have a function name to give return node.children[0].children[0].children[0].data.text # Alternatively, we could have the special `a(b)` node. else if node.type is 'specialMethodCall' return node.children[0].data.text return null config.SHOULD_SOCKET = (opts, node) -> # We will not socket if we are the identifier # in a single-identifier function call like `a(b, c)` # and `a` is in the known functions list. # # We can only be such an identifier if we have the appropriate number of parents; # check. unless opts.knownFunctions? and ((node.parent? and node.parent.parent? and node.parent.parent.parent?) or node.parent?.type is 'specialMethodCall') return true # Check to see whether the thing we are in is a function if (node.parent?.type is 'specialMethodCall' or getMethodName(node.parent.parent.parent)? and # Check to see whether we are the first child node.parent.parent is node.parent.parent.parent.children[0] and node.parent is node.parent.parent.children[0] and node is node.parent.children[0]) and # Finally, check to see if our name is a known function name node.data.text of opts.knownFunctions # If the checks pass, do not socket. return false return true # Color and shape callbacks look up the method name # in the known functions list if available. config.COLOR_CALLBACK = (opts, node) -> return null unless opts.knownFunctions? name = getMethodName node if name? and name of opts.knownFunctions return opts.knownFunctions[name].color else return null config.SHAPE_CALLBACK = (opts, node) -> return null unless opts.knownFunctions? name = getMethodName node if name? and name of opts.knownFunctions return opts.knownFunctions[name].shape else return null config.isComment = (text) -> text.match(/^(\s*\/\/.*)|(#.*)$/)? config.parseComment = (text) -> # Try standard comment comment = text.match(/^(\s*\/\/)(.*)$/) if comment? sockets = [ [comment[1].length, comment[1].length + comment[2].length] ] color = 'comment' return {sockets, color} if text.match(/^#\s*((?:else)|(?:endif))$/) sockets = [] color = 'purple' return {sockets, color} # Try #define directive binary = text.match(/^(#\s*(?:(?:define))\s*)([a-zA-Z_][0-9a-zA-Z_]*)(\s+)(.*)$/) if binary? sockets = [ [binary[1].length, binary[1].length + binary[2].length] [binary[1].length + binary[2].length + binary[3].length, binary[1].length + binary[2].length + binary[3].length + binary[4].length] ] color = 'purple' return {sockets, color} # Try functional #define directive. binary = text.match(/^(#\s*define\s*)([a-zA-Z_][0-9a-zA-Z_]*\s*\((?:[a-zA-Z_][0-9a-zA-Z_]*,\s)*[a-zA-Z_][0-9a-zA-Z_]*\s*\))(\s+)(.*)$/) if binary? sockets = [ [binary[1].length, binary[1].length + binary[2].length] [binary[1].length + binary[2].length + binary[3].length, binary[1].length + binary[2].length + binary[3].length + binary[4].length] ] color = 'purple' return {sockets, color} # Try any of the unary directives: #define, #if, #ifdef, #ifndef, #undef, #pragma unary = text.match(/^(#\s*(?:(?:define)|(?:ifdef)|(?:if)|(?:ifndef)|(?:undef)|(?:pragma))\s*)(.*)$/) if unary? sockets = [ [unary[1].length, unary[1].length + unary[2].length] ] color = 'purple' return {sockets, color} # Try #include, which must include the quotations unary = text.match(/^(#\s*include\s*<)(.*)>\s*$/) if unary? sockets = [ [unary[1].length, unary[1].length + unary[2].length] ] color = 'purple' return {sockets, color} unary = text.match(/^(#\s*include\s*")(.*)"\s*$/) if unary? sockets = [ [unary[1].length, unary[1].length + unary[2].length] ] color = 'purple' return {sockets, color} config.getDefaultSelectionRange = (string) -> start = 0; end = string.length if string.length > 1 and string[0] is string[string.length - 1] and string[0] is '"' start += 1; end -= 1 if string.length > 1 and string[0] is '<' and string[string.length - 1] is '>' start += 1; end -= 1 if string.length is 3 and string[0] is string[string.length - 1] is '\'' start += 1; end -= 1 return {start, end} config.stringFixer = (string) -> if /^['"]|['"]$/.test string return fixQuotedString [string] else return string config.empty = '__0_droplet__' config.emptyIndent = '' # TODO Implement removing parentheses at some point #config.unParenWrap = (leading, trailing, node, context) -> # while true # if leading().match(/^\s*\(/)? and trailing().match(/\)\s*/)? # leading leading().replace(/^\s*\(\s*/, '') # trailing trailing().replace(/\s*\)\s*$/, '') # else # break # DEBUG config.unParenWrap = null module.exports = parser.wrapParser antlrHelper.createANTLRParser 'C', config
[ { "context": "fileTypes: [\n \"swift\"\n]\nname: \"Swift Kitura\"\npatterns: [\n {\n match: \"Kitura|Router(Reques", "end": 44, "score": 0.7090116143226624, "start": 32, "tag": "NAME", "value": "Swift Kitura" } ]
grammars/swift kitura.cson
tetodorov/atom-kitura
0
fileTypes: [ "swift" ] name: "Swift Kitura" patterns: [ { match: "Kitura|Router(Request|Response)?|BodyParser|ContentType|StaticFileServer" name: "support.type" } { match: "get|post|put|patch|delete|any|run" name: "support.function" } { include: "source.swift" } ] scopeName: "source.swift.kitura"
21933
fileTypes: [ "swift" ] name: "<NAME>" patterns: [ { match: "Kitura|Router(Request|Response)?|BodyParser|ContentType|StaticFileServer" name: "support.type" } { match: "get|post|put|patch|delete|any|run" name: "support.function" } { include: "source.swift" } ] scopeName: "source.swift.kitura"
true
fileTypes: [ "swift" ] name: "PI:NAME:<NAME>END_PI" patterns: [ { match: "Kitura|Router(Request|Response)?|BodyParser|ContentType|StaticFileServer" name: "support.type" } { match: "get|post|put|patch|delete|any|run" name: "support.function" } { include: "source.swift" } ] scopeName: "source.swift.kitura"
[ { "context": "bel>\n <label>Password <input type=\"password\" name=\"password\"></label>\n <button", "end": 665, "score": 0.9978266954421997, "start": 657, "tag": "PASSWORD", "value": "password" } ]
spec/selection_spec.coffee
ghuntley/zombie
1
{ Vows, assert, brains, Browser } = require("./helpers") Vows.describe("Selection").addBatch "content selection": topic: -> brains.get "/browser/walking", (req, res)-> res.send """ <html> <head> <script src="/jquery.js"></script> <script src="/sammy.js"></script> <script src="/browser/app.js"></script> </head> <body> <div id="main"> <a href="/browser/dead">Kill</a> <form action="#/dead" method="post"> <label>Email <input type="text" name="email"></label> <label>Password <input type="password" name="password"></label> <button>Sign Me Up</button> </form> </div> <div class="now">Walking Aimlessly</div> </body> </html> """ brains.get "/browser/app.js", (req, res)-> res.send """ Sammy("#main", function(app) { app.get("#/", function(context) { document.title = "The Living"; }); app.get("#/dead", function(context) { context.swap("The Living Dead"); }); app.post("#/dead", function(context) { document.title = "Signed up"; }); }); $(function() { Sammy("#main").run("#/"); }); """ browser = new Browser browser.wants "http://localhost:3003/browser/walking", @callback "queryAll": topic: (browser)-> browser.queryAll(".now") "should return array of nodes": (nodes)-> assert.lengthOf nodes, 1 "query method": topic: (browser)-> browser.query(".now") "should return single node": (node)-> assert.equal node.tagName, "DIV" "query text": topic: (browser)-> browser "should query from document": (browser)-> assert.equal browser.text(".now"), "Walking Aimlessly" "should query from context (exists)": (browser)-> assert.equal browser.text(".now"), "Walking Aimlessly" "should query from context (unrelated)": (browser)-> assert.equal browser.text(".now", browser.querySelector("form")), "" "should combine multiple elements": (browser)-> assert.equal browser.text("form label"), "Email Password " "query html": topic: (browser)-> browser "should query from document": (browser)-> assert.equal browser.html(".now"), "<div class=\"now\">Walking Aimlessly</div>" "should query from context (exists)": (browser)-> assert.equal browser.html(".now", browser.body), "<div class=\"now\">Walking Aimlessly</div>" "should query from context (unrelated)": (browser)-> assert.equal browser.html(".now", browser.querySelector("form")), "" "should combine multiple elements": (browser)-> assert.equal browser.html("title, #main a"), "<title>The Living</title><a href=\"/browser/dead\">Kill</a>" "jQuery": topic: (browser)-> browser.evaluate('window.jQuery') "should query by id": ($)-> assert.equal $('#main').size(), 1 "should query by element name": ($)-> assert.equal $('form').attr('action'), '#/dead' "should query by element name (multiple)": ($)-> assert.equal $('label').size(), 2 "should query with descendant selectors": ($)-> assert.equal $('body #main a').text(), 'Kill' "should query in context": ($)-> assert.equal $('body').find('#main a', 'body').text(), 'Kill' "should query in context with find()": ($)-> assert.equal $('body').find('#main a').text(), 'Kill' .export(module)
115491
{ Vows, assert, brains, Browser } = require("./helpers") Vows.describe("Selection").addBatch "content selection": topic: -> brains.get "/browser/walking", (req, res)-> res.send """ <html> <head> <script src="/jquery.js"></script> <script src="/sammy.js"></script> <script src="/browser/app.js"></script> </head> <body> <div id="main"> <a href="/browser/dead">Kill</a> <form action="#/dead" method="post"> <label>Email <input type="text" name="email"></label> <label>Password <input type="<PASSWORD>" name="password"></label> <button>Sign Me Up</button> </form> </div> <div class="now">Walking Aimlessly</div> </body> </html> """ brains.get "/browser/app.js", (req, res)-> res.send """ Sammy("#main", function(app) { app.get("#/", function(context) { document.title = "The Living"; }); app.get("#/dead", function(context) { context.swap("The Living Dead"); }); app.post("#/dead", function(context) { document.title = "Signed up"; }); }); $(function() { Sammy("#main").run("#/"); }); """ browser = new Browser browser.wants "http://localhost:3003/browser/walking", @callback "queryAll": topic: (browser)-> browser.queryAll(".now") "should return array of nodes": (nodes)-> assert.lengthOf nodes, 1 "query method": topic: (browser)-> browser.query(".now") "should return single node": (node)-> assert.equal node.tagName, "DIV" "query text": topic: (browser)-> browser "should query from document": (browser)-> assert.equal browser.text(".now"), "Walking Aimlessly" "should query from context (exists)": (browser)-> assert.equal browser.text(".now"), "Walking Aimlessly" "should query from context (unrelated)": (browser)-> assert.equal browser.text(".now", browser.querySelector("form")), "" "should combine multiple elements": (browser)-> assert.equal browser.text("form label"), "Email Password " "query html": topic: (browser)-> browser "should query from document": (browser)-> assert.equal browser.html(".now"), "<div class=\"now\">Walking Aimlessly</div>" "should query from context (exists)": (browser)-> assert.equal browser.html(".now", browser.body), "<div class=\"now\">Walking Aimlessly</div>" "should query from context (unrelated)": (browser)-> assert.equal browser.html(".now", browser.querySelector("form")), "" "should combine multiple elements": (browser)-> assert.equal browser.html("title, #main a"), "<title>The Living</title><a href=\"/browser/dead\">Kill</a>" "jQuery": topic: (browser)-> browser.evaluate('window.jQuery') "should query by id": ($)-> assert.equal $('#main').size(), 1 "should query by element name": ($)-> assert.equal $('form').attr('action'), '#/dead' "should query by element name (multiple)": ($)-> assert.equal $('label').size(), 2 "should query with descendant selectors": ($)-> assert.equal $('body #main a').text(), 'Kill' "should query in context": ($)-> assert.equal $('body').find('#main a', 'body').text(), 'Kill' "should query in context with find()": ($)-> assert.equal $('body').find('#main a').text(), 'Kill' .export(module)
true
{ Vows, assert, brains, Browser } = require("./helpers") Vows.describe("Selection").addBatch "content selection": topic: -> brains.get "/browser/walking", (req, res)-> res.send """ <html> <head> <script src="/jquery.js"></script> <script src="/sammy.js"></script> <script src="/browser/app.js"></script> </head> <body> <div id="main"> <a href="/browser/dead">Kill</a> <form action="#/dead" method="post"> <label>Email <input type="text" name="email"></label> <label>Password <input type="PI:PASSWORD:<PASSWORD>END_PI" name="password"></label> <button>Sign Me Up</button> </form> </div> <div class="now">Walking Aimlessly</div> </body> </html> """ brains.get "/browser/app.js", (req, res)-> res.send """ Sammy("#main", function(app) { app.get("#/", function(context) { document.title = "The Living"; }); app.get("#/dead", function(context) { context.swap("The Living Dead"); }); app.post("#/dead", function(context) { document.title = "Signed up"; }); }); $(function() { Sammy("#main").run("#/"); }); """ browser = new Browser browser.wants "http://localhost:3003/browser/walking", @callback "queryAll": topic: (browser)-> browser.queryAll(".now") "should return array of nodes": (nodes)-> assert.lengthOf nodes, 1 "query method": topic: (browser)-> browser.query(".now") "should return single node": (node)-> assert.equal node.tagName, "DIV" "query text": topic: (browser)-> browser "should query from document": (browser)-> assert.equal browser.text(".now"), "Walking Aimlessly" "should query from context (exists)": (browser)-> assert.equal browser.text(".now"), "Walking Aimlessly" "should query from context (unrelated)": (browser)-> assert.equal browser.text(".now", browser.querySelector("form")), "" "should combine multiple elements": (browser)-> assert.equal browser.text("form label"), "Email Password " "query html": topic: (browser)-> browser "should query from document": (browser)-> assert.equal browser.html(".now"), "<div class=\"now\">Walking Aimlessly</div>" "should query from context (exists)": (browser)-> assert.equal browser.html(".now", browser.body), "<div class=\"now\">Walking Aimlessly</div>" "should query from context (unrelated)": (browser)-> assert.equal browser.html(".now", browser.querySelector("form")), "" "should combine multiple elements": (browser)-> assert.equal browser.html("title, #main a"), "<title>The Living</title><a href=\"/browser/dead\">Kill</a>" "jQuery": topic: (browser)-> browser.evaluate('window.jQuery') "should query by id": ($)-> assert.equal $('#main').size(), 1 "should query by element name": ($)-> assert.equal $('form').attr('action'), '#/dead' "should query by element name (multiple)": ($)-> assert.equal $('label').size(), 2 "should query with descendant selectors": ($)-> assert.equal $('body #main a').text(), 'Kill' "should query in context": ($)-> assert.equal $('body').find('#main a', 'body').text(), 'Kill' "should query in context with find()": ($)-> assert.equal $('body').find('#main a').text(), 'Kill' .export(module)
[ { "context": "AppController\n\n @options =\n name : 'Admin'\n background : yes\n\n\n NAV_ITEMS =\n team", "end": 1521, "score": 0.9909763932228088, "start": 1516, "tag": "NAME", "value": "Admin" } ]
client/admin/lib/index.coffee
ezgikaysi/koding
1
kd = require 'kd' AppController = require 'app/appcontroller' LogsView = require './views/logs' AdminAPIView = require './views/api/adminapiview' AdminAppView = require './views/customviews/adminappview' TeamInviteView = require './views/koding-admin/teaminviteview' TeamManageView = require './views/koding-admin/teammanageview' AdminMembersView = require './views/members/adminmembersview' AdminResourcesView = require './views/resources/adminresourcesview' AdministrationView = require './views/koding-admin/administrationview' CustomViewsManager = require './views/customviews/customviewsmanager' TopicModerationView = require './views/moderation/topicmoderationview' OnboardingAdminView = require './views/onboarding/onboardingadminview' AdminInvitationsView = require './views/invitations/admininvitationsview' GroupPermissionsView = require './views/permissions/grouppermissionsview' GroupPlanBillingView = require './views/plan-billing/groupplanbillingview' GroupsBlockedUserView = require './views/members/groupsblockeduserview' GroupGeneralSettingsView = require './views/general/groupgeneralsettingsview' AdminIntegrationParentView = require './views/integrations/adminintegrationparentview' require('./routehandler')() module.exports = class AdminAppController extends AppController @options = name : 'Admin' background : yes NAV_ITEMS = teams : title : 'Team Settings' items : [ { slug : 'General', title : 'General', viewClass : GroupGeneralSettingsView, role: 'member' } { slug : 'Members', title : 'Members', viewClass : AdminMembersView } { slug : 'Invitations', title : 'Invitations', viewClass : AdminInvitationsView } # { slug : 'Permissions', title : 'Permissions', viewClass : GroupPermissionsView } { slug : 'APIAccess', title : 'API Access', viewClass : AdminAPIView } { slug : 'Resources', title : 'Resources', viewClass : AdminResourcesView , beta: yes } { slug : 'Logs', title : 'Team Logs', viewClass : LogsView , beta: yes } # { slug : 'Plan-Billing', title : 'Plan & Billing', viewClass : GroupPlanBillingView } ] koding : title : 'Koding Administration' items : [ { slug : 'TeamManage', title : 'Manage teams', viewClass : TeamManageView } { slug : 'Blocked', title : 'Blocked Users', viewClass : GroupsBlockedUserView } { slug : 'Widgets', title : 'Custom Views', viewClass : CustomViewsManager } { slug : 'Onboarding', title : 'Onboarding', viewClass : OnboardingAdminView } { slug : 'Moderation', title : 'Topic Moderation', viewClass : TopicModerationView } { slug : 'Administration', title : 'Administration', viewClass : AdministrationView } { slug : 'TeamInvite', title : 'Invite teams', viewClass : TeamInviteView } ] constructor: (options = {}, data) -> data ?= kd.singletons.groupsController.getCurrentGroup() options.view ?= new AdminAppView title : 'Team Settings' cssClass : 'AppModal AppModal--admin team-settings' width : 1000 height : '90%' overlay : yes tabData : NAV_ITEMS , data super options, data openSection: (section, query, action, identifier) -> targetPane = null @mainView.ready => @mainView.tabs.panes.forEach (pane) -> paneAction = pane.getOption 'action' paneSlug = pane.getOption 'slug' if identifier and action is paneAction targetPane = pane else if paneSlug is section targetPane = pane if targetPane @mainView.tabs.showPane targetPane targetPaneView = targetPane.getMainView() if identifier targetPaneView.handleIdentifier? identifier, action else targetPaneView.handleAction? action if identifier or action targetPaneView.emit 'SubTabRequested', action, identifier { parentTabTitle } = targetPane.getOptions() if parentTabTitle for handle in @getView().tabs.handles if handle.getOption('title') is parentTabTitle handle.setClass 'active' else kd.singletons.router.handleRoute "/#{@options.name}" checkRoute: (route) -> /^\/Admin.*/.test route loadView: (modal) -> modal.once 'KDObjectWillBeDestroyed', => return if modal.dontChangeRoute { router } = kd.singletons previousRoutes = router.visitedRoutes.filter (route) => not @checkRoute route if previousRoutes.length > 0 then router.handleRoute previousRoutes.last else router.handleRoute router.getDefaultRoute() fetchNavItems: (cb) -> cb NAV_ITEMS
202206
kd = require 'kd' AppController = require 'app/appcontroller' LogsView = require './views/logs' AdminAPIView = require './views/api/adminapiview' AdminAppView = require './views/customviews/adminappview' TeamInviteView = require './views/koding-admin/teaminviteview' TeamManageView = require './views/koding-admin/teammanageview' AdminMembersView = require './views/members/adminmembersview' AdminResourcesView = require './views/resources/adminresourcesview' AdministrationView = require './views/koding-admin/administrationview' CustomViewsManager = require './views/customviews/customviewsmanager' TopicModerationView = require './views/moderation/topicmoderationview' OnboardingAdminView = require './views/onboarding/onboardingadminview' AdminInvitationsView = require './views/invitations/admininvitationsview' GroupPermissionsView = require './views/permissions/grouppermissionsview' GroupPlanBillingView = require './views/plan-billing/groupplanbillingview' GroupsBlockedUserView = require './views/members/groupsblockeduserview' GroupGeneralSettingsView = require './views/general/groupgeneralsettingsview' AdminIntegrationParentView = require './views/integrations/adminintegrationparentview' require('./routehandler')() module.exports = class AdminAppController extends AppController @options = name : '<NAME>' background : yes NAV_ITEMS = teams : title : 'Team Settings' items : [ { slug : 'General', title : 'General', viewClass : GroupGeneralSettingsView, role: 'member' } { slug : 'Members', title : 'Members', viewClass : AdminMembersView } { slug : 'Invitations', title : 'Invitations', viewClass : AdminInvitationsView } # { slug : 'Permissions', title : 'Permissions', viewClass : GroupPermissionsView } { slug : 'APIAccess', title : 'API Access', viewClass : AdminAPIView } { slug : 'Resources', title : 'Resources', viewClass : AdminResourcesView , beta: yes } { slug : 'Logs', title : 'Team Logs', viewClass : LogsView , beta: yes } # { slug : 'Plan-Billing', title : 'Plan & Billing', viewClass : GroupPlanBillingView } ] koding : title : 'Koding Administration' items : [ { slug : 'TeamManage', title : 'Manage teams', viewClass : TeamManageView } { slug : 'Blocked', title : 'Blocked Users', viewClass : GroupsBlockedUserView } { slug : 'Widgets', title : 'Custom Views', viewClass : CustomViewsManager } { slug : 'Onboarding', title : 'Onboarding', viewClass : OnboardingAdminView } { slug : 'Moderation', title : 'Topic Moderation', viewClass : TopicModerationView } { slug : 'Administration', title : 'Administration', viewClass : AdministrationView } { slug : 'TeamInvite', title : 'Invite teams', viewClass : TeamInviteView } ] constructor: (options = {}, data) -> data ?= kd.singletons.groupsController.getCurrentGroup() options.view ?= new AdminAppView title : 'Team Settings' cssClass : 'AppModal AppModal--admin team-settings' width : 1000 height : '90%' overlay : yes tabData : NAV_ITEMS , data super options, data openSection: (section, query, action, identifier) -> targetPane = null @mainView.ready => @mainView.tabs.panes.forEach (pane) -> paneAction = pane.getOption 'action' paneSlug = pane.getOption 'slug' if identifier and action is paneAction targetPane = pane else if paneSlug is section targetPane = pane if targetPane @mainView.tabs.showPane targetPane targetPaneView = targetPane.getMainView() if identifier targetPaneView.handleIdentifier? identifier, action else targetPaneView.handleAction? action if identifier or action targetPaneView.emit 'SubTabRequested', action, identifier { parentTabTitle } = targetPane.getOptions() if parentTabTitle for handle in @getView().tabs.handles if handle.getOption('title') is parentTabTitle handle.setClass 'active' else kd.singletons.router.handleRoute "/#{@options.name}" checkRoute: (route) -> /^\/Admin.*/.test route loadView: (modal) -> modal.once 'KDObjectWillBeDestroyed', => return if modal.dontChangeRoute { router } = kd.singletons previousRoutes = router.visitedRoutes.filter (route) => not @checkRoute route if previousRoutes.length > 0 then router.handleRoute previousRoutes.last else router.handleRoute router.getDefaultRoute() fetchNavItems: (cb) -> cb NAV_ITEMS
true
kd = require 'kd' AppController = require 'app/appcontroller' LogsView = require './views/logs' AdminAPIView = require './views/api/adminapiview' AdminAppView = require './views/customviews/adminappview' TeamInviteView = require './views/koding-admin/teaminviteview' TeamManageView = require './views/koding-admin/teammanageview' AdminMembersView = require './views/members/adminmembersview' AdminResourcesView = require './views/resources/adminresourcesview' AdministrationView = require './views/koding-admin/administrationview' CustomViewsManager = require './views/customviews/customviewsmanager' TopicModerationView = require './views/moderation/topicmoderationview' OnboardingAdminView = require './views/onboarding/onboardingadminview' AdminInvitationsView = require './views/invitations/admininvitationsview' GroupPermissionsView = require './views/permissions/grouppermissionsview' GroupPlanBillingView = require './views/plan-billing/groupplanbillingview' GroupsBlockedUserView = require './views/members/groupsblockeduserview' GroupGeneralSettingsView = require './views/general/groupgeneralsettingsview' AdminIntegrationParentView = require './views/integrations/adminintegrationparentview' require('./routehandler')() module.exports = class AdminAppController extends AppController @options = name : 'PI:NAME:<NAME>END_PI' background : yes NAV_ITEMS = teams : title : 'Team Settings' items : [ { slug : 'General', title : 'General', viewClass : GroupGeneralSettingsView, role: 'member' } { slug : 'Members', title : 'Members', viewClass : AdminMembersView } { slug : 'Invitations', title : 'Invitations', viewClass : AdminInvitationsView } # { slug : 'Permissions', title : 'Permissions', viewClass : GroupPermissionsView } { slug : 'APIAccess', title : 'API Access', viewClass : AdminAPIView } { slug : 'Resources', title : 'Resources', viewClass : AdminResourcesView , beta: yes } { slug : 'Logs', title : 'Team Logs', viewClass : LogsView , beta: yes } # { slug : 'Plan-Billing', title : 'Plan & Billing', viewClass : GroupPlanBillingView } ] koding : title : 'Koding Administration' items : [ { slug : 'TeamManage', title : 'Manage teams', viewClass : TeamManageView } { slug : 'Blocked', title : 'Blocked Users', viewClass : GroupsBlockedUserView } { slug : 'Widgets', title : 'Custom Views', viewClass : CustomViewsManager } { slug : 'Onboarding', title : 'Onboarding', viewClass : OnboardingAdminView } { slug : 'Moderation', title : 'Topic Moderation', viewClass : TopicModerationView } { slug : 'Administration', title : 'Administration', viewClass : AdministrationView } { slug : 'TeamInvite', title : 'Invite teams', viewClass : TeamInviteView } ] constructor: (options = {}, data) -> data ?= kd.singletons.groupsController.getCurrentGroup() options.view ?= new AdminAppView title : 'Team Settings' cssClass : 'AppModal AppModal--admin team-settings' width : 1000 height : '90%' overlay : yes tabData : NAV_ITEMS , data super options, data openSection: (section, query, action, identifier) -> targetPane = null @mainView.ready => @mainView.tabs.panes.forEach (pane) -> paneAction = pane.getOption 'action' paneSlug = pane.getOption 'slug' if identifier and action is paneAction targetPane = pane else if paneSlug is section targetPane = pane if targetPane @mainView.tabs.showPane targetPane targetPaneView = targetPane.getMainView() if identifier targetPaneView.handleIdentifier? identifier, action else targetPaneView.handleAction? action if identifier or action targetPaneView.emit 'SubTabRequested', action, identifier { parentTabTitle } = targetPane.getOptions() if parentTabTitle for handle in @getView().tabs.handles if handle.getOption('title') is parentTabTitle handle.setClass 'active' else kd.singletons.router.handleRoute "/#{@options.name}" checkRoute: (route) -> /^\/Admin.*/.test route loadView: (modal) -> modal.once 'KDObjectWillBeDestroyed', => return if modal.dontChangeRoute { router } = kd.singletons previousRoutes = router.visitedRoutes.filter (route) => not @checkRoute route if previousRoutes.length > 0 then router.handleRoute previousRoutes.last else router.handleRoute router.getDefaultRoute() fetchNavItems: (cb) -> cb NAV_ITEMS
[ { "context": "!success)\n\tthrow bdb.errmsg()\n\nkeys = bdb.range(\"t0800\",true,\"t0900\",true,100)\n\nfor key in keys\n\tvv = bd", "end": 656, "score": 0.9838393926620483, "start": 651, "tag": "KEY", "value": "t0800" }, { "context": "row bdb.errmsg()\n\nkeys = bdb.range(\"t0800\"...
tcbn/coffee/read/tcbn_read.coffee
ekzemplaro/data_base_language
3
#! /usr/local/bin/coffee # --------------------------------------------------------------- # tcbn_read.coffee # # Sep/14/2011 # # --------------------------------------------------------------- fs = require("fs") sys = require('sys') TC = require('/var/www/data_base/common/node_common/lib/tokyocabinet') # --------------------------------------------------------------- console.log "*** 開始 ***" # # --------------------------------------------------------------- BDB = TC.BDB bdb = new BDB file_in = "/var/tmp/tokyo_cabinet/cities.tcb" success = bdb.open(file_in, BDB.OWRITER | BDB.OCREAT) if (!success) throw bdb.errmsg() keys = bdb.range("t0800",true,"t0900",true,100) for key in keys vv = bdb.get(key) if (vv == null) throw bdb.errmsg() unit_aa = JSON.parse(vv) out_str = key + "\t" out_str += unit_aa['name'] + "\t" out_str += unit_aa['population'] + "\t" out_str += unit_aa['date_mod'] sys.puts(out_str) console.log ("*** 終了 ***") # ---------------------------------------------------------------
152970
#! /usr/local/bin/coffee # --------------------------------------------------------------- # tcbn_read.coffee # # Sep/14/2011 # # --------------------------------------------------------------- fs = require("fs") sys = require('sys') TC = require('/var/www/data_base/common/node_common/lib/tokyocabinet') # --------------------------------------------------------------- console.log "*** 開始 ***" # # --------------------------------------------------------------- BDB = TC.BDB bdb = new BDB file_in = "/var/tmp/tokyo_cabinet/cities.tcb" success = bdb.open(file_in, BDB.OWRITER | BDB.OCREAT) if (!success) throw bdb.errmsg() keys = bdb.range("<KEY>",true,"<KEY>",true,100) for key in keys vv = bdb.get(key) if (vv == null) throw bdb.errmsg() unit_aa = JSON.parse(vv) out_str = key + "\t" out_str += unit_aa['name'] + "\t" out_str += unit_aa['population'] + "\t" out_str += unit_aa['date_mod'] sys.puts(out_str) console.log ("*** 終了 ***") # ---------------------------------------------------------------
true
#! /usr/local/bin/coffee # --------------------------------------------------------------- # tcbn_read.coffee # # Sep/14/2011 # # --------------------------------------------------------------- fs = require("fs") sys = require('sys') TC = require('/var/www/data_base/common/node_common/lib/tokyocabinet') # --------------------------------------------------------------- console.log "*** 開始 ***" # # --------------------------------------------------------------- BDB = TC.BDB bdb = new BDB file_in = "/var/tmp/tokyo_cabinet/cities.tcb" success = bdb.open(file_in, BDB.OWRITER | BDB.OCREAT) if (!success) throw bdb.errmsg() keys = bdb.range("PI:KEY:<KEY>END_PI",true,"PI:KEY:<KEY>END_PI",true,100) for key in keys vv = bdb.get(key) if (vv == null) throw bdb.errmsg() unit_aa = JSON.parse(vv) out_str = key + "\t" out_str += unit_aa['name'] + "\t" out_str += unit_aa['population'] + "\t" out_str += unit_aa['date_mod'] sys.puts(out_str) console.log ("*** 終了 ***") # ---------------------------------------------------------------
[ { "context": "tient'\n name: [\n {\n given: ['Niccolò', 'Great']\n family: ['Paganini']\n ", "end": 228, "score": 0.9997273087501526, "start": 221, "tag": "NAME", "value": "Niccolò" }, { "context": " name: [\n {\n given: ['Niccolò'...
test/fhir/search_string_spec.coffee
micabe/fhirbase
0
search = require('../../src/fhir/search_string') test = require('../helpers.coffee') assert = require('assert') testCases = [ { resource: { resourceType: 'Patient' name: [ { given: ['Niccolò', 'Great'] family: ['Paganini'] prefix: ['Music'] } { given: ['Niky'] family: ['Pogy'] } ] address: [ { use: 'home' type: 'both' line: ["534 Erewhon St"] city: 'PleasantVille' district: 'Rainbow' state: 'Vic' postalCode: '3999' } { use: 'work' type: 'both' line: ["432 Hill Bvd"] city: 'Xtown' state: 'CA' postalCode: '9993' } ] }, specs: [ { path: ['Patient', 'name'] elementType: 'HumanName' result: ['^^Niccolo$$', '^^Great$$', '^^Music$$', '^^Paganini$$', '^^Niky$$', '^^Pogy$$'] order: 'paganini0niccolò0great0music' } { path: ['Patient', 'address', 'city'] elementType: 'string' result: ['^^PleasantVille$$','^^Xtown$$'] order: 'pleasantville' } { path: ['Patient', 'address'] elementType: 'Address' result: ['^^Vic$$', '^^PleasantVille$$', '^^Rainbow$$', '^^534 Erewhon St$$'] order: '0pleasantville0vic0rainbow0534 erewhon st039990' } ] }, { # tables with PostgreSQL reserved name <https://github.com/fhirbase/fhirbase-plv8/issues/77> resource: { resourceType: 'Task' foo: 'bar' }, specs: [ { path: ['Task', 'foo'] elementType: 'string' result: 'bar' order: 'bar' } ] } ] describe "extract_as_string", -> testCases.forEach (testCase)-> testCase.specs.forEach (spec)-> it JSON.stringify(spec.path) + ' : ' + spec.elementType, -> metas = [ {path: ['Patient', 'unknownPath'], elementType: spec.elementType} {path: spec.path, elementType: spec.elementType}] res = search.fhir_extract_as_string({}, testCase.resource, metas) for str in spec.result assert(res.indexOf(str) > -1, "#{str} not in #{res}") order = search.fhir_sort_as_string({}, testCase.resource, metas) assert.deepEqual(order, spec.order)
64405
search = require('../../src/fhir/search_string') test = require('../helpers.coffee') assert = require('assert') testCases = [ { resource: { resourceType: 'Patient' name: [ { given: ['<NAME>', '<NAME>'] family: ['<NAME>'] prefix: ['<NAME>'] } { given: ['<NAME>'] family: ['<NAME>'] } ] address: [ { use: 'home' type: 'both' line: ["534 Erewhon St"] city: 'PleasantVille' district: 'Rainbow' state: 'Vic' postalCode: '3999' } { use: 'work' type: 'both' line: ["432 Hill Bvd"] city: 'Xtown' state: 'CA' postalCode: '9993' } ] }, specs: [ { path: ['Patient', 'name'] elementType: 'HumanName' result: ['^^Nic<NAME>$$', '^^Great$$', '^^Music$$', '^^Pagan<NAME>$$', '^^Niky$$', '^^Pogy$$'] order: 'paganini0niccolò0great0music' } { path: ['Patient', 'address', 'city'] elementType: 'string' result: ['^^PleasantVille$$','^^Xtown$$'] order: 'pleasantville' } { path: ['Patient', 'address'] elementType: 'Address' result: ['^^Vic$$', '^^PleasantVille$$', '^^Rainbow$$', '^^534 Erewhon St$$'] order: '0pleasantville0vic0rainbow0534 erewhon st039990' } ] }, { # tables with PostgreSQL reserved name <https://github.com/fhirbase/fhirbase-plv8/issues/77> resource: { resourceType: 'Task' foo: 'bar' }, specs: [ { path: ['Task', 'foo'] elementType: 'string' result: 'bar' order: 'bar' } ] } ] describe "extract_as_string", -> testCases.forEach (testCase)-> testCase.specs.forEach (spec)-> it JSON.stringify(spec.path) + ' : ' + spec.elementType, -> metas = [ {path: ['Patient', 'unknownPath'], elementType: spec.elementType} {path: spec.path, elementType: spec.elementType}] res = search.fhir_extract_as_string({}, testCase.resource, metas) for str in spec.result assert(res.indexOf(str) > -1, "#{str} not in #{res}") order = search.fhir_sort_as_string({}, testCase.resource, metas) assert.deepEqual(order, spec.order)
true
search = require('../../src/fhir/search_string') test = require('../helpers.coffee') assert = require('assert') testCases = [ { resource: { resourceType: 'Patient' name: [ { given: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] family: ['PI:NAME:<NAME>END_PI'] prefix: ['PI:NAME:<NAME>END_PI'] } { given: ['PI:NAME:<NAME>END_PI'] family: ['PI:NAME:<NAME>END_PI'] } ] address: [ { use: 'home' type: 'both' line: ["534 Erewhon St"] city: 'PleasantVille' district: 'Rainbow' state: 'Vic' postalCode: '3999' } { use: 'work' type: 'both' line: ["432 Hill Bvd"] city: 'Xtown' state: 'CA' postalCode: '9993' } ] }, specs: [ { path: ['Patient', 'name'] elementType: 'HumanName' result: ['^^NicPI:NAME:<NAME>END_PI$$', '^^Great$$', '^^Music$$', '^^PaganPI:NAME:<NAME>END_PI$$', '^^Niky$$', '^^Pogy$$'] order: 'paganini0niccolò0great0music' } { path: ['Patient', 'address', 'city'] elementType: 'string' result: ['^^PleasantVille$$','^^Xtown$$'] order: 'pleasantville' } { path: ['Patient', 'address'] elementType: 'Address' result: ['^^Vic$$', '^^PleasantVille$$', '^^Rainbow$$', '^^534 Erewhon St$$'] order: '0pleasantville0vic0rainbow0534 erewhon st039990' } ] }, { # tables with PostgreSQL reserved name <https://github.com/fhirbase/fhirbase-plv8/issues/77> resource: { resourceType: 'Task' foo: 'bar' }, specs: [ { path: ['Task', 'foo'] elementType: 'string' result: 'bar' order: 'bar' } ] } ] describe "extract_as_string", -> testCases.forEach (testCase)-> testCase.specs.forEach (spec)-> it JSON.stringify(spec.path) + ' : ' + spec.elementType, -> metas = [ {path: ['Patient', 'unknownPath'], elementType: spec.elementType} {path: spec.path, elementType: spec.elementType}] res = search.fhir_extract_as_string({}, testCase.resource, metas) for str in spec.result assert(res.indexOf(str) > -1, "#{str} not in #{res}") order = search.fhir_sort_as_string({}, testCase.resource, metas) assert.deepEqual(order, spec.order)
[ { "context": "Rails Embedded Ruby support\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nColorifier.erb = new Class Colorifier.html,\n\n ", "end": 72, "score": 0.9998807907104492, "start": 55, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
src/lang/erb.coffee
MadRabbit/colorifier
1
# # Rails Embedded Ruby support # # Copyright (C) 2012 Nikolay Nemshilov # Colorifier.erb = new Class Colorifier.html, paint: (text)-> @$super text, (text)-> @_ruby(text) _ruby: (text)-> @___ or= [] tokens = @___ text.replace /(&lt;%)([\s\S]*?)(%&gt;)/ig, (m, _1, _2, _3)-> tokens.push(ruby.paint(_2)) "#{_1}___dummy_#{tokens.length}___#{_3}" ruby = new Colorifier.ruby()
21082
# # Rails Embedded Ruby support # # Copyright (C) 2012 <NAME> # Colorifier.erb = new Class Colorifier.html, paint: (text)-> @$super text, (text)-> @_ruby(text) _ruby: (text)-> @___ or= [] tokens = @___ text.replace /(&lt;%)([\s\S]*?)(%&gt;)/ig, (m, _1, _2, _3)-> tokens.push(ruby.paint(_2)) "#{_1}___dummy_#{tokens.length}___#{_3}" ruby = new Colorifier.ruby()
true
# # Rails Embedded Ruby support # # Copyright (C) 2012 PI:NAME:<NAME>END_PI # Colorifier.erb = new Class Colorifier.html, paint: (text)-> @$super text, (text)-> @_ruby(text) _ruby: (text)-> @___ or= [] tokens = @___ text.replace /(&lt;%)([\s\S]*?)(%&gt;)/ig, (m, _1, _2, _3)-> tokens.push(ruby.paint(_2)) "#{_1}___dummy_#{tokens.length}___#{_3}" ruby = new Colorifier.ruby()
[ { "context": "mail_info = {\n subject: \"こんにちは\"\n from: \"test@example.com\"\n body: \"お久しぶりです。げんきですか?\"\n}\n\nfor key, value of m", "end": 58, "score": 0.9999257922172546, "start": 42, "tag": "EMAIL", "value": "test@example.com" } ]
ch04/04-coffee/for_of.coffee
gogosub77/node-webscraping
0
mail_info = { subject: "こんにちは" from: "test@example.com" body: "お久しぶりです。げんきですか?" } for key, value of mail_info console.log "#{key} : #{value}"
26232
mail_info = { subject: "こんにちは" from: "<EMAIL>" body: "お久しぶりです。げんきですか?" } for key, value of mail_info console.log "#{key} : #{value}"
true
mail_info = { subject: "こんにちは" from: "PI:EMAIL:<EMAIL>END_PI" body: "お久しぶりです。げんきですか?" } for key, value of mail_info console.log "#{key} : #{value}"
[ { "context": "le allow you to use the gooey effect\n#\n# @author Olivier Bossel <olivier.bossel@gmail.com>\n# @created 22.01.16\n#", "end": 107, "score": 0.9998802542686462, "start": 93, "tag": "NAME", "value": "Olivier Bossel" }, { "context": "se the gooey effect\n#\n# @author ...
node_modules/sugarcss/coffee/sugar-gooey.coffee
hagsey/nlpt2
0
### # Sugar-gooey.js # # This little js file allow you to use the gooey effect # # @author Olivier Bossel <olivier.bossel@gmail.com> # @created 22.01.16 # @updated 20.01.16 # @version 1.0.0 ### ((factory) -> if typeof define == 'function' and define.amd # AMD. Register as an anonymous module. define [ ], factory else if typeof exports == 'object' # Node/CommonJS factory() else # Browser globals factory() return ) () -> window.SugarGooey = # track if already inited _inited : false # enabled enabled : true ### Init ### init : () -> # update inited state @_inited = true # wait until the dom is loaded if document.readyState == 'interactive' then @_init() else document.addEventListener 'DOMContentLoaded', (e) => @_init() ### Internal init ### _init : -> # do nothing if not enabled return if not @enabled # put filters into page @_injectFilter() # listen for animations @_listenAnimation() # init element for item in document.querySelectorAll('[data-gooey]') item.dispatchEvent(new CustomEvent('DOMNodeInserted', { bubbles : true, cancelable : true })); ### Inject filter ### _injectFilter : -> # gooey style = ['position:absolute;','left:-1000px;'] if /Chrome/.test(navigator.userAgent) and /Google Inc/.test(navigator.vendor) style.push 'display:none;' gooey = """ <svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="#{style.join(' ')}"> <defs> <filter id="gooey"> <feGaussianBlur in="SourceGraphic" stdDeviation="0" result="blur" /> <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 19 -9" result="gooey" /> <feComposite in="SourceGraphic" in2="gooey" operator="atop"/> </filter> </defs> </svg> """ gooey_elm = document.createElement 'div' gooey_elm.innerHTML = gooey @gooey_defs = gooey_elm.querySelector 'defs' @gooey_svg = gooey_elm.firstChild @gooey = gooey_elm.querySelector '#gooey' # append filters to page body = document.querySelector('body') body.appendChild @gooey_svg ### Listen for animations ### _listenAnimation : -> document.addEventListener 'DOMNodeInserted', (e) => elm = e.target if elm.dataset and elm.dataset.gooey != undefined and not elm._gooeyFilter @_handleFilter elm ### Handle filter ### _handleFilter : (elm, recursive = false) -> # clone the filter tag in svg elm._gooeyFilter = @gooey.cloneNode true # set a new id id = 'gooeyFilter-' + @_uniqId() elm._gooeyFilter.setAttribute 'id', id # append new filter in defs @gooey_defs.appendChild elm._gooeyFilter # set the new filter to element @_applyFilter elm, 'url("#'+id+'")' # set the blur effect amount = parseInt(elm.dataset.gooey || 10) elm._gooeyFilter.firstElementChild.setAttribute 'stdDeviation', amount elm._gooeyFilter.children[1].setAttribute 'values', '1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 ' + (9 + amount) + ' -9' ### Apply filter ### _applyFilter : (elm, filter) -> for vendor in ["-webkit-", "-moz-", "-ms-", "o-", ""] elm.style[vendor+'filter'] = filter ### UniqId ### _uniqId : -> return new Date().getTime() + Math.round(Math.random() * 999999999); n = Math.floor(Math.random()*11); k = Math.floor(Math.random()* 1000000); m = String.fromCharCode(n)+k; return m.trim() # init the filter SugarGooey.init() # return the Sugar object SugarGooey
81014
### # Sugar-gooey.js # # This little js file allow you to use the gooey effect # # @author <NAME> <<EMAIL>> # @created 22.01.16 # @updated 20.01.16 # @version 1.0.0 ### ((factory) -> if typeof define == 'function' and define.amd # AMD. Register as an anonymous module. define [ ], factory else if typeof exports == 'object' # Node/CommonJS factory() else # Browser globals factory() return ) () -> window.SugarGooey = # track if already inited _inited : false # enabled enabled : true ### Init ### init : () -> # update inited state @_inited = true # wait until the dom is loaded if document.readyState == 'interactive' then @_init() else document.addEventListener 'DOMContentLoaded', (e) => @_init() ### Internal init ### _init : -> # do nothing if not enabled return if not @enabled # put filters into page @_injectFilter() # listen for animations @_listenAnimation() # init element for item in document.querySelectorAll('[data-gooey]') item.dispatchEvent(new CustomEvent('DOMNodeInserted', { bubbles : true, cancelable : true })); ### Inject filter ### _injectFilter : -> # gooey style = ['position:absolute;','left:-1000px;'] if /Chrome/.test(navigator.userAgent) and /Google Inc/.test(navigator.vendor) style.push 'display:none;' gooey = """ <svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="#{style.join(' ')}"> <defs> <filter id="gooey"> <feGaussianBlur in="SourceGraphic" stdDeviation="0" result="blur" /> <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 19 -9" result="gooey" /> <feComposite in="SourceGraphic" in2="gooey" operator="atop"/> </filter> </defs> </svg> """ gooey_elm = document.createElement 'div' gooey_elm.innerHTML = gooey @gooey_defs = gooey_elm.querySelector 'defs' @gooey_svg = gooey_elm.firstChild @gooey = gooey_elm.querySelector '#gooey' # append filters to page body = document.querySelector('body') body.appendChild @gooey_svg ### Listen for animations ### _listenAnimation : -> document.addEventListener 'DOMNodeInserted', (e) => elm = e.target if elm.dataset and elm.dataset.gooey != undefined and not elm._gooeyFilter @_handleFilter elm ### Handle filter ### _handleFilter : (elm, recursive = false) -> # clone the filter tag in svg elm._gooeyFilter = @gooey.cloneNode true # set a new id id = 'gooeyFilter-' + @_uniqId() elm._gooeyFilter.setAttribute 'id', id # append new filter in defs @gooey_defs.appendChild elm._gooeyFilter # set the new filter to element @_applyFilter elm, 'url("#'+id+'")' # set the blur effect amount = parseInt(elm.dataset.gooey || 10) elm._gooeyFilter.firstElementChild.setAttribute 'stdDeviation', amount elm._gooeyFilter.children[1].setAttribute 'values', '1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 ' + (9 + amount) + ' -9' ### Apply filter ### _applyFilter : (elm, filter) -> for vendor in ["-webkit-", "-moz-", "-ms-", "o-", ""] elm.style[vendor+'filter'] = filter ### UniqId ### _uniqId : -> return new Date().getTime() + Math.round(Math.random() * 999999999); n = Math.floor(Math.random()*11); k = Math.floor(Math.random()* 1000000); m = String.fromCharCode(n)+k; return m.trim() # init the filter SugarGooey.init() # return the Sugar object SugarGooey
true
### # Sugar-gooey.js # # This little js file allow you to use the gooey effect # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # @created 22.01.16 # @updated 20.01.16 # @version 1.0.0 ### ((factory) -> if typeof define == 'function' and define.amd # AMD. Register as an anonymous module. define [ ], factory else if typeof exports == 'object' # Node/CommonJS factory() else # Browser globals factory() return ) () -> window.SugarGooey = # track if already inited _inited : false # enabled enabled : true ### Init ### init : () -> # update inited state @_inited = true # wait until the dom is loaded if document.readyState == 'interactive' then @_init() else document.addEventListener 'DOMContentLoaded', (e) => @_init() ### Internal init ### _init : -> # do nothing if not enabled return if not @enabled # put filters into page @_injectFilter() # listen for animations @_listenAnimation() # init element for item in document.querySelectorAll('[data-gooey]') item.dispatchEvent(new CustomEvent('DOMNodeInserted', { bubbles : true, cancelable : true })); ### Inject filter ### _injectFilter : -> # gooey style = ['position:absolute;','left:-1000px;'] if /Chrome/.test(navigator.userAgent) and /Google Inc/.test(navigator.vendor) style.push 'display:none;' gooey = """ <svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="#{style.join(' ')}"> <defs> <filter id="gooey"> <feGaussianBlur in="SourceGraphic" stdDeviation="0" result="blur" /> <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 19 -9" result="gooey" /> <feComposite in="SourceGraphic" in2="gooey" operator="atop"/> </filter> </defs> </svg> """ gooey_elm = document.createElement 'div' gooey_elm.innerHTML = gooey @gooey_defs = gooey_elm.querySelector 'defs' @gooey_svg = gooey_elm.firstChild @gooey = gooey_elm.querySelector '#gooey' # append filters to page body = document.querySelector('body') body.appendChild @gooey_svg ### Listen for animations ### _listenAnimation : -> document.addEventListener 'DOMNodeInserted', (e) => elm = e.target if elm.dataset and elm.dataset.gooey != undefined and not elm._gooeyFilter @_handleFilter elm ### Handle filter ### _handleFilter : (elm, recursive = false) -> # clone the filter tag in svg elm._gooeyFilter = @gooey.cloneNode true # set a new id id = 'gooeyFilter-' + @_uniqId() elm._gooeyFilter.setAttribute 'id', id # append new filter in defs @gooey_defs.appendChild elm._gooeyFilter # set the new filter to element @_applyFilter elm, 'url("#'+id+'")' # set the blur effect amount = parseInt(elm.dataset.gooey || 10) elm._gooeyFilter.firstElementChild.setAttribute 'stdDeviation', amount elm._gooeyFilter.children[1].setAttribute 'values', '1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 ' + (9 + amount) + ' -9' ### Apply filter ### _applyFilter : (elm, filter) -> for vendor in ["-webkit-", "-moz-", "-ms-", "o-", ""] elm.style[vendor+'filter'] = filter ### UniqId ### _uniqId : -> return new Date().getTime() + Math.round(Math.random() * 999999999); n = Math.floor(Math.random()*11); k = Math.floor(Math.random()* 1000000); m = String.fromCharCode(n)+k; return m.trim() # init the filter SugarGooey.init() # return the Sugar object SugarGooey
[ { "context": "assName = 'scribe'\n\n contributors: [\n {name: 'Ryan Faidley'}\n {name: 'Mischa Lewis-Norelle', github: 'mle", "end": 332, "score": 0.9998835325241089, "start": 320, "tag": "NAME", "value": "Ryan Faidley" }, { "context": "ibutors: [\n {name: 'Ryan Faidley'}\n...
app/views/contribute/ScribeView.coffee
adamcsillag/codecombat
2
ContributeClassView = require './ContributeClassView' template = require 'templates/contribute/scribe' {me} = require 'core/auth' module.exports = class ScribeView extends ContributeClassView id: 'scribe-view' template: template initialize: -> @contributorClassName = 'scribe' contributors: [ {name: 'Ryan Faidley'} {name: 'Mischa Lewis-Norelle', github: 'mlewisno'} {name: 'Tavio'} {name: 'Ronnie Cheng', github: 'rhc2104'} {name: 'engstrom'} {name: 'Dman19993'} {name: 'mattinsler'} ]
21955
ContributeClassView = require './ContributeClassView' template = require 'templates/contribute/scribe' {me} = require 'core/auth' module.exports = class ScribeView extends ContributeClassView id: 'scribe-view' template: template initialize: -> @contributorClassName = 'scribe' contributors: [ {name: '<NAME>'} {name: '<NAME>', github: 'mlewisno'} {name: '<NAME>'} {name: '<NAME>', github: 'rhc2104'} {name: 'engstrom'} {name: '<NAME>19993'} {name: 'mattinsler'} ]
true
ContributeClassView = require './ContributeClassView' template = require 'templates/contribute/scribe' {me} = require 'core/auth' module.exports = class ScribeView extends ContributeClassView id: 'scribe-view' template: template initialize: -> @contributorClassName = 'scribe' contributors: [ {name: 'PI:NAME:<NAME>END_PI'} {name: 'PI:NAME:<NAME>END_PI', github: 'mlewisno'} {name: 'PI:NAME:<NAME>END_PI'} {name: 'PI:NAME:<NAME>END_PI', github: 'rhc2104'} {name: 'engstrom'} {name: 'PI:NAME:<NAME>END_PI19993'} {name: 'mattinsler'} ]
[ { "context": "mfabrik GmbH\n * MIT Licence\n * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org\n#", "end": 166, "score": 0.9885415434837341, "start": 152, "tag": "USERNAME", "value": "programmfabrik" }, { "context": "le_input\"\n\t\t\t\tform:\n\t\t\t...
demo/src/demos/FormLayoutDemo.coffee
programmfabrik/coffeescript-ui
10
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### class Demo.FormLayoutDemo extends Demo getGroup: -> "Test" display: -> @demo_table = new Demo.DemoTable("cui-form-layout-demo") form_options = class: "cui-form-layout-demo-example-default" @demo_table.addExample("default", @createExampleForm(form_options)) form_options = class: "cui-form-layout-demo-example-maximize-center" @demo_table.addExample("maximized center column with mixin", @createExampleForm(form_options)) form_options = class: "cui-form-layout-demo-example-maximize-right" @demo_table.addExample("maximized right column with mixin", @createExampleForm(form_options)) form_options = class: "cui-form-layout-demo-example-grid" render_as_grid: true @demo_table.addExample("grid layout", @createGridExampleForm(form_options)) @demo_table.table createExampleForm: (form_options) -> select_options = [ text: "data name 1" value: 1 , text: "data name 2" value: 2 ] form_data = width_type: 1 option: true default_form_options = type: CUI.Form horizontal: false data: form_data fields: [ type: CUI.Select name: "width_type" form: label: "Layout" options: select_options , type: CUI.Checkbox text: "option" name: "option" form: label: "Simple Input that could easliy get very long" , placeholder: "INPUT" type: CUI.Input name: "simple_input" form: label: "text 1" right: label: "a simple text input" ] # add form options to defaults for key,value of form_options default_form_options[key] = value form = CUI.DataField.new(default_form_options) form.start() form createGridExampleForm: (form_options) -> select_options = [ text: "data name 1" value: 1 , text: "data name 2" value: 2 ] form_data = width_type: 1 option: true default_form_options = type: CUI.Form horizontal: false data: form_data fields: [ type: CUI.Select name: "width_type" form: grid: "1/2" label: "Title" options: select_options , type: CUI.Checkbox text: "option" name: "option" form: grid: "1/2" label: "Some Option" , placeholder: "INPUT" type: CUI.Input name: "simple_input" form: grid: "1/2" label: "First Name" right: label: "a simple text input" , placeholder: "INPUT" type: CUI.Input name: "simple_input" form: grid: "1/2" label: "Last Name" right: label: "a simple text input" ] # add form options to defaults for key,value of form_options default_form_options[key] = value form = CUI.DataField.new(default_form_options) form.start() form Demo.register(new Demo.FormLayoutDemo())
17006
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### class Demo.FormLayoutDemo extends Demo getGroup: -> "Test" display: -> @demo_table = new Demo.DemoTable("cui-form-layout-demo") form_options = class: "cui-form-layout-demo-example-default" @demo_table.addExample("default", @createExampleForm(form_options)) form_options = class: "cui-form-layout-demo-example-maximize-center" @demo_table.addExample("maximized center column with mixin", @createExampleForm(form_options)) form_options = class: "cui-form-layout-demo-example-maximize-right" @demo_table.addExample("maximized right column with mixin", @createExampleForm(form_options)) form_options = class: "cui-form-layout-demo-example-grid" render_as_grid: true @demo_table.addExample("grid layout", @createGridExampleForm(form_options)) @demo_table.table createExampleForm: (form_options) -> select_options = [ text: "data name 1" value: 1 , text: "data name 2" value: 2 ] form_data = width_type: 1 option: true default_form_options = type: CUI.Form horizontal: false data: form_data fields: [ type: CUI.Select name: "width_type" form: label: "Layout" options: select_options , type: CUI.Checkbox text: "option" name: "option" form: label: "Simple Input that could easliy get very long" , placeholder: "INPUT" type: CUI.Input name: "simple_input" form: label: "text 1" right: label: "a simple text input" ] # add form options to defaults for key,value of form_options default_form_options[key] = value form = CUI.DataField.new(default_form_options) form.start() form createGridExampleForm: (form_options) -> select_options = [ text: "data name 1" value: 1 , text: "data name 2" value: 2 ] form_data = width_type: 1 option: true default_form_options = type: CUI.Form horizontal: false data: form_data fields: [ type: CUI.Select name: "width_type" form: grid: "1/2" label: "Title" options: select_options , type: CUI.Checkbox text: "option" name: "option" form: grid: "1/2" label: "Some Option" , placeholder: "INPUT" type: CUI.Input name: "simple_input" form: grid: "1/2" label: "<NAME>" right: label: "a simple text input" , placeholder: "INPUT" type: CUI.Input name: "simple_input" form: grid: "1/2" label: "<NAME>" right: label: "a simple text input" ] # add form options to defaults for key,value of form_options default_form_options[key] = value form = CUI.DataField.new(default_form_options) form.start() form Demo.register(new Demo.FormLayoutDemo())
true
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### class Demo.FormLayoutDemo extends Demo getGroup: -> "Test" display: -> @demo_table = new Demo.DemoTable("cui-form-layout-demo") form_options = class: "cui-form-layout-demo-example-default" @demo_table.addExample("default", @createExampleForm(form_options)) form_options = class: "cui-form-layout-demo-example-maximize-center" @demo_table.addExample("maximized center column with mixin", @createExampleForm(form_options)) form_options = class: "cui-form-layout-demo-example-maximize-right" @demo_table.addExample("maximized right column with mixin", @createExampleForm(form_options)) form_options = class: "cui-form-layout-demo-example-grid" render_as_grid: true @demo_table.addExample("grid layout", @createGridExampleForm(form_options)) @demo_table.table createExampleForm: (form_options) -> select_options = [ text: "data name 1" value: 1 , text: "data name 2" value: 2 ] form_data = width_type: 1 option: true default_form_options = type: CUI.Form horizontal: false data: form_data fields: [ type: CUI.Select name: "width_type" form: label: "Layout" options: select_options , type: CUI.Checkbox text: "option" name: "option" form: label: "Simple Input that could easliy get very long" , placeholder: "INPUT" type: CUI.Input name: "simple_input" form: label: "text 1" right: label: "a simple text input" ] # add form options to defaults for key,value of form_options default_form_options[key] = value form = CUI.DataField.new(default_form_options) form.start() form createGridExampleForm: (form_options) -> select_options = [ text: "data name 1" value: 1 , text: "data name 2" value: 2 ] form_data = width_type: 1 option: true default_form_options = type: CUI.Form horizontal: false data: form_data fields: [ type: CUI.Select name: "width_type" form: grid: "1/2" label: "Title" options: select_options , type: CUI.Checkbox text: "option" name: "option" form: grid: "1/2" label: "Some Option" , placeholder: "INPUT" type: CUI.Input name: "simple_input" form: grid: "1/2" label: "PI:NAME:<NAME>END_PI" right: label: "a simple text input" , placeholder: "INPUT" type: CUI.Input name: "simple_input" form: grid: "1/2" label: "PI:NAME:<NAME>END_PI" right: label: "a simple text input" ] # add form options to defaults for key,value of form_options default_form_options[key] = value form = CUI.DataField.new(default_form_options) form.start() form Demo.register(new Demo.FormLayoutDemo())
[ { "context": "e.getName()\n\n contact =\n name: 'contact'\n url: '/contact'\n template", "end": 579, "score": 0.9688158631324768, "start": 572, "tag": "NAME", "value": "contact" }, { "context": "ontact'\n\n contactList =\n nam...
ui-router/demo-2/router.coffee
mrdulin/angularjs
0
class config @$inject = ['$stateProvider', '$urlRouterProvider'] constructor: ($stateProvider, $urlRouterProvider)-> $urlRouterProvider .when '/', 'home' .otherwise '/home' ##这种对象形式的路由要注意的是name和parent字段 home = name: 'home' url: '/home' templateUrl: './home/home.tpl.html' controller: 'HomeController' controllerAs: 'home' resolve: name: (HomeService) -> HomeService.getName() contact = name: 'contact' url: '/contact' templateUrl: './contact/contact.tpl.html' controller: 'ContactController as contact' contactList = name: 'contact.list' #url前加'^'符号,则该url的路径变成绝对路径,此例不加'^'则url为/contact/list,加了以后变位/list url: '^/list' parent: contact templateUrl: './contact/contactList/contactList.tpl.html' controller: 'ContactListController' controllerAs: 'contactList' about = name: 'about' params: {'aboutId': '123'} url: '/about/:aboutId' template: """ <div class="container-fluid"> <p>This is about page</p> </div> """ contactDetail = name: 'contact.detail' #和'/detail/:contactId'功能相同 url: '^/detail/{contactId}?from&to' parent: 'contact' templateUrl: './contact/contactDetail/contactDetail.tpl.html' controller: 'ContactDetailController' controllerAs: 'contactDetail' $stateProvider .state home .state contact .state contactList .state contactDetail .state about return angular .module 'app' .config config
31553
class config @$inject = ['$stateProvider', '$urlRouterProvider'] constructor: ($stateProvider, $urlRouterProvider)-> $urlRouterProvider .when '/', 'home' .otherwise '/home' ##这种对象形式的路由要注意的是name和parent字段 home = name: 'home' url: '/home' templateUrl: './home/home.tpl.html' controller: 'HomeController' controllerAs: 'home' resolve: name: (HomeService) -> HomeService.getName() contact = name: '<NAME>' url: '/contact' templateUrl: './contact/contact.tpl.html' controller: 'ContactController as contact' contactList = name: '<NAME>' #url前加'^'符号,则该url的路径变成绝对路径,此例不加'^'则url为/contact/list,加了以后变位/list url: '^/list' parent: contact templateUrl: './contact/contactList/contactList.tpl.html' controller: 'ContactListController' controllerAs: 'contactList' about = name: 'about' params: {'aboutId': '123'} url: '/about/:aboutId' template: """ <div class="container-fluid"> <p>This is about page</p> </div> """ contactDetail = name: '<NAME>.detail' #和'/detail/:contactId'功能相同 url: '^/detail/{contactId}?from&to' parent: 'contact' templateUrl: './contact/contactDetail/contactDetail.tpl.html' controller: 'ContactDetailController' controllerAs: 'contactDetail' $stateProvider .state home .state contact .state contactList .state contactDetail .state about return angular .module 'app' .config config
true
class config @$inject = ['$stateProvider', '$urlRouterProvider'] constructor: ($stateProvider, $urlRouterProvider)-> $urlRouterProvider .when '/', 'home' .otherwise '/home' ##这种对象形式的路由要注意的是name和parent字段 home = name: 'home' url: '/home' templateUrl: './home/home.tpl.html' controller: 'HomeController' controllerAs: 'home' resolve: name: (HomeService) -> HomeService.getName() contact = name: 'PI:NAME:<NAME>END_PI' url: '/contact' templateUrl: './contact/contact.tpl.html' controller: 'ContactController as contact' contactList = name: 'PI:NAME:<NAME>END_PI' #url前加'^'符号,则该url的路径变成绝对路径,此例不加'^'则url为/contact/list,加了以后变位/list url: '^/list' parent: contact templateUrl: './contact/contactList/contactList.tpl.html' controller: 'ContactListController' controllerAs: 'contactList' about = name: 'about' params: {'aboutId': '123'} url: '/about/:aboutId' template: """ <div class="container-fluid"> <p>This is about page</p> </div> """ contactDetail = name: 'PI:NAME:<NAME>END_PI.detail' #和'/detail/:contactId'功能相同 url: '^/detail/{contactId}?from&to' parent: 'contact' templateUrl: './contact/contactDetail/contactDetail.tpl.html' controller: 'ContactDetailController' controllerAs: 'contactDetail' $stateProvider .state home .state contact .state contactList .state contactDetail .state about return angular .module 'app' .config config
[ { "context": "scribe '#fillUser', ->\n user = {\n email: 'example@example.com'\n bill_address: {\n family_name: 'foo'", "end": 320, "score": 0.9999213218688965, "start": 301, "tag": "EMAIL", "value": "example@example.com" } ]
backend/spec/javascripts/comable/admin/user_selector_spec.coffee
appirits/comable
14
#= require jquery #= require jasmine-jquery #= require comable/admin/user_selector describe 'UserSelector', -> described_class = null subject = null beforeEach -> described_class = UserSelector subject = described_class.prototype describe '#fillUser', -> user = { email: 'example@example.com' bill_address: { family_name: 'foo' first_name: 'bar' zip_code: '123-4567' state_name: 'Tokyo' } } it 'fills email filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="email" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.email) it 'fills bill-family-name filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-family-name" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.family_name) it 'fills bill-first-name filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-first-name" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.first_name) it 'fills bill-zip-code filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-zip-code" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.zip_code) it 'fills bill-state-name filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-state-name" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.state_name)
110819
#= require jquery #= require jasmine-jquery #= require comable/admin/user_selector describe 'UserSelector', -> described_class = null subject = null beforeEach -> described_class = UserSelector subject = described_class.prototype describe '#fillUser', -> user = { email: '<EMAIL>' bill_address: { family_name: 'foo' first_name: 'bar' zip_code: '123-4567' state_name: 'Tokyo' } } it 'fills email filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="email" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.email) it 'fills bill-family-name filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-family-name" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.family_name) it 'fills bill-first-name filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-first-name" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.first_name) it 'fills bill-zip-code filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-zip-code" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.zip_code) it 'fills bill-state-name filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-state-name" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.state_name)
true
#= require jquery #= require jasmine-jquery #= require comable/admin/user_selector describe 'UserSelector', -> described_class = null subject = null beforeEach -> described_class = UserSelector subject = described_class.prototype describe '#fillUser', -> user = { email: 'PI:EMAIL:<EMAIL>END_PI' bill_address: { family_name: 'foo' first_name: 'bar' zip_code: '123-4567' state_name: 'Tokyo' } } it 'fills email filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="email" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.email) it 'fills bill-family-name filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-family-name" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.family_name) it 'fills bill-first-name filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-first-name" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.first_name) it 'fills bill-zip-code filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-zip-code" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.zip_code) it 'fills bill-state-name filed', -> setFixtures('<div id="js-user-selector"><input type="text" data-name="bill-state-name" /></div>') subject.$user = $('#js-user-selector') subject.fillUser(user) expect(subject.$user.find('input')).toHaveValue(user.bill_address.state_name)
[ { "context": "\n email: email\n firstName: firstName\n lastName: lastName\n order:\n ", "end": 2051, "score": 0.999625027179718, "start": 2042, "tag": "NAME", "value": "firstName" }, { "context": " firstName: firstName\n las...
test/server/order.coffee
hanzo-io/hanzo.js
147
promise = require 'broken' sleep = (delay) -> new Promise (resolve, reject) -> setTimeout resolve, delay describe 'Api.order', -> fixture = null ord = null before -> fixture = shippingAddress: line1: 'line1' line2: 'line2' city: 'city' state: 'state' postalCode: '11111' country: 'USA' currency: 'usd' items:[{ productSlug: 'sad-keanu-shirt' quantity: 1 }] describe '.create', -> it 'should create orders', -> ord = order = yield api.order.create fixture order.shippingAddress.line1.should.equal 'line1' order.shippingAddress.line2.should.equal 'line2' order.shippingAddress.city.should.equal 'city' order.shippingAddress.state.should.equal 'state' order.shippingAddress.postalCode.should.equal '11111' order.shippingAddress.country.should.equal 'USA' order.currency.should.equal 'usd' order.total.should.equal 2500 order.status.should.equal 'open' order.paymentStatus.should.equal 'unpaid' order.items.length.should.equal 1 order.items[0].productSlug.should.equal 'sad-keanu-shirt' order.items[0].quantity.should.equal 1 describe '.get', -> it 'should get order', -> order = yield api.order.get ord.id order.total.should.eq 2500 describe '.list', -> it 'should list orders', -> {count, models} = yield api.order.list() models.length.should.be.gt 0 count.should.be.gt 0 describe '.update', -> it 'should update orders', -> order = yield api.order.update id: ord.id shippingAddress: line1: 'line1u' order.shippingAddress.line1.should.equal 'line1u' describe '.delete', -> it 'should delete orders', -> yield api.order.delete ord.id describe '.refund', -> it 'should partial and fully refund', -> order = yield api.checkout.charge user: email: email firstName: firstName lastName: lastName order: shippingAddress: line1: 'line1' line2: 'line2' city: 'city' state: 'state' postalCode: '11111' country: 'USA' currency: 'usd' items: [{ productSlug: 'sad-keanu-shirt' quantity: 1 }] payment: account: number: '4242424242424242' cvc: '424' month: '1' year: '2020' yield sleep 100 refundedOrder = yield api.order.refund id: order.id amount: 100 refundedOrder.id.should.equal order.id refundedOrder.refunded.should.equal 100 refundedOrder.status.should.equal 'open' refundedOrder.paymentStatus.should.equal 'paid' yield sleep 100 refundedOrder2 = yield api.order.refund id: order.id amount: 2400 refundedOrder2.id.should.equal order.id refundedOrder2.refunded.should.equal 2500 refundedOrder2.status.should.equal 'cancelled' refundedOrder2.paymentStatus.should.equal 'refunded'
112857
promise = require 'broken' sleep = (delay) -> new Promise (resolve, reject) -> setTimeout resolve, delay describe 'Api.order', -> fixture = null ord = null before -> fixture = shippingAddress: line1: 'line1' line2: 'line2' city: 'city' state: 'state' postalCode: '11111' country: 'USA' currency: 'usd' items:[{ productSlug: 'sad-keanu-shirt' quantity: 1 }] describe '.create', -> it 'should create orders', -> ord = order = yield api.order.create fixture order.shippingAddress.line1.should.equal 'line1' order.shippingAddress.line2.should.equal 'line2' order.shippingAddress.city.should.equal 'city' order.shippingAddress.state.should.equal 'state' order.shippingAddress.postalCode.should.equal '11111' order.shippingAddress.country.should.equal 'USA' order.currency.should.equal 'usd' order.total.should.equal 2500 order.status.should.equal 'open' order.paymentStatus.should.equal 'unpaid' order.items.length.should.equal 1 order.items[0].productSlug.should.equal 'sad-keanu-shirt' order.items[0].quantity.should.equal 1 describe '.get', -> it 'should get order', -> order = yield api.order.get ord.id order.total.should.eq 2500 describe '.list', -> it 'should list orders', -> {count, models} = yield api.order.list() models.length.should.be.gt 0 count.should.be.gt 0 describe '.update', -> it 'should update orders', -> order = yield api.order.update id: ord.id shippingAddress: line1: 'line1u' order.shippingAddress.line1.should.equal 'line1u' describe '.delete', -> it 'should delete orders', -> yield api.order.delete ord.id describe '.refund', -> it 'should partial and fully refund', -> order = yield api.checkout.charge user: email: email firstName: <NAME> lastName: <NAME> order: shippingAddress: line1: 'line1' line2: 'line2' city: 'city' state: 'state' postalCode: '11111' country: 'USA' currency: 'usd' items: [{ productSlug: 'sad-keanu-shirt' quantity: 1 }] payment: account: number: '4242424242424242' cvc: '424' month: '1' year: '2020' yield sleep 100 refundedOrder = yield api.order.refund id: order.id amount: 100 refundedOrder.id.should.equal order.id refundedOrder.refunded.should.equal 100 refundedOrder.status.should.equal 'open' refundedOrder.paymentStatus.should.equal 'paid' yield sleep 100 refundedOrder2 = yield api.order.refund id: order.id amount: 2400 refundedOrder2.id.should.equal order.id refundedOrder2.refunded.should.equal 2500 refundedOrder2.status.should.equal 'cancelled' refundedOrder2.paymentStatus.should.equal 'refunded'
true
promise = require 'broken' sleep = (delay) -> new Promise (resolve, reject) -> setTimeout resolve, delay describe 'Api.order', -> fixture = null ord = null before -> fixture = shippingAddress: line1: 'line1' line2: 'line2' city: 'city' state: 'state' postalCode: '11111' country: 'USA' currency: 'usd' items:[{ productSlug: 'sad-keanu-shirt' quantity: 1 }] describe '.create', -> it 'should create orders', -> ord = order = yield api.order.create fixture order.shippingAddress.line1.should.equal 'line1' order.shippingAddress.line2.should.equal 'line2' order.shippingAddress.city.should.equal 'city' order.shippingAddress.state.should.equal 'state' order.shippingAddress.postalCode.should.equal '11111' order.shippingAddress.country.should.equal 'USA' order.currency.should.equal 'usd' order.total.should.equal 2500 order.status.should.equal 'open' order.paymentStatus.should.equal 'unpaid' order.items.length.should.equal 1 order.items[0].productSlug.should.equal 'sad-keanu-shirt' order.items[0].quantity.should.equal 1 describe '.get', -> it 'should get order', -> order = yield api.order.get ord.id order.total.should.eq 2500 describe '.list', -> it 'should list orders', -> {count, models} = yield api.order.list() models.length.should.be.gt 0 count.should.be.gt 0 describe '.update', -> it 'should update orders', -> order = yield api.order.update id: ord.id shippingAddress: line1: 'line1u' order.shippingAddress.line1.should.equal 'line1u' describe '.delete', -> it 'should delete orders', -> yield api.order.delete ord.id describe '.refund', -> it 'should partial and fully refund', -> order = yield api.checkout.charge user: email: email firstName: PI:NAME:<NAME>END_PI lastName: PI:NAME:<NAME>END_PI order: shippingAddress: line1: 'line1' line2: 'line2' city: 'city' state: 'state' postalCode: '11111' country: 'USA' currency: 'usd' items: [{ productSlug: 'sad-keanu-shirt' quantity: 1 }] payment: account: number: '4242424242424242' cvc: '424' month: '1' year: '2020' yield sleep 100 refundedOrder = yield api.order.refund id: order.id amount: 100 refundedOrder.id.should.equal order.id refundedOrder.refunded.should.equal 100 refundedOrder.status.should.equal 'open' refundedOrder.paymentStatus.should.equal 'paid' yield sleep 100 refundedOrder2 = yield api.order.refund id: order.id amount: 2400 refundedOrder2.id.should.equal order.id refundedOrder2.refunded.should.equal 2500 refundedOrder2.status.should.equal 'cancelled' refundedOrder2.paymentStatus.should.equal 'refunded'
[ { "context": "nt:\n address: req.body.parentEmail\n if /@codecombat.com/.test(context.recipient.address) or not _.str.tri", "end": 438, "score": 0.9634086489677429, "start": 423, "tag": "EMAIL", "value": "@codecombat.com" }, { "context": "ess: req.body.teacherEmail\n b...
server/middleware/contact.coffee
johanvl/codecombat
1
sendwithus = require '../sendwithus' utils = require '../lib/utils' errors = require '../commons/errors' wrap = require 'co-express' database = require '../commons/database' parse = require '../commons/parse' module.exports = sendParentSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.coppa_deny_parent_signup recipient: address: req.body.parentEmail if /@codecombat.com/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_signup_instructions recipient: address: req.body.teacherEmail bcc: [{address: 'schools@codecombat.com'}] template_data: student_name: req.body.studentName if /@codecombat.com/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherGameDevProjectShare: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_game_dev_project_share recipient: address: req.body.teacherEmail bcc: [{address: 'schools@codecombat.com'}] template_data: student_name: req.user.broadName() code_language: req.body.codeLanguage level_link: "https://codecombat.com/play/game-dev-level/#{req.body.sessionId}" level_name: req.body.levelName if /@codecombat.com/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send()
70791
sendwithus = require '../sendwithus' utils = require '../lib/utils' errors = require '../commons/errors' wrap = require 'co-express' database = require '../commons/database' parse = require '../commons/parse' module.exports = sendParentSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.coppa_deny_parent_signup recipient: address: req.body.parentEmail if /<EMAIL>/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_signup_instructions recipient: address: req.body.teacherEmail bcc: [{address: '<EMAIL>'}] template_data: student_name: req.body.studentName if /<EMAIL>/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherGameDevProjectShare: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_game_dev_project_share recipient: address: req.body.teacherEmail bcc: [{address: '<EMAIL>'}] template_data: student_name: req.user.broadName() code_language: req.body.codeLanguage level_link: "https://codecombat.com/play/game-dev-level/#{req.body.sessionId}" level_name: req.body.levelName if /@<EMAIL>/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send()
true
sendwithus = require '../sendwithus' utils = require '../lib/utils' errors = require '../commons/errors' wrap = require 'co-express' database = require '../commons/database' parse = require '../commons/parse' module.exports = sendParentSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.coppa_deny_parent_signup recipient: address: req.body.parentEmail if /PI:EMAIL:<EMAIL>END_PI/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_signup_instructions recipient: address: req.body.teacherEmail bcc: [{address: 'PI:EMAIL:<EMAIL>END_PI'}] template_data: student_name: req.body.studentName if /PI:EMAIL:<EMAIL>END_PI/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherGameDevProjectShare: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_game_dev_project_share recipient: address: req.body.teacherEmail bcc: [{address: 'PI:EMAIL:<EMAIL>END_PI'}] template_data: student_name: req.user.broadName() code_language: req.body.codeLanguage level_link: "https://codecombat.com/play/game-dev-level/#{req.body.sessionId}" level_name: req.body.levelName if /@PI:EMAIL:<EMAIL>END_PI/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send()
[ { "context": "the left operand of relational operators\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------", "end": 112, "score": 0.9998745918273926, "start": 98, "tag": "NAME", "value": "Toru Nagashima" } ]
src/rules/no-unsafe-negation.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to disallow negating the left operand of relational operators # @author Toru Nagashima ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Checks whether the given operator is a relational operator or not. # # @param {string} op - The operator type to check. # @returns {boolean} `true` if the operator is a relational operator. ### isRelationalOperator = (op) -> op in ['in', 'not in', 'of', 'not of', 'instanceof', 'not instanceof'] ###* # Checks whether the given node is a logical negation expression or not. # # @param {ASTNode} node - The node to check. # @returns {boolean} `true` if the node is a logical negation expression. ### isNegation = (node) -> node.type is 'UnaryExpression' and node.operator in ['!', 'not'] #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow negating the left operand of relational operators' category: 'Possible Errors' recommended: yes url: 'https://eslint.org/docs/rules/no-unsafe-negation' schema: [] # fixable: 'code' create: (context) -> sourceCode = context.getSourceCode() BinaryExpression: (node) -> if ( isRelationalOperator(node.operator) and isNegation(node.left) and not astUtils.isParenthesised sourceCode, node.left ) context.report { node loc: node.left.loc message: "Unexpected negating the left operand of '{{operator}}' operator." data: node # fix: (fixer) -> # negationToken = sourceCode.getFirstToken node.left # fixRange = [ # if ( # node.left.operator is 'not' and # /^\s+/.test sourceCode.getText()[negationToken.range[1]..] # ) # negationToken.range[1] + 1 # else # negationToken.range[1] # node.range[1] # ] # text = sourceCode.text.slice fixRange[0], fixRange[1] # fixer.replaceTextRange fixRange, "(#{text})" }
94270
###* # @fileoverview Rule to disallow negating the left operand of relational operators # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Checks whether the given operator is a relational operator or not. # # @param {string} op - The operator type to check. # @returns {boolean} `true` if the operator is a relational operator. ### isRelationalOperator = (op) -> op in ['in', 'not in', 'of', 'not of', 'instanceof', 'not instanceof'] ###* # Checks whether the given node is a logical negation expression or not. # # @param {ASTNode} node - The node to check. # @returns {boolean} `true` if the node is a logical negation expression. ### isNegation = (node) -> node.type is 'UnaryExpression' and node.operator in ['!', 'not'] #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow negating the left operand of relational operators' category: 'Possible Errors' recommended: yes url: 'https://eslint.org/docs/rules/no-unsafe-negation' schema: [] # fixable: 'code' create: (context) -> sourceCode = context.getSourceCode() BinaryExpression: (node) -> if ( isRelationalOperator(node.operator) and isNegation(node.left) and not astUtils.isParenthesised sourceCode, node.left ) context.report { node loc: node.left.loc message: "Unexpected negating the left operand of '{{operator}}' operator." data: node # fix: (fixer) -> # negationToken = sourceCode.getFirstToken node.left # fixRange = [ # if ( # node.left.operator is 'not' and # /^\s+/.test sourceCode.getText()[negationToken.range[1]..] # ) # negationToken.range[1] + 1 # else # negationToken.range[1] # node.range[1] # ] # text = sourceCode.text.slice fixRange[0], fixRange[1] # fixer.replaceTextRange fixRange, "(#{text})" }
true
###* # @fileoverview Rule to disallow negating the left operand of relational operators # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Checks whether the given operator is a relational operator or not. # # @param {string} op - The operator type to check. # @returns {boolean} `true` if the operator is a relational operator. ### isRelationalOperator = (op) -> op in ['in', 'not in', 'of', 'not of', 'instanceof', 'not instanceof'] ###* # Checks whether the given node is a logical negation expression or not. # # @param {ASTNode} node - The node to check. # @returns {boolean} `true` if the node is a logical negation expression. ### isNegation = (node) -> node.type is 'UnaryExpression' and node.operator in ['!', 'not'] #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow negating the left operand of relational operators' category: 'Possible Errors' recommended: yes url: 'https://eslint.org/docs/rules/no-unsafe-negation' schema: [] # fixable: 'code' create: (context) -> sourceCode = context.getSourceCode() BinaryExpression: (node) -> if ( isRelationalOperator(node.operator) and isNegation(node.left) and not astUtils.isParenthesised sourceCode, node.left ) context.report { node loc: node.left.loc message: "Unexpected negating the left operand of '{{operator}}' operator." data: node # fix: (fixer) -> # negationToken = sourceCode.getFirstToken node.left # fixRange = [ # if ( # node.left.operator is 'not' and # /^\s+/.test sourceCode.getText()[negationToken.range[1]..] # ) # negationToken.range[1] + 1 # else # negationToken.range[1] # node.range[1] # ] # text = sourceCode.text.slice fixRange[0], fixRange[1] # fixer.replaceTextRange fixRange, "(#{text})" }
[ { "context": "tail\n reply: reply\n key: reply.get('id')\n ), if @props.isLogined then @renderEditor()", "end": 2489, "score": 0.6243258118629456, "start": 2487, "tag": "KEY", "value": "id" } ]
src/app/topic-detail.coffee
cnodejs/cnodejs-reader
65
'use strict' hsl = require('hsl') React = require('react') keycode = require('keycode') Immutable = require('immutable') reset = require('../util/reset') configs = require('../configs') controller = require('../controller') Time = React.createFactory(require('./time')) Hint = React.createFactory(require('./hint')) Space = React.createFactory(require('./space')) Button = React.createFactory(require('./button')) Author = React.createFactory(require('./author')) Content = React.createFactory(require('./content')) ReplyDetail = React.createFactory(require('./reply-detail')) _React$DOM = React.DOM div = _React$DOM.div textarea = _React$DOM.textarea a = _React$DOM.a module.exports = React.createClass( displayName: 'topic-detail' propTypes: topic: React.PropTypes.instanceOf(Immutable.Map).isRequired isLogined: React.PropTypes.bool.isRequired getInitialState: -> { text: '' } onTextChange: (event) -> @setState text: event.target.value onSubmit: -> controller.replyCreate topic_id: @props.topic.get('id') content: @state.text @setState text: '' onTextKeyDown: (event) -> if keycode(event.keyCode) == 'enter' and (event.ctrlKey or event.metaKey) @onSubmit() undefined renderEditor: -> div { style: @styleEditor() }, Space(height: 20), textarea( style: @styleText() value: @state.text onChange: @onTextChange onKeyDown: @onTextKeyDown placeholder: 'reply...'), Space(height: 10), div({ style: @styleWrapper() }, Content(text: @state.text)), Space(height: 10), div({ style: @styleToolbar() }, Button( text: 'submit' onClick: @onSubmit)), Space(height: 400) render: -> topic = @props.topic replies = topic.get('replies') div { style: @styleRoot() }, div({ style: @styleContent }, div({ style: @styleTitle() }, topic.get('title')), Space(height: 20), div({ style: @styleInfo() }, Author( author: topic.get('author') showName: true), Space(width: 10), Time(time: topic.get('create_at')), Space(width: 10), Hint(text: topic.get('reply_count') + '/' + topic.get('visit_count')), Space(width: 10), a({ target: '_blank' style: @styleLink() href: configs.domain + '/topic/' + topic.get('id') }, '🔗')), Space(height: 20), Content(text: topic.get('content'))), div({ style: @styleReplies() }, div({ style: @styleSection() }, replies.size + ' reples'), replies.map((reply) -> ReplyDetail reply: reply key: reply.get('id') ), if @props.isLogined then @renderEditor() else undefined) styleRoot: -> { display: 'flex' width: '1600px' overflowY: 'auto' height: '100%' backgroundColor: 'white' } styleContent: width: '800px' paddingBottom: '300px' paddingLeft: '40px' paddingRight: '40px' height: '100%' overflowY: 'auto' borderRight: '1px solid ' + hsl(0, 0, 90) styleReplies: -> { width: '800px' height: '100%' display: 'inline-block' overflowY: 'auto' padding: '20px 40px' } styleTitle: -> { fontSize: '18px' fontWeight: 'bold' fontFamily: reset.contentFonts lineHeight: '2.8em' } styleInfo: -> { display: 'flex' alignItems: 'center' justifyContent: 'flex-start' } styleSection: -> { fontFamily: reset.fashionFonts fontWeight: 'bold' marginBottom: '20px' } styleEditor: -> {} styleToolbar: -> { display: 'flex' flexDirection: 'row' justifyContent: 'flex-end' } styleText: -> { width: '100%' border: '1px solid ' + hsl(0, 0, 90) outline: 'none' minHeight: 100 fontSize: '14px' lineHeight: '1.8em' fontFamily: reset.codeFonts padding: 10 resize: 'resize-y' } styleWrapper: -> { padding: 10 border: '1px solid ' + hsl(0, 0, 90) } styleLink: -> { textDecoration: 'none' fontFamily: reset.contentFonts fontSize: '12px' } )
68496
'use strict' hsl = require('hsl') React = require('react') keycode = require('keycode') Immutable = require('immutable') reset = require('../util/reset') configs = require('../configs') controller = require('../controller') Time = React.createFactory(require('./time')) Hint = React.createFactory(require('./hint')) Space = React.createFactory(require('./space')) Button = React.createFactory(require('./button')) Author = React.createFactory(require('./author')) Content = React.createFactory(require('./content')) ReplyDetail = React.createFactory(require('./reply-detail')) _React$DOM = React.DOM div = _React$DOM.div textarea = _React$DOM.textarea a = _React$DOM.a module.exports = React.createClass( displayName: 'topic-detail' propTypes: topic: React.PropTypes.instanceOf(Immutable.Map).isRequired isLogined: React.PropTypes.bool.isRequired getInitialState: -> { text: '' } onTextChange: (event) -> @setState text: event.target.value onSubmit: -> controller.replyCreate topic_id: @props.topic.get('id') content: @state.text @setState text: '' onTextKeyDown: (event) -> if keycode(event.keyCode) == 'enter' and (event.ctrlKey or event.metaKey) @onSubmit() undefined renderEditor: -> div { style: @styleEditor() }, Space(height: 20), textarea( style: @styleText() value: @state.text onChange: @onTextChange onKeyDown: @onTextKeyDown placeholder: 'reply...'), Space(height: 10), div({ style: @styleWrapper() }, Content(text: @state.text)), Space(height: 10), div({ style: @styleToolbar() }, Button( text: 'submit' onClick: @onSubmit)), Space(height: 400) render: -> topic = @props.topic replies = topic.get('replies') div { style: @styleRoot() }, div({ style: @styleContent }, div({ style: @styleTitle() }, topic.get('title')), Space(height: 20), div({ style: @styleInfo() }, Author( author: topic.get('author') showName: true), Space(width: 10), Time(time: topic.get('create_at')), Space(width: 10), Hint(text: topic.get('reply_count') + '/' + topic.get('visit_count')), Space(width: 10), a({ target: '_blank' style: @styleLink() href: configs.domain + '/topic/' + topic.get('id') }, '🔗')), Space(height: 20), Content(text: topic.get('content'))), div({ style: @styleReplies() }, div({ style: @styleSection() }, replies.size + ' reples'), replies.map((reply) -> ReplyDetail reply: reply key: reply.get('<KEY>') ), if @props.isLogined then @renderEditor() else undefined) styleRoot: -> { display: 'flex' width: '1600px' overflowY: 'auto' height: '100%' backgroundColor: 'white' } styleContent: width: '800px' paddingBottom: '300px' paddingLeft: '40px' paddingRight: '40px' height: '100%' overflowY: 'auto' borderRight: '1px solid ' + hsl(0, 0, 90) styleReplies: -> { width: '800px' height: '100%' display: 'inline-block' overflowY: 'auto' padding: '20px 40px' } styleTitle: -> { fontSize: '18px' fontWeight: 'bold' fontFamily: reset.contentFonts lineHeight: '2.8em' } styleInfo: -> { display: 'flex' alignItems: 'center' justifyContent: 'flex-start' } styleSection: -> { fontFamily: reset.fashionFonts fontWeight: 'bold' marginBottom: '20px' } styleEditor: -> {} styleToolbar: -> { display: 'flex' flexDirection: 'row' justifyContent: 'flex-end' } styleText: -> { width: '100%' border: '1px solid ' + hsl(0, 0, 90) outline: 'none' minHeight: 100 fontSize: '14px' lineHeight: '1.8em' fontFamily: reset.codeFonts padding: 10 resize: 'resize-y' } styleWrapper: -> { padding: 10 border: '1px solid ' + hsl(0, 0, 90) } styleLink: -> { textDecoration: 'none' fontFamily: reset.contentFonts fontSize: '12px' } )
true
'use strict' hsl = require('hsl') React = require('react') keycode = require('keycode') Immutable = require('immutable') reset = require('../util/reset') configs = require('../configs') controller = require('../controller') Time = React.createFactory(require('./time')) Hint = React.createFactory(require('./hint')) Space = React.createFactory(require('./space')) Button = React.createFactory(require('./button')) Author = React.createFactory(require('./author')) Content = React.createFactory(require('./content')) ReplyDetail = React.createFactory(require('./reply-detail')) _React$DOM = React.DOM div = _React$DOM.div textarea = _React$DOM.textarea a = _React$DOM.a module.exports = React.createClass( displayName: 'topic-detail' propTypes: topic: React.PropTypes.instanceOf(Immutable.Map).isRequired isLogined: React.PropTypes.bool.isRequired getInitialState: -> { text: '' } onTextChange: (event) -> @setState text: event.target.value onSubmit: -> controller.replyCreate topic_id: @props.topic.get('id') content: @state.text @setState text: '' onTextKeyDown: (event) -> if keycode(event.keyCode) == 'enter' and (event.ctrlKey or event.metaKey) @onSubmit() undefined renderEditor: -> div { style: @styleEditor() }, Space(height: 20), textarea( style: @styleText() value: @state.text onChange: @onTextChange onKeyDown: @onTextKeyDown placeholder: 'reply...'), Space(height: 10), div({ style: @styleWrapper() }, Content(text: @state.text)), Space(height: 10), div({ style: @styleToolbar() }, Button( text: 'submit' onClick: @onSubmit)), Space(height: 400) render: -> topic = @props.topic replies = topic.get('replies') div { style: @styleRoot() }, div({ style: @styleContent }, div({ style: @styleTitle() }, topic.get('title')), Space(height: 20), div({ style: @styleInfo() }, Author( author: topic.get('author') showName: true), Space(width: 10), Time(time: topic.get('create_at')), Space(width: 10), Hint(text: topic.get('reply_count') + '/' + topic.get('visit_count')), Space(width: 10), a({ target: '_blank' style: @styleLink() href: configs.domain + '/topic/' + topic.get('id') }, '🔗')), Space(height: 20), Content(text: topic.get('content'))), div({ style: @styleReplies() }, div({ style: @styleSection() }, replies.size + ' reples'), replies.map((reply) -> ReplyDetail reply: reply key: reply.get('PI:KEY:<KEY>END_PI') ), if @props.isLogined then @renderEditor() else undefined) styleRoot: -> { display: 'flex' width: '1600px' overflowY: 'auto' height: '100%' backgroundColor: 'white' } styleContent: width: '800px' paddingBottom: '300px' paddingLeft: '40px' paddingRight: '40px' height: '100%' overflowY: 'auto' borderRight: '1px solid ' + hsl(0, 0, 90) styleReplies: -> { width: '800px' height: '100%' display: 'inline-block' overflowY: 'auto' padding: '20px 40px' } styleTitle: -> { fontSize: '18px' fontWeight: 'bold' fontFamily: reset.contentFonts lineHeight: '2.8em' } styleInfo: -> { display: 'flex' alignItems: 'center' justifyContent: 'flex-start' } styleSection: -> { fontFamily: reset.fashionFonts fontWeight: 'bold' marginBottom: '20px' } styleEditor: -> {} styleToolbar: -> { display: 'flex' flexDirection: 'row' justifyContent: 'flex-end' } styleText: -> { width: '100%' border: '1px solid ' + hsl(0, 0, 90) outline: 'none' minHeight: 100 fontSize: '14px' lineHeight: '1.8em' fontFamily: reset.codeFonts padding: 10 resize: 'resize-y' } styleWrapper: -> { padding: 10 border: '1px solid ' + hsl(0, 0, 90) } styleLink: -> { textDecoration: 'none' fontFamily: reset.contentFonts fontSize: '12px' } )
[ { "context": "e Music\n * @category Web Components\n * @author Nazar Mokrynskyi <nazar@mokrynskyi.com>\n * @copyright Copyright (c", "end": 96, "score": 0.9998939037322998, "start": 80, "tag": "NAME", "value": "Nazar Mokrynskyi" }, { "context": "y Web Components\n * @author N...
html/cs-music-player/script.coffee
mariot/Klif-Mozika
0
###* * @package CleverStyle Music * @category Web Components * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @copyright Copyright (c) 2014-2015, Nazar Mokrynskyi * @license MIT License, see license.txt ### music_storage = navigator.getDeviceStorage('music') sound_processing = cs.sound_processing music_library = cs.music_library music_playlist = cs.music_playlist music_settings = cs.music_settings body = document.querySelector('body') seeking_bar = null update_cover_timeout = 0 resize_image = (src, max_size, callback) -> image = new Image image.onload = -> canvas = document.createElement('canvas') if image.height > max_size || image.width > max_size image.width *= max_size / image.height image.height = max_size ctx = canvas.getContext('2d') ctx.clearRect(0, 0, canvas.width, canvas.height) canvas.width = image.width canvas.height = image.height ctx.mozImageSmoothingEnabled = false; ctx.drawImage(image, 0, 0, image.width, image.height) callback(canvas.toDataURL()) image.src = src Polymer( 'cs-music-player' title : '' artist : '' ready : -> seeking_bar = @shadowRoot.querySelector('cs-seeking-bar') $(seeking_bar).on('seeking-update', (e, data) => @seeking(data.percents) ) @player = do => player_element = document.createElement('audio') sound_processing.add_to_element(player_element) cs.bus.on('sound-processing/update', -> sound_processing.update_element(player_element) # TODO: uncomment when equalizer will be able to deal with aurora.js # if aurora_player # sound_processing.add_to_element(aurora_player.device.device.node) ) aurora_player = null playing_started = 0 # Change channel type to play in background player_element.mozAudioChannelType = 'content' object_url = null player_element.addEventListener('loadeddata', -> URL.revokeObjectURL(object_url) object_url = null ) player_element.addEventListener('error', => if new Date - playing_started > 1000 @player.pause() else play_with_aurora() ) player_element.addEventListener('ended', => # Pause @play() switch music_settings.repeat when 'one' music_playlist.current (id) => @play(id) else @next() ) player_element.addEventListener('timeupdate', => @update(player_element.currentTime, player_element.duration) ) play_with_aurora = (just_load) => aurora_player = AV.Player.fromURL(object_url) aurora_player.on('ready', -> @device.device.node.context.mozAudioChannelType = 'content' # TODO: uncomment when equalizer will be able to deal with aurora.js # sound_processing.add_to_element(@device.device.node) ) aurora_player.on('end', => # Pause @play() switch music_settings.repeat when 'one' music_playlist.current (id) => @play(id) else @next() ) aurora_player.on('duration', (duration) -> duration /= 1000 aurora_player.on('progress', -> @update(aurora_player.currentTime / 1000, duration) ) ) if !just_load aurora_player.play() return { open_new_file : (blob, filename, just_load) -> playing_started = new Date if @playing @pause() if aurora_player aurora_player.stop() aurora_player = null if object_url URL.revokeObjectURL(object_url) object_url = URL.createObjectURL(blob) if filename.substr(0, -4) == 'alac' || filename.substr(0, -4) == 'alac.mp3' play_with_aurora(just_load) else player_element.src = object_url player_element.load() this.file_loaded = true if !just_load player_element.play() @playing = true play : -> playing_started = new Date if aurora_player aurora_player.play() else player_element.play() @playing = true pause : -> if aurora_player aurora_player.pause() else player_element.pause() @playing = false seeking : (percents) => if aurora_player aurora_player.seek(aurora_player.duration * percents / 100) else if player_element.duration player_element.pause() player_element.currentTime = player_element.duration * percents / 100 if cs.bus.state.player == 'playing' player_element.play() else @play() } @play(null, null, true) update : (current_time, duration) -> progress_percentage = if duration then current_time / duration * 100 else 0 if progress_percentage != seeking_bar.progress_percentage && progress_percentage >= 0 && progress_percentage <= 100 && !isNaN(progress_percentage) seeking_bar.progress_percentage = progress_percentage current_time = time_format(current_time) if current_time != seeking_bar.current_time seeking_bar.current_time = current_time duration = if duration then time_format(duration) else '00:00' if duration != seeking_bar.duration seeking_bar.duration = duration play : (id, callback, just_load) -> id = if !isNaN(parseInt(id)) then id else undefined if typeof callback != 'function' callback = -> else callback.bind(@) element = @ play_button = element.shadowRoot.querySelector('[icon=play]') if @player.file_loaded && !id if @player.playing @player.pause() play_button.icon = 'play' cs.bus.trigger('player/pause') cs.bus.state.player = 'paused' else @player.play() play_button.icon = 'pause' cs.bus.trigger('player/resume') cs.bus.state.player = 'playing' else if id music_library.get(id, (data) -> get_file = music_storage.get(data.name) get_file.onsuccess = -> blob = @result element.player.open_new_file(blob, data.name, just_load) do -> if !just_load play_button.icon = 'pause' cs.bus.trigger('player/play', id) cs.bus.state.player = 'playing' music_library.get_meta(id, (data) -> if data element.title = data.title || _('unknown') element.artist = data.artist if data.artist && data.album element.artist += ": #{data.album}" else element.title = _('unknown') element.artist = '' ) update_cover = (cover) -> cover = cover || 'img/bg.jpg' if body.style.backgroundImage != "url(#{cover})" cs_cover = element.shadowRoot.querySelector('cs-cover') cs_cover.style.backgroundImage = "url(#{cover})" # No blurring in low performance mode if music_settings.low_performance body.style.backgroundImage = "url(#{cover})" else # Resize cover to needed size to decrease memory consumption and speed-up blurring resize_image( cover Math.max(cs_cover.clientHeight, cs_cover.clientWidth) (cover) -> # Start blurring of resized image el = document.createElement('div') new Blur( el : el path : cover radius : 10 callback : -> body.style.backgroundImage = el.style.backgroundImage setTimeout (-> URL.revokeObjectURL(cover) ), 500 callback() ) ) parseAudioMetadata( blob (metadata) -> cover = metadata.picture if cover cover = URL.createObjectURL(cover) update_cover(cover) -> update_cover('img/bg.jpg') ) get_file.onerror = (e) -> alert _( 'cant-play-this-file' error : e.target.error.name ) ) else music_playlist.current (id) => @play(id, callback, just_load) prev : (callback) -> music_playlist.prev (id) => @play(id, callback) next : (callback) -> music_playlist.next (id) => @play(id, callback) menu : -> @go_to_screen('menu') seeking : (percents) -> @player.seeking(percents) )
219394
###* * @package CleverStyle Music * @category Web Components * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2014-2015, <NAME> * @license MIT License, see license.txt ### music_storage = navigator.getDeviceStorage('music') sound_processing = cs.sound_processing music_library = cs.music_library music_playlist = cs.music_playlist music_settings = cs.music_settings body = document.querySelector('body') seeking_bar = null update_cover_timeout = 0 resize_image = (src, max_size, callback) -> image = new Image image.onload = -> canvas = document.createElement('canvas') if image.height > max_size || image.width > max_size image.width *= max_size / image.height image.height = max_size ctx = canvas.getContext('2d') ctx.clearRect(0, 0, canvas.width, canvas.height) canvas.width = image.width canvas.height = image.height ctx.mozImageSmoothingEnabled = false; ctx.drawImage(image, 0, 0, image.width, image.height) callback(canvas.toDataURL()) image.src = src Polymer( 'cs-music-player' title : '' artist : '' ready : -> seeking_bar = @shadowRoot.querySelector('cs-seeking-bar') $(seeking_bar).on('seeking-update', (e, data) => @seeking(data.percents) ) @player = do => player_element = document.createElement('audio') sound_processing.add_to_element(player_element) cs.bus.on('sound-processing/update', -> sound_processing.update_element(player_element) # TODO: uncomment when equalizer will be able to deal with aurora.js # if aurora_player # sound_processing.add_to_element(aurora_player.device.device.node) ) aurora_player = null playing_started = 0 # Change channel type to play in background player_element.mozAudioChannelType = 'content' object_url = null player_element.addEventListener('loadeddata', -> URL.revokeObjectURL(object_url) object_url = null ) player_element.addEventListener('error', => if new Date - playing_started > 1000 @player.pause() else play_with_aurora() ) player_element.addEventListener('ended', => # Pause @play() switch music_settings.repeat when 'one' music_playlist.current (id) => @play(id) else @next() ) player_element.addEventListener('timeupdate', => @update(player_element.currentTime, player_element.duration) ) play_with_aurora = (just_load) => aurora_player = AV.Player.fromURL(object_url) aurora_player.on('ready', -> @device.device.node.context.mozAudioChannelType = 'content' # TODO: uncomment when equalizer will be able to deal with aurora.js # sound_processing.add_to_element(@device.device.node) ) aurora_player.on('end', => # Pause @play() switch music_settings.repeat when 'one' music_playlist.current (id) => @play(id) else @next() ) aurora_player.on('duration', (duration) -> duration /= 1000 aurora_player.on('progress', -> @update(aurora_player.currentTime / 1000, duration) ) ) if !just_load aurora_player.play() return { open_new_file : (blob, filename, just_load) -> playing_started = new Date if @playing @pause() if aurora_player aurora_player.stop() aurora_player = null if object_url URL.revokeObjectURL(object_url) object_url = URL.createObjectURL(blob) if filename.substr(0, -4) == 'alac' || filename.substr(0, -4) == 'alac.mp3' play_with_aurora(just_load) else player_element.src = object_url player_element.load() this.file_loaded = true if !just_load player_element.play() @playing = true play : -> playing_started = new Date if aurora_player aurora_player.play() else player_element.play() @playing = true pause : -> if aurora_player aurora_player.pause() else player_element.pause() @playing = false seeking : (percents) => if aurora_player aurora_player.seek(aurora_player.duration * percents / 100) else if player_element.duration player_element.pause() player_element.currentTime = player_element.duration * percents / 100 if cs.bus.state.player == 'playing' player_element.play() else @play() } @play(null, null, true) update : (current_time, duration) -> progress_percentage = if duration then current_time / duration * 100 else 0 if progress_percentage != seeking_bar.progress_percentage && progress_percentage >= 0 && progress_percentage <= 100 && !isNaN(progress_percentage) seeking_bar.progress_percentage = progress_percentage current_time = time_format(current_time) if current_time != seeking_bar.current_time seeking_bar.current_time = current_time duration = if duration then time_format(duration) else '00:00' if duration != seeking_bar.duration seeking_bar.duration = duration play : (id, callback, just_load) -> id = if !isNaN(parseInt(id)) then id else undefined if typeof callback != 'function' callback = -> else callback.bind(@) element = @ play_button = element.shadowRoot.querySelector('[icon=play]') if @player.file_loaded && !id if @player.playing @player.pause() play_button.icon = 'play' cs.bus.trigger('player/pause') cs.bus.state.player = 'paused' else @player.play() play_button.icon = 'pause' cs.bus.trigger('player/resume') cs.bus.state.player = 'playing' else if id music_library.get(id, (data) -> get_file = music_storage.get(data.name) get_file.onsuccess = -> blob = @result element.player.open_new_file(blob, data.name, just_load) do -> if !just_load play_button.icon = 'pause' cs.bus.trigger('player/play', id) cs.bus.state.player = 'playing' music_library.get_meta(id, (data) -> if data element.title = data.title || _('unknown') element.artist = data.artist if data.artist && data.album element.artist += ": #{data.album}" else element.title = _('unknown') element.artist = '' ) update_cover = (cover) -> cover = cover || 'img/bg.jpg' if body.style.backgroundImage != "url(#{cover})" cs_cover = element.shadowRoot.querySelector('cs-cover') cs_cover.style.backgroundImage = "url(#{cover})" # No blurring in low performance mode if music_settings.low_performance body.style.backgroundImage = "url(#{cover})" else # Resize cover to needed size to decrease memory consumption and speed-up blurring resize_image( cover Math.max(cs_cover.clientHeight, cs_cover.clientWidth) (cover) -> # Start blurring of resized image el = document.createElement('div') new Blur( el : el path : cover radius : 10 callback : -> body.style.backgroundImage = el.style.backgroundImage setTimeout (-> URL.revokeObjectURL(cover) ), 500 callback() ) ) parseAudioMetadata( blob (metadata) -> cover = metadata.picture if cover cover = URL.createObjectURL(cover) update_cover(cover) -> update_cover('img/bg.jpg') ) get_file.onerror = (e) -> alert _( 'cant-play-this-file' error : e.target.error.name ) ) else music_playlist.current (id) => @play(id, callback, just_load) prev : (callback) -> music_playlist.prev (id) => @play(id, callback) next : (callback) -> music_playlist.next (id) => @play(id, callback) menu : -> @go_to_screen('menu') seeking : (percents) -> @player.seeking(percents) )
true
###* * @package CleverStyle Music * @category Web Components * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * @copyright Copyright (c) 2014-2015, PI:NAME:<NAME>END_PI * @license MIT License, see license.txt ### music_storage = navigator.getDeviceStorage('music') sound_processing = cs.sound_processing music_library = cs.music_library music_playlist = cs.music_playlist music_settings = cs.music_settings body = document.querySelector('body') seeking_bar = null update_cover_timeout = 0 resize_image = (src, max_size, callback) -> image = new Image image.onload = -> canvas = document.createElement('canvas') if image.height > max_size || image.width > max_size image.width *= max_size / image.height image.height = max_size ctx = canvas.getContext('2d') ctx.clearRect(0, 0, canvas.width, canvas.height) canvas.width = image.width canvas.height = image.height ctx.mozImageSmoothingEnabled = false; ctx.drawImage(image, 0, 0, image.width, image.height) callback(canvas.toDataURL()) image.src = src Polymer( 'cs-music-player' title : '' artist : '' ready : -> seeking_bar = @shadowRoot.querySelector('cs-seeking-bar') $(seeking_bar).on('seeking-update', (e, data) => @seeking(data.percents) ) @player = do => player_element = document.createElement('audio') sound_processing.add_to_element(player_element) cs.bus.on('sound-processing/update', -> sound_processing.update_element(player_element) # TODO: uncomment when equalizer will be able to deal with aurora.js # if aurora_player # sound_processing.add_to_element(aurora_player.device.device.node) ) aurora_player = null playing_started = 0 # Change channel type to play in background player_element.mozAudioChannelType = 'content' object_url = null player_element.addEventListener('loadeddata', -> URL.revokeObjectURL(object_url) object_url = null ) player_element.addEventListener('error', => if new Date - playing_started > 1000 @player.pause() else play_with_aurora() ) player_element.addEventListener('ended', => # Pause @play() switch music_settings.repeat when 'one' music_playlist.current (id) => @play(id) else @next() ) player_element.addEventListener('timeupdate', => @update(player_element.currentTime, player_element.duration) ) play_with_aurora = (just_load) => aurora_player = AV.Player.fromURL(object_url) aurora_player.on('ready', -> @device.device.node.context.mozAudioChannelType = 'content' # TODO: uncomment when equalizer will be able to deal with aurora.js # sound_processing.add_to_element(@device.device.node) ) aurora_player.on('end', => # Pause @play() switch music_settings.repeat when 'one' music_playlist.current (id) => @play(id) else @next() ) aurora_player.on('duration', (duration) -> duration /= 1000 aurora_player.on('progress', -> @update(aurora_player.currentTime / 1000, duration) ) ) if !just_load aurora_player.play() return { open_new_file : (blob, filename, just_load) -> playing_started = new Date if @playing @pause() if aurora_player aurora_player.stop() aurora_player = null if object_url URL.revokeObjectURL(object_url) object_url = URL.createObjectURL(blob) if filename.substr(0, -4) == 'alac' || filename.substr(0, -4) == 'alac.mp3' play_with_aurora(just_load) else player_element.src = object_url player_element.load() this.file_loaded = true if !just_load player_element.play() @playing = true play : -> playing_started = new Date if aurora_player aurora_player.play() else player_element.play() @playing = true pause : -> if aurora_player aurora_player.pause() else player_element.pause() @playing = false seeking : (percents) => if aurora_player aurora_player.seek(aurora_player.duration * percents / 100) else if player_element.duration player_element.pause() player_element.currentTime = player_element.duration * percents / 100 if cs.bus.state.player == 'playing' player_element.play() else @play() } @play(null, null, true) update : (current_time, duration) -> progress_percentage = if duration then current_time / duration * 100 else 0 if progress_percentage != seeking_bar.progress_percentage && progress_percentage >= 0 && progress_percentage <= 100 && !isNaN(progress_percentage) seeking_bar.progress_percentage = progress_percentage current_time = time_format(current_time) if current_time != seeking_bar.current_time seeking_bar.current_time = current_time duration = if duration then time_format(duration) else '00:00' if duration != seeking_bar.duration seeking_bar.duration = duration play : (id, callback, just_load) -> id = if !isNaN(parseInt(id)) then id else undefined if typeof callback != 'function' callback = -> else callback.bind(@) element = @ play_button = element.shadowRoot.querySelector('[icon=play]') if @player.file_loaded && !id if @player.playing @player.pause() play_button.icon = 'play' cs.bus.trigger('player/pause') cs.bus.state.player = 'paused' else @player.play() play_button.icon = 'pause' cs.bus.trigger('player/resume') cs.bus.state.player = 'playing' else if id music_library.get(id, (data) -> get_file = music_storage.get(data.name) get_file.onsuccess = -> blob = @result element.player.open_new_file(blob, data.name, just_load) do -> if !just_load play_button.icon = 'pause' cs.bus.trigger('player/play', id) cs.bus.state.player = 'playing' music_library.get_meta(id, (data) -> if data element.title = data.title || _('unknown') element.artist = data.artist if data.artist && data.album element.artist += ": #{data.album}" else element.title = _('unknown') element.artist = '' ) update_cover = (cover) -> cover = cover || 'img/bg.jpg' if body.style.backgroundImage != "url(#{cover})" cs_cover = element.shadowRoot.querySelector('cs-cover') cs_cover.style.backgroundImage = "url(#{cover})" # No blurring in low performance mode if music_settings.low_performance body.style.backgroundImage = "url(#{cover})" else # Resize cover to needed size to decrease memory consumption and speed-up blurring resize_image( cover Math.max(cs_cover.clientHeight, cs_cover.clientWidth) (cover) -> # Start blurring of resized image el = document.createElement('div') new Blur( el : el path : cover radius : 10 callback : -> body.style.backgroundImage = el.style.backgroundImage setTimeout (-> URL.revokeObjectURL(cover) ), 500 callback() ) ) parseAudioMetadata( blob (metadata) -> cover = metadata.picture if cover cover = URL.createObjectURL(cover) update_cover(cover) -> update_cover('img/bg.jpg') ) get_file.onerror = (e) -> alert _( 'cant-play-this-file' error : e.target.error.name ) ) else music_playlist.current (id) => @play(id, callback, just_load) prev : (callback) -> music_playlist.prev (id) => @play(id, callback) next : (callback) -> music_playlist.next (id) => @play(id, callback) menu : -> @go_to_screen('menu') seeking : (percents) -> @player.seeking(percents) )
[ { "context": " debug: debug\n\n client.setAccessToken('abcde')\n\n assert client.accessToken is 'abcd", "end": 556, "score": 0.9469712972640991, "start": 551, "tag": "KEY", "value": "abcde" }, { "context": "bcde')\n\n assert client.accessToken is 'abc...
spec/loopback-client.coffee
CureApp/loopback-promised
10
LoopbackPromised = require '../src/loopback-promised' LoopbackClient = require '../src/loopback-client' LoopbackUserClient = require '../src/loopback-user-client' before -> @timeout 5000 require('./init') debug = true baseURL = 'localhost:4157/test-api' lbPromised = LoopbackPromised.createInstance baseURL: baseURL describe 'LoopbackClient', -> describe 'setAccessToken', -> it 'sets access token', -> client = lbPromised.createClient 'notebooks', debug: debug client.setAccessToken('abcde') assert client.accessToken is 'abcde' describe 'create', -> it 'creates an item', -> client = lbPromised.createClient 'notebooks', debug: debug client.create( name: 'Computer Science' options: version: 2 references: ['The Elements of Statistical Learning'] ).then (responseBody) -> assert responseBody.name is 'Computer Science' assert responseBody.options? assert responseBody.options.version is 2 assert responseBody.options.references.length is 1 it 'creates items when array is given', -> client = lbPromised.createClient 'notebooks', debug: debug client.create([ { name: 'Physics' } { name: 'Japanese' } { name: 'JavaScript'} ]).then (results) -> assert results instanceof Array assert results.length is 3 assert result.name? for result in results describe 'count', -> it 'counts items', -> client = lbPromised.createClient 'notebooks', debug: debug client.count().then (num) -> assert num is 4 it 'counts items with condition', -> client = lbPromised.createClient 'notebooks', debug: debug where = name: 'Computer Science' client.count(where).then (num) -> assert num is 1 it 'counts no items when no matching items', -> client = lbPromised.createClient 'notebooks', debug: debug where = name: 'Philosophy' client.count(where).then (num) -> assert num is 0 describe 'upsert', -> newId = null client = lbPromised.createClient 'notebooks', debug: debug it 'creates when not exists', -> client.upsert(name: 'Genetics', genre: 'Biology').then (responseBody) -> assert responseBody.id? assert responseBody.name is 'Genetics' assert responseBody.genre is 'Biology' newId = responseBody.id it 'updates when id exists', -> client.upsert(id: newId, name: 'BioGenetics', difficulty: 'difficult').then (responseBody) -> assert responseBody.id is newId assert responseBody.name is 'BioGenetics' assert responseBody.genre is 'Biology' assert responseBody.difficulty is 'difficult' describe 'exists', -> client = lbPromised.createClient 'notebooks', debug: debug existingId = null notExistingId = 'abcd' before -> client.findOne(where: name: 'JavaScript').then (notebook) -> existingId = notebook.id it 'returns false when not exists', -> client.exists(notExistingId).then (responseBody) -> assert responseBody.exists is false it 'returns true when exists', -> client.exists(existingId).then (responseBody) -> assert responseBody.exists is true describe 'findById', -> existingId = null notExistingId = 'abcd' beforeEach -> @client = lbPromised.createClient 'notebooks', debug: debug @client.findOne(where: name: 'JavaScript').then (notebook) -> existingId = notebook.id it 'returns error when not exists', -> @client.findById(notExistingId).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.code is 'MODEL_NOT_FOUND' assert err.isLoopbackResponseError is true ) it 'returns object when exists', -> @client.findById(existingId).then (responseBody) -> assert responseBody.name is 'JavaScript' it 'timeouts when timeout property is given and exceeds', -> @client.timeout = 1 @client.findById(existingId).catch (e) -> assert e.message.match /timeout/ describe 'find', -> client = lbPromised.createClient 'notebooks', debug: debug it 'returns all models when filter is not set', -> client.find().then (responseBody) -> assert responseBody instanceof Array assert responseBody.length > 4 it 'returns specific field(s) when fields filter is set', -> client.find(fields: 'name').then (responseBody) -> assert responseBody instanceof Array assert responseBody.length > 4 for item in responseBody assert Object.keys(item).length is 1 assert item.name? it 'can set limit', -> client.find(limit: 3).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 3 it 'can set skip', -> Promise.all([ client.find(limit: 2) client.find(limit: 1, skip: 1) ]).then (results) -> assert results[0][1].name is results[1][0].name it 'can set order. default order is ASC', -> client.find(order: 'name').then (responseBody) -> assert responseBody instanceof Array prevName = null for item in responseBody if prevName? assert (item.name > prevName) is true prevName = item.name it 'can set order DESC', -> client.find(order: 'name DESC').then (responseBody) -> assert responseBody instanceof Array prevName = null for item in responseBody if prevName? assert (item.name < prevName) is true prevName = item.name it 'can set order ASC', -> client.find(order: 'name ASC').then (responseBody) -> assert responseBody instanceof Array prevName = null for item in responseBody if prevName? assert (item.name > prevName) is true prevName = item.name it 'can set where (null)', -> client.find(where: null).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 0 it 'can set where (equals)', -> client.find(where: name: 'Physics').then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 1 assert responseBody[0].name is 'Physics' it 'can set where (or)', -> client.find(order: 'name', where: or: [{name: 'Physics'}, {name: 'BioGenetics'}]).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 2 assert responseBody[0].name is 'BioGenetics' assert responseBody[1].name is 'Physics' it 'can set where (key: null)', -> client.find(where: difficulty: null).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 4 it 'can set where (key: undefined)', -> client.find(where: difficulty: undefined).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 0 it 'can set where (implicit "and")', -> client.find(order: 'name', where: name: 'BioGenetics', difficulty: 'difficult').then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 1 assert responseBody[0].name is 'BioGenetics' it 'can set where (explicit "and")', -> client.find(order: 'name', where: and: [{name: 'BioGenetics'}, {difficulty: 'difficult'}]).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 1 assert responseBody[0].name is 'BioGenetics' it 'can set where (greater than, less than)', -> client.find(order: 'name', where: and: [{name: gt: 'Ja'}, {name: lt: 'K'}]).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 2 assert responseBody[0].name is 'Japanese' assert responseBody[1].name is 'JavaScript' it 'can set where (like)', -> client.find(order: 'name', where: name: like: "ic").then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 2 assert responseBody[0].name is 'BioGenetics' assert responseBody[1].name is 'Physics' describe 'findOne', -> client = lbPromised.createClient 'notebooks', debug: debug it 'can get one result', -> client.findOne(order: 'name', where: name: like: "ic").then (responseBody) -> assert responseBody.name is 'BioGenetics' it 'gets null when not match', -> client.findOne(order: 'name', where: name: like: "xxx").then (responseBody) -> assert not responseBody? describe 'destroyById', -> client = lbPromised.createClient 'notebooks', debug: debug idToDestroy = null wrongId = 'abcde' before -> client.create(name: 'xxxxx').then (notebook) -> idToDestroy = notebook.id it 'returns 200 and count information is returned', -> client.destroyById(wrongId).then (responseBody) -> assert responseBody.count is 0 it 'destroys a model with id', -> client.destroyById(idToDestroy).then (responseBody) -> assert responseBody.count is 1 client.exists(idToDestroy).then (responseBody) -> assert responseBody.exists is false describe 'destroy', -> client = lbPromised.createClient 'notebooks', debug: debug modelToDestroy = null before -> client.create(name: 'xxxxx').then (notebook) -> modelToDestroy = notebook it 'destroys a model', -> client.destroy(modelToDestroy).then (responseBody) -> assert responseBody.count is 1 client.exists(modelToDestroy.id).then (responseBody) -> assert responseBody.exists is false describe 'updateAttributes', -> client = lbPromised.createClient 'notebooks', debug: debug existingId = null notExistingId = 'abcd' before -> client.findOne(where: name: 'JavaScript').then (notebook) -> existingId = notebook.id it 'returns error when id is invalid', -> data = version: 2 client.updateAttributes(notExistingId, data).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.code is 'MODEL_NOT_FOUND' assert err.isLoopbackResponseError is true ) it 'returns updated model when id is valid', -> data = version: 2 client.updateAttributes(existingId, data).then (responseBody) -> assert responseBody.id is existingId assert responseBody.name is 'JavaScript' assert responseBody.version is 2 describe 'updateAll', -> client = lbPromised.createClient 'notebooks', debug: debug it 'updates all matched models', -> where = name: like: 'ic' data = isAcademic: true isScientific: true # TODO: this is the spec of Loopback (they return 204). We should take this into account or change the API client.updateAll(where, data).then (responseBody) -> assert responseBody.count is 2 client.find(order: 'name', where: {isAcademic: true, isScientific: true}).then (results) -> assert results instanceof Array assert results.length is 2 assert results[0].name is 'BioGenetics' assert results[1].name is 'Physics'
49360
LoopbackPromised = require '../src/loopback-promised' LoopbackClient = require '../src/loopback-client' LoopbackUserClient = require '../src/loopback-user-client' before -> @timeout 5000 require('./init') debug = true baseURL = 'localhost:4157/test-api' lbPromised = LoopbackPromised.createInstance baseURL: baseURL describe 'LoopbackClient', -> describe 'setAccessToken', -> it 'sets access token', -> client = lbPromised.createClient 'notebooks', debug: debug client.setAccessToken('<KEY>') assert client.accessToken is '<KEY>' describe 'create', -> it 'creates an item', -> client = lbPromised.createClient 'notebooks', debug: debug client.create( name: 'Computer Science' options: version: 2 references: ['The Elements of Statistical Learning'] ).then (responseBody) -> assert responseBody.name is 'Computer Science' assert responseBody.options? assert responseBody.options.version is 2 assert responseBody.options.references.length is 1 it 'creates items when array is given', -> client = lbPromised.createClient 'notebooks', debug: debug client.create([ { name: 'Physics' } { name: 'Japanese' } { name: 'JavaScript'} ]).then (results) -> assert results instanceof Array assert results.length is 3 assert result.name? for result in results describe 'count', -> it 'counts items', -> client = lbPromised.createClient 'notebooks', debug: debug client.count().then (num) -> assert num is 4 it 'counts items with condition', -> client = lbPromised.createClient 'notebooks', debug: debug where = name: 'Computer Science' client.count(where).then (num) -> assert num is 1 it 'counts no items when no matching items', -> client = lbPromised.createClient 'notebooks', debug: debug where = name: 'Philosophy' client.count(where).then (num) -> assert num is 0 describe 'upsert', -> newId = null client = lbPromised.createClient 'notebooks', debug: debug it 'creates when not exists', -> client.upsert(name: 'Genetics', genre: 'Biology').then (responseBody) -> assert responseBody.id? assert responseBody.name is 'Genetics' assert responseBody.genre is 'Biology' newId = responseBody.id it 'updates when id exists', -> client.upsert(id: newId, name: 'BioGenetics', difficulty: 'difficult').then (responseBody) -> assert responseBody.id is newId assert responseBody.name is 'BioGenetics' assert responseBody.genre is 'Biology' assert responseBody.difficulty is 'difficult' describe 'exists', -> client = lbPromised.createClient 'notebooks', debug: debug existingId = null notExistingId = 'abcd' before -> client.findOne(where: name: 'JavaScript').then (notebook) -> existingId = notebook.id it 'returns false when not exists', -> client.exists(notExistingId).then (responseBody) -> assert responseBody.exists is false it 'returns true when exists', -> client.exists(existingId).then (responseBody) -> assert responseBody.exists is true describe 'findById', -> existingId = null notExistingId = 'abcd' beforeEach -> @client = lbPromised.createClient 'notebooks', debug: debug @client.findOne(where: name: 'JavaScript').then (notebook) -> existingId = notebook.id it 'returns error when not exists', -> @client.findById(notExistingId).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.code is 'MODEL_NOT_FOUND' assert err.isLoopbackResponseError is true ) it 'returns object when exists', -> @client.findById(existingId).then (responseBody) -> assert responseBody.name is 'JavaScript' it 'timeouts when timeout property is given and exceeds', -> @client.timeout = 1 @client.findById(existingId).catch (e) -> assert e.message.match /timeout/ describe 'find', -> client = lbPromised.createClient 'notebooks', debug: debug it 'returns all models when filter is not set', -> client.find().then (responseBody) -> assert responseBody instanceof Array assert responseBody.length > 4 it 'returns specific field(s) when fields filter is set', -> client.find(fields: 'name').then (responseBody) -> assert responseBody instanceof Array assert responseBody.length > 4 for item in responseBody assert Object.keys(item).length is 1 assert item.name? it 'can set limit', -> client.find(limit: 3).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 3 it 'can set skip', -> Promise.all([ client.find(limit: 2) client.find(limit: 1, skip: 1) ]).then (results) -> assert results[0][1].name is results[1][0].name it 'can set order. default order is ASC', -> client.find(order: 'name').then (responseBody) -> assert responseBody instanceof Array prevName = null for item in responseBody if prevName? assert (item.name > prevName) is true prevName = item.name it 'can set order DESC', -> client.find(order: 'name DESC').then (responseBody) -> assert responseBody instanceof Array prevName = null for item in responseBody if prevName? assert (item.name < prevName) is true prevName = item.name it 'can set order ASC', -> client.find(order: 'name ASC').then (responseBody) -> assert responseBody instanceof Array prevName = null for item in responseBody if prevName? assert (item.name > prevName) is true prevName = item.name it 'can set where (null)', -> client.find(where: null).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 0 it 'can set where (equals)', -> client.find(where: name: 'Physics').then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 1 assert responseBody[0].name is 'Physics' it 'can set where (or)', -> client.find(order: 'name', where: or: [{name: 'Physics'}, {name: 'BioGenetics'}]).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 2 assert responseBody[0].name is 'BioGenetics' assert responseBody[1].name is 'Physics' it 'can set where (key: null)', -> client.find(where: difficulty: null).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 4 it 'can set where (key: undefined)', -> client.find(where: difficulty: undefined).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 0 it 'can set where (implicit "and")', -> client.find(order: 'name', where: name: 'BioGenetics', difficulty: 'difficult').then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 1 assert responseBody[0].name is 'BioGenetics' it 'can set where (explicit "and")', -> client.find(order: 'name', where: and: [{name: 'BioGenetics'}, {difficulty: 'difficult'}]).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 1 assert responseBody[0].name is 'BioGenetics' it 'can set where (greater than, less than)', -> client.find(order: 'name', where: and: [{name: gt: 'Ja'}, {name: lt: 'K'}]).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 2 assert responseBody[0].name is 'Japanese' assert responseBody[1].name is 'JavaScript' it 'can set where (like)', -> client.find(order: 'name', where: name: like: "ic").then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 2 assert responseBody[0].name is 'BioGenetics' assert responseBody[1].name is 'Physics' describe 'findOne', -> client = lbPromised.createClient 'notebooks', debug: debug it 'can get one result', -> client.findOne(order: 'name', where: name: like: "ic").then (responseBody) -> assert responseBody.name is 'BioGenetics' it 'gets null when not match', -> client.findOne(order: 'name', where: name: like: "xxx").then (responseBody) -> assert not responseBody? describe 'destroyById', -> client = lbPromised.createClient 'notebooks', debug: debug idToDestroy = null wrongId = 'abcde' before -> client.create(name: 'xxxxx').then (notebook) -> idToDestroy = notebook.id it 'returns 200 and count information is returned', -> client.destroyById(wrongId).then (responseBody) -> assert responseBody.count is 0 it 'destroys a model with id', -> client.destroyById(idToDestroy).then (responseBody) -> assert responseBody.count is 1 client.exists(idToDestroy).then (responseBody) -> assert responseBody.exists is false describe 'destroy', -> client = lbPromised.createClient 'notebooks', debug: debug modelToDestroy = null before -> client.create(name: 'xxxxx').then (notebook) -> modelToDestroy = notebook it 'destroys a model', -> client.destroy(modelToDestroy).then (responseBody) -> assert responseBody.count is 1 client.exists(modelToDestroy.id).then (responseBody) -> assert responseBody.exists is false describe 'updateAttributes', -> client = lbPromised.createClient 'notebooks', debug: debug existingId = null notExistingId = 'abcd' before -> client.findOne(where: name: 'JavaScript').then (notebook) -> existingId = notebook.id it 'returns error when id is invalid', -> data = version: 2 client.updateAttributes(notExistingId, data).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.code is 'MODEL_NOT_FOUND' assert err.isLoopbackResponseError is true ) it 'returns updated model when id is valid', -> data = version: 2 client.updateAttributes(existingId, data).then (responseBody) -> assert responseBody.id is existingId assert responseBody.name is 'JavaScript' assert responseBody.version is 2 describe 'updateAll', -> client = lbPromised.createClient 'notebooks', debug: debug it 'updates all matched models', -> where = name: like: 'ic' data = isAcademic: true isScientific: true # TODO: this is the spec of Loopback (they return 204). We should take this into account or change the API client.updateAll(where, data).then (responseBody) -> assert responseBody.count is 2 client.find(order: 'name', where: {isAcademic: true, isScientific: true}).then (results) -> assert results instanceof Array assert results.length is 2 assert results[0].name is 'BioGenetics' assert results[1].name is 'Physics'
true
LoopbackPromised = require '../src/loopback-promised' LoopbackClient = require '../src/loopback-client' LoopbackUserClient = require '../src/loopback-user-client' before -> @timeout 5000 require('./init') debug = true baseURL = 'localhost:4157/test-api' lbPromised = LoopbackPromised.createInstance baseURL: baseURL describe 'LoopbackClient', -> describe 'setAccessToken', -> it 'sets access token', -> client = lbPromised.createClient 'notebooks', debug: debug client.setAccessToken('PI:KEY:<KEY>END_PI') assert client.accessToken is 'PI:KEY:<KEY>END_PI' describe 'create', -> it 'creates an item', -> client = lbPromised.createClient 'notebooks', debug: debug client.create( name: 'Computer Science' options: version: 2 references: ['The Elements of Statistical Learning'] ).then (responseBody) -> assert responseBody.name is 'Computer Science' assert responseBody.options? assert responseBody.options.version is 2 assert responseBody.options.references.length is 1 it 'creates items when array is given', -> client = lbPromised.createClient 'notebooks', debug: debug client.create([ { name: 'Physics' } { name: 'Japanese' } { name: 'JavaScript'} ]).then (results) -> assert results instanceof Array assert results.length is 3 assert result.name? for result in results describe 'count', -> it 'counts items', -> client = lbPromised.createClient 'notebooks', debug: debug client.count().then (num) -> assert num is 4 it 'counts items with condition', -> client = lbPromised.createClient 'notebooks', debug: debug where = name: 'Computer Science' client.count(where).then (num) -> assert num is 1 it 'counts no items when no matching items', -> client = lbPromised.createClient 'notebooks', debug: debug where = name: 'Philosophy' client.count(where).then (num) -> assert num is 0 describe 'upsert', -> newId = null client = lbPromised.createClient 'notebooks', debug: debug it 'creates when not exists', -> client.upsert(name: 'Genetics', genre: 'Biology').then (responseBody) -> assert responseBody.id? assert responseBody.name is 'Genetics' assert responseBody.genre is 'Biology' newId = responseBody.id it 'updates when id exists', -> client.upsert(id: newId, name: 'BioGenetics', difficulty: 'difficult').then (responseBody) -> assert responseBody.id is newId assert responseBody.name is 'BioGenetics' assert responseBody.genre is 'Biology' assert responseBody.difficulty is 'difficult' describe 'exists', -> client = lbPromised.createClient 'notebooks', debug: debug existingId = null notExistingId = 'abcd' before -> client.findOne(where: name: 'JavaScript').then (notebook) -> existingId = notebook.id it 'returns false when not exists', -> client.exists(notExistingId).then (responseBody) -> assert responseBody.exists is false it 'returns true when exists', -> client.exists(existingId).then (responseBody) -> assert responseBody.exists is true describe 'findById', -> existingId = null notExistingId = 'abcd' beforeEach -> @client = lbPromised.createClient 'notebooks', debug: debug @client.findOne(where: name: 'JavaScript').then (notebook) -> existingId = notebook.id it 'returns error when not exists', -> @client.findById(notExistingId).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.code is 'MODEL_NOT_FOUND' assert err.isLoopbackResponseError is true ) it 'returns object when exists', -> @client.findById(existingId).then (responseBody) -> assert responseBody.name is 'JavaScript' it 'timeouts when timeout property is given and exceeds', -> @client.timeout = 1 @client.findById(existingId).catch (e) -> assert e.message.match /timeout/ describe 'find', -> client = lbPromised.createClient 'notebooks', debug: debug it 'returns all models when filter is not set', -> client.find().then (responseBody) -> assert responseBody instanceof Array assert responseBody.length > 4 it 'returns specific field(s) when fields filter is set', -> client.find(fields: 'name').then (responseBody) -> assert responseBody instanceof Array assert responseBody.length > 4 for item in responseBody assert Object.keys(item).length is 1 assert item.name? it 'can set limit', -> client.find(limit: 3).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 3 it 'can set skip', -> Promise.all([ client.find(limit: 2) client.find(limit: 1, skip: 1) ]).then (results) -> assert results[0][1].name is results[1][0].name it 'can set order. default order is ASC', -> client.find(order: 'name').then (responseBody) -> assert responseBody instanceof Array prevName = null for item in responseBody if prevName? assert (item.name > prevName) is true prevName = item.name it 'can set order DESC', -> client.find(order: 'name DESC').then (responseBody) -> assert responseBody instanceof Array prevName = null for item in responseBody if prevName? assert (item.name < prevName) is true prevName = item.name it 'can set order ASC', -> client.find(order: 'name ASC').then (responseBody) -> assert responseBody instanceof Array prevName = null for item in responseBody if prevName? assert (item.name > prevName) is true prevName = item.name it 'can set where (null)', -> client.find(where: null).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 0 it 'can set where (equals)', -> client.find(where: name: 'Physics').then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 1 assert responseBody[0].name is 'Physics' it 'can set where (or)', -> client.find(order: 'name', where: or: [{name: 'Physics'}, {name: 'BioGenetics'}]).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 2 assert responseBody[0].name is 'BioGenetics' assert responseBody[1].name is 'Physics' it 'can set where (key: null)', -> client.find(where: difficulty: null).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 4 it 'can set where (key: undefined)', -> client.find(where: difficulty: undefined).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 0 it 'can set where (implicit "and")', -> client.find(order: 'name', where: name: 'BioGenetics', difficulty: 'difficult').then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 1 assert responseBody[0].name is 'BioGenetics' it 'can set where (explicit "and")', -> client.find(order: 'name', where: and: [{name: 'BioGenetics'}, {difficulty: 'difficult'}]).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 1 assert responseBody[0].name is 'BioGenetics' it 'can set where (greater than, less than)', -> client.find(order: 'name', where: and: [{name: gt: 'Ja'}, {name: lt: 'K'}]).then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 2 assert responseBody[0].name is 'Japanese' assert responseBody[1].name is 'JavaScript' it 'can set where (like)', -> client.find(order: 'name', where: name: like: "ic").then (responseBody) -> assert responseBody instanceof Array assert responseBody.length is 2 assert responseBody[0].name is 'BioGenetics' assert responseBody[1].name is 'Physics' describe 'findOne', -> client = lbPromised.createClient 'notebooks', debug: debug it 'can get one result', -> client.findOne(order: 'name', where: name: like: "ic").then (responseBody) -> assert responseBody.name is 'BioGenetics' it 'gets null when not match', -> client.findOne(order: 'name', where: name: like: "xxx").then (responseBody) -> assert not responseBody? describe 'destroyById', -> client = lbPromised.createClient 'notebooks', debug: debug idToDestroy = null wrongId = 'abcde' before -> client.create(name: 'xxxxx').then (notebook) -> idToDestroy = notebook.id it 'returns 200 and count information is returned', -> client.destroyById(wrongId).then (responseBody) -> assert responseBody.count is 0 it 'destroys a model with id', -> client.destroyById(idToDestroy).then (responseBody) -> assert responseBody.count is 1 client.exists(idToDestroy).then (responseBody) -> assert responseBody.exists is false describe 'destroy', -> client = lbPromised.createClient 'notebooks', debug: debug modelToDestroy = null before -> client.create(name: 'xxxxx').then (notebook) -> modelToDestroy = notebook it 'destroys a model', -> client.destroy(modelToDestroy).then (responseBody) -> assert responseBody.count is 1 client.exists(modelToDestroy.id).then (responseBody) -> assert responseBody.exists is false describe 'updateAttributes', -> client = lbPromised.createClient 'notebooks', debug: debug existingId = null notExistingId = 'abcd' before -> client.findOne(where: name: 'JavaScript').then (notebook) -> existingId = notebook.id it 'returns error when id is invalid', -> data = version: 2 client.updateAttributes(notExistingId, data).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.code is 'MODEL_NOT_FOUND' assert err.isLoopbackResponseError is true ) it 'returns updated model when id is valid', -> data = version: 2 client.updateAttributes(existingId, data).then (responseBody) -> assert responseBody.id is existingId assert responseBody.name is 'JavaScript' assert responseBody.version is 2 describe 'updateAll', -> client = lbPromised.createClient 'notebooks', debug: debug it 'updates all matched models', -> where = name: like: 'ic' data = isAcademic: true isScientific: true # TODO: this is the spec of Loopback (they return 204). We should take this into account or change the API client.updateAll(where, data).then (responseBody) -> assert responseBody.count is 2 client.find(order: 'name', where: {isAcademic: true, isScientific: true}).then (results) -> assert results instanceof Array assert results.length is 2 assert results[0].name is 'BioGenetics' assert results[1].name is 'Physics'
[ { "context": "learPasscode()\n # TODO remove\n @passcode = 'testsecret'\n\n # session length is in minutes\n setPasscode:", "end": 338, "score": 0.9992771148681641, "start": 328, "tag": "PASSWORD", "value": "testsecret" } ]
utils/encservice.coffee
jiangts/EncJournal
0
EncLayer = require './enclayer' FSLayer = require './fslayer' path = require 'path' # High level APIs to be called by enc-cli and the web app class EncService constructor: (@rootDir, @promptPasscode) -> @fs = new FSLayer(@rootDir) @enc = new EncLayer(@rootDir) @clearPasscode() # TODO remove @passcode = 'testsecret' # session length is in minutes setPasscode: (@passcode, sessionLength = 1000 * 60 * 10) -> now = new Date() @expireDate = new Date() @expireDate.setTime(now.getTime() + sessionLength) now = null checkValidPasscode: () -> if not @passcode? or new Date() > @expireDate @clearPasscode() @promptPasscode() return false return true clearPasscode: -> @passcode = null listEncFiles: (dirpath, callback) -> @checkValidPasscode() @fs.listFiles(dirpath, (error, data) => for file, i in data if path.extname file is '.enc' data[i] = @enc.decrypt(text, @passcode, 'hex') callback(error, data) ) createEncFile: (dirpath, filename, content) -> @checkValidPasscode() filename = @enc.encrypt(filename, @passcode, 'hex') + '.enc' content = @enc.encrypt(content, @passcode) @fs.createFile(path.join(dirpath, filename), content) readEncFile: (dirpath, filename, callback) -> @checkValidPasscode() @fs.readFile(path.join(dirpath, filename), (error, data) => if error then return callback(error, null, null) data = @enc.decrypt(data, @passcode) filename = @enc.decrypt(filename, @passcode, 'hex') callback(error, filename, data) ) updateEncFile: (dirpath, filename, content) -> @checkValidPasscode() @fs.updateFile(path.join dirpath, filename, content) module.exports = EncService
186068
EncLayer = require './enclayer' FSLayer = require './fslayer' path = require 'path' # High level APIs to be called by enc-cli and the web app class EncService constructor: (@rootDir, @promptPasscode) -> @fs = new FSLayer(@rootDir) @enc = new EncLayer(@rootDir) @clearPasscode() # TODO remove @passcode = '<PASSWORD>' # session length is in minutes setPasscode: (@passcode, sessionLength = 1000 * 60 * 10) -> now = new Date() @expireDate = new Date() @expireDate.setTime(now.getTime() + sessionLength) now = null checkValidPasscode: () -> if not @passcode? or new Date() > @expireDate @clearPasscode() @promptPasscode() return false return true clearPasscode: -> @passcode = null listEncFiles: (dirpath, callback) -> @checkValidPasscode() @fs.listFiles(dirpath, (error, data) => for file, i in data if path.extname file is '.enc' data[i] = @enc.decrypt(text, @passcode, 'hex') callback(error, data) ) createEncFile: (dirpath, filename, content) -> @checkValidPasscode() filename = @enc.encrypt(filename, @passcode, 'hex') + '.enc' content = @enc.encrypt(content, @passcode) @fs.createFile(path.join(dirpath, filename), content) readEncFile: (dirpath, filename, callback) -> @checkValidPasscode() @fs.readFile(path.join(dirpath, filename), (error, data) => if error then return callback(error, null, null) data = @enc.decrypt(data, @passcode) filename = @enc.decrypt(filename, @passcode, 'hex') callback(error, filename, data) ) updateEncFile: (dirpath, filename, content) -> @checkValidPasscode() @fs.updateFile(path.join dirpath, filename, content) module.exports = EncService
true
EncLayer = require './enclayer' FSLayer = require './fslayer' path = require 'path' # High level APIs to be called by enc-cli and the web app class EncService constructor: (@rootDir, @promptPasscode) -> @fs = new FSLayer(@rootDir) @enc = new EncLayer(@rootDir) @clearPasscode() # TODO remove @passcode = 'PI:PASSWORD:<PASSWORD>END_PI' # session length is in minutes setPasscode: (@passcode, sessionLength = 1000 * 60 * 10) -> now = new Date() @expireDate = new Date() @expireDate.setTime(now.getTime() + sessionLength) now = null checkValidPasscode: () -> if not @passcode? or new Date() > @expireDate @clearPasscode() @promptPasscode() return false return true clearPasscode: -> @passcode = null listEncFiles: (dirpath, callback) -> @checkValidPasscode() @fs.listFiles(dirpath, (error, data) => for file, i in data if path.extname file is '.enc' data[i] = @enc.decrypt(text, @passcode, 'hex') callback(error, data) ) createEncFile: (dirpath, filename, content) -> @checkValidPasscode() filename = @enc.encrypt(filename, @passcode, 'hex') + '.enc' content = @enc.encrypt(content, @passcode) @fs.createFile(path.join(dirpath, filename), content) readEncFile: (dirpath, filename, callback) -> @checkValidPasscode() @fs.readFile(path.join(dirpath, filename), (error, data) => if error then return callback(error, null, null) data = @enc.decrypt(data, @passcode) filename = @enc.decrypt(filename, @passcode, 'hex') callback(error, filename, data) ) updateEncFile: (dirpath, filename, content) -> @checkValidPasscode() @fs.updateFile(path.join dirpath, filename, content) module.exports = EncService
[ { "context": "\napiKey = \"eb34bd67.megadroneshare\"\n\n# A deep merge of two objects (as opposed to th", "end": 34, "score": 0.9997179508209229, "start": 11, "tag": "KEY", "value": "eb34bd67.megadroneshare" }, { "context": "eader per RFC2617 Authorization: DroneApi apikey=\"blah.bla...
src/scripts/services/dapiServices.coffee
SecureCloud-biz/droneshare
41
apiKey = "eb34bd67.megadroneshare" # A deep merge of two objects (as opposed to the shallow merge from angular.extend) merge = (obj1, obj2) -> result = {} # (kinda non ideomatic, but oh well) for k, v of obj1 newv = if (k of obj2) && (typeof v == "object") merge(v, obj2[k]) # if an object merge else v result[k] = newv for k, v of obj2 # add missing keys if !(k of result) result[k] = v result atmosphereOptions = contentType : 'application/json' transport : 'websocket' connectTimeout : 10000 # 10s timeout before fallback to streaming reconnectInterval : 30000 enableXDR: true timeout : 60000 pollingInterval : 5000 fallbackTransport: 'long-polling' # Server might has issues with 'long-polling' headers: api_key: apiKey #onError: (resp) => # @log.error("Atmosphere error: #{resp}") #onTransportFailure: (msg, resp) => # @log.error("Transport failure #{msg} #{resp}") #onOpen: (resp) => # @log.info("Got open response #{resp.status}") class DapiService @$inject: ['$log', '$http', '$routeParams'] constructor: (@log, @http, routeParams) -> useLocalServer = routeParams.local ? false #useLocalServer = true base = if useLocalServer 'http://localhost:8080' else 'https://api.droneshare.com' # Normally api.3drobotics.com is recommended, but if you'd like cookies used for your application's login info # you can create a CNAME under your domain that points to api.3drobotics.com and reference the CNAME here. path = '/api/v1/' @apiBase = base + path @log.debug("Creating service " + @urlBase()) # If set, this string is the human friendly error message about our last server error @error = null @config = withCredentials: true # Needed to send cookies useXDomain: true # needed to send cookies in POST # FIXME - better to include in an auth header per RFC2617 Authorization: DroneApi apikey="blah.blah" #params: # api_key: "userkey.appkey" headers: Authorization: 'DroneApi apikey="' + apiKey + '"' urlBase: -> @apiBase + @endpoint getError: => @error class RESTService extends DapiService get: (params = {}) -> @log.debug("Getting from #{@endpoint}") cfg = params: params angular.extend(cfg, @config) @http.get(@urlBase(), cfg).then (results) -> results.data # Return a URL that points to the specified ID urlId: (id) -> "#{@urlBase()}/#{id}" # Async read the specified ID getId: (id) -> @log.debug("Getting #{@endpoint}/#{id}") c = angular.extend({}, @config) @http.get(@urlId(id), c) .then (results) -> results.data putId: (id, obj, c) => @log.debug("Saving #{@endpoint}/#{id}") c = angular.extend(c ? {}, @config) @http.put("#{@urlBase()}/#{id}", obj, c) postId: (id, obj, c) => @log.debug("Posting to #{@endpoint}/#{id}") c = merge(c ? {}, @config) @http.post("#{@urlBase()}/#{id}", obj, c) delete: (id, c) => @log.debug("Deleting #{@endpoint}/#{id}") c = angular.extend(c ? {}, @config) @http.delete("#{@urlBase()}/#{id}", c) # Dynamically create a new record append: (obj, c) => @log.debug("Appending to #{@endpoint}") c = angular.extend(c ? {}, @config) @http.put("#{@urlBase()}", obj, c) class AuthService extends RESTService @$inject: ['$log', '$http', '$routeParams'] constructor: (log, http, routeParams) -> super(log, http, routeParams) @setLoggedOut() # Preinit user @checkLogin() # Do an initial fetch endpoint: "auth" logout: () -> @setLoggedOut() @postId("logout") create: (payload) -> @log.debug("Attempting create for #{payload}") @postId("create", payload) .success (results) => @log.debug("Created in!") @setLoggedIn(results) login: (loginName, password) -> # Use a form style post config = headers: 'Content-Type': 'application/x-www-form-urlencoded' @log.debug("Attempting login for #{loginName}") data = $.param login: loginName password: password @postId("login", data, config) .success (results) => @log.debug("Logged in!") @setLoggedIn(results) .error (results, status) => @log.debug("Not logged in #{results}, #{status}") @setLoggedOut() password_reset: (loginName) -> @log.debug("Attempting password reset for #{loginName}") @postId("pwreset/#{loginName}", {}) password_reset_confirm: (loginName, token, newPassword) -> @log.debug("Attempting password confirm for #{loginName}") @postId("pwreset/#{loginName}/#{token}", JSON.stringify(newPassword)) .success (results) => @log.debug("Password reset complete!") @setLoggedIn(results) email_confirm: (loginName, token) -> @log.debug("Attempting email confirm for #{loginName}") @postId("emailconfirm/#{loginName}/#{token}", {}) # Returns the updated user record setLoggedIn: (userRecord) => @user = userRecord @user.loggedIn = true @user setLoggedOut: () => @user = loggedIn: false getUser: () => @user checkLogin: () -> @getId("user") .then (results) => @log.debug("login complete!") @error = null @setLoggedIn(results) , (results) => @log.error("Login check failed #{results.status}: #{results.statusText}") if results.status == 0 @error = "DroneAPI server is offline, please try again later." @setLoggedOut() class UserService extends RESTService endpoint: "user" class VehicleService extends RESTService endpoint: "vehicle" vehicleTypes: [ "quadcopter" "tricopter" "coaxial" "hexarotor" "octorotor" "fixed-wing" "ground-rover" "submarine" "airship" "flapping-wing" "boat" "free-balloon" "antenna-tracker" "generic" "rocket" "helicopter" ] class MissionService extends RESTService @$inject: ['$log', '$http', '$routeParams', 'atmosphere', 'authService'] constructor: (log, http, routeParams, @atmosphere, @authService) -> @fetchParams = @getFetchParams() @createdAt = 'desc' @userWatching = @authService.getUser() super(log, http, routeParams) endpoint: "mission" getAllMissions: (fetchParams) => fetchParams or= @getFetchParams() @getMissionsFromParams(fetchParams) getUserMissions: (userLogin, filterParams = false) => fetchParams = field_userName: userLogin # if we want to limit the user data set even further # and add more filters we should always use getUserMissions # with the second param being arguments angular.extend(fetchParams, filterParams) if filterParams @getMissionsFromParams(fetchParams) getVehicleTypeMissions: (vehicleType) => fetchParams = field_vehicleType: vehicleType @getMissionsFromParams(fetchParams) getDurationMissions: (duration, opt = 'GT') => fetchParams = {} fetchParams["field_flightDuration[#{opt}]"] = duration @getMissionsFromParams(fetchParams) getMaxAltMissions: (altitude, opt = 'GT') => fetchParams = {} fetchParams["field_maxAlt[#{opt}]"] = altitude @getMissionsFromParams(fetchParams) getMaxGroundSpeedMissions: (speed, opt = 'GT') => fetchParams = {} fetchParams["field_maxGroundspeed[#{opt}]"] = speed @getMissionsFromParams(fetchParams) getMaxAirSpeedMissions: (speed, opt = 'GT') => fetchParams = {} fetchParams["field_maxAirspeed[#{opt}]"] = speed @getMissionsFromParams(fetchParams) getLatitudeMissions: (latitude, opt = 'GT') => fetchParams = {} fetchParams["field_latitude[#{opt}]"] = latitude @getMissionsFromParams(fetchParams) getLongitudeMissions: (longitude, opt = 'GT') => fetchParams = {} fetchParams["field_longitude[#{opt}"] = longitude @getMissionsFromParams(fetchParams) getMissionsFromParams: (params) => angular.extend(params, @getFetchParams()) @getMissions(params) getMissions: (params) => missions = @get(params) missions.then @fixMissionRecords fixMissionRecords: (results) => (@fixMissionRecord(record) for record in results) fixMissionRecord: (record) => date = new Date(record.createdOn) record.dateString = "#{date.toDateString()} - #{date.toLocaleTimeString()}" record.text = record.summaryText ? "Mission #{record.id}" # If the user is looking at their own maps, then zoom in a bit more (because they are probably in same area of world) isMine = @userWatching.loggedIn && (record.userName == @userWatching.login) record.staticZoom = if isMine then 10 else 8 record getFetchParams: -> fetchParams = order_by: 'createdAt' order_dir: @createdAt page_offset: 0 page_size: 12 atmosphere_connect: () => request = url: @urlBase() + '/live' angular.extend(request, @config) angular.extend(request, atmosphereOptions) if @authService.getUser().login? request.headers.login = @authService.getUser().login @atmosphere.init(request) atmosphere_disconnect: () => @atmosphere.close() get_staticmap: () => @getId("staticMap") get_parameters: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/parameters.json", c) .success (results) -> results.data get_plotdata: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/dseries", c) .success (results) -> results.data get_analysis: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/analysis.json", c) .success (results) -> results.data get_geojson: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/messages.geo.json", c) # Server admin operations - not useful to users/developers class AdminService extends RESTService @$inject: ['$log', '$http', '$routeParams', 'atmosphere'] constructor: (log, http, routeParams, @atmosphere) -> super(log, http, routeParams) request = url: @urlBase() + '/log' angular.extend(request, @config) angular.extend(request, atmosphereOptions) @atmosphere.init(request) endpoint: "admin" startSim: (typ) => @log.info("Service starting sim " + typ) @postId("sim/" + typ) importOld: (count) => @log.info("importing " + count) @postId("import/" + count) getDebugInfo: () => @getId("debugInfo") module = angular.module('app') module.service 'missionService', MissionService module.service 'userService', UserService module.service 'vehicleService', VehicleService module.service 'authService', AuthService module.service 'adminService', AdminService
87025
apiKey = "<KEY>" # A deep merge of two objects (as opposed to the shallow merge from angular.extend) merge = (obj1, obj2) -> result = {} # (kinda non ideomatic, but oh well) for k, v of obj1 newv = if (k of obj2) && (typeof v == "object") merge(v, obj2[k]) # if an object merge else v result[k] = newv for k, v of obj2 # add missing keys if !(k of result) result[k] = v result atmosphereOptions = contentType : 'application/json' transport : 'websocket' connectTimeout : 10000 # 10s timeout before fallback to streaming reconnectInterval : 30000 enableXDR: true timeout : 60000 pollingInterval : 5000 fallbackTransport: 'long-polling' # Server might has issues with 'long-polling' headers: api_key: apiKey #onError: (resp) => # @log.error("Atmosphere error: #{resp}") #onTransportFailure: (msg, resp) => # @log.error("Transport failure #{msg} #{resp}") #onOpen: (resp) => # @log.info("Got open response #{resp.status}") class DapiService @$inject: ['$log', '$http', '$routeParams'] constructor: (@log, @http, routeParams) -> useLocalServer = routeParams.local ? false #useLocalServer = true base = if useLocalServer 'http://localhost:8080' else 'https://api.droneshare.com' # Normally api.3drobotics.com is recommended, but if you'd like cookies used for your application's login info # you can create a CNAME under your domain that points to api.3drobotics.com and reference the CNAME here. path = '/api/v1/' @apiBase = base + path @log.debug("Creating service " + @urlBase()) # If set, this string is the human friendly error message about our last server error @error = null @config = withCredentials: true # Needed to send cookies useXDomain: true # needed to send cookies in POST # FIXME - better to include in an auth header per RFC2617 Authorization: DroneApi apikey="<KEY>" #params: # api_key: "<KEY>" headers: Authorization: 'DroneApi apikey="' + apiKey + '"' urlBase: -> @apiBase + @endpoint getError: => @error class RESTService extends DapiService get: (params = {}) -> @log.debug("Getting from #{@endpoint}") cfg = params: params angular.extend(cfg, @config) @http.get(@urlBase(), cfg).then (results) -> results.data # Return a URL that points to the specified ID urlId: (id) -> "#{@urlBase()}/#{id}" # Async read the specified ID getId: (id) -> @log.debug("Getting #{@endpoint}/#{id}") c = angular.extend({}, @config) @http.get(@urlId(id), c) .then (results) -> results.data putId: (id, obj, c) => @log.debug("Saving #{@endpoint}/#{id}") c = angular.extend(c ? {}, @config) @http.put("#{@urlBase()}/#{id}", obj, c) postId: (id, obj, c) => @log.debug("Posting to #{@endpoint}/#{id}") c = merge(c ? {}, @config) @http.post("#{@urlBase()}/#{id}", obj, c) delete: (id, c) => @log.debug("Deleting #{@endpoint}/#{id}") c = angular.extend(c ? {}, @config) @http.delete("#{@urlBase()}/#{id}", c) # Dynamically create a new record append: (obj, c) => @log.debug("Appending to #{@endpoint}") c = angular.extend(c ? {}, @config) @http.put("#{@urlBase()}", obj, c) class AuthService extends RESTService @$inject: ['$log', '$http', '$routeParams'] constructor: (log, http, routeParams) -> super(log, http, routeParams) @setLoggedOut() # Preinit user @checkLogin() # Do an initial fetch endpoint: "auth" logout: () -> @setLoggedOut() @postId("logout") create: (payload) -> @log.debug("Attempting create for #{payload}") @postId("create", payload) .success (results) => @log.debug("Created in!") @setLoggedIn(results) login: (loginName, password) -> # Use a form style post config = headers: 'Content-Type': 'application/x-www-form-urlencoded' @log.debug("Attempting login for #{loginName}") data = $.param login: login<NAME> password: <PASSWORD> @postId("login", data, config) .success (results) => @log.debug("Logged in!") @setLoggedIn(results) .error (results, status) => @log.debug("Not logged in #{results}, #{status}") @setLoggedOut() password_reset: (loginName) -> @log.debug("Attempting password reset for #{loginName}") @postId("pwreset/#{loginName}", {}) password_reset_confirm: (loginName, token, newPassword) -> @log.debug("Attempting password confirm for #{loginName}") @postId("pwreset/#{loginName}/#{token}", JSON.stringify(newPassword)) .success (results) => @log.debug("Password reset complete!") @setLoggedIn(results) email_confirm: (loginName, token) -> @log.debug("Attempting email confirm for #{loginName}") @postId("emailconfirm/#{loginName}/#{token}", {}) # Returns the updated user record setLoggedIn: (userRecord) => @user = userRecord @user.loggedIn = true @user setLoggedOut: () => @user = loggedIn: false getUser: () => @user checkLogin: () -> @getId("user") .then (results) => @log.debug("login complete!") @error = null @setLoggedIn(results) , (results) => @log.error("Login check failed #{results.status}: #{results.statusText}") if results.status == 0 @error = "DroneAPI server is offline, please try again later." @setLoggedOut() class UserService extends RESTService endpoint: "user" class VehicleService extends RESTService endpoint: "vehicle" vehicleTypes: [ "quadcopter" "tricopter" "coaxial" "hexarotor" "octorotor" "fixed-wing" "ground-rover" "submarine" "airship" "flapping-wing" "boat" "free-balloon" "antenna-tracker" "generic" "rocket" "helicopter" ] class MissionService extends RESTService @$inject: ['$log', '$http', '$routeParams', 'atmosphere', 'authService'] constructor: (log, http, routeParams, @atmosphere, @authService) -> @fetchParams = @getFetchParams() @createdAt = 'desc' @userWatching = @authService.getUser() super(log, http, routeParams) endpoint: "mission" getAllMissions: (fetchParams) => fetchParams or= @getFetchParams() @getMissionsFromParams(fetchParams) getUserMissions: (userLogin, filterParams = false) => fetchParams = field_userName: userLogin # if we want to limit the user data set even further # and add more filters we should always use getUserMissions # with the second param being arguments angular.extend(fetchParams, filterParams) if filterParams @getMissionsFromParams(fetchParams) getVehicleTypeMissions: (vehicleType) => fetchParams = field_vehicleType: vehicleType @getMissionsFromParams(fetchParams) getDurationMissions: (duration, opt = 'GT') => fetchParams = {} fetchParams["field_flightDuration[#{opt}]"] = duration @getMissionsFromParams(fetchParams) getMaxAltMissions: (altitude, opt = 'GT') => fetchParams = {} fetchParams["field_maxAlt[#{opt}]"] = altitude @getMissionsFromParams(fetchParams) getMaxGroundSpeedMissions: (speed, opt = 'GT') => fetchParams = {} fetchParams["field_maxGroundspeed[#{opt}]"] = speed @getMissionsFromParams(fetchParams) getMaxAirSpeedMissions: (speed, opt = 'GT') => fetchParams = {} fetchParams["field_maxAirspeed[#{opt}]"] = speed @getMissionsFromParams(fetchParams) getLatitudeMissions: (latitude, opt = 'GT') => fetchParams = {} fetchParams["field_latitude[#{opt}]"] = latitude @getMissionsFromParams(fetchParams) getLongitudeMissions: (longitude, opt = 'GT') => fetchParams = {} fetchParams["field_longitude[#{opt}"] = longitude @getMissionsFromParams(fetchParams) getMissionsFromParams: (params) => angular.extend(params, @getFetchParams()) @getMissions(params) getMissions: (params) => missions = @get(params) missions.then @fixMissionRecords fixMissionRecords: (results) => (@fixMissionRecord(record) for record in results) fixMissionRecord: (record) => date = new Date(record.createdOn) record.dateString = "#{date.toDateString()} - #{date.toLocaleTimeString()}" record.text = record.summaryText ? "Mission #{record.id}" # If the user is looking at their own maps, then zoom in a bit more (because they are probably in same area of world) isMine = @userWatching.loggedIn && (record.userName == @userWatching.login) record.staticZoom = if isMine then 10 else 8 record getFetchParams: -> fetchParams = order_by: 'createdAt' order_dir: @createdAt page_offset: 0 page_size: 12 atmosphere_connect: () => request = url: @urlBase() + '/live' angular.extend(request, @config) angular.extend(request, atmosphereOptions) if @authService.getUser().login? request.headers.login = @authService.getUser().login @atmosphere.init(request) atmosphere_disconnect: () => @atmosphere.close() get_staticmap: () => @getId("staticMap") get_parameters: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/parameters.json", c) .success (results) -> results.data get_plotdata: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/dseries", c) .success (results) -> results.data get_analysis: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/analysis.json", c) .success (results) -> results.data get_geojson: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/messages.geo.json", c) # Server admin operations - not useful to users/developers class AdminService extends RESTService @$inject: ['$log', '$http', '$routeParams', 'atmosphere'] constructor: (log, http, routeParams, @atmosphere) -> super(log, http, routeParams) request = url: @urlBase() + '/log' angular.extend(request, @config) angular.extend(request, atmosphereOptions) @atmosphere.init(request) endpoint: "admin" startSim: (typ) => @log.info("Service starting sim " + typ) @postId("sim/" + typ) importOld: (count) => @log.info("importing " + count) @postId("import/" + count) getDebugInfo: () => @getId("debugInfo") module = angular.module('app') module.service 'missionService', MissionService module.service 'userService', UserService module.service 'vehicleService', VehicleService module.service 'authService', AuthService module.service 'adminService', AdminService
true
apiKey = "PI:KEY:<KEY>END_PI" # A deep merge of two objects (as opposed to the shallow merge from angular.extend) merge = (obj1, obj2) -> result = {} # (kinda non ideomatic, but oh well) for k, v of obj1 newv = if (k of obj2) && (typeof v == "object") merge(v, obj2[k]) # if an object merge else v result[k] = newv for k, v of obj2 # add missing keys if !(k of result) result[k] = v result atmosphereOptions = contentType : 'application/json' transport : 'websocket' connectTimeout : 10000 # 10s timeout before fallback to streaming reconnectInterval : 30000 enableXDR: true timeout : 60000 pollingInterval : 5000 fallbackTransport: 'long-polling' # Server might has issues with 'long-polling' headers: api_key: apiKey #onError: (resp) => # @log.error("Atmosphere error: #{resp}") #onTransportFailure: (msg, resp) => # @log.error("Transport failure #{msg} #{resp}") #onOpen: (resp) => # @log.info("Got open response #{resp.status}") class DapiService @$inject: ['$log', '$http', '$routeParams'] constructor: (@log, @http, routeParams) -> useLocalServer = routeParams.local ? false #useLocalServer = true base = if useLocalServer 'http://localhost:8080' else 'https://api.droneshare.com' # Normally api.3drobotics.com is recommended, but if you'd like cookies used for your application's login info # you can create a CNAME under your domain that points to api.3drobotics.com and reference the CNAME here. path = '/api/v1/' @apiBase = base + path @log.debug("Creating service " + @urlBase()) # If set, this string is the human friendly error message about our last server error @error = null @config = withCredentials: true # Needed to send cookies useXDomain: true # needed to send cookies in POST # FIXME - better to include in an auth header per RFC2617 Authorization: DroneApi apikey="PI:KEY:<KEY>END_PI" #params: # api_key: "PI:KEY:<KEY>END_PI" headers: Authorization: 'DroneApi apikey="' + apiKey + '"' urlBase: -> @apiBase + @endpoint getError: => @error class RESTService extends DapiService get: (params = {}) -> @log.debug("Getting from #{@endpoint}") cfg = params: params angular.extend(cfg, @config) @http.get(@urlBase(), cfg).then (results) -> results.data # Return a URL that points to the specified ID urlId: (id) -> "#{@urlBase()}/#{id}" # Async read the specified ID getId: (id) -> @log.debug("Getting #{@endpoint}/#{id}") c = angular.extend({}, @config) @http.get(@urlId(id), c) .then (results) -> results.data putId: (id, obj, c) => @log.debug("Saving #{@endpoint}/#{id}") c = angular.extend(c ? {}, @config) @http.put("#{@urlBase()}/#{id}", obj, c) postId: (id, obj, c) => @log.debug("Posting to #{@endpoint}/#{id}") c = merge(c ? {}, @config) @http.post("#{@urlBase()}/#{id}", obj, c) delete: (id, c) => @log.debug("Deleting #{@endpoint}/#{id}") c = angular.extend(c ? {}, @config) @http.delete("#{@urlBase()}/#{id}", c) # Dynamically create a new record append: (obj, c) => @log.debug("Appending to #{@endpoint}") c = angular.extend(c ? {}, @config) @http.put("#{@urlBase()}", obj, c) class AuthService extends RESTService @$inject: ['$log', '$http', '$routeParams'] constructor: (log, http, routeParams) -> super(log, http, routeParams) @setLoggedOut() # Preinit user @checkLogin() # Do an initial fetch endpoint: "auth" logout: () -> @setLoggedOut() @postId("logout") create: (payload) -> @log.debug("Attempting create for #{payload}") @postId("create", payload) .success (results) => @log.debug("Created in!") @setLoggedIn(results) login: (loginName, password) -> # Use a form style post config = headers: 'Content-Type': 'application/x-www-form-urlencoded' @log.debug("Attempting login for #{loginName}") data = $.param login: loginPI:NAME:<NAME>END_PI password: PI:PASSWORD:<PASSWORD>END_PI @postId("login", data, config) .success (results) => @log.debug("Logged in!") @setLoggedIn(results) .error (results, status) => @log.debug("Not logged in #{results}, #{status}") @setLoggedOut() password_reset: (loginName) -> @log.debug("Attempting password reset for #{loginName}") @postId("pwreset/#{loginName}", {}) password_reset_confirm: (loginName, token, newPassword) -> @log.debug("Attempting password confirm for #{loginName}") @postId("pwreset/#{loginName}/#{token}", JSON.stringify(newPassword)) .success (results) => @log.debug("Password reset complete!") @setLoggedIn(results) email_confirm: (loginName, token) -> @log.debug("Attempting email confirm for #{loginName}") @postId("emailconfirm/#{loginName}/#{token}", {}) # Returns the updated user record setLoggedIn: (userRecord) => @user = userRecord @user.loggedIn = true @user setLoggedOut: () => @user = loggedIn: false getUser: () => @user checkLogin: () -> @getId("user") .then (results) => @log.debug("login complete!") @error = null @setLoggedIn(results) , (results) => @log.error("Login check failed #{results.status}: #{results.statusText}") if results.status == 0 @error = "DroneAPI server is offline, please try again later." @setLoggedOut() class UserService extends RESTService endpoint: "user" class VehicleService extends RESTService endpoint: "vehicle" vehicleTypes: [ "quadcopter" "tricopter" "coaxial" "hexarotor" "octorotor" "fixed-wing" "ground-rover" "submarine" "airship" "flapping-wing" "boat" "free-balloon" "antenna-tracker" "generic" "rocket" "helicopter" ] class MissionService extends RESTService @$inject: ['$log', '$http', '$routeParams', 'atmosphere', 'authService'] constructor: (log, http, routeParams, @atmosphere, @authService) -> @fetchParams = @getFetchParams() @createdAt = 'desc' @userWatching = @authService.getUser() super(log, http, routeParams) endpoint: "mission" getAllMissions: (fetchParams) => fetchParams or= @getFetchParams() @getMissionsFromParams(fetchParams) getUserMissions: (userLogin, filterParams = false) => fetchParams = field_userName: userLogin # if we want to limit the user data set even further # and add more filters we should always use getUserMissions # with the second param being arguments angular.extend(fetchParams, filterParams) if filterParams @getMissionsFromParams(fetchParams) getVehicleTypeMissions: (vehicleType) => fetchParams = field_vehicleType: vehicleType @getMissionsFromParams(fetchParams) getDurationMissions: (duration, opt = 'GT') => fetchParams = {} fetchParams["field_flightDuration[#{opt}]"] = duration @getMissionsFromParams(fetchParams) getMaxAltMissions: (altitude, opt = 'GT') => fetchParams = {} fetchParams["field_maxAlt[#{opt}]"] = altitude @getMissionsFromParams(fetchParams) getMaxGroundSpeedMissions: (speed, opt = 'GT') => fetchParams = {} fetchParams["field_maxGroundspeed[#{opt}]"] = speed @getMissionsFromParams(fetchParams) getMaxAirSpeedMissions: (speed, opt = 'GT') => fetchParams = {} fetchParams["field_maxAirspeed[#{opt}]"] = speed @getMissionsFromParams(fetchParams) getLatitudeMissions: (latitude, opt = 'GT') => fetchParams = {} fetchParams["field_latitude[#{opt}]"] = latitude @getMissionsFromParams(fetchParams) getLongitudeMissions: (longitude, opt = 'GT') => fetchParams = {} fetchParams["field_longitude[#{opt}"] = longitude @getMissionsFromParams(fetchParams) getMissionsFromParams: (params) => angular.extend(params, @getFetchParams()) @getMissions(params) getMissions: (params) => missions = @get(params) missions.then @fixMissionRecords fixMissionRecords: (results) => (@fixMissionRecord(record) for record in results) fixMissionRecord: (record) => date = new Date(record.createdOn) record.dateString = "#{date.toDateString()} - #{date.toLocaleTimeString()}" record.text = record.summaryText ? "Mission #{record.id}" # If the user is looking at their own maps, then zoom in a bit more (because they are probably in same area of world) isMine = @userWatching.loggedIn && (record.userName == @userWatching.login) record.staticZoom = if isMine then 10 else 8 record getFetchParams: -> fetchParams = order_by: 'createdAt' order_dir: @createdAt page_offset: 0 page_size: 12 atmosphere_connect: () => request = url: @urlBase() + '/live' angular.extend(request, @config) angular.extend(request, atmosphereOptions) if @authService.getUser().login? request.headers.login = @authService.getUser().login @atmosphere.init(request) atmosphere_disconnect: () => @atmosphere.close() get_staticmap: () => @getId("staticMap") get_parameters: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/parameters.json", c) .success (results) -> results.data get_plotdata: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/dseries", c) .success (results) -> results.data get_analysis: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/analysis.json", c) .success (results) -> results.data get_geojson: (id) => c = angular.extend({}, @config) @http.get("#{@urlBase()}/#{id}/messages.geo.json", c) # Server admin operations - not useful to users/developers class AdminService extends RESTService @$inject: ['$log', '$http', '$routeParams', 'atmosphere'] constructor: (log, http, routeParams, @atmosphere) -> super(log, http, routeParams) request = url: @urlBase() + '/log' angular.extend(request, @config) angular.extend(request, atmosphereOptions) @atmosphere.init(request) endpoint: "admin" startSim: (typ) => @log.info("Service starting sim " + typ) @postId("sim/" + typ) importOld: (count) => @log.info("importing " + count) @postId("import/" + count) getDebugInfo: () => @getId("debugInfo") module = angular.module('app') module.service 'missionService', MissionService module.service 'userService', UserService module.service 'vehicleService', VehicleService module.service 'authService', AuthService module.service 'adminService', AdminService
[ { "context": "---------------------------------\n# Copyright 2013 I.B.M.\n# \n# Licensed under the Apache License, Version 2", "end": 952, "score": 0.9939495921134949, "start": 947, "tag": "NAME", "value": "I.B.M" } ]
lib-src/coffee/node/cli.coffee
pmuellr/nodprof
6
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" nopt = require "nopt" _ = require "underscore" pkg = require "../../package.json" nodprof = require "../.." utils = require "../common/utils" logger = require "../common/logger" config = require "./config" profiler = require "./profiler" server = require "./server" cli = exports #------------------------------------------------------------------------------- cli.run = -> {args, config} = config.getConfiguration process.argv[2..] logger.setDebug config.debug logger.setVerbose config.verbose if config.serve server.run config else profiler.run {args, config} #------------------------------------------------------------------------------- cli.run() if require.main is module #------------------------------------------------------------------------------- # 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. #-------------------------------------------------------------------------------
199237
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" nopt = require "nopt" _ = require "underscore" pkg = require "../../package.json" nodprof = require "../.." utils = require "../common/utils" logger = require "../common/logger" config = require "./config" profiler = require "./profiler" server = require "./server" cli = exports #------------------------------------------------------------------------------- cli.run = -> {args, config} = config.getConfiguration process.argv[2..] logger.setDebug config.debug logger.setVerbose config.verbose if config.serve server.run config else profiler.run {args, config} #------------------------------------------------------------------------------- cli.run() if require.main is module #------------------------------------------------------------------------------- # 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. fs = require "fs" path = require "path" nopt = require "nopt" _ = require "underscore" pkg = require "../../package.json" nodprof = require "../.." utils = require "../common/utils" logger = require "../common/logger" config = require "./config" profiler = require "./profiler" server = require "./server" cli = exports #------------------------------------------------------------------------------- cli.run = -> {args, config} = config.getConfiguration process.argv[2..] logger.setDebug config.debug logger.setVerbose config.verbose if config.serve server.run config else profiler.run {args, config} #------------------------------------------------------------------------------- cli.run() if require.main is module #------------------------------------------------------------------------------- # 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": "text onto HTML canvas elements\n\nWritten in 2013 by Karl Naylor <kpn103@yahoo.com>\n\nTo the extent possible under ", "end": 106, "score": 0.9998897314071655, "start": 95, "tag": "NAME", "value": "Karl Naylor" }, { "context": " canvas elements\n\nWritten in 2013 by Kar...
src/content/coffee/handywriteOnCanvas/geometry.coffee
karlorg/phonetify
1
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by Karl Naylor <kpn103@yahoo.com> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define -> geometry = {} TAU = Math.PI * 2 # TAU is one full turn in radians # do not modify existing Vectors or their constituent points, kk? geometry.Vector = class Vector constructor: (@p0, @p1) -> normalized: -> len = Math.sqrt( (@p1.x - @p0.x) * (@p1.x - @p0.x) + (@p1.y - @p0.y) * (@p1.y - @p0.y)) scale = 1 / len return new Vector( @p0, { x: ((@p1.x - @p0.x) * scale) + @p0.x y: ((@p1.y - @p0.y) * scale) + @p0.y }) angle: -> # since 'true' arctangent is multivalued and `Math.atan` is limited # to +/- TAU/4, we need to rotate the result by TAU/2 if p1 is to # the left of p0 return Math.atan( (@p1.y - @p0.y) / (@p1.x - @p0.x) ) + if @p1.x < @p0.x then TAU / 2 else 0 geometry.rotatePoint = (p, theta) -> {x, y} = p cosTheta = Math.cos theta sinTheta = Math.sin theta return { x: x * cosTheta - y * sinTheta y: y * cosTheta + x * sinTheta } geometry.vectorFromAngle = (angle) -> { x, y } = geometry.rotatePoint({x:1, y:0}, angle) return new Vector({ x: 0, y: 0 }, { x: x, y: y }) geometry.pointSum = (points) -> return { x: (p.x for p in points).reduce( (a,b) -> a+b ) y: (p.y for p in points).reduce( (a,b) -> a+b ) } return geometry
14092
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by <NAME> <<EMAIL>> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define -> geometry = {} TAU = Math.PI * 2 # TAU is one full turn in radians # do not modify existing Vectors or their constituent points, kk? geometry.Vector = class Vector constructor: (@p0, @p1) -> normalized: -> len = Math.sqrt( (@p1.x - @p0.x) * (@p1.x - @p0.x) + (@p1.y - @p0.y) * (@p1.y - @p0.y)) scale = 1 / len return new Vector( @p0, { x: ((@p1.x - @p0.x) * scale) + @p0.x y: ((@p1.y - @p0.y) * scale) + @p0.y }) angle: -> # since 'true' arctangent is multivalued and `Math.atan` is limited # to +/- TAU/4, we need to rotate the result by TAU/2 if p1 is to # the left of p0 return Math.atan( (@p1.y - @p0.y) / (@p1.x - @p0.x) ) + if @p1.x < @p0.x then TAU / 2 else 0 geometry.rotatePoint = (p, theta) -> {x, y} = p cosTheta = Math.cos theta sinTheta = Math.sin theta return { x: x * cosTheta - y * sinTheta y: y * cosTheta + x * sinTheta } geometry.vectorFromAngle = (angle) -> { x, y } = geometry.rotatePoint({x:1, y:0}, angle) return new Vector({ x: 0, y: 0 }, { x: x, y: y }) geometry.pointSum = (points) -> return { x: (p.x for p in points).reduce( (a,b) -> a+b ) y: (p.y for p in points).reduce( (a,b) -> a+b ) } return geometry
true
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define -> geometry = {} TAU = Math.PI * 2 # TAU is one full turn in radians # do not modify existing Vectors or their constituent points, kk? geometry.Vector = class Vector constructor: (@p0, @p1) -> normalized: -> len = Math.sqrt( (@p1.x - @p0.x) * (@p1.x - @p0.x) + (@p1.y - @p0.y) * (@p1.y - @p0.y)) scale = 1 / len return new Vector( @p0, { x: ((@p1.x - @p0.x) * scale) + @p0.x y: ((@p1.y - @p0.y) * scale) + @p0.y }) angle: -> # since 'true' arctangent is multivalued and `Math.atan` is limited # to +/- TAU/4, we need to rotate the result by TAU/2 if p1 is to # the left of p0 return Math.atan( (@p1.y - @p0.y) / (@p1.x - @p0.x) ) + if @p1.x < @p0.x then TAU / 2 else 0 geometry.rotatePoint = (p, theta) -> {x, y} = p cosTheta = Math.cos theta sinTheta = Math.sin theta return { x: x * cosTheta - y * sinTheta y: y * cosTheta + x * sinTheta } geometry.vectorFromAngle = (angle) -> { x, y } = geometry.rotatePoint({x:1, y:0}, angle) return new Vector({ x: 0, y: 0 }, { x: x, y: y }) geometry.pointSum = (points) -> return { x: (p.x for p in points).reduce( (a,b) -> a+b ) y: (p.y for p in points).reduce( (a,b) -> a+b ) } return geometry
[ { "context": "e: 13}\n\t\t\t\t{name: \"Queen\", value: 12}\n\t\t\t\t{name: \"Jack\", value: 11}\n\t\t\t\t{name: \"10\", value: 10}\n\t\t\t\t{nam", "end": 1183, "score": 0.9741065502166748, "start": 1179, "tag": "NAME", "value": "Jack" } ]
test/10-matches.coffee
clanofthecloud/javascript-client
1
should = require 'should' Clan = require('../src/Clan.coffee')('testgame-key', 'testgame-secret') # app credentials dataset = require './0-dataset.json' events_gamer = null matches = null events_friend = null matches_friend = null matchID = null lastEventId = null describe 'Matches', -> it 'should login first as gamer', (done)-> Clan.login null, (err, gamer)-> gamer.should.have.property('gamer_id') gamer.should.have.property('gamer_secret') events_gamer = Clan.withGamer(gamer).events('private') matches = Clan.withGamer(gamer).matches(Clan.privateDomain) done(err) it 'should login now as friend', (done)-> Clan.login null, (err, friend)-> friend.should.have.property('gamer_id') friend.should.have.property('gamer_secret') events_friend = Clan.withGamer(friend).events('private') matches_friend = Clan.withGamer(friend).matches(Clan.privateDomain) done(err) it 'should create a match', (done)-> match = description: "Batlle Card Sample" maxPlayers: 2 customProperties: {type: "battle", cardsCount: "8"} shoe: [ {name: "Ace", value: 14} {name: "King", value: 13} {name: "Queen", value: 12} {name: "Jack", value: 11} {name: "10", value: 10} {name: "9", value: 9} {name: "8", value: 8} {name: "7", value: 7} ] matches.create match, (err, res)-> should(err).be.null res.should.have.property('match') res.match.should.have.property('_id') res.match.should.have.property('lastEventId') matchID = res.match._id lastEventId = res.match.lastEventId done(err) it 'friend should list open matches', (done)-> matches_friend.list {type: "battle"}, (err, list)-> should(err).be.null list.should.have.property('matches') list.matches.should.be.Array() done(err) it 'friend should join a match', (done)-> matches_friend.join matchID, {}, (err, res)-> should(err).be.null res.should.have.property('match') res.match.should.have.property('_id') res.match._id.should.eql(matchID) done(err) it 'gamer should receive a message', (done)-> events_gamer.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.join') done(err) it 'should get match data', (done)-> matches.get matchID, (err, data)-> should(err).be.null should.exist(data.match.lastEventId) lastEventId = data.match.lastEventId done(err) it 'gamer should make a move', (done)-> move = type : "bet" amount : 10 matches.move matchID, lastEventId, move, (err, res)-> if err? then return done(err) should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId done(err) it 'friend should recieve a message', (done)-> events_friend.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.move') done(err) it 'friend should get match data', (done)-> matches_friend.get matchID, (err, data)-> should(err).be.null should.exist(data.match.lastEventId) lastEventId = data.match.lastEventId done(err) it 'friend should make a move', (done)-> move = type : "bet" amount : 10 matches_friend.move matchID, lastEventId, move, (err, res)-> should(err).be.null should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId done(err) it 'gamer should recieve a message', (done)-> events_gamer.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.move') done(err) it 'gamer should draw cards', (done)-> matches.draw matchID, lastEventId, 4, {}, (err, res)-> should(err).be.null should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId should.exist(res.drawnItems) res.drawnItems.length.should.eql(4) done(err) it 'friend should recieve a message', (done)-> events_friend.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.shoedraw') done(err) it 'friend should draw cards', (done)-> matches_friend.draw matchID, lastEventId, 4, {}, (err, res)-> should(err).be.null should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId should.exist(res.drawnItems) res.drawnItems.length.should.eql(4) done(err) it 'gamer should recieve a message', (done)-> events_gamer.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.shoedraw') done(err) it 'should finish the match', (done)-> matches.finish matchID, lastEventId, {}, (err, res)-> should(err).be.null done(err) it 'should reveal the shoe after the match has ended', (done)-> matches.get matchID, (err, data)-> should(err).be.null should.exist(data.match.shoe) done(err) it 'should delete the match', (done)-> matches.del matchID, (err, res)-> should(err).be.null done(err)
217101
should = require 'should' Clan = require('../src/Clan.coffee')('testgame-key', 'testgame-secret') # app credentials dataset = require './0-dataset.json' events_gamer = null matches = null events_friend = null matches_friend = null matchID = null lastEventId = null describe 'Matches', -> it 'should login first as gamer', (done)-> Clan.login null, (err, gamer)-> gamer.should.have.property('gamer_id') gamer.should.have.property('gamer_secret') events_gamer = Clan.withGamer(gamer).events('private') matches = Clan.withGamer(gamer).matches(Clan.privateDomain) done(err) it 'should login now as friend', (done)-> Clan.login null, (err, friend)-> friend.should.have.property('gamer_id') friend.should.have.property('gamer_secret') events_friend = Clan.withGamer(friend).events('private') matches_friend = Clan.withGamer(friend).matches(Clan.privateDomain) done(err) it 'should create a match', (done)-> match = description: "Batlle Card Sample" maxPlayers: 2 customProperties: {type: "battle", cardsCount: "8"} shoe: [ {name: "Ace", value: 14} {name: "King", value: 13} {name: "Queen", value: 12} {name: "<NAME>", value: 11} {name: "10", value: 10} {name: "9", value: 9} {name: "8", value: 8} {name: "7", value: 7} ] matches.create match, (err, res)-> should(err).be.null res.should.have.property('match') res.match.should.have.property('_id') res.match.should.have.property('lastEventId') matchID = res.match._id lastEventId = res.match.lastEventId done(err) it 'friend should list open matches', (done)-> matches_friend.list {type: "battle"}, (err, list)-> should(err).be.null list.should.have.property('matches') list.matches.should.be.Array() done(err) it 'friend should join a match', (done)-> matches_friend.join matchID, {}, (err, res)-> should(err).be.null res.should.have.property('match') res.match.should.have.property('_id') res.match._id.should.eql(matchID) done(err) it 'gamer should receive a message', (done)-> events_gamer.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.join') done(err) it 'should get match data', (done)-> matches.get matchID, (err, data)-> should(err).be.null should.exist(data.match.lastEventId) lastEventId = data.match.lastEventId done(err) it 'gamer should make a move', (done)-> move = type : "bet" amount : 10 matches.move matchID, lastEventId, move, (err, res)-> if err? then return done(err) should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId done(err) it 'friend should recieve a message', (done)-> events_friend.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.move') done(err) it 'friend should get match data', (done)-> matches_friend.get matchID, (err, data)-> should(err).be.null should.exist(data.match.lastEventId) lastEventId = data.match.lastEventId done(err) it 'friend should make a move', (done)-> move = type : "bet" amount : 10 matches_friend.move matchID, lastEventId, move, (err, res)-> should(err).be.null should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId done(err) it 'gamer should recieve a message', (done)-> events_gamer.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.move') done(err) it 'gamer should draw cards', (done)-> matches.draw matchID, lastEventId, 4, {}, (err, res)-> should(err).be.null should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId should.exist(res.drawnItems) res.drawnItems.length.should.eql(4) done(err) it 'friend should recieve a message', (done)-> events_friend.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.shoedraw') done(err) it 'friend should draw cards', (done)-> matches_friend.draw matchID, lastEventId, 4, {}, (err, res)-> should(err).be.null should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId should.exist(res.drawnItems) res.drawnItems.length.should.eql(4) done(err) it 'gamer should recieve a message', (done)-> events_gamer.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.shoedraw') done(err) it 'should finish the match', (done)-> matches.finish matchID, lastEventId, {}, (err, res)-> should(err).be.null done(err) it 'should reveal the shoe after the match has ended', (done)-> matches.get matchID, (err, data)-> should(err).be.null should.exist(data.match.shoe) done(err) it 'should delete the match', (done)-> matches.del matchID, (err, res)-> should(err).be.null done(err)
true
should = require 'should' Clan = require('../src/Clan.coffee')('testgame-key', 'testgame-secret') # app credentials dataset = require './0-dataset.json' events_gamer = null matches = null events_friend = null matches_friend = null matchID = null lastEventId = null describe 'Matches', -> it 'should login first as gamer', (done)-> Clan.login null, (err, gamer)-> gamer.should.have.property('gamer_id') gamer.should.have.property('gamer_secret') events_gamer = Clan.withGamer(gamer).events('private') matches = Clan.withGamer(gamer).matches(Clan.privateDomain) done(err) it 'should login now as friend', (done)-> Clan.login null, (err, friend)-> friend.should.have.property('gamer_id') friend.should.have.property('gamer_secret') events_friend = Clan.withGamer(friend).events('private') matches_friend = Clan.withGamer(friend).matches(Clan.privateDomain) done(err) it 'should create a match', (done)-> match = description: "Batlle Card Sample" maxPlayers: 2 customProperties: {type: "battle", cardsCount: "8"} shoe: [ {name: "Ace", value: 14} {name: "King", value: 13} {name: "Queen", value: 12} {name: "PI:NAME:<NAME>END_PI", value: 11} {name: "10", value: 10} {name: "9", value: 9} {name: "8", value: 8} {name: "7", value: 7} ] matches.create match, (err, res)-> should(err).be.null res.should.have.property('match') res.match.should.have.property('_id') res.match.should.have.property('lastEventId') matchID = res.match._id lastEventId = res.match.lastEventId done(err) it 'friend should list open matches', (done)-> matches_friend.list {type: "battle"}, (err, list)-> should(err).be.null list.should.have.property('matches') list.matches.should.be.Array() done(err) it 'friend should join a match', (done)-> matches_friend.join matchID, {}, (err, res)-> should(err).be.null res.should.have.property('match') res.match.should.have.property('_id') res.match._id.should.eql(matchID) done(err) it 'gamer should receive a message', (done)-> events_gamer.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.join') done(err) it 'should get match data', (done)-> matches.get matchID, (err, data)-> should(err).be.null should.exist(data.match.lastEventId) lastEventId = data.match.lastEventId done(err) it 'gamer should make a move', (done)-> move = type : "bet" amount : 10 matches.move matchID, lastEventId, move, (err, res)-> if err? then return done(err) should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId done(err) it 'friend should recieve a message', (done)-> events_friend.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.move') done(err) it 'friend should get match data', (done)-> matches_friend.get matchID, (err, data)-> should(err).be.null should.exist(data.match.lastEventId) lastEventId = data.match.lastEventId done(err) it 'friend should make a move', (done)-> move = type : "bet" amount : 10 matches_friend.move matchID, lastEventId, move, (err, res)-> should(err).be.null should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId done(err) it 'gamer should recieve a message', (done)-> events_gamer.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.move') done(err) it 'gamer should draw cards', (done)-> matches.draw matchID, lastEventId, 4, {}, (err, res)-> should(err).be.null should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId should.exist(res.drawnItems) res.drawnItems.length.should.eql(4) done(err) it 'friend should recieve a message', (done)-> events_friend.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.shoedraw') done(err) it 'friend should draw cards', (done)-> matches_friend.draw matchID, lastEventId, 4, {}, (err, res)-> should(err).be.null should.exist(res.match.lastEventId) lastEventId = res.match.lastEventId should.exist(res.drawnItems) res.drawnItems.length.should.eql(4) done(err) it 'gamer should recieve a message', (done)-> events_gamer.receive 'auto', (err, message)-> should(err).be.null message.should.have.property('type') message.type.should.eql('match.shoedraw') done(err) it 'should finish the match', (done)-> matches.finish matchID, lastEventId, {}, (err, res)-> should(err).be.null done(err) it 'should reveal the shoe after the match has ended', (done)-> matches.get matchID, (err, data)-> should(err).be.null should.exist(data.match.shoe) done(err) it 'should delete the match', (done)-> matches.del matchID, (err, res)-> should(err).be.null done(err)
[ { "context": "he .env, update the value\n\t\t\t\tpair = answers.key + '=' + answers.value\n\t\t\t\tif env.search(new RegExp('^' ", "end": 5061, "score": 0.9330450892448425, "start": 5058, "tag": "KEY", "value": "'='" }, { "context": ".blTask 'slack start', -> slack.send\n\t\tusername...
tools/shipit.coffee
BKWLD/benchpress
3
### This file exports an object that can be to merge configuration into some defaults and then apply them to shipit ### # Deps _ = require 'lodash' crypto = require 'crypto' child_process = require 'child_process' inquirer = require 'inquirer' Slack = require 'node-slack' shipitDeploy = require 'shipit-deploy' shipitShared = require 'shipit-shared' colors = require 'colors' # The Bukwild slack webhook, shared between projects slack = new Slack process.env.SLACK_WEBHOOK # Receives the shipit object and config that should be merged in module.exports = {} module.exports.init = (shipit, config) -> # Load shipit plugins shipitDeploy(shipit) shipitShared(shipit) # Prep some shared vars workspace = "/tmp/#{config.appName}-#{getEnvironment()}" # The default config defaults = default: workspace: workspace # Where the deploy gets prepped locally repositoryUrl: getOrigin() # The repo URL ignores: [ # Don't copy these up '.git', 'node_modules', '.env', '.DS_Store' ] # Config for symlinked directories shared: overwrite: true triggerEvent: false files: [ '.env' ] dirs: [ { path: 'public/wp-content/uploads', chmod: '-R 775' } ] # Merge staging settings with some defaults staging: branch: 'master' # The branch to pull from keepReleases: 1 # Merge production settings with some defaults production: branch: 'production' keepReleases: 3 # Merge stages into the default config and pass to Shipit shipit.initConfig _.defaultsDeep(config, defaults) # ############################################################################ # Events # Tasks that get run before shipit begins shipit.on 'deploy', -> shipit.start 'slack start' if config.slackChannel # After git repo is pulled locally, do yarn installs and then webpack compile shipit.on 'fetched', -> shipit.start ['composer', 'compile'] # After the the remote is updated, run post commands shipit.on 'updated', -> shipit.start ['env:create', 'shared'] # Tasks that get run when shipit ends (the `deployed` even't wasnt firing) shipit.on 'cleaned', -> shipit.start 'slack end' if config.slackChannel # ############################################################################ # Local tasks # Run the Webpack compile task, which is dependant on node dependencies shipit.blTask 'compile', ['composer', 'yarn'], -> shipit.local 'yarn minify', { cwd: workspace } # Install node dependencies shipit.blTask 'yarn', -> shipit.local 'yarn install', { cwd: workspace } # Install composer dependencies locally so that composer.phar doesn't need to # be added the the repository shipit.blTask 'composer', -> shipit.local 'composer install', { cwd: workspace } # ############################################################################ # Manipulate .env files # Vars env_path = "#{shipit.config.deployTo}/shared/.env" # On initial deploy, prompt user for .env values shipit.blTask 'env:create', (done) -> # Check if any of the app servers are missing .env files shipit.remote "[ -f \"#{env_path}\" ] && echo 1 || echo 0" .then (servers) -> # If all servers have an env file, do nothing return done() if !_.find(servers, (server) -> server.stdout.trim() == '0') # Ask user questions to populate the .env file shipit.log '\nNo .env file on remote. Creating using your answers:'.yellow.bold inquirer.prompt firstDeployQuestions(), (answers) -> # Write the env file to the server after converting the answers object # to a multiline string env = _.map(answers, (val, key) -> "#{key}=#{val}").join("\n") shipit.remote "mkdir -p '#{shipit.config.deployTo}/shared'" .then -> shipit.remote "echo '#{env}' > #{env_path}" # Create the database if it doesn't exist .then -> shipit.log 'Creating database if it doesn\'t exist...' shipit.remote "mysql -h #{answers.DB_HOST} -u #{answers.DB_USERNAME} -p#{answers.DB_PASSWORD} -e 'CREATE DATABASE IF NOT EXISTS `#{answers.DB_DATABASE}`'" # Done with this task .then -> done() # Prevent the promise from being returned return # Read the env file shipit.blTask 'env:get', -> getEnv().then (servers) -> shipit.log servers[0].stdout.yellow getEnv = -> shipit.remote "mkdir -p '#{shipit.config.deployTo}/shared'" .then -> shipit.remote "touch #{env_path}" .then -> shipit.remote "cat #{env_path}" # Write a key-vlaue pair to the .env file shipit.blTask 'env:set', (done) -> # Ask user what key-value is being touched shipit.log '\nSupply the key-value pair you want to add:'.yellow.bold inquirer.prompt [ { type: 'input', name: 'key', message: 'Key' } { type: 'input', name: 'value', message: 'Value' } ], (answers) -> # Get the .env contents from each server, creating the .env file if needed getEnv().then (servers) -> env = servers[0].stdout.trim() # If the key is already in the .env, update the value pair = answers.key + '=' + answers.value if env.search(new RegExp('^' + answers.key + '=', 'm')) > -1 env = env.replace(new RegExp('^' + answers.key + '=.*$', 'm'), pair) # Otherwise, append to the file else env += "\n" + pair # Write the updated env file shipit.remote "echo '#{env}' > #{env_path}" .then -> done() # Done # ############################################################################ # Project management tasks # Tell Slack about deploy starting shipit.blTask 'slack start', -> slack.send username: 'Starting deployment' text: ":clock1: *#{getDeveloperName()}* is deploying to *#{getEnvironment()}*" channel: config.slackChannel # Tell Slack about deploy finished shipit.blTask 'slack end', -> slack.send username: 'Finished deployment' text: ":checkered_flag: #{shipit.config.url}" channel: config.slackChannel # ############################################################################## # Utils - Helpers used in the Shipit config # ############################################################################## # Determine the repository URL by using the git `origin` remote getOrigin = -> child_process .execSync('git config --local --get remote.origin.url') .toString('utf8') .trim() # Get the environment that is being deployed to getEnvironment = -> process.argv[2] # Get someone's git username and return a promise getDeveloperName = -> name = child_process.execSync 'git config user.name' names = name.toString('utf8').trim().split(' ') return "#{names[0]} #{names[1][0]}." # Muster the questions to prompt the user on initial deploy firstDeployQuestions = -> [ { type: 'input' name: 'APP_ENV' message: 'Environment' default: getEnvironment() } { type: 'input' name: 'DB_HOST' message: 'Database host' default: 'localhost' } { type: 'input' name: 'DB_NAME' message: 'Database name' } { type: 'input' name: 'DB_USERNAME' message: 'Database user' } { type: 'input' name: 'DB_PASSWORD' message: 'Database pass' } ]
54336
### This file exports an object that can be to merge configuration into some defaults and then apply them to shipit ### # Deps _ = require 'lodash' crypto = require 'crypto' child_process = require 'child_process' inquirer = require 'inquirer' Slack = require 'node-slack' shipitDeploy = require 'shipit-deploy' shipitShared = require 'shipit-shared' colors = require 'colors' # The Bukwild slack webhook, shared between projects slack = new Slack process.env.SLACK_WEBHOOK # Receives the shipit object and config that should be merged in module.exports = {} module.exports.init = (shipit, config) -> # Load shipit plugins shipitDeploy(shipit) shipitShared(shipit) # Prep some shared vars workspace = "/tmp/#{config.appName}-#{getEnvironment()}" # The default config defaults = default: workspace: workspace # Where the deploy gets prepped locally repositoryUrl: getOrigin() # The repo URL ignores: [ # Don't copy these up '.git', 'node_modules', '.env', '.DS_Store' ] # Config for symlinked directories shared: overwrite: true triggerEvent: false files: [ '.env' ] dirs: [ { path: 'public/wp-content/uploads', chmod: '-R 775' } ] # Merge staging settings with some defaults staging: branch: 'master' # The branch to pull from keepReleases: 1 # Merge production settings with some defaults production: branch: 'production' keepReleases: 3 # Merge stages into the default config and pass to Shipit shipit.initConfig _.defaultsDeep(config, defaults) # ############################################################################ # Events # Tasks that get run before shipit begins shipit.on 'deploy', -> shipit.start 'slack start' if config.slackChannel # After git repo is pulled locally, do yarn installs and then webpack compile shipit.on 'fetched', -> shipit.start ['composer', 'compile'] # After the the remote is updated, run post commands shipit.on 'updated', -> shipit.start ['env:create', 'shared'] # Tasks that get run when shipit ends (the `deployed` even't wasnt firing) shipit.on 'cleaned', -> shipit.start 'slack end' if config.slackChannel # ############################################################################ # Local tasks # Run the Webpack compile task, which is dependant on node dependencies shipit.blTask 'compile', ['composer', 'yarn'], -> shipit.local 'yarn minify', { cwd: workspace } # Install node dependencies shipit.blTask 'yarn', -> shipit.local 'yarn install', { cwd: workspace } # Install composer dependencies locally so that composer.phar doesn't need to # be added the the repository shipit.blTask 'composer', -> shipit.local 'composer install', { cwd: workspace } # ############################################################################ # Manipulate .env files # Vars env_path = "#{shipit.config.deployTo}/shared/.env" # On initial deploy, prompt user for .env values shipit.blTask 'env:create', (done) -> # Check if any of the app servers are missing .env files shipit.remote "[ -f \"#{env_path}\" ] && echo 1 || echo 0" .then (servers) -> # If all servers have an env file, do nothing return done() if !_.find(servers, (server) -> server.stdout.trim() == '0') # Ask user questions to populate the .env file shipit.log '\nNo .env file on remote. Creating using your answers:'.yellow.bold inquirer.prompt firstDeployQuestions(), (answers) -> # Write the env file to the server after converting the answers object # to a multiline string env = _.map(answers, (val, key) -> "#{key}=#{val}").join("\n") shipit.remote "mkdir -p '#{shipit.config.deployTo}/shared'" .then -> shipit.remote "echo '#{env}' > #{env_path}" # Create the database if it doesn't exist .then -> shipit.log 'Creating database if it doesn\'t exist...' shipit.remote "mysql -h #{answers.DB_HOST} -u #{answers.DB_USERNAME} -p#{answers.DB_PASSWORD} -e 'CREATE DATABASE IF NOT EXISTS `#{answers.DB_DATABASE}`'" # Done with this task .then -> done() # Prevent the promise from being returned return # Read the env file shipit.blTask 'env:get', -> getEnv().then (servers) -> shipit.log servers[0].stdout.yellow getEnv = -> shipit.remote "mkdir -p '#{shipit.config.deployTo}/shared'" .then -> shipit.remote "touch #{env_path}" .then -> shipit.remote "cat #{env_path}" # Write a key-vlaue pair to the .env file shipit.blTask 'env:set', (done) -> # Ask user what key-value is being touched shipit.log '\nSupply the key-value pair you want to add:'.yellow.bold inquirer.prompt [ { type: 'input', name: 'key', message: 'Key' } { type: 'input', name: 'value', message: 'Value' } ], (answers) -> # Get the .env contents from each server, creating the .env file if needed getEnv().then (servers) -> env = servers[0].stdout.trim() # If the key is already in the .env, update the value pair = answers.key + <KEY> + answers.value if env.search(new RegExp('^' + answers.key + '=', 'm')) > -1 env = env.replace(new RegExp('^' + answers.key + '=.*$', 'm'), pair) # Otherwise, append to the file else env += "\n" + pair # Write the updated env file shipit.remote "echo '#{env}' > #{env_path}" .then -> done() # Done # ############################################################################ # Project management tasks # Tell Slack about deploy starting shipit.blTask 'slack start', -> slack.send username: 'Starting deployment' text: ":clock1: *#{getDeveloperName()}* is deploying to *#{getEnvironment()}*" channel: config.slackChannel # Tell Slack about deploy finished shipit.blTask 'slack end', -> slack.send username: 'Finished deployment' text: ":checkered_flag: #{shipit.config.url}" channel: config.slackChannel # ############################################################################## # Utils - Helpers used in the Shipit config # ############################################################################## # Determine the repository URL by using the git `origin` remote getOrigin = -> child_process .execSync('git config --local --get remote.origin.url') .toString('utf8') .trim() # Get the environment that is being deployed to getEnvironment = -> process.argv[2] # Get someone's git username and return a promise getDeveloperName = -> name = child_process.execSync 'git config user.name' names = name.toString('utf8').trim().split(' ') return "#{names[0]} #{names[1][0]}." # Muster the questions to prompt the user on initial deploy firstDeployQuestions = -> [ { type: 'input' name: 'APP_ENV' message: 'Environment' default: getEnvironment() } { type: 'input' name: 'DB_HOST' message: 'Database host' default: 'localhost' } { type: 'input' name: 'DB_NAME' message: 'Database name' } { type: 'input' name: 'DB_USERNAME' message: 'Database user' } { type: 'input' name: 'DB_PASSWORD' message: 'Database pass' } ]
true
### This file exports an object that can be to merge configuration into some defaults and then apply them to shipit ### # Deps _ = require 'lodash' crypto = require 'crypto' child_process = require 'child_process' inquirer = require 'inquirer' Slack = require 'node-slack' shipitDeploy = require 'shipit-deploy' shipitShared = require 'shipit-shared' colors = require 'colors' # The Bukwild slack webhook, shared between projects slack = new Slack process.env.SLACK_WEBHOOK # Receives the shipit object and config that should be merged in module.exports = {} module.exports.init = (shipit, config) -> # Load shipit plugins shipitDeploy(shipit) shipitShared(shipit) # Prep some shared vars workspace = "/tmp/#{config.appName}-#{getEnvironment()}" # The default config defaults = default: workspace: workspace # Where the deploy gets prepped locally repositoryUrl: getOrigin() # The repo URL ignores: [ # Don't copy these up '.git', 'node_modules', '.env', '.DS_Store' ] # Config for symlinked directories shared: overwrite: true triggerEvent: false files: [ '.env' ] dirs: [ { path: 'public/wp-content/uploads', chmod: '-R 775' } ] # Merge staging settings with some defaults staging: branch: 'master' # The branch to pull from keepReleases: 1 # Merge production settings with some defaults production: branch: 'production' keepReleases: 3 # Merge stages into the default config and pass to Shipit shipit.initConfig _.defaultsDeep(config, defaults) # ############################################################################ # Events # Tasks that get run before shipit begins shipit.on 'deploy', -> shipit.start 'slack start' if config.slackChannel # After git repo is pulled locally, do yarn installs and then webpack compile shipit.on 'fetched', -> shipit.start ['composer', 'compile'] # After the the remote is updated, run post commands shipit.on 'updated', -> shipit.start ['env:create', 'shared'] # Tasks that get run when shipit ends (the `deployed` even't wasnt firing) shipit.on 'cleaned', -> shipit.start 'slack end' if config.slackChannel # ############################################################################ # Local tasks # Run the Webpack compile task, which is dependant on node dependencies shipit.blTask 'compile', ['composer', 'yarn'], -> shipit.local 'yarn minify', { cwd: workspace } # Install node dependencies shipit.blTask 'yarn', -> shipit.local 'yarn install', { cwd: workspace } # Install composer dependencies locally so that composer.phar doesn't need to # be added the the repository shipit.blTask 'composer', -> shipit.local 'composer install', { cwd: workspace } # ############################################################################ # Manipulate .env files # Vars env_path = "#{shipit.config.deployTo}/shared/.env" # On initial deploy, prompt user for .env values shipit.blTask 'env:create', (done) -> # Check if any of the app servers are missing .env files shipit.remote "[ -f \"#{env_path}\" ] && echo 1 || echo 0" .then (servers) -> # If all servers have an env file, do nothing return done() if !_.find(servers, (server) -> server.stdout.trim() == '0') # Ask user questions to populate the .env file shipit.log '\nNo .env file on remote. Creating using your answers:'.yellow.bold inquirer.prompt firstDeployQuestions(), (answers) -> # Write the env file to the server after converting the answers object # to a multiline string env = _.map(answers, (val, key) -> "#{key}=#{val}").join("\n") shipit.remote "mkdir -p '#{shipit.config.deployTo}/shared'" .then -> shipit.remote "echo '#{env}' > #{env_path}" # Create the database if it doesn't exist .then -> shipit.log 'Creating database if it doesn\'t exist...' shipit.remote "mysql -h #{answers.DB_HOST} -u #{answers.DB_USERNAME} -p#{answers.DB_PASSWORD} -e 'CREATE DATABASE IF NOT EXISTS `#{answers.DB_DATABASE}`'" # Done with this task .then -> done() # Prevent the promise from being returned return # Read the env file shipit.blTask 'env:get', -> getEnv().then (servers) -> shipit.log servers[0].stdout.yellow getEnv = -> shipit.remote "mkdir -p '#{shipit.config.deployTo}/shared'" .then -> shipit.remote "touch #{env_path}" .then -> shipit.remote "cat #{env_path}" # Write a key-vlaue pair to the .env file shipit.blTask 'env:set', (done) -> # Ask user what key-value is being touched shipit.log '\nSupply the key-value pair you want to add:'.yellow.bold inquirer.prompt [ { type: 'input', name: 'key', message: 'Key' } { type: 'input', name: 'value', message: 'Value' } ], (answers) -> # Get the .env contents from each server, creating the .env file if needed getEnv().then (servers) -> env = servers[0].stdout.trim() # If the key is already in the .env, update the value pair = answers.key + PI:KEY:<KEY>END_PI + answers.value if env.search(new RegExp('^' + answers.key + '=', 'm')) > -1 env = env.replace(new RegExp('^' + answers.key + '=.*$', 'm'), pair) # Otherwise, append to the file else env += "\n" + pair # Write the updated env file shipit.remote "echo '#{env}' > #{env_path}" .then -> done() # Done # ############################################################################ # Project management tasks # Tell Slack about deploy starting shipit.blTask 'slack start', -> slack.send username: 'Starting deployment' text: ":clock1: *#{getDeveloperName()}* is deploying to *#{getEnvironment()}*" channel: config.slackChannel # Tell Slack about deploy finished shipit.blTask 'slack end', -> slack.send username: 'Finished deployment' text: ":checkered_flag: #{shipit.config.url}" channel: config.slackChannel # ############################################################################## # Utils - Helpers used in the Shipit config # ############################################################################## # Determine the repository URL by using the git `origin` remote getOrigin = -> child_process .execSync('git config --local --get remote.origin.url') .toString('utf8') .trim() # Get the environment that is being deployed to getEnvironment = -> process.argv[2] # Get someone's git username and return a promise getDeveloperName = -> name = child_process.execSync 'git config user.name' names = name.toString('utf8').trim().split(' ') return "#{names[0]} #{names[1][0]}." # Muster the questions to prompt the user on initial deploy firstDeployQuestions = -> [ { type: 'input' name: 'APP_ENV' message: 'Environment' default: getEnvironment() } { type: 'input' name: 'DB_HOST' message: 'Database host' default: 'localhost' } { type: 'input' name: 'DB_NAME' message: 'Database name' } { type: 'input' name: 'DB_USERNAME' message: 'Database user' } { type: 'input' name: 'DB_PASSWORD' message: 'Database pass' } ]
[ { "context": "#\n# Copyright 2016 Kinvey, Inc.\n#\n# Licensed under the Apache License, Vers", "end": 25, "score": 0.5352257490158081, "start": 19, "tag": "NAME", "value": "Kinvey" } ]
lib/routes/configuration.coffee
enterstudio/business-logic-mock-proxy
2
# # Copyright 2016 Kinvey, 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. # async = require 'async' Busboy = require 'busboy' JSONStream = require 'JSONStream' JSZip = require 'jszip' dataStore = require '../data-store' errors = require '../errors' dropAllData = (req, res, next) -> dataStore.dropDatabase (err) -> if err then return next errors.createKinveyError 'MongoError', err.toString() res.status(204).send() next() importCollectionData = (req, res, next) -> importStats = {} pending = 0 try busboy = new Busboy { headers: req.headers } catch e msg = e.message?.toLowerCase?() ? e.toString?() ? '' if msg.indexOf('unsupported content type') >= 0 return next errors.createKinveyError 'DataImportError', 'Only JSON files can be imported' return next errors.createKinveyError 'DataImportError', msg # only drop a collection once per import request. # this avoids accidentally inserting data into a collection and then dropping it droppedCollections = {} dropCollectionOnlyOnce = (collectionName, callback) -> if droppedCollections.hasOwnProperty collectionName return callback() droppedCollections[collectionName] = true dataStore.dropCollection collectionName, callback busboy.on 'file', (field, file, filename, encoding, mimetype) -> pending += 1 if req.query?.collectionName? collectionName = req.query.collectionName else jsonIndex = filename.indexOf '.json' if jsonIndex >= 0 collectionName = filename.substring 0, jsonIndex else collectionName = filename dropCollectionOnlyOnce collectionName, (err, result) -> # an error will be returned if the collection doesn't exist. ignore it. dataStore.createCollection collectionName, (err, collection) -> if err then return next errors.createKinveyError 'DataImportError', err.toString() stream = file.pipe JSONStream.parse '*' stream.on 'data', (data) -> pending += 1 collection.insert data, { w: 1 }, (err, insertedEntities) -> if err? console.log err msg = err.stack ? err.message ? err.description ? err.error?.debug if typeof msg is 'object' try msg = JSON.stringify msg importStats[collectionName] ?= {} importStats[collectionName].importErrors ?= [] importStats[collectionName].importErrors.push msg else importStats[collectionName] ?= {} importStats[collectionName].numberImported ?= 0 importStats[collectionName].numberImported += 1 pending -= 1 stream.on 'end', -> pending -= 1 # Fail if the file size limit has been reached. stream.on 'limit', -> next? errors.createKinveyError 'DataImportError', 'File size limit exceeded' next = null # Reset. # Terminate on error. stream.on 'error', (err) -> # Continue (once). next? errors.createKinveyError 'DataImportError', 'There might be a syntax error in the file you are trying to import' next = null # Reset. sendResponseWhenFinished = () -> if pending > 0 return setTimeout sendResponseWhenFinished, 500 res.status(201).json importStats next() busboy.on 'finish', sendResponseWhenFinished req.pipe busboy getCollectionNames = (req, res, next) -> if req.query?.collectionName? req.collectionNames = [{ name: req.query.collectionName }] next() else dataStore.collectionNames (err, collectionNames) -> if err then return next errors.createKinveyError 'MongoError', err.toString() req.collectionNames = collectionNames next() exportCollectionData = (req, res, next) -> zip = new JSZip() collectionIterator = (collection, doneWithCollection) -> namespacedCollectionName = collection.name collectionName = namespacedCollectionName.substring(namespacedCollectionName.indexOf('.') + 1) dataStore.collection(collectionName).find({}).toArray (err, collectionData) -> if err then return next errors.createKinveyError 'MongoError', err.toString() try zip.file "#{collectionName}.json", JSON.stringify collectionData catch e return next errors.createKinveyError 'MongoError', e.toString() doneWithCollection() async.each req.collectionNames, collectionIterator, (err) -> if err then return next errors.createKinveyError 'MongoError', err.toString() try zippedBuffer = zip.generate { type: 'nodebuffer' } catch e return next errors.createKinveyError 'MongoError', e.toString() if req.query?.collectionName? filename = req.query.collectionName else filename = 'collectionData' filename += '-' + (new Date().getTime()) + '.zip' res.header 'Content-Disposition', 'attachment; filename=' + filename res.status(200).send zippedBuffer module.exports.installRoutes = (app) -> app.post '/configuration/collectionData/dropAllData', dropAllData app.post '/configuration/collectionData/import', importCollectionData app.get '/configuration/collectionData/export', getCollectionNames, exportCollectionData
170399
# # Copyright 2016 <NAME>, 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. # async = require 'async' Busboy = require 'busboy' JSONStream = require 'JSONStream' JSZip = require 'jszip' dataStore = require '../data-store' errors = require '../errors' dropAllData = (req, res, next) -> dataStore.dropDatabase (err) -> if err then return next errors.createKinveyError 'MongoError', err.toString() res.status(204).send() next() importCollectionData = (req, res, next) -> importStats = {} pending = 0 try busboy = new Busboy { headers: req.headers } catch e msg = e.message?.toLowerCase?() ? e.toString?() ? '' if msg.indexOf('unsupported content type') >= 0 return next errors.createKinveyError 'DataImportError', 'Only JSON files can be imported' return next errors.createKinveyError 'DataImportError', msg # only drop a collection once per import request. # this avoids accidentally inserting data into a collection and then dropping it droppedCollections = {} dropCollectionOnlyOnce = (collectionName, callback) -> if droppedCollections.hasOwnProperty collectionName return callback() droppedCollections[collectionName] = true dataStore.dropCollection collectionName, callback busboy.on 'file', (field, file, filename, encoding, mimetype) -> pending += 1 if req.query?.collectionName? collectionName = req.query.collectionName else jsonIndex = filename.indexOf '.json' if jsonIndex >= 0 collectionName = filename.substring 0, jsonIndex else collectionName = filename dropCollectionOnlyOnce collectionName, (err, result) -> # an error will be returned if the collection doesn't exist. ignore it. dataStore.createCollection collectionName, (err, collection) -> if err then return next errors.createKinveyError 'DataImportError', err.toString() stream = file.pipe JSONStream.parse '*' stream.on 'data', (data) -> pending += 1 collection.insert data, { w: 1 }, (err, insertedEntities) -> if err? console.log err msg = err.stack ? err.message ? err.description ? err.error?.debug if typeof msg is 'object' try msg = JSON.stringify msg importStats[collectionName] ?= {} importStats[collectionName].importErrors ?= [] importStats[collectionName].importErrors.push msg else importStats[collectionName] ?= {} importStats[collectionName].numberImported ?= 0 importStats[collectionName].numberImported += 1 pending -= 1 stream.on 'end', -> pending -= 1 # Fail if the file size limit has been reached. stream.on 'limit', -> next? errors.createKinveyError 'DataImportError', 'File size limit exceeded' next = null # Reset. # Terminate on error. stream.on 'error', (err) -> # Continue (once). next? errors.createKinveyError 'DataImportError', 'There might be a syntax error in the file you are trying to import' next = null # Reset. sendResponseWhenFinished = () -> if pending > 0 return setTimeout sendResponseWhenFinished, 500 res.status(201).json importStats next() busboy.on 'finish', sendResponseWhenFinished req.pipe busboy getCollectionNames = (req, res, next) -> if req.query?.collectionName? req.collectionNames = [{ name: req.query.collectionName }] next() else dataStore.collectionNames (err, collectionNames) -> if err then return next errors.createKinveyError 'MongoError', err.toString() req.collectionNames = collectionNames next() exportCollectionData = (req, res, next) -> zip = new JSZip() collectionIterator = (collection, doneWithCollection) -> namespacedCollectionName = collection.name collectionName = namespacedCollectionName.substring(namespacedCollectionName.indexOf('.') + 1) dataStore.collection(collectionName).find({}).toArray (err, collectionData) -> if err then return next errors.createKinveyError 'MongoError', err.toString() try zip.file "#{collectionName}.json", JSON.stringify collectionData catch e return next errors.createKinveyError 'MongoError', e.toString() doneWithCollection() async.each req.collectionNames, collectionIterator, (err) -> if err then return next errors.createKinveyError 'MongoError', err.toString() try zippedBuffer = zip.generate { type: 'nodebuffer' } catch e return next errors.createKinveyError 'MongoError', e.toString() if req.query?.collectionName? filename = req.query.collectionName else filename = 'collectionData' filename += '-' + (new Date().getTime()) + '.zip' res.header 'Content-Disposition', 'attachment; filename=' + filename res.status(200).send zippedBuffer module.exports.installRoutes = (app) -> app.post '/configuration/collectionData/dropAllData', dropAllData app.post '/configuration/collectionData/import', importCollectionData app.get '/configuration/collectionData/export', getCollectionNames, exportCollectionData
true
# # Copyright 2016 PI:NAME:<NAME>END_PI, 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. # async = require 'async' Busboy = require 'busboy' JSONStream = require 'JSONStream' JSZip = require 'jszip' dataStore = require '../data-store' errors = require '../errors' dropAllData = (req, res, next) -> dataStore.dropDatabase (err) -> if err then return next errors.createKinveyError 'MongoError', err.toString() res.status(204).send() next() importCollectionData = (req, res, next) -> importStats = {} pending = 0 try busboy = new Busboy { headers: req.headers } catch e msg = e.message?.toLowerCase?() ? e.toString?() ? '' if msg.indexOf('unsupported content type') >= 0 return next errors.createKinveyError 'DataImportError', 'Only JSON files can be imported' return next errors.createKinveyError 'DataImportError', msg # only drop a collection once per import request. # this avoids accidentally inserting data into a collection and then dropping it droppedCollections = {} dropCollectionOnlyOnce = (collectionName, callback) -> if droppedCollections.hasOwnProperty collectionName return callback() droppedCollections[collectionName] = true dataStore.dropCollection collectionName, callback busboy.on 'file', (field, file, filename, encoding, mimetype) -> pending += 1 if req.query?.collectionName? collectionName = req.query.collectionName else jsonIndex = filename.indexOf '.json' if jsonIndex >= 0 collectionName = filename.substring 0, jsonIndex else collectionName = filename dropCollectionOnlyOnce collectionName, (err, result) -> # an error will be returned if the collection doesn't exist. ignore it. dataStore.createCollection collectionName, (err, collection) -> if err then return next errors.createKinveyError 'DataImportError', err.toString() stream = file.pipe JSONStream.parse '*' stream.on 'data', (data) -> pending += 1 collection.insert data, { w: 1 }, (err, insertedEntities) -> if err? console.log err msg = err.stack ? err.message ? err.description ? err.error?.debug if typeof msg is 'object' try msg = JSON.stringify msg importStats[collectionName] ?= {} importStats[collectionName].importErrors ?= [] importStats[collectionName].importErrors.push msg else importStats[collectionName] ?= {} importStats[collectionName].numberImported ?= 0 importStats[collectionName].numberImported += 1 pending -= 1 stream.on 'end', -> pending -= 1 # Fail if the file size limit has been reached. stream.on 'limit', -> next? errors.createKinveyError 'DataImportError', 'File size limit exceeded' next = null # Reset. # Terminate on error. stream.on 'error', (err) -> # Continue (once). next? errors.createKinveyError 'DataImportError', 'There might be a syntax error in the file you are trying to import' next = null # Reset. sendResponseWhenFinished = () -> if pending > 0 return setTimeout sendResponseWhenFinished, 500 res.status(201).json importStats next() busboy.on 'finish', sendResponseWhenFinished req.pipe busboy getCollectionNames = (req, res, next) -> if req.query?.collectionName? req.collectionNames = [{ name: req.query.collectionName }] next() else dataStore.collectionNames (err, collectionNames) -> if err then return next errors.createKinveyError 'MongoError', err.toString() req.collectionNames = collectionNames next() exportCollectionData = (req, res, next) -> zip = new JSZip() collectionIterator = (collection, doneWithCollection) -> namespacedCollectionName = collection.name collectionName = namespacedCollectionName.substring(namespacedCollectionName.indexOf('.') + 1) dataStore.collection(collectionName).find({}).toArray (err, collectionData) -> if err then return next errors.createKinveyError 'MongoError', err.toString() try zip.file "#{collectionName}.json", JSON.stringify collectionData catch e return next errors.createKinveyError 'MongoError', e.toString() doneWithCollection() async.each req.collectionNames, collectionIterator, (err) -> if err then return next errors.createKinveyError 'MongoError', err.toString() try zippedBuffer = zip.generate { type: 'nodebuffer' } catch e return next errors.createKinveyError 'MongoError', e.toString() if req.query?.collectionName? filename = req.query.collectionName else filename = 'collectionData' filename += '-' + (new Date().getTime()) + '.zip' res.header 'Content-Disposition', 'attachment; filename=' + filename res.status(200).send zippedBuffer module.exports.installRoutes = (app) -> app.post '/configuration/collectionData/dropAllData', dropAllData app.post '/configuration/collectionData/import', importCollectionData app.get '/configuration/collectionData/export', getCollectionNames, exportCollectionData
[ { "context": " backbone-orm.js 0.7.14\n Copyright (c) 2013-2016 Vidigami\n License: MIT (http://www.opensource.org/license", "end": 63, "score": 0.9998615980148315, "start": 55, "tag": "NAME", "value": "Vidigami" }, { "context": "ses/mit-license.php)\n Source: https://github.com/...
src/cache/model_cache.coffee
dk-dev/backbone-orm
54
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 Vidigami License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### Backbone = require 'backbone' _ = require 'underscore' Queue = require '../lib/queue' MemoryStore = require './memory_store' module.exports = class ModelCache constructor: -> @enabled = false @caches = {} @options = {modelTypes: {}} @verbose = false # @verbose = true # Configure the cache singleton # # options: # max: default maximum number of items or max size of the cache # max_age/maxAge: default maximum number of items or max size of the cache # model_types/modelTypes: {'ModelName': options} # configure: (options={}) -> @enabled = options.enabled for key, value of options if _.isObject(value) @options[key] or= {} values = @options[key] values[value_key] = value_value for value_key, value_value of value else @options[key] = value @reset() configureSync: (model_type, sync_fn) -> return sync_fn if model_type::_orm_never_cache or not @createCache(model_type) return (require './sync')(model_type, sync_fn) reset: -> @createCache(value.model_type) for key, value of @caches # @nodoc createCache: (model_type) -> throw new Error "Missing model name for cache" unless model_name = model_type?.model_name cuid = model_type.cuid or= _.uniqueId('cuid') # delete old cache if cache_info = @caches[cuid] delete @caches[cuid]; cache_info.cache.reset(); cache_info.model_type.cache = null return null unless @enabled # there are options meaning a cache should be created unless options = @options.modelTypes[model_name] return null unless (@options.store or @options.max or @options.max_age) # no options so no cache options = @options cache_info = @caches[cuid] = {cache: options.store?() or new MemoryStore(options), model_type: model_type} return model_type.cache = cache_info.cache
198431
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 <NAME> License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### Backbone = require 'backbone' _ = require 'underscore' Queue = require '../lib/queue' MemoryStore = require './memory_store' module.exports = class ModelCache constructor: -> @enabled = false @caches = {} @options = {modelTypes: {}} @verbose = false # @verbose = true # Configure the cache singleton # # options: # max: default maximum number of items or max size of the cache # max_age/maxAge: default maximum number of items or max size of the cache # model_types/modelTypes: {'ModelName': options} # configure: (options={}) -> @enabled = options.enabled for key, value of options if _.isObject(value) @options[key] or= {} values = @options[key] values[value_key] = value_value for value_key, value_value of value else @options[key] = value @reset() configureSync: (model_type, sync_fn) -> return sync_fn if model_type::_orm_never_cache or not @createCache(model_type) return (require './sync')(model_type, sync_fn) reset: -> @createCache(value.model_type) for key, value of @caches # @nodoc createCache: (model_type) -> throw new Error "Missing model name for cache" unless model_name = model_type?.model_name cuid = model_type.cuid or= _.uniqueId('cuid') # delete old cache if cache_info = @caches[cuid] delete @caches[cuid]; cache_info.cache.reset(); cache_info.model_type.cache = null return null unless @enabled # there are options meaning a cache should be created unless options = @options.modelTypes[model_name] return null unless (@options.store or @options.max or @options.max_age) # no options so no cache options = @options cache_info = @caches[cuid] = {cache: options.store?() or new MemoryStore(options), model_type: model_type} return model_type.cache = cache_info.cache
true
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 PI:NAME:<NAME>END_PI License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### Backbone = require 'backbone' _ = require 'underscore' Queue = require '../lib/queue' MemoryStore = require './memory_store' module.exports = class ModelCache constructor: -> @enabled = false @caches = {} @options = {modelTypes: {}} @verbose = false # @verbose = true # Configure the cache singleton # # options: # max: default maximum number of items or max size of the cache # max_age/maxAge: default maximum number of items or max size of the cache # model_types/modelTypes: {'ModelName': options} # configure: (options={}) -> @enabled = options.enabled for key, value of options if _.isObject(value) @options[key] or= {} values = @options[key] values[value_key] = value_value for value_key, value_value of value else @options[key] = value @reset() configureSync: (model_type, sync_fn) -> return sync_fn if model_type::_orm_never_cache or not @createCache(model_type) return (require './sync')(model_type, sync_fn) reset: -> @createCache(value.model_type) for key, value of @caches # @nodoc createCache: (model_type) -> throw new Error "Missing model name for cache" unless model_name = model_type?.model_name cuid = model_type.cuid or= _.uniqueId('cuid') # delete old cache if cache_info = @caches[cuid] delete @caches[cuid]; cache_info.cache.reset(); cache_info.model_type.cache = null return null unless @enabled # there are options meaning a cache should be created unless options = @options.modelTypes[model_name] return null unless (@options.store or @options.max or @options.max_age) # no options so no cache options = @options cache_info = @caches[cuid] = {cache: options.store?() or new MemoryStore(options), model_type: model_type} return model_type.cache = cache_info.cache
[ { "context": " ( done ) ->\n AgentModel.create(\n email: 'test+graph+routes@joukou.com'\n name: 'test/graph/routes'\n password: ", "end": 1134, "score": 0.9999004006385803, "start": 1106, "tag": "EMAIL", "value": "test+graph+routes@joukou.com" }, { "context": "\n ...
test/persona/graph/routes.coffee
joukou/joukou-api
0
"use strict" ###* Copyright 2014 Joukou Ltd 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. ### assert = require( 'assert' ) chai = require( 'chai' ) should = chai.should() chai.use( require( 'chai-http' ) ) async = require( 'async' ) server = require( '../../../dist/server' ) riakpbc = require( '../../../dist/riak/pbc' ) AgentModel = require( '../../../dist/agent/Model' ) GraphModel = require( '../../../dist/persona/graph/Model' ) PersonaModel = require( '../../../dist/persona/Model' ) describe 'persona/graph/routes', -> agentKey = null personaKey = null before ( done ) -> AgentModel.create( email: 'test+graph+routes@joukou.com' name: 'test/graph/routes' password: 'password' ).then( ( agent ) -> agent.save() ) .then( ( agent ) -> agentKey = agent.getKey() PersonaModel.create( name: 'test/graph/routes' agents: [ { key: agentKey role: 'creator' } ] ) ) .then( ( persona ) -> persona.save() ) .then( ( persona ) -> personaKey = persona.getKey() done() ) .fail( ( err ) -> done( err ) ) after ( done ) -> async.parallel([ ( next ) -> riakpbc.del( type: 'agent' bucket: 'agent' key: agentKey , ( err, reply ) -> next( err ) ) ( next ) -> riakpbc.del( type: 'persona' bucket: 'persona' key: personaKey , ( err, reply ) -> next( err ) ) ], ( err ) -> done( err ) ) describe 'POST /persona/:personaKey/graph', -> specify 'creates a graph', ( done ) -> chai.request( server ) .post( "/persona/#{personaKey}/graph" ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('test+graph+routes@joukou.com:password').toString('base64')}" ) req.send( name: 'Test Graph Routes' ) ) .res( ( res ) -> res.should.have.status( 201 ) res.headers.location.should.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ ) graphKey = res.headers.location.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ] chai.request( server ) .get( res.headers.location ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('test+graph+routes@joukou.com:password').toString('base64')}" ) ) .res( ( res ) -> res.should.have.status( 200 ) res.body.should.deep.equal( name: 'Test Graph Routes' _embedded: 'joukou:process': [] 'joukou:connection': [] _links: 'joukou:persona': [ { href: "/persona/#{personaKey}" } ] 'joukou:process-create': [ { title: 'Add a Process to this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/process" } ] 'joukou:processes': [ { title: 'List of Processes for this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/process" } ] 'joukou:connection-create': [ { title: 'Add a Connection to this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/connection" } ] 'joukou:connections': [ { title: 'List of Connections for this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/connection" } ] self: href: "/persona/#{personaKey}/graph/#{graphKey}" curies: [ { name: 'joukou' templated: true href: 'https://rels.joukou.com/{rel}' } ] ) riakpbc.del( type: 'graph' bucket: 'graph' key: graphKey , ( err, reply ) -> done( err ) ) ) ) describe 'GET /persona/:personaKey/graph/:graphKey', -> specify 'responds with 404 NotFound status code if the provided graph key is not valid', ( done ) -> chai.request( server ) .get( '/persona/e78cd405-8dce-472d-82bb-88c9862a58d1/graph/7ec23d7d-9522-478c-97a4-2f577335e023' ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('test+graph+routes@joukou.com:password').toString('base64')}" ) ) .res( ( res ) -> res.should.have.status( 404 ) res.body.should.be.empty done() ) describe 'POST /persona/:personaKey/graph/:graphKey/process', -> graphKey = null before ( done ) -> GraphModel.create( properties: name: 'Add Process Test' personas: [ { key: personaKey } ] ) .then( ( graph ) -> graph.save() ) .then( ( graph ) -> graphKey = graph.getKey() done() ) .fail( ( err ) -> done( err ) ) specify 'adds a process to a graph', ( done ) -> chai.request( server ) .post( "/persona/#{personaKey}/graph/#{graphKey}/process" ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('test+graph+routes@joukou.com:password').toString('base64')}" ) req.send( _links: 'joukou:circle': href: "/persona/#{personaKey}/circle/7eee9052-5a7e-410d-9cb7-6e099c489001" metadata: x: 100 y: 100 ) ) .res( ( res ) -> res.should.have.status( 201 ) res.headers.location.should.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/process\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ ) processKey = res.headers.location.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/process\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ] res.body.should.deep.equal( _links: self: href: "/persona/#{personaKey}/graph/#{graphKey}/process" curies: [ { name: 'joukou' templated: true href: 'https://rels.joukou.com/{rel}' } ] 'joukou:process': [ href: "/persona/#{personaKey}/graph/#{graphKey}/process/#{processKey}" ] ) chai.request( server ) .get( res.headers.location ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('test+graph+routes@joukou.com:password').toString('base64')}" ) ) .res( ( res ) -> res.should.have.status( 200 ) res.body.should.deep.equal( metadata: x: 100 y: 100 _links: self: href: "/persona/#{personaKey}/graph/#{graphKey}/process/#{processKey}" curies: [ { name: 'joukou' templated: true href: 'https://rels.joukou.com/{rel}' } ] 'joukou:circle': [ { href: "/persona/#{personaKey}/circle/7eee9052-5a7e-410d-9cb7-6e099c489001" } ] ) done() ) )
29256
"use strict" ###* Copyright 2014 Joukou Ltd 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. ### assert = require( 'assert' ) chai = require( 'chai' ) should = chai.should() chai.use( require( 'chai-http' ) ) async = require( 'async' ) server = require( '../../../dist/server' ) riakpbc = require( '../../../dist/riak/pbc' ) AgentModel = require( '../../../dist/agent/Model' ) GraphModel = require( '../../../dist/persona/graph/Model' ) PersonaModel = require( '../../../dist/persona/Model' ) describe 'persona/graph/routes', -> agentKey = null personaKey = null before ( done ) -> AgentModel.create( email: '<EMAIL>' name: 'test/graph/routes' password: '<PASSWORD>' ).then( ( agent ) -> agent.save() ) .then( ( agent ) -> agentKey = agent.getKey() PersonaModel.create( name: 'test/graph/routes' agents: [ { key: agentKey role: 'creator' } ] ) ) .then( ( persona ) -> persona.save() ) .then( ( persona ) -> personaKey = persona.getKey() done() ) .fail( ( err ) -> done( err ) ) after ( done ) -> async.parallel([ ( next ) -> riakpbc.del( type: 'agent' bucket: 'agent' key: agentKey , ( err, reply ) -> next( err ) ) ( next ) -> riakpbc.del( type: 'persona' bucket: 'persona' key: personaKey , ( err, reply ) -> next( err ) ) ], ( err ) -> done( err ) ) describe 'POST /persona/:personaKey/graph', -> specify 'creates a graph', ( done ) -> chai.request( server ) .post( "/persona/#{personaKey}/graph" ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('<EMAIL>:password').toString('base64')}" ) req.send( name: 'Test Graph Routes' ) ) .res( ( res ) -> res.should.have.status( 201 ) res.headers.location.should.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ ) graphKey = res.headers.location.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ] chai.request( server ) .get( res.headers.location ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('<EMAIL>:password').toString('base64')}" ) ) .res( ( res ) -> res.should.have.status( 200 ) res.body.should.deep.equal( name: 'Test Graph Routes' _embedded: 'joukou:process': [] 'joukou:connection': [] _links: 'joukou:persona': [ { href: "/persona/#{personaKey}" } ] 'joukou:process-create': [ { title: 'Add a Process to this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/process" } ] 'joukou:processes': [ { title: 'List of Processes for this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/process" } ] 'joukou:connection-create': [ { title: 'Add a Connection to this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/connection" } ] 'joukou:connections': [ { title: 'List of Connections for this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/connection" } ] self: href: "/persona/#{personaKey}/graph/#{graphKey}" curies: [ { name: 'joukou' templated: true href: 'https://rels.joukou.com/{rel}' } ] ) riakpbc.del( type: 'graph' bucket: 'graph' key: graphKey , ( err, reply ) -> done( err ) ) ) ) describe 'GET /persona/:personaKey/graph/:graphKey', -> specify 'responds with 404 NotFound status code if the provided graph key is not valid', ( done ) -> chai.request( server ) .get( '/persona/e78cd405-8dce-472d-82bb-88c9862a58d1/graph/7ec23d7d-9522-478c-97a4-2f577335e023' ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('<EMAIL>:password').toString('base64')}" ) ) .res( ( res ) -> res.should.have.status( 404 ) res.body.should.be.empty done() ) describe 'POST /persona/:personaKey/graph/:graphKey/process', -> graphKey = null before ( done ) -> GraphModel.create( properties: name: '<NAME>' personas: [ { key: personaKey } ] ) .then( ( graph ) -> graph.save() ) .then( ( graph ) -> graphKey = graph.getKey() done() ) .fail( ( err ) -> done( err ) ) specify 'adds a process to a graph', ( done ) -> chai.request( server ) .post( "/persona/#{personaKey}/graph/#{graphKey}/process" ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('<EMAIL>+<EMAIL>:password').toString('base64')}" ) req.send( _links: 'joukou:circle': href: "/persona/#{personaKey}/circle/7eee9052-5a7e-410d-9cb7-6e099c489001" metadata: x: 100 y: 100 ) ) .res( ( res ) -> res.should.have.status( 201 ) res.headers.location.should.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/process\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ ) processKey = res.headers.location.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/process\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ] res.body.should.deep.equal( _links: self: href: "/persona/#{personaKey}/graph/#{graphKey}/process" curies: [ { name: '<NAME>' templated: true href: 'https://rels.joukou.com/{rel}' } ] 'joukou:process': [ href: "/persona/#{personaKey}/graph/#{graphKey}/process/#{processKey}" ] ) chai.request( server ) .get( res.headers.location ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('<EMAIL>:password').toString('base64')}" ) ) .res( ( res ) -> res.should.have.status( 200 ) res.body.should.deep.equal( metadata: x: 100 y: 100 _links: self: href: "/persona/#{personaKey}/graph/#{graphKey}/process/#{processKey}" curies: [ { name: '<NAME>' templated: true href: 'https://rels.joukou.com/{rel}' } ] 'joukou:circle': [ { href: "/persona/#{personaKey}/circle/7eee9052-5a7e-410d-9cb7-6e099c489001" } ] ) done() ) )
true
"use strict" ###* Copyright 2014 Joukou Ltd 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. ### assert = require( 'assert' ) chai = require( 'chai' ) should = chai.should() chai.use( require( 'chai-http' ) ) async = require( 'async' ) server = require( '../../../dist/server' ) riakpbc = require( '../../../dist/riak/pbc' ) AgentModel = require( '../../../dist/agent/Model' ) GraphModel = require( '../../../dist/persona/graph/Model' ) PersonaModel = require( '../../../dist/persona/Model' ) describe 'persona/graph/routes', -> agentKey = null personaKey = null before ( done ) -> AgentModel.create( email: 'PI:EMAIL:<EMAIL>END_PI' name: 'test/graph/routes' password: 'PI:PASSWORD:<PASSWORD>END_PI' ).then( ( agent ) -> agent.save() ) .then( ( agent ) -> agentKey = agent.getKey() PersonaModel.create( name: 'test/graph/routes' agents: [ { key: agentKey role: 'creator' } ] ) ) .then( ( persona ) -> persona.save() ) .then( ( persona ) -> personaKey = persona.getKey() done() ) .fail( ( err ) -> done( err ) ) after ( done ) -> async.parallel([ ( next ) -> riakpbc.del( type: 'agent' bucket: 'agent' key: agentKey , ( err, reply ) -> next( err ) ) ( next ) -> riakpbc.del( type: 'persona' bucket: 'persona' key: personaKey , ( err, reply ) -> next( err ) ) ], ( err ) -> done( err ) ) describe 'POST /persona/:personaKey/graph', -> specify 'creates a graph', ( done ) -> chai.request( server ) .post( "/persona/#{personaKey}/graph" ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('PI:EMAIL:<EMAIL>END_PI:password').toString('base64')}" ) req.send( name: 'Test Graph Routes' ) ) .res( ( res ) -> res.should.have.status( 201 ) res.headers.location.should.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ ) graphKey = res.headers.location.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ] chai.request( server ) .get( res.headers.location ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('PI:EMAIL:<EMAIL>END_PI:password').toString('base64')}" ) ) .res( ( res ) -> res.should.have.status( 200 ) res.body.should.deep.equal( name: 'Test Graph Routes' _embedded: 'joukou:process': [] 'joukou:connection': [] _links: 'joukou:persona': [ { href: "/persona/#{personaKey}" } ] 'joukou:process-create': [ { title: 'Add a Process to this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/process" } ] 'joukou:processes': [ { title: 'List of Processes for this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/process" } ] 'joukou:connection-create': [ { title: 'Add a Connection to this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/connection" } ] 'joukou:connections': [ { title: 'List of Connections for this Graph' href: "/persona/#{personaKey}/graph/#{graphKey}/connection" } ] self: href: "/persona/#{personaKey}/graph/#{graphKey}" curies: [ { name: 'joukou' templated: true href: 'https://rels.joukou.com/{rel}' } ] ) riakpbc.del( type: 'graph' bucket: 'graph' key: graphKey , ( err, reply ) -> done( err ) ) ) ) describe 'GET /persona/:personaKey/graph/:graphKey', -> specify 'responds with 404 NotFound status code if the provided graph key is not valid', ( done ) -> chai.request( server ) .get( '/persona/e78cd405-8dce-472d-82bb-88c9862a58d1/graph/7ec23d7d-9522-478c-97a4-2f577335e023' ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('PI:EMAIL:<EMAIL>END_PI:password').toString('base64')}" ) ) .res( ( res ) -> res.should.have.status( 404 ) res.body.should.be.empty done() ) describe 'POST /persona/:personaKey/graph/:graphKey/process', -> graphKey = null before ( done ) -> GraphModel.create( properties: name: 'PI:NAME:<NAME>END_PI' personas: [ { key: personaKey } ] ) .then( ( graph ) -> graph.save() ) .then( ( graph ) -> graphKey = graph.getKey() done() ) .fail( ( err ) -> done( err ) ) specify 'adds a process to a graph', ( done ) -> chai.request( server ) .post( "/persona/#{personaKey}/graph/#{graphKey}/process" ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('PI:EMAIL:<EMAIL>END_PI+PI:EMAIL:<EMAIL>END_PI:password').toString('base64')}" ) req.send( _links: 'joukou:circle': href: "/persona/#{personaKey}/circle/7eee9052-5a7e-410d-9cb7-6e099c489001" metadata: x: 100 y: 100 ) ) .res( ( res ) -> res.should.have.status( 201 ) res.headers.location.should.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/process\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ ) processKey = res.headers.location.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/graph\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\/process\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ] res.body.should.deep.equal( _links: self: href: "/persona/#{personaKey}/graph/#{graphKey}/process" curies: [ { name: 'PI:NAME:<NAME>END_PI' templated: true href: 'https://rels.joukou.com/{rel}' } ] 'joukou:process': [ href: "/persona/#{personaKey}/graph/#{graphKey}/process/#{processKey}" ] ) chai.request( server ) .get( res.headers.location ) .req( ( req ) -> req.set( 'Authorization', "Basic #{new Buffer('PI:EMAIL:<EMAIL>END_PI:password').toString('base64')}" ) ) .res( ( res ) -> res.should.have.status( 200 ) res.body.should.deep.equal( metadata: x: 100 y: 100 _links: self: href: "/persona/#{personaKey}/graph/#{graphKey}/process/#{processKey}" curies: [ { name: 'PI:NAME:<NAME>END_PI' templated: true href: 'https://rels.joukou.com/{rel}' } ] 'joukou:circle': [ { href: "/persona/#{personaKey}/circle/7eee9052-5a7e-410d-9cb7-6e099c489001" } ] ) done() ) )
[ { "context": "eModel\"\n view.defines\n stateful:\n key1: \"val1\"\n key2: \"val2\"\n\n it \"should create a state ", "end": 213, "score": 0.9942843914031982, "start": 209, "tag": "KEY", "value": "val1" }, { "context": "nes\n stateful:\n key1: \"val1\"\n k...
spec/javascripts/concerns/state_model_spec.coffee
datapimp/luca
4
describe 'The State Model Concern', -> view = Luca.register "Luca.components.StatefulView" view.extends "Luca.View" view.mixesIn "StateModel" view.defines stateful: key1: "val1" key2: "val2" it "should create a state model on the view", -> view = new Luca.components.StatefulView() expect( view.state ).toBeDefined() expect( Luca.isBackboneModel(view.state) ).toEqual true it "should delegate the get method on the state model to the view", -> view = new Luca.components.StatefulView() expect( view.get ).toBeDefined() expect( view.get('key1') ).toEqual 'val1' it "should delegate the set method on the state model to the view", -> view = new Luca.components.StatefulView() view.set('key1','boom') expect( view.state.get('key1') ).toEqual 'boom' it "should apply the default state attributes", -> view = new Luca.components.StatefulView() expect( view.state.toJSON() ).toEqual key1:"val1", key2: "val2" it "should define a get/set method on the view which effect state", -> view = new Luca.components.StatefulView() view.set('testsetter', 'works') expect( view.get('testsetter') ).toEqual('works') describe 'State Change Event Bindings', -> it "should trigger state change events on the view", -> view = new Luca.components.StatefulView() view.set('key1','boom') expect( view ).toHaveTriggered("state:change") it "should trigger individual attribute change events on the view", -> view = new Luca.components.StatefulView() view.set('key1','boom') expect( view ).toHaveTriggered("state:change:key1") it "should respond to @stateChangeEvents configuration", -> view = new Luca.components.StatefulView onKeyChange: sinon.spy() blah: sinon.spy() stateChangeEvents: "key1" : "onKeyChange" "key2" : "blah" view.set('key1','boom') expect( view.blah ).not.toHaveBeenCalled() expect( view.onKeyChange ).toHaveBeenCalled()
47675
describe 'The State Model Concern', -> view = Luca.register "Luca.components.StatefulView" view.extends "Luca.View" view.mixesIn "StateModel" view.defines stateful: key1: "<KEY>" key2: "<KEY>" it "should create a state model on the view", -> view = new Luca.components.StatefulView() expect( view.state ).toBeDefined() expect( Luca.isBackboneModel(view.state) ).toEqual true it "should delegate the get method on the state model to the view", -> view = new Luca.components.StatefulView() expect( view.get ).toBeDefined() expect( view.get('key1') ).toEqual '<KEY>' it "should delegate the set method on the state model to the view", -> view = new Luca.components.StatefulView() view.set('key1','<KEY>') expect( view.state.get('key1') ).toEqual 'boom' it "should apply the default state attributes", -> view = new Luca.components.StatefulView() expect( view.state.toJSON() ).toEqual key1:"val<KEY>", key2: "<KEY>" it "should define a get/set method on the view which effect state", -> view = new Luca.components.StatefulView() view.set('testsetter', 'works') expect( view.get('testsetter') ).toEqual('works') describe 'State Change Event Bindings', -> it "should trigger state change events on the view", -> view = new Luca.components.StatefulView() view.set('key1','<KEY>') expect( view ).toHaveTriggered("state:change") it "should trigger individual attribute change events on the view", -> view = new Luca.components.StatefulView() view.set('key1','<KEY>') expect( view ).toHaveTriggered("state:change:key1") it "should respond to @stateChangeEvents configuration", -> view = new Luca.components.StatefulView onKeyChange: sinon.spy() blah: sinon.spy() stateChangeEvents: "key1" : "onKeyChange" "key2" : "blah" view.set('key1','<KEY>') expect( view.blah ).not.toHaveBeenCalled() expect( view.onKeyChange ).toHaveBeenCalled()
true
describe 'The State Model Concern', -> view = Luca.register "Luca.components.StatefulView" view.extends "Luca.View" view.mixesIn "StateModel" view.defines stateful: key1: "PI:KEY:<KEY>END_PI" key2: "PI:KEY:<KEY>END_PI" it "should create a state model on the view", -> view = new Luca.components.StatefulView() expect( view.state ).toBeDefined() expect( Luca.isBackboneModel(view.state) ).toEqual true it "should delegate the get method on the state model to the view", -> view = new Luca.components.StatefulView() expect( view.get ).toBeDefined() expect( view.get('key1') ).toEqual 'PI:KEY:<KEY>END_PI' it "should delegate the set method on the state model to the view", -> view = new Luca.components.StatefulView() view.set('key1','PI:KEY:<KEY>END_PI') expect( view.state.get('key1') ).toEqual 'boom' it "should apply the default state attributes", -> view = new Luca.components.StatefulView() expect( view.state.toJSON() ).toEqual key1:"valPI:KEY:<KEY>END_PI", key2: "PI:KEY:<KEY>END_PI" it "should define a get/set method on the view which effect state", -> view = new Luca.components.StatefulView() view.set('testsetter', 'works') expect( view.get('testsetter') ).toEqual('works') describe 'State Change Event Bindings', -> it "should trigger state change events on the view", -> view = new Luca.components.StatefulView() view.set('key1','PI:KEY:<KEY>END_PI') expect( view ).toHaveTriggered("state:change") it "should trigger individual attribute change events on the view", -> view = new Luca.components.StatefulView() view.set('key1','PI:KEY:<KEY>END_PI') expect( view ).toHaveTriggered("state:change:key1") it "should respond to @stateChangeEvents configuration", -> view = new Luca.components.StatefulView onKeyChange: sinon.spy() blah: sinon.spy() stateChangeEvents: "key1" : "onKeyChange" "key2" : "blah" view.set('key1','PI:KEY:<KEY>END_PI') expect( view.blah ).not.toHaveBeenCalled() expect( view.onKeyChange ).toHaveBeenCalled()
[ { "context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @", "end": 33, "score": 0.9998902082443237, "start": 17, "tag": "NAME", "value": "Abdelhakim RAFIK" }, { "context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki...
src/app/models/comment.coffee
AbdelhakimRafik/Project
1
### * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 Abdelhakim RAFIK * @date June 2021 ### ### Comments model ### module.exports = (sequelize, DataTypes) -> # define the model sequelize.define 'Comment', parent: allowNull: true type: DataTypes.INTEGER content: allowNull: false type: DataTypes.STRING validate: isAlphanumeric: true articleId: allowNull: false type: DataTypes.INTEGER userId: allowNull: false type: DataTypes.INTEGER status: allowNull: false type: DataTypes.BOOLEAN defaultValue: true createdAt: allowNull: false type: DataTypes.DATE updatedAt: allowNull: false type: DataTypes.DATE
40579
### * @author <NAME> * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 <NAME> * @date June 2021 ### ### Comments model ### module.exports = (sequelize, DataTypes) -> # define the model sequelize.define 'Comment', parent: allowNull: true type: DataTypes.INTEGER content: allowNull: false type: DataTypes.STRING validate: isAlphanumeric: true articleId: allowNull: false type: DataTypes.INTEGER userId: allowNull: false type: DataTypes.INTEGER status: allowNull: false type: DataTypes.BOOLEAN defaultValue: true createdAt: allowNull: false type: DataTypes.DATE updatedAt: allowNull: false type: DataTypes.DATE
true
### * @author PI:NAME:<NAME>END_PI * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI * @date June 2021 ### ### Comments model ### module.exports = (sequelize, DataTypes) -> # define the model sequelize.define 'Comment', parent: allowNull: true type: DataTypes.INTEGER content: allowNull: false type: DataTypes.STRING validate: isAlphanumeric: true articleId: allowNull: false type: DataTypes.INTEGER userId: allowNull: false type: DataTypes.INTEGER status: allowNull: false type: DataTypes.BOOLEAN defaultValue: true createdAt: allowNull: false type: DataTypes.DATE updatedAt: allowNull: false type: DataTypes.DATE
[ { "context": " if cmdData.length > 2\n keyData = [cmdData[1], cmdData[2]]\n fun = keyData.join('.')\n ", "end": 15543, "score": 0.9624279141426086, "start": 15520, "tag": "KEY", "value": "cmdData[1], cmdData[2]]" }, { "context": "ata[1], cmdData[...
halite/lattice/app/view/console.coffee
CARFAX/halite
212
mainApp = angular.module("MainApp") #get reference to MainApp module mainApp.controller 'ConsoleCtlr', ['$scope', '$location', '$route', '$q', '$filter', '$templateCache', 'Configuration','AppData', 'AppPref', 'Item', 'Itemizer', 'Minioner', 'Resulter', 'Jobber', 'ArgInfo', 'Runner', 'Wheeler', 'Commander', 'Pagerage', 'SaltApiSrvc', 'SaltApiEvtSrvc', 'SessionStore', 'ErrorReporter', 'JobDelegate', '$filter', ($scope, $location, $route, $q, $filter, $templateCache, Configuration, AppData, AppPref, Item, Itemizer, Minioner, Resulter, Jobber, ArgInfo, Runner, Wheeler, Commander, Pagerage, SaltApiSrvc, SaltApiEvtSrvc, SessionStore, ErrorReporter, JobDelegate ) -> $scope.location = $location $scope.route = $route $scope.winLoc = window.location #console.log("ConsoleCtlr") $scope.monitorMode = null $scope.graining = false $scope.pinging = false $scope.statusing = false $scope.eventing = false $scope.commanding = false $scope.docSearch = false $scope.newPagerage = (itemCount) -> return (new Pagerage(itemCount)) $scope.grainsSortBy = ["id"] $scope.grainsSortBy = ["any", "id", "host", "domain", "server_id"] if AppPref.get('fetchGrains', false) $scope.grainsFilterBy = "id" $scope.grainsFilterBy = "any" if AppPref.get('fetchGrains', false) $scope.filterage = grains: $scope.grainsSortBy grain: $scope.grainsFilterBy target: "" express: "" $scope.setFilterGrain = (index) -> $scope.filterage.grain = $scope.filterage.grains[index] $scope.setFilterExpress() return true $scope.setFilterTarget = (target) -> $scope.filterage.target = target $scope.setFilterExpress() return true $scope.setFilterExpress = () -> # console.log "setFilterExpress" if $scope.filterage.grain is "any" #$scope.filterage.express = $scope.filterage.target regex = RegExp($scope.filterage.target, "i") $scope.filterage.express = (minion) -> for grain in minion.grains.values() if angular.isString(grain) and grain.match(regex) return true return false else regex = RegExp($scope.filterage.target,"i") name = $scope.filterage.grain $scope.filterage.express = (minion) -> if AppPref.get('fetchGrains', false) return minion.grains.get(name).toString().match(regex) else return minion.id.match(regex) return true $scope.eventReverse = true $scope.jobReverse = true $scope.commandReverse = false $scope.minionSortageTargets = ["id"] $scope.minionSortageTargets = ["id", "grains", "ping", "active"] if AppPref.get('fetchGrains', false) $scope.sortage = targets: $scope.minionSortageTargets target: "id" reverse: false $scope.setSortTarget = (index) -> $scope.sortage.target = $scope.sortage.targets[index] return true $scope.sortMinions = (minion) -> if $scope.sortage.target is "id" if AppPref.get('fetchGrains', false) result = minion.grains.get("id") else result = minion.id else if $scope.sortage.target is "grains" result = minion.grains.get($scope.sortage.target)? else result = minion[$scope.sortage.target] result = if result? then result else false return result $scope.sortJobs = (job) -> result = job.jid result = if result? then result else false return result $scope.sortEvents = (event) -> result = event.utag result = if result? then result else false return result $scope.sortCommands = (command) -> result = command.name result = if result? then result else false return result $scope.resultKeys = ["retcode", "fail", "success", "done"] $scope.expandMode = (ensual) -> if angular.isArray(ensual) for x in ensual if angular.isObject(x) return 'list' return 'vect' else if angular.isObject(ensual) return 'dict' return 'lone' $scope.ensuals = (ensual) -> #makes and array so we can create new scope with ng-repeat #work around to recursive scope expression for ng-include return ([ensual]) $scope.actions = State: highstate: mode: 'async' tgt: '*' fun: 'state.highstate' show_highstate: mode: 'async' tgt: '*' fun: 'state.show_highstate' show_lowstate: mode: 'async' tgt: '*' fun: 'state.running' running: mode: 'async' tgt: '*' fun: 'state.running' Test: ping: mode: 'async' tgt: '*' fun: 'test.ping' echo: mode: 'async' tgt: '*' fun: 'test.echo' arg: ['Hello World'] conf_test: mode: 'async' tgt: '*' fun: 'test.conf_test' fib: mode: 'async' tgt: '*' fun: 'test.fib' arg: [8] collatz: mode: 'async' tgt: '*' fun: 'test.collatz' arg: [8] sleep: mode: 'async' tgt: '*' fun: 'test.sleep' arg: ['5'] rand_sleep: mode: 'async' tgt: '*' fun: 'test.rand_sleep' arg: ['max=10'] get_opts: mode: 'async' tgt: '*' fun: 'test.get_opts' providers: mode: 'async' tgt: '*' fun: 'test.providers' version: mode: 'async' tgt: '*' fun: 'test.version' versions_information: mode: 'async' tgt: '*' $scope.ply = (cmds) -> target = if $scope.command.cmd.tgt isnt "" then $scope.command.cmd.tgt else "*" unless angular.isArray(cmds) cmds = [cmds] for cmd in cmds cmd.tgt = target $scope.action(cmds) $scope.command = result: {} history: {} lastCmds: null parameters: null cmd: mode: 'async' fun: '' tgt: '*' arg: [""] expr_form: 'glob' size: (obj) -> return _.size(obj) addArg: () -> @cmd.arg.push('') @parameters?.push('Enter Input') #@cmd.arg[_.size(@cmd.arg)] = "" delArg: () -> if @cmd.arg.length > 1 @cmd.arg = @cmd.arg[0..-2] if @parameters?.length > 0 @parameters.pop() #if _.size(@cmd.arg) > 1 # delete @cmd.arg[_.size(@cmd.arg) - 1] buildArgs: () -> ### Build the arg array to be consumed by the server ### ret = [] reqArgsLen = 0 if $scope.command.requiredArgs? reqArgsLen = $scope.command.requiredArgs.length for item, j in $scope.command.requiredArgs ret.push(@cmd.arg[j]) if $scope.defaultVals? for arg, i in $scope.defaultVals offset = reqArgsLen + i if @cmd.arg[offset]? ret.push(@cmd.arg[offset]) else ret.push(arg) return ret getArgs: () -> #return (val for own key, val of @cmd.arg when val isnt '') return (arg for arg in @cmd.arg when arg isnt '') getCmds: () -> if @cmd.fun.split(".").length == 3 # runner or wheel not minion job cmds = [ fun: @cmd.fun, mode: @cmd.mode, arg: @buildArgs() ] else cmds = [ fun: @cmd.fun, mode: @cmd.mode, tgt: if @cmd.tgt isnt "" then @cmd.tgt else "", arg: @buildArgs(), expr_form: @cmd.expr_form ] return cmds humanize: (cmds) -> unless cmds cmds = @getCmds() return (((part for part in [cmd.fun, cmd.tgt].concat(cmd.arg) \ when part? and part isnt '').join(' ') for cmd in cmds).join(',').trim()) $scope.command.cmd.tgt = "" $scope.expressionFormats = Glob: 'glob' 'Perl Regex': 'pcre' List: 'list' Grain: 'grain' 'Grain Perl Regex': 'grain_pcre' Pillar: 'pillar' 'Node Group': 'nodegroup' Range: 'range' Compound: 'compound' $scope.$watch "command.cmd.expr_form", (newVal, oldVal, scope) -> if newVal == oldVal return if newVal == 'glob' $scope.command.cmd.tgt = "*" else $scope.command.cmd.tgt = "" $scope.fixTarget = () -> if $scope.command.cmd.tgt? and $scope.command.cmd.expr_form == 'list' #remove spaces after commas $scope.command.cmd.tgt = $scope.command.cmd.tgt.replace(/,\s+/g,',') $scope.humanize = (cmds) -> unless angular.isArray(cmds) cmds = [cmds] return (((part for part in [cmd.fun, cmd.tgt].concat(cmd.arg) \ when part? and part isnt '').join(' ') for cmd in cmds).join(',').trim()) $scope.action = (cmds) -> $scope.commanding = true if not cmds cmds = $scope.command.getCmds() command = $scope.snagCommand($scope.humanize(cmds), cmds) #console.log('Calling SaltApiSrvc.action') SaltApiSrvc.action($scope, cmds ) .success (data, status, headers, config ) -> results = data.return for result, index in results if not _.isEmpty(result) parts = cmds[index].fun.split(".") # split on "." character if parts.length == 3 if parts[0] =='runner' job = JobDelegate.startRun(result, cmds[index]) #runner result is tag command.jobs.set(job.jid, job) else if parts[0] == 'wheel' job = JobDelegate.startWheel(result, cmds[index]) #runner result is tag command.jobs.set(job.jid, job) else job = JobDelegate.startJob(result, cmds[index]) command.jobs.set(job.jid, job) $scope.commanding = false return true .error (data, status, headers, config) -> ErrorReporter.addAlert('warning', data.error) $scope.commanding = false $scope.fetchPings = (target) -> target = if target then target else "*" cmd = mode: "async" fun: "test.ping" tgt: target $scope.pinging = true SaltApiSrvc.run($scope, [cmd]) .success (data, status, headers, config) -> result = data.return?[0] if result job = JobDelegate.startJob(result, cmd) $scope.pinging = false return true .error (data, status, headers, config) -> ErrorReporter.addAlert("warning", "Failed to detect pings from #{target}") $scope.pinging = false return true $scope.searchDocs = () -> if not $scope.command.cmd.fun? or not $scope.docSearch or $scope.command.cmd.fun == '' $scope.docSearchResults = '' return true matching = _.filter($scope.docKeys, (key) -> return key.indexOf($scope.command.cmd.fun.toLowerCase()) != -1) matchingDocs = (key + "\n" + $scope.docs[key] + "\n" for key in matching) $scope.docSearchResults = matchingDocs.join('') return true $scope.isSearchable = () -> return $scope.docsLoaded $scope.testClick = (name) -> console.log "click #{name}" $scope.testFocus = (name) -> console.log "focus #{name}" $scope.removeLookupJidJobs = (job) -> return job.name != 'runner.jobs.lookup_jid' $scope.removeArgspecJobs = (job) -> return job.name.toLowerCase().indexOf('sys.argspec') != 0 $scope.jobPresentationFilter = (job) -> return $scope.removeArgspecJobs(job) and $scope.removeLookupJidJobs(job) $scope.defaultVals = null $scope.setParameters = (requiredArgs, optionalArgs, defaultvals) -> $scope.command.requiredArgs = requiredArgs $scope.command.optionalArgs = optionalArgs $scope.defaultVals = defaultvals $scope.fillCommandArgs() return true $scope.commandArgs = [] $scope.fillCommandArgs = () -> $scope.commandArgs = [] $scope.command.cmd.arg = [null] _.each($scope.command.requiredArgs, (arg) -> $scope.commandArgs.push new ArgInfo(arg, true)) _.each($scope.command.optionalArgs, (arg, index) -> $scope.commandArgs.push new ArgInfo(arg, false, $scope.defaultVals[index])) return true $scope.extractArgSpec = (returnFrom) -> required = [] defaults = [] defaults_vals = null argspec = null cmdData = $scope.command.cmd.fun?.split('.') return unless cmdData fun = $scope.command.cmd.fun if cmdData.length > 2 keyData = [cmdData[1], cmdData[2]] fun = keyData.join('.') argspec = _.find(returnFrom, (commandKey) -> return commandKey[fun]? ) else argspec = _.find(returnFrom, (minion) -> return minion[fun]? ) if argspec? info = argspec[fun] if info.args? required = (String(x) for x in info.args) if info.defaults? defaults = (required.pop() for arg in info.defaults) defaults.reverse() defaults_vals = (String(x) for x in info.defaults) else defaults = null else defaults = null else defaults = null required = null return {required: required, defaults: defaults, defaults_vals: defaults_vals} $scope.argSpec = () -> return unless $scope.getMinions()?.keys()?.length > 0 cmd = module: $scope.command.cmd.fun client: 'minion' mode: 'sync' tgt: $scope.getMinions().keys()[0] SaltApiSrvc.signature($scope, cmd) .success (data, status, headers, config) -> argSpec = $scope.extractArgSpec(data.return?[0]) $scope.setParameters(argSpec['required'], argSpec['defaults'], argSpec['defaults_vals']) return true .error (data, status, headers, config) -> $scope.setParameters(null, null, null) return true return true $scope.handleCommandChange = () -> $scope.searchDocs() $scope.argSpec() $scope.canExecuteCommands = () -> return not $scope.commandForm.$invalid and $scope.command.requiredArgs? $scope.getGrainsIfRequired = (mid) -> return if AppPref.get("fetchGrains", false) $scope.fetchGrains mid, false return true $scope.clearSaltData = () -> $scope.command.history = {} return $scope.$on "ClearSaltData", $scope.clearSaltData return true ]
19762
mainApp = angular.module("MainApp") #get reference to MainApp module mainApp.controller 'ConsoleCtlr', ['$scope', '$location', '$route', '$q', '$filter', '$templateCache', 'Configuration','AppData', 'AppPref', 'Item', 'Itemizer', 'Minioner', 'Resulter', 'Jobber', 'ArgInfo', 'Runner', 'Wheeler', 'Commander', 'Pagerage', 'SaltApiSrvc', 'SaltApiEvtSrvc', 'SessionStore', 'ErrorReporter', 'JobDelegate', '$filter', ($scope, $location, $route, $q, $filter, $templateCache, Configuration, AppData, AppPref, Item, Itemizer, Minioner, Resulter, Jobber, ArgInfo, Runner, Wheeler, Commander, Pagerage, SaltApiSrvc, SaltApiEvtSrvc, SessionStore, ErrorReporter, JobDelegate ) -> $scope.location = $location $scope.route = $route $scope.winLoc = window.location #console.log("ConsoleCtlr") $scope.monitorMode = null $scope.graining = false $scope.pinging = false $scope.statusing = false $scope.eventing = false $scope.commanding = false $scope.docSearch = false $scope.newPagerage = (itemCount) -> return (new Pagerage(itemCount)) $scope.grainsSortBy = ["id"] $scope.grainsSortBy = ["any", "id", "host", "domain", "server_id"] if AppPref.get('fetchGrains', false) $scope.grainsFilterBy = "id" $scope.grainsFilterBy = "any" if AppPref.get('fetchGrains', false) $scope.filterage = grains: $scope.grainsSortBy grain: $scope.grainsFilterBy target: "" express: "" $scope.setFilterGrain = (index) -> $scope.filterage.grain = $scope.filterage.grains[index] $scope.setFilterExpress() return true $scope.setFilterTarget = (target) -> $scope.filterage.target = target $scope.setFilterExpress() return true $scope.setFilterExpress = () -> # console.log "setFilterExpress" if $scope.filterage.grain is "any" #$scope.filterage.express = $scope.filterage.target regex = RegExp($scope.filterage.target, "i") $scope.filterage.express = (minion) -> for grain in minion.grains.values() if angular.isString(grain) and grain.match(regex) return true return false else regex = RegExp($scope.filterage.target,"i") name = $scope.filterage.grain $scope.filterage.express = (minion) -> if AppPref.get('fetchGrains', false) return minion.grains.get(name).toString().match(regex) else return minion.id.match(regex) return true $scope.eventReverse = true $scope.jobReverse = true $scope.commandReverse = false $scope.minionSortageTargets = ["id"] $scope.minionSortageTargets = ["id", "grains", "ping", "active"] if AppPref.get('fetchGrains', false) $scope.sortage = targets: $scope.minionSortageTargets target: "id" reverse: false $scope.setSortTarget = (index) -> $scope.sortage.target = $scope.sortage.targets[index] return true $scope.sortMinions = (minion) -> if $scope.sortage.target is "id" if AppPref.get('fetchGrains', false) result = minion.grains.get("id") else result = minion.id else if $scope.sortage.target is "grains" result = minion.grains.get($scope.sortage.target)? else result = minion[$scope.sortage.target] result = if result? then result else false return result $scope.sortJobs = (job) -> result = job.jid result = if result? then result else false return result $scope.sortEvents = (event) -> result = event.utag result = if result? then result else false return result $scope.sortCommands = (command) -> result = command.name result = if result? then result else false return result $scope.resultKeys = ["retcode", "fail", "success", "done"] $scope.expandMode = (ensual) -> if angular.isArray(ensual) for x in ensual if angular.isObject(x) return 'list' return 'vect' else if angular.isObject(ensual) return 'dict' return 'lone' $scope.ensuals = (ensual) -> #makes and array so we can create new scope with ng-repeat #work around to recursive scope expression for ng-include return ([ensual]) $scope.actions = State: highstate: mode: 'async' tgt: '*' fun: 'state.highstate' show_highstate: mode: 'async' tgt: '*' fun: 'state.show_highstate' show_lowstate: mode: 'async' tgt: '*' fun: 'state.running' running: mode: 'async' tgt: '*' fun: 'state.running' Test: ping: mode: 'async' tgt: '*' fun: 'test.ping' echo: mode: 'async' tgt: '*' fun: 'test.echo' arg: ['Hello World'] conf_test: mode: 'async' tgt: '*' fun: 'test.conf_test' fib: mode: 'async' tgt: '*' fun: 'test.fib' arg: [8] collatz: mode: 'async' tgt: '*' fun: 'test.collatz' arg: [8] sleep: mode: 'async' tgt: '*' fun: 'test.sleep' arg: ['5'] rand_sleep: mode: 'async' tgt: '*' fun: 'test.rand_sleep' arg: ['max=10'] get_opts: mode: 'async' tgt: '*' fun: 'test.get_opts' providers: mode: 'async' tgt: '*' fun: 'test.providers' version: mode: 'async' tgt: '*' fun: 'test.version' versions_information: mode: 'async' tgt: '*' $scope.ply = (cmds) -> target = if $scope.command.cmd.tgt isnt "" then $scope.command.cmd.tgt else "*" unless angular.isArray(cmds) cmds = [cmds] for cmd in cmds cmd.tgt = target $scope.action(cmds) $scope.command = result: {} history: {} lastCmds: null parameters: null cmd: mode: 'async' fun: '' tgt: '*' arg: [""] expr_form: 'glob' size: (obj) -> return _.size(obj) addArg: () -> @cmd.arg.push('') @parameters?.push('Enter Input') #@cmd.arg[_.size(@cmd.arg)] = "" delArg: () -> if @cmd.arg.length > 1 @cmd.arg = @cmd.arg[0..-2] if @parameters?.length > 0 @parameters.pop() #if _.size(@cmd.arg) > 1 # delete @cmd.arg[_.size(@cmd.arg) - 1] buildArgs: () -> ### Build the arg array to be consumed by the server ### ret = [] reqArgsLen = 0 if $scope.command.requiredArgs? reqArgsLen = $scope.command.requiredArgs.length for item, j in $scope.command.requiredArgs ret.push(@cmd.arg[j]) if $scope.defaultVals? for arg, i in $scope.defaultVals offset = reqArgsLen + i if @cmd.arg[offset]? ret.push(@cmd.arg[offset]) else ret.push(arg) return ret getArgs: () -> #return (val for own key, val of @cmd.arg when val isnt '') return (arg for arg in @cmd.arg when arg isnt '') getCmds: () -> if @cmd.fun.split(".").length == 3 # runner or wheel not minion job cmds = [ fun: @cmd.fun, mode: @cmd.mode, arg: @buildArgs() ] else cmds = [ fun: @cmd.fun, mode: @cmd.mode, tgt: if @cmd.tgt isnt "" then @cmd.tgt else "", arg: @buildArgs(), expr_form: @cmd.expr_form ] return cmds humanize: (cmds) -> unless cmds cmds = @getCmds() return (((part for part in [cmd.fun, cmd.tgt].concat(cmd.arg) \ when part? and part isnt '').join(' ') for cmd in cmds).join(',').trim()) $scope.command.cmd.tgt = "" $scope.expressionFormats = Glob: 'glob' 'Perl Regex': 'pcre' List: 'list' Grain: 'grain' 'Grain Perl Regex': 'grain_pcre' Pillar: 'pillar' 'Node Group': 'nodegroup' Range: 'range' Compound: 'compound' $scope.$watch "command.cmd.expr_form", (newVal, oldVal, scope) -> if newVal == oldVal return if newVal == 'glob' $scope.command.cmd.tgt = "*" else $scope.command.cmd.tgt = "" $scope.fixTarget = () -> if $scope.command.cmd.tgt? and $scope.command.cmd.expr_form == 'list' #remove spaces after commas $scope.command.cmd.tgt = $scope.command.cmd.tgt.replace(/,\s+/g,',') $scope.humanize = (cmds) -> unless angular.isArray(cmds) cmds = [cmds] return (((part for part in [cmd.fun, cmd.tgt].concat(cmd.arg) \ when part? and part isnt '').join(' ') for cmd in cmds).join(',').trim()) $scope.action = (cmds) -> $scope.commanding = true if not cmds cmds = $scope.command.getCmds() command = $scope.snagCommand($scope.humanize(cmds), cmds) #console.log('Calling SaltApiSrvc.action') SaltApiSrvc.action($scope, cmds ) .success (data, status, headers, config ) -> results = data.return for result, index in results if not _.isEmpty(result) parts = cmds[index].fun.split(".") # split on "." character if parts.length == 3 if parts[0] =='runner' job = JobDelegate.startRun(result, cmds[index]) #runner result is tag command.jobs.set(job.jid, job) else if parts[0] == 'wheel' job = JobDelegate.startWheel(result, cmds[index]) #runner result is tag command.jobs.set(job.jid, job) else job = JobDelegate.startJob(result, cmds[index]) command.jobs.set(job.jid, job) $scope.commanding = false return true .error (data, status, headers, config) -> ErrorReporter.addAlert('warning', data.error) $scope.commanding = false $scope.fetchPings = (target) -> target = if target then target else "*" cmd = mode: "async" fun: "test.ping" tgt: target $scope.pinging = true SaltApiSrvc.run($scope, [cmd]) .success (data, status, headers, config) -> result = data.return?[0] if result job = JobDelegate.startJob(result, cmd) $scope.pinging = false return true .error (data, status, headers, config) -> ErrorReporter.addAlert("warning", "Failed to detect pings from #{target}") $scope.pinging = false return true $scope.searchDocs = () -> if not $scope.command.cmd.fun? or not $scope.docSearch or $scope.command.cmd.fun == '' $scope.docSearchResults = '' return true matching = _.filter($scope.docKeys, (key) -> return key.indexOf($scope.command.cmd.fun.toLowerCase()) != -1) matchingDocs = (key + "\n" + $scope.docs[key] + "\n" for key in matching) $scope.docSearchResults = matchingDocs.join('') return true $scope.isSearchable = () -> return $scope.docsLoaded $scope.testClick = (name) -> console.log "click #{name}" $scope.testFocus = (name) -> console.log "focus #{name}" $scope.removeLookupJidJobs = (job) -> return job.name != 'runner.jobs.lookup_jid' $scope.removeArgspecJobs = (job) -> return job.name.toLowerCase().indexOf('sys.argspec') != 0 $scope.jobPresentationFilter = (job) -> return $scope.removeArgspecJobs(job) and $scope.removeLookupJidJobs(job) $scope.defaultVals = null $scope.setParameters = (requiredArgs, optionalArgs, defaultvals) -> $scope.command.requiredArgs = requiredArgs $scope.command.optionalArgs = optionalArgs $scope.defaultVals = defaultvals $scope.fillCommandArgs() return true $scope.commandArgs = [] $scope.fillCommandArgs = () -> $scope.commandArgs = [] $scope.command.cmd.arg = [null] _.each($scope.command.requiredArgs, (arg) -> $scope.commandArgs.push new ArgInfo(arg, true)) _.each($scope.command.optionalArgs, (arg, index) -> $scope.commandArgs.push new ArgInfo(arg, false, $scope.defaultVals[index])) return true $scope.extractArgSpec = (returnFrom) -> required = [] defaults = [] defaults_vals = null argspec = null cmdData = $scope.command.cmd.fun?.split('.') return unless cmdData fun = $scope.command.cmd.fun if cmdData.length > 2 keyData = [<KEY> fun = keyData.<KEY> argspec = _.find(returnFrom, (commandKey) -> return commandKey[fun]? ) else argspec = _.find(returnFrom, (minion) -> return minion[fun]? ) if argspec? info = argspec[fun] if info.args? required = (String(x) for x in info.args) if info.defaults? defaults = (required.pop() for arg in info.defaults) defaults.reverse() defaults_vals = (String(x) for x in info.defaults) else defaults = null else defaults = null else defaults = null required = null return {required: required, defaults: defaults, defaults_vals: defaults_vals} $scope.argSpec = () -> return unless $scope.getMinions()?.keys()?.length > 0 cmd = module: $scope.command.cmd.fun client: 'minion' mode: 'sync' tgt: $scope.getMinions().keys()[0] SaltApiSrvc.signature($scope, cmd) .success (data, status, headers, config) -> argSpec = $scope.extractArgSpec(data.return?[0]) $scope.setParameters(argSpec['required'], argSpec['defaults'], argSpec['defaults_vals']) return true .error (data, status, headers, config) -> $scope.setParameters(null, null, null) return true return true $scope.handleCommandChange = () -> $scope.searchDocs() $scope.argSpec() $scope.canExecuteCommands = () -> return not $scope.commandForm.$invalid and $scope.command.requiredArgs? $scope.getGrainsIfRequired = (mid) -> return if AppPref.get("fetchGrains", false) $scope.fetchGrains mid, false return true $scope.clearSaltData = () -> $scope.command.history = {} return $scope.$on "ClearSaltData", $scope.clearSaltData return true ]
true
mainApp = angular.module("MainApp") #get reference to MainApp module mainApp.controller 'ConsoleCtlr', ['$scope', '$location', '$route', '$q', '$filter', '$templateCache', 'Configuration','AppData', 'AppPref', 'Item', 'Itemizer', 'Minioner', 'Resulter', 'Jobber', 'ArgInfo', 'Runner', 'Wheeler', 'Commander', 'Pagerage', 'SaltApiSrvc', 'SaltApiEvtSrvc', 'SessionStore', 'ErrorReporter', 'JobDelegate', '$filter', ($scope, $location, $route, $q, $filter, $templateCache, Configuration, AppData, AppPref, Item, Itemizer, Minioner, Resulter, Jobber, ArgInfo, Runner, Wheeler, Commander, Pagerage, SaltApiSrvc, SaltApiEvtSrvc, SessionStore, ErrorReporter, JobDelegate ) -> $scope.location = $location $scope.route = $route $scope.winLoc = window.location #console.log("ConsoleCtlr") $scope.monitorMode = null $scope.graining = false $scope.pinging = false $scope.statusing = false $scope.eventing = false $scope.commanding = false $scope.docSearch = false $scope.newPagerage = (itemCount) -> return (new Pagerage(itemCount)) $scope.grainsSortBy = ["id"] $scope.grainsSortBy = ["any", "id", "host", "domain", "server_id"] if AppPref.get('fetchGrains', false) $scope.grainsFilterBy = "id" $scope.grainsFilterBy = "any" if AppPref.get('fetchGrains', false) $scope.filterage = grains: $scope.grainsSortBy grain: $scope.grainsFilterBy target: "" express: "" $scope.setFilterGrain = (index) -> $scope.filterage.grain = $scope.filterage.grains[index] $scope.setFilterExpress() return true $scope.setFilterTarget = (target) -> $scope.filterage.target = target $scope.setFilterExpress() return true $scope.setFilterExpress = () -> # console.log "setFilterExpress" if $scope.filterage.grain is "any" #$scope.filterage.express = $scope.filterage.target regex = RegExp($scope.filterage.target, "i") $scope.filterage.express = (minion) -> for grain in minion.grains.values() if angular.isString(grain) and grain.match(regex) return true return false else regex = RegExp($scope.filterage.target,"i") name = $scope.filterage.grain $scope.filterage.express = (minion) -> if AppPref.get('fetchGrains', false) return minion.grains.get(name).toString().match(regex) else return minion.id.match(regex) return true $scope.eventReverse = true $scope.jobReverse = true $scope.commandReverse = false $scope.minionSortageTargets = ["id"] $scope.minionSortageTargets = ["id", "grains", "ping", "active"] if AppPref.get('fetchGrains', false) $scope.sortage = targets: $scope.minionSortageTargets target: "id" reverse: false $scope.setSortTarget = (index) -> $scope.sortage.target = $scope.sortage.targets[index] return true $scope.sortMinions = (minion) -> if $scope.sortage.target is "id" if AppPref.get('fetchGrains', false) result = minion.grains.get("id") else result = minion.id else if $scope.sortage.target is "grains" result = minion.grains.get($scope.sortage.target)? else result = minion[$scope.sortage.target] result = if result? then result else false return result $scope.sortJobs = (job) -> result = job.jid result = if result? then result else false return result $scope.sortEvents = (event) -> result = event.utag result = if result? then result else false return result $scope.sortCommands = (command) -> result = command.name result = if result? then result else false return result $scope.resultKeys = ["retcode", "fail", "success", "done"] $scope.expandMode = (ensual) -> if angular.isArray(ensual) for x in ensual if angular.isObject(x) return 'list' return 'vect' else if angular.isObject(ensual) return 'dict' return 'lone' $scope.ensuals = (ensual) -> #makes and array so we can create new scope with ng-repeat #work around to recursive scope expression for ng-include return ([ensual]) $scope.actions = State: highstate: mode: 'async' tgt: '*' fun: 'state.highstate' show_highstate: mode: 'async' tgt: '*' fun: 'state.show_highstate' show_lowstate: mode: 'async' tgt: '*' fun: 'state.running' running: mode: 'async' tgt: '*' fun: 'state.running' Test: ping: mode: 'async' tgt: '*' fun: 'test.ping' echo: mode: 'async' tgt: '*' fun: 'test.echo' arg: ['Hello World'] conf_test: mode: 'async' tgt: '*' fun: 'test.conf_test' fib: mode: 'async' tgt: '*' fun: 'test.fib' arg: [8] collatz: mode: 'async' tgt: '*' fun: 'test.collatz' arg: [8] sleep: mode: 'async' tgt: '*' fun: 'test.sleep' arg: ['5'] rand_sleep: mode: 'async' tgt: '*' fun: 'test.rand_sleep' arg: ['max=10'] get_opts: mode: 'async' tgt: '*' fun: 'test.get_opts' providers: mode: 'async' tgt: '*' fun: 'test.providers' version: mode: 'async' tgt: '*' fun: 'test.version' versions_information: mode: 'async' tgt: '*' $scope.ply = (cmds) -> target = if $scope.command.cmd.tgt isnt "" then $scope.command.cmd.tgt else "*" unless angular.isArray(cmds) cmds = [cmds] for cmd in cmds cmd.tgt = target $scope.action(cmds) $scope.command = result: {} history: {} lastCmds: null parameters: null cmd: mode: 'async' fun: '' tgt: '*' arg: [""] expr_form: 'glob' size: (obj) -> return _.size(obj) addArg: () -> @cmd.arg.push('') @parameters?.push('Enter Input') #@cmd.arg[_.size(@cmd.arg)] = "" delArg: () -> if @cmd.arg.length > 1 @cmd.arg = @cmd.arg[0..-2] if @parameters?.length > 0 @parameters.pop() #if _.size(@cmd.arg) > 1 # delete @cmd.arg[_.size(@cmd.arg) - 1] buildArgs: () -> ### Build the arg array to be consumed by the server ### ret = [] reqArgsLen = 0 if $scope.command.requiredArgs? reqArgsLen = $scope.command.requiredArgs.length for item, j in $scope.command.requiredArgs ret.push(@cmd.arg[j]) if $scope.defaultVals? for arg, i in $scope.defaultVals offset = reqArgsLen + i if @cmd.arg[offset]? ret.push(@cmd.arg[offset]) else ret.push(arg) return ret getArgs: () -> #return (val for own key, val of @cmd.arg when val isnt '') return (arg for arg in @cmd.arg when arg isnt '') getCmds: () -> if @cmd.fun.split(".").length == 3 # runner or wheel not minion job cmds = [ fun: @cmd.fun, mode: @cmd.mode, arg: @buildArgs() ] else cmds = [ fun: @cmd.fun, mode: @cmd.mode, tgt: if @cmd.tgt isnt "" then @cmd.tgt else "", arg: @buildArgs(), expr_form: @cmd.expr_form ] return cmds humanize: (cmds) -> unless cmds cmds = @getCmds() return (((part for part in [cmd.fun, cmd.tgt].concat(cmd.arg) \ when part? and part isnt '').join(' ') for cmd in cmds).join(',').trim()) $scope.command.cmd.tgt = "" $scope.expressionFormats = Glob: 'glob' 'Perl Regex': 'pcre' List: 'list' Grain: 'grain' 'Grain Perl Regex': 'grain_pcre' Pillar: 'pillar' 'Node Group': 'nodegroup' Range: 'range' Compound: 'compound' $scope.$watch "command.cmd.expr_form", (newVal, oldVal, scope) -> if newVal == oldVal return if newVal == 'glob' $scope.command.cmd.tgt = "*" else $scope.command.cmd.tgt = "" $scope.fixTarget = () -> if $scope.command.cmd.tgt? and $scope.command.cmd.expr_form == 'list' #remove spaces after commas $scope.command.cmd.tgt = $scope.command.cmd.tgt.replace(/,\s+/g,',') $scope.humanize = (cmds) -> unless angular.isArray(cmds) cmds = [cmds] return (((part for part in [cmd.fun, cmd.tgt].concat(cmd.arg) \ when part? and part isnt '').join(' ') for cmd in cmds).join(',').trim()) $scope.action = (cmds) -> $scope.commanding = true if not cmds cmds = $scope.command.getCmds() command = $scope.snagCommand($scope.humanize(cmds), cmds) #console.log('Calling SaltApiSrvc.action') SaltApiSrvc.action($scope, cmds ) .success (data, status, headers, config ) -> results = data.return for result, index in results if not _.isEmpty(result) parts = cmds[index].fun.split(".") # split on "." character if parts.length == 3 if parts[0] =='runner' job = JobDelegate.startRun(result, cmds[index]) #runner result is tag command.jobs.set(job.jid, job) else if parts[0] == 'wheel' job = JobDelegate.startWheel(result, cmds[index]) #runner result is tag command.jobs.set(job.jid, job) else job = JobDelegate.startJob(result, cmds[index]) command.jobs.set(job.jid, job) $scope.commanding = false return true .error (data, status, headers, config) -> ErrorReporter.addAlert('warning', data.error) $scope.commanding = false $scope.fetchPings = (target) -> target = if target then target else "*" cmd = mode: "async" fun: "test.ping" tgt: target $scope.pinging = true SaltApiSrvc.run($scope, [cmd]) .success (data, status, headers, config) -> result = data.return?[0] if result job = JobDelegate.startJob(result, cmd) $scope.pinging = false return true .error (data, status, headers, config) -> ErrorReporter.addAlert("warning", "Failed to detect pings from #{target}") $scope.pinging = false return true $scope.searchDocs = () -> if not $scope.command.cmd.fun? or not $scope.docSearch or $scope.command.cmd.fun == '' $scope.docSearchResults = '' return true matching = _.filter($scope.docKeys, (key) -> return key.indexOf($scope.command.cmd.fun.toLowerCase()) != -1) matchingDocs = (key + "\n" + $scope.docs[key] + "\n" for key in matching) $scope.docSearchResults = matchingDocs.join('') return true $scope.isSearchable = () -> return $scope.docsLoaded $scope.testClick = (name) -> console.log "click #{name}" $scope.testFocus = (name) -> console.log "focus #{name}" $scope.removeLookupJidJobs = (job) -> return job.name != 'runner.jobs.lookup_jid' $scope.removeArgspecJobs = (job) -> return job.name.toLowerCase().indexOf('sys.argspec') != 0 $scope.jobPresentationFilter = (job) -> return $scope.removeArgspecJobs(job) and $scope.removeLookupJidJobs(job) $scope.defaultVals = null $scope.setParameters = (requiredArgs, optionalArgs, defaultvals) -> $scope.command.requiredArgs = requiredArgs $scope.command.optionalArgs = optionalArgs $scope.defaultVals = defaultvals $scope.fillCommandArgs() return true $scope.commandArgs = [] $scope.fillCommandArgs = () -> $scope.commandArgs = [] $scope.command.cmd.arg = [null] _.each($scope.command.requiredArgs, (arg) -> $scope.commandArgs.push new ArgInfo(arg, true)) _.each($scope.command.optionalArgs, (arg, index) -> $scope.commandArgs.push new ArgInfo(arg, false, $scope.defaultVals[index])) return true $scope.extractArgSpec = (returnFrom) -> required = [] defaults = [] defaults_vals = null argspec = null cmdData = $scope.command.cmd.fun?.split('.') return unless cmdData fun = $scope.command.cmd.fun if cmdData.length > 2 keyData = [PI:KEY:<KEY>END_PI fun = keyData.PI:KEY:<KEY>END_PI argspec = _.find(returnFrom, (commandKey) -> return commandKey[fun]? ) else argspec = _.find(returnFrom, (minion) -> return minion[fun]? ) if argspec? info = argspec[fun] if info.args? required = (String(x) for x in info.args) if info.defaults? defaults = (required.pop() for arg in info.defaults) defaults.reverse() defaults_vals = (String(x) for x in info.defaults) else defaults = null else defaults = null else defaults = null required = null return {required: required, defaults: defaults, defaults_vals: defaults_vals} $scope.argSpec = () -> return unless $scope.getMinions()?.keys()?.length > 0 cmd = module: $scope.command.cmd.fun client: 'minion' mode: 'sync' tgt: $scope.getMinions().keys()[0] SaltApiSrvc.signature($scope, cmd) .success (data, status, headers, config) -> argSpec = $scope.extractArgSpec(data.return?[0]) $scope.setParameters(argSpec['required'], argSpec['defaults'], argSpec['defaults_vals']) return true .error (data, status, headers, config) -> $scope.setParameters(null, null, null) return true return true $scope.handleCommandChange = () -> $scope.searchDocs() $scope.argSpec() $scope.canExecuteCommands = () -> return not $scope.commandForm.$invalid and $scope.command.requiredArgs? $scope.getGrainsIfRequired = (mid) -> return if AppPref.get("fetchGrains", false) $scope.fetchGrains mid, false return true $scope.clearSaltData = () -> $scope.command.history = {} return $scope.$on "ClearSaltData", $scope.clearSaltData return true ]
[ { "context": "in shows our login part in home view.\n\n @author Sebastian Sachtleben\n###\nclass Login extends FormView\n\n\tentity: 'ui/me", "end": 183, "score": 0.9998968243598938, "start": 163, "tag": "NAME", "value": "Sebastian Sachtleben" } ]
app/assets/javascripts/site/views/header/login.coffee
ssachtleben/herowar
1
FormView = require 'views/formView' templates = require 'templates' app = require 'application' ### The Login shows our login part in home view. @author Sebastian Sachtleben ### class Login extends FormView entity: 'ui/me' template: templates.get 'header/login.tmpl' url: '/login/email/auth' validateForm: ($Form) -> isValid = true inputEmail = $Form.find 'input[name="email"]' if inputEmail.val().length <= 4 @setInputState inputEmail, 'error' $.gritter.add title: 'Login failed', text: 'The email doesn\'t exists.' isValid = false else @setInputState inputEmail, '' passwordUsername = $Form.find 'input[name="password"]' if passwordUsername.val().length <= 4 @setInputState passwordUsername, 'error' if isValid $.gritter.add title: 'Login failed', text: 'The password doesn\'t match.' isValid = false else @setInputState passwordUsername, '' isValid onSuccess: (data, textStatus, jqXHR) -> # TODO: this method is never called ?!? @model.set data @model.validateResponse(data) app.navigate 'play', true onError: (jqXHR, textStatus, errorThrown) -> # TODO: why is successful login goes to error?!?! return window.location.reload() if jqXHR.status is 200 $.gritter.add title: 'Login failed', text: 'Email or password is incorrect' return Login
214363
FormView = require 'views/formView' templates = require 'templates' app = require 'application' ### The Login shows our login part in home view. @author <NAME> ### class Login extends FormView entity: 'ui/me' template: templates.get 'header/login.tmpl' url: '/login/email/auth' validateForm: ($Form) -> isValid = true inputEmail = $Form.find 'input[name="email"]' if inputEmail.val().length <= 4 @setInputState inputEmail, 'error' $.gritter.add title: 'Login failed', text: 'The email doesn\'t exists.' isValid = false else @setInputState inputEmail, '' passwordUsername = $Form.find 'input[name="password"]' if passwordUsername.val().length <= 4 @setInputState passwordUsername, 'error' if isValid $.gritter.add title: 'Login failed', text: 'The password doesn\'t match.' isValid = false else @setInputState passwordUsername, '' isValid onSuccess: (data, textStatus, jqXHR) -> # TODO: this method is never called ?!? @model.set data @model.validateResponse(data) app.navigate 'play', true onError: (jqXHR, textStatus, errorThrown) -> # TODO: why is successful login goes to error?!?! return window.location.reload() if jqXHR.status is 200 $.gritter.add title: 'Login failed', text: 'Email or password is incorrect' return Login
true
FormView = require 'views/formView' templates = require 'templates' app = require 'application' ### The Login shows our login part in home view. @author PI:NAME:<NAME>END_PI ### class Login extends FormView entity: 'ui/me' template: templates.get 'header/login.tmpl' url: '/login/email/auth' validateForm: ($Form) -> isValid = true inputEmail = $Form.find 'input[name="email"]' if inputEmail.val().length <= 4 @setInputState inputEmail, 'error' $.gritter.add title: 'Login failed', text: 'The email doesn\'t exists.' isValid = false else @setInputState inputEmail, '' passwordUsername = $Form.find 'input[name="password"]' if passwordUsername.val().length <= 4 @setInputState passwordUsername, 'error' if isValid $.gritter.add title: 'Login failed', text: 'The password doesn\'t match.' isValid = false else @setInputState passwordUsername, '' isValid onSuccess: (data, textStatus, jqXHR) -> # TODO: this method is never called ?!? @model.set data @model.validateResponse(data) app.navigate 'play', true onError: (jqXHR, textStatus, errorThrown) -> # TODO: why is successful login goes to error?!?! return window.location.reload() if jqXHR.status is 200 $.gritter.add title: 'Login failed', text: 'Email or password is incorrect' return Login
[ { "context": "or.call 'addOutgoingIntegration',\n\t\t\t\t\tusername: 'rocket.cat'\n\t\t\t\t\turls: [options.target_url]\n\t\t\t\t\tname: optio", "end": 2636, "score": 0.9995508193969727, "start": 2626, "tag": "USERNAME", "value": "rocket.cat" }, { "context": "or.call 'addOutgoingInte...
packages/rocketchat-integrations/server/api/api.coffee
NMandapaty/Rocket.Chat
0
vm = Npm.require('vm') compiledScripts = {} getIntegrationScript = (integration) -> compiledScript = compiledScripts[integration._id] if compiledScript? and +compiledScript._updatedAt is +integration._updatedAt return compiledScript.script script = integration.scriptCompiled vmScript = undefined sandbox = _: _ s: s console: console Store: set: (key, val) -> return store[key] = val get: (key) -> return store[key] try logger.incoming.info 'Will evaluate script of Trigger', integration.name logger.incoming.debug script vmScript = vm.createScript script, 'script.js' vmScript.runInNewContext sandbox if sandbox.Script? compiledScripts[integration._id] = script: new sandbox.Script() _updatedAt: integration._updatedAt return compiledScripts[integration._id].script catch e logger.incoming.error '[Error evaluating Script in Trigger', integration.name, ':]' logger.incoming.error script.replace(/^/gm, ' ') logger.incoming.error "[Stack:]" logger.incoming.error e.stack.replace(/^/gm, ' ') throw RocketChat.API.v1.failure 'error-evaluating-script' if not sandbox.Script? logger.incoming.error '[Class "Script" not in Trigger', integration.name, ']' throw RocketChat.API.v1.failure 'class-script-not-found' Api = new Restivus enableCors: true apiPath: 'hooks/' auth: user: -> payloadKeys = Object.keys @bodyParams payloadIsWrapped = @bodyParams?.payload? and payloadKeys.length == 1 if payloadIsWrapped and @request.headers['content-type'] is 'application/x-www-form-urlencoded' try @bodyParams = JSON.parse @bodyParams.payload catch e return { error: { statusCode: 400 body: { success: false error: e.message } } } @integration = RocketChat.models.Integrations.findOne _id: @request.params.integrationId token: decodeURIComponent @request.params.token if not @integration? logger.incoming.info "Invalid integration id", @request.params.integrationId, "or token", @request.params.token return user = RocketChat.models.Users.findOne _id: @integration.userId return user: user createIntegration = (options, user) -> logger.incoming.info 'Add integration', options.name logger.incoming.debug options Meteor.runAsUser user._id, => switch options['event'] when 'newMessageOnChannel' options.data ?= {} if options.data.channel_name? and options.data.channel_name.indexOf('#') is -1 options.data.channel_name = '#' + options.data.channel_name Meteor.call 'addOutgoingIntegration', username: 'rocket.cat' urls: [options.target_url] name: options.name channel: options.data.channel_name triggerWords: options.data.trigger_words when 'newMessageToUser' if options.data.username.indexOf('@') is -1 options.data.username = '@' + options.data.username Meteor.call 'addOutgoingIntegration', username: 'rocket.cat' urls: [options.target_url] name: options.name channel: options.data.username triggerWords: options.data.trigger_words return RocketChat.API.v1.success() removeIntegration = (options, user) -> logger.incoming.info 'Remove integration' logger.incoming.debug options integrationToRemove = RocketChat.models.Integrations.findOne urls: options.target_url Meteor.runAsUser user._id, => Meteor.call 'deleteOutgoingIntegration', integrationToRemove._id return RocketChat.API.v1.success() executeIntegrationRest = -> logger.incoming.info 'Post integration', @integration.name logger.incoming.debug '@urlParams', @urlParams logger.incoming.debug '@bodyParams', @bodyParams if @integration.enabled isnt true return {} = statusCode: 503 body: 'Service Unavailable' defaultValues = channel: @integration.channel alias: @integration.alias avatar: @integration.avatar emoji: @integration.emoji if @integration.scriptEnabled is true and @integration.scriptCompiled? and @integration.scriptCompiled.trim() isnt '' script = undefined try script = getIntegrationScript(@integration) catch e return e request = url: hash: @request._parsedUrl.hash search: @request._parsedUrl.search query: @queryParams pathname: @request._parsedUrl.pathname path: @request._parsedUrl.path url_raw: @request.url url_params: @urlParams content: @bodyParams content_raw: @request._readableState?.buffer?.toString() headers: @request.headers user: _id: @user._id name: @user.name username: @user.username try sandbox = _: _ s: s console: console Store: set: (key, val) -> return store[key] = val get: (key) -> return store[key] script: script request: request result = vm.runInNewContext('script.process_incoming_request({ request: request })', sandbox, { timeout: 3000 }) if result?.error? return RocketChat.API.v1.failure result.error @bodyParams = result?.content logger.incoming.debug '[Process Incoming Request result of Trigger', @integration.name, ':]' logger.incoming.debug 'result', @bodyParams catch e logger.incoming.error '[Error running Script in Trigger', @integration.name, ':]' logger.incoming.error @integration.scriptCompiled.replace(/^/gm, ' ') logger.incoming.error "[Stack:]" logger.incoming.error e.stack.replace(/^/gm, ' ') return RocketChat.API.v1.failure 'error-running-script' if not @bodyParams? return RocketChat.API.v1.failure 'body-empty' @bodyParams.bot = i: @integration._id try message = processWebhookMessage @bodyParams, @user, defaultValues if _.isEmpty message return RocketChat.API.v1.failure 'unknown-error' return RocketChat.API.v1.success() catch e return RocketChat.API.v1.failure e.error addIntegrationRest = -> return createIntegration @bodyParams, @user removeIntegrationRest = -> return removeIntegration @bodyParams, @user integrationSampleRest = -> logger.incoming.info 'Sample Integration' return {} = statusCode: 200 body: [ token: Random.id(24) channel_id: Random.id() channel_name: 'general' timestamp: new Date user_id: Random.id() user_name: 'rocket.cat' text: 'Sample text 1' trigger_word: 'Sample' , token: Random.id(24) channel_id: Random.id() channel_name: 'general' timestamp: new Date user_id: Random.id() user_name: 'rocket.cat' text: 'Sample text 2' trigger_word: 'Sample' , token: Random.id(24) channel_id: Random.id() channel_name: 'general' timestamp: new Date user_id: Random.id() user_name: 'rocket.cat' text: 'Sample text 3' trigger_word: 'Sample' ] integrationInfoRest = -> logger.incoming.info 'Info integration' return {} = statusCode: 200 body: success: true Api.addRoute ':integrationId/:userId/:token', authRequired: true, {post: executeIntegrationRest, get: executeIntegrationRest} Api.addRoute ':integrationId/:token', authRequired: true, {post: executeIntegrationRest, get: executeIntegrationRest} Api.addRoute 'sample/:integrationId/:userId/:token', authRequired: true, {get: integrationSampleRest} Api.addRoute 'sample/:integrationId/:token', authRequired: true, {get: integrationSampleRest} Api.addRoute 'info/:integrationId/:userId/:token', authRequired: true, {get: integrationInfoRest} Api.addRoute 'info/:integrationId/:token', authRequired: true, {get: integrationInfoRest} Api.addRoute 'add/:integrationId/:userId/:token', authRequired: true, {post: addIntegrationRest} Api.addRoute 'add/:integrationId/:token', authRequired: true, {post: addIntegrationRest} Api.addRoute 'remove/:integrationId/:userId/:token', authRequired: true, {post: removeIntegrationRest} Api.addRoute 'remove/:integrationId/:token', authRequired: true, {post: removeIntegrationRest}
127504
vm = Npm.require('vm') compiledScripts = {} getIntegrationScript = (integration) -> compiledScript = compiledScripts[integration._id] if compiledScript? and +compiledScript._updatedAt is +integration._updatedAt return compiledScript.script script = integration.scriptCompiled vmScript = undefined sandbox = _: _ s: s console: console Store: set: (key, val) -> return store[key] = val get: (key) -> return store[key] try logger.incoming.info 'Will evaluate script of Trigger', integration.name logger.incoming.debug script vmScript = vm.createScript script, 'script.js' vmScript.runInNewContext sandbox if sandbox.Script? compiledScripts[integration._id] = script: new sandbox.Script() _updatedAt: integration._updatedAt return compiledScripts[integration._id].script catch e logger.incoming.error '[Error evaluating Script in Trigger', integration.name, ':]' logger.incoming.error script.replace(/^/gm, ' ') logger.incoming.error "[Stack:]" logger.incoming.error e.stack.replace(/^/gm, ' ') throw RocketChat.API.v1.failure 'error-evaluating-script' if not sandbox.Script? logger.incoming.error '[Class "Script" not in Trigger', integration.name, ']' throw RocketChat.API.v1.failure 'class-script-not-found' Api = new Restivus enableCors: true apiPath: 'hooks/' auth: user: -> payloadKeys = Object.keys @bodyParams payloadIsWrapped = @bodyParams?.payload? and payloadKeys.length == 1 if payloadIsWrapped and @request.headers['content-type'] is 'application/x-www-form-urlencoded' try @bodyParams = JSON.parse @bodyParams.payload catch e return { error: { statusCode: 400 body: { success: false error: e.message } } } @integration = RocketChat.models.Integrations.findOne _id: @request.params.integrationId token: decodeURIComponent @request.params.token if not @integration? logger.incoming.info "Invalid integration id", @request.params.integrationId, "or token", @request.params.token return user = RocketChat.models.Users.findOne _id: @integration.userId return user: user createIntegration = (options, user) -> logger.incoming.info 'Add integration', options.name logger.incoming.debug options Meteor.runAsUser user._id, => switch options['event'] when 'newMessageOnChannel' options.data ?= {} if options.data.channel_name? and options.data.channel_name.indexOf('#') is -1 options.data.channel_name = '#' + options.data.channel_name Meteor.call 'addOutgoingIntegration', username: 'rocket.cat' urls: [options.target_url] name: options.name channel: options.data.channel_name triggerWords: options.data.trigger_words when 'newMessageToUser' if options.data.username.indexOf('@') is -1 options.data.username = '@' + options.data.username Meteor.call 'addOutgoingIntegration', username: 'rocket.cat' urls: [options.target_url] name: options.name channel: options.data.username triggerWords: options.data.trigger_words return RocketChat.API.v1.success() removeIntegration = (options, user) -> logger.incoming.info 'Remove integration' logger.incoming.debug options integrationToRemove = RocketChat.models.Integrations.findOne urls: options.target_url Meteor.runAsUser user._id, => Meteor.call 'deleteOutgoingIntegration', integrationToRemove._id return RocketChat.API.v1.success() executeIntegrationRest = -> logger.incoming.info 'Post integration', @integration.name logger.incoming.debug '@urlParams', @urlParams logger.incoming.debug '@bodyParams', @bodyParams if @integration.enabled isnt true return {} = statusCode: 503 body: 'Service Unavailable' defaultValues = channel: @integration.channel alias: @integration.alias avatar: @integration.avatar emoji: @integration.emoji if @integration.scriptEnabled is true and @integration.scriptCompiled? and @integration.scriptCompiled.trim() isnt '' script = undefined try script = getIntegrationScript(@integration) catch e return e request = url: hash: @request._parsedUrl.hash search: @request._parsedUrl.search query: @queryParams pathname: @request._parsedUrl.pathname path: @request._parsedUrl.path url_raw: @request.url url_params: @urlParams content: @bodyParams content_raw: @request._readableState?.buffer?.toString() headers: @request.headers user: _id: @user._id name: @user.name username: @user.username try sandbox = _: _ s: s console: console Store: set: (key, val) -> return store[key] = val get: (key) -> return store[key] script: script request: request result = vm.runInNewContext('script.process_incoming_request({ request: request })', sandbox, { timeout: 3000 }) if result?.error? return RocketChat.API.v1.failure result.error @bodyParams = result?.content logger.incoming.debug '[Process Incoming Request result of Trigger', @integration.name, ':]' logger.incoming.debug 'result', @bodyParams catch e logger.incoming.error '[Error running Script in Trigger', @integration.name, ':]' logger.incoming.error @integration.scriptCompiled.replace(/^/gm, ' ') logger.incoming.error "[Stack:]" logger.incoming.error e.stack.replace(/^/gm, ' ') return RocketChat.API.v1.failure 'error-running-script' if not @bodyParams? return RocketChat.API.v1.failure 'body-empty' @bodyParams.bot = i: @integration._id try message = processWebhookMessage @bodyParams, @user, defaultValues if _.isEmpty message return RocketChat.API.v1.failure 'unknown-error' return RocketChat.API.v1.success() catch e return RocketChat.API.v1.failure e.error addIntegrationRest = -> return createIntegration @bodyParams, @user removeIntegrationRest = -> return removeIntegration @bodyParams, @user integrationSampleRest = -> logger.incoming.info 'Sample Integration' return {} = statusCode: 200 body: [ token: Random.<KEY>(24) channel_id: Random.id() channel_name: 'general' timestamp: new Date user_id: Random.id() user_name: 'rocket.cat' text: 'Sample text 1' trigger_word: 'Sample' , token: Random.<KEY>(24) channel_id: Random.id() channel_name: 'general' timestamp: new Date user_id: Random.id() user_name: 'rocket.cat' text: 'Sample text 2' trigger_word: 'Sample' , token: Random.<KEY>(24) channel_id: Random.id() channel_name: 'general' timestamp: new Date user_id: Random.id() user_name: 'rocket.cat' text: 'Sample text 3' trigger_word: 'Sample' ] integrationInfoRest = -> logger.incoming.info 'Info integration' return {} = statusCode: 200 body: success: true Api.addRoute ':integrationId/:userId/:token', authRequired: true, {post: executeIntegrationRest, get: executeIntegrationRest} Api.addRoute ':integrationId/:token', authRequired: true, {post: executeIntegrationRest, get: executeIntegrationRest} Api.addRoute 'sample/:integrationId/:userId/:token', authRequired: true, {get: integrationSampleRest} Api.addRoute 'sample/:integrationId/:token', authRequired: true, {get: integrationSampleRest} Api.addRoute 'info/:integrationId/:userId/:token', authRequired: true, {get: integrationInfoRest} Api.addRoute 'info/:integrationId/:token', authRequired: true, {get: integrationInfoRest} Api.addRoute 'add/:integrationId/:userId/:token', authRequired: true, {post: addIntegrationRest} Api.addRoute 'add/:integrationId/:token', authRequired: true, {post: addIntegrationRest} Api.addRoute 'remove/:integrationId/:userId/:token', authRequired: true, {post: removeIntegrationRest} Api.addRoute 'remove/:integrationId/:token', authRequired: true, {post: removeIntegrationRest}
true
vm = Npm.require('vm') compiledScripts = {} getIntegrationScript = (integration) -> compiledScript = compiledScripts[integration._id] if compiledScript? and +compiledScript._updatedAt is +integration._updatedAt return compiledScript.script script = integration.scriptCompiled vmScript = undefined sandbox = _: _ s: s console: console Store: set: (key, val) -> return store[key] = val get: (key) -> return store[key] try logger.incoming.info 'Will evaluate script of Trigger', integration.name logger.incoming.debug script vmScript = vm.createScript script, 'script.js' vmScript.runInNewContext sandbox if sandbox.Script? compiledScripts[integration._id] = script: new sandbox.Script() _updatedAt: integration._updatedAt return compiledScripts[integration._id].script catch e logger.incoming.error '[Error evaluating Script in Trigger', integration.name, ':]' logger.incoming.error script.replace(/^/gm, ' ') logger.incoming.error "[Stack:]" logger.incoming.error e.stack.replace(/^/gm, ' ') throw RocketChat.API.v1.failure 'error-evaluating-script' if not sandbox.Script? logger.incoming.error '[Class "Script" not in Trigger', integration.name, ']' throw RocketChat.API.v1.failure 'class-script-not-found' Api = new Restivus enableCors: true apiPath: 'hooks/' auth: user: -> payloadKeys = Object.keys @bodyParams payloadIsWrapped = @bodyParams?.payload? and payloadKeys.length == 1 if payloadIsWrapped and @request.headers['content-type'] is 'application/x-www-form-urlencoded' try @bodyParams = JSON.parse @bodyParams.payload catch e return { error: { statusCode: 400 body: { success: false error: e.message } } } @integration = RocketChat.models.Integrations.findOne _id: @request.params.integrationId token: decodeURIComponent @request.params.token if not @integration? logger.incoming.info "Invalid integration id", @request.params.integrationId, "or token", @request.params.token return user = RocketChat.models.Users.findOne _id: @integration.userId return user: user createIntegration = (options, user) -> logger.incoming.info 'Add integration', options.name logger.incoming.debug options Meteor.runAsUser user._id, => switch options['event'] when 'newMessageOnChannel' options.data ?= {} if options.data.channel_name? and options.data.channel_name.indexOf('#') is -1 options.data.channel_name = '#' + options.data.channel_name Meteor.call 'addOutgoingIntegration', username: 'rocket.cat' urls: [options.target_url] name: options.name channel: options.data.channel_name triggerWords: options.data.trigger_words when 'newMessageToUser' if options.data.username.indexOf('@') is -1 options.data.username = '@' + options.data.username Meteor.call 'addOutgoingIntegration', username: 'rocket.cat' urls: [options.target_url] name: options.name channel: options.data.username triggerWords: options.data.trigger_words return RocketChat.API.v1.success() removeIntegration = (options, user) -> logger.incoming.info 'Remove integration' logger.incoming.debug options integrationToRemove = RocketChat.models.Integrations.findOne urls: options.target_url Meteor.runAsUser user._id, => Meteor.call 'deleteOutgoingIntegration', integrationToRemove._id return RocketChat.API.v1.success() executeIntegrationRest = -> logger.incoming.info 'Post integration', @integration.name logger.incoming.debug '@urlParams', @urlParams logger.incoming.debug '@bodyParams', @bodyParams if @integration.enabled isnt true return {} = statusCode: 503 body: 'Service Unavailable' defaultValues = channel: @integration.channel alias: @integration.alias avatar: @integration.avatar emoji: @integration.emoji if @integration.scriptEnabled is true and @integration.scriptCompiled? and @integration.scriptCompiled.trim() isnt '' script = undefined try script = getIntegrationScript(@integration) catch e return e request = url: hash: @request._parsedUrl.hash search: @request._parsedUrl.search query: @queryParams pathname: @request._parsedUrl.pathname path: @request._parsedUrl.path url_raw: @request.url url_params: @urlParams content: @bodyParams content_raw: @request._readableState?.buffer?.toString() headers: @request.headers user: _id: @user._id name: @user.name username: @user.username try sandbox = _: _ s: s console: console Store: set: (key, val) -> return store[key] = val get: (key) -> return store[key] script: script request: request result = vm.runInNewContext('script.process_incoming_request({ request: request })', sandbox, { timeout: 3000 }) if result?.error? return RocketChat.API.v1.failure result.error @bodyParams = result?.content logger.incoming.debug '[Process Incoming Request result of Trigger', @integration.name, ':]' logger.incoming.debug 'result', @bodyParams catch e logger.incoming.error '[Error running Script in Trigger', @integration.name, ':]' logger.incoming.error @integration.scriptCompiled.replace(/^/gm, ' ') logger.incoming.error "[Stack:]" logger.incoming.error e.stack.replace(/^/gm, ' ') return RocketChat.API.v1.failure 'error-running-script' if not @bodyParams? return RocketChat.API.v1.failure 'body-empty' @bodyParams.bot = i: @integration._id try message = processWebhookMessage @bodyParams, @user, defaultValues if _.isEmpty message return RocketChat.API.v1.failure 'unknown-error' return RocketChat.API.v1.success() catch e return RocketChat.API.v1.failure e.error addIntegrationRest = -> return createIntegration @bodyParams, @user removeIntegrationRest = -> return removeIntegration @bodyParams, @user integrationSampleRest = -> logger.incoming.info 'Sample Integration' return {} = statusCode: 200 body: [ token: Random.PI:KEY:<KEY>END_PI(24) channel_id: Random.id() channel_name: 'general' timestamp: new Date user_id: Random.id() user_name: 'rocket.cat' text: 'Sample text 1' trigger_word: 'Sample' , token: Random.PI:KEY:<KEY>END_PI(24) channel_id: Random.id() channel_name: 'general' timestamp: new Date user_id: Random.id() user_name: 'rocket.cat' text: 'Sample text 2' trigger_word: 'Sample' , token: Random.PI:KEY:<KEY>END_PI(24) channel_id: Random.id() channel_name: 'general' timestamp: new Date user_id: Random.id() user_name: 'rocket.cat' text: 'Sample text 3' trigger_word: 'Sample' ] integrationInfoRest = -> logger.incoming.info 'Info integration' return {} = statusCode: 200 body: success: true Api.addRoute ':integrationId/:userId/:token', authRequired: true, {post: executeIntegrationRest, get: executeIntegrationRest} Api.addRoute ':integrationId/:token', authRequired: true, {post: executeIntegrationRest, get: executeIntegrationRest} Api.addRoute 'sample/:integrationId/:userId/:token', authRequired: true, {get: integrationSampleRest} Api.addRoute 'sample/:integrationId/:token', authRequired: true, {get: integrationSampleRest} Api.addRoute 'info/:integrationId/:userId/:token', authRequired: true, {get: integrationInfoRest} Api.addRoute 'info/:integrationId/:token', authRequired: true, {get: integrationInfoRest} Api.addRoute 'add/:integrationId/:userId/:token', authRequired: true, {post: addIntegrationRest} Api.addRoute 'add/:integrationId/:token', authRequired: true, {post: addIntegrationRest} Api.addRoute 'remove/:integrationId/:userId/:token', authRequired: true, {post: removeIntegrationRest} Api.addRoute 'remove/:integrationId/:token', authRequired: true, {post: removeIntegrationRest}
[ { "context": "plication extends Chaplin.Application\n\n password: null\n\n constructor: (options) ->\n @password = opti", "end": 577, "score": 0.9838510155677795, "start": 573, "tag": "PASSWORD", "value": "null" }, { "context": "ername: constants.storage.username\n password...
app/application.coffee
jordidiaz/hm
0
StorageManager = require './storage/storage-manager' NotificationManager = require 'lib/notification-manager' DataBindingManager = require 'lib/data-binding-manager' mediator = require 'mediator' Charges = require './storage/models/charges' MonthCharges = require './storage/models/month-charges' Months = require './storage/models/months' Resume = require './storage/models/resume' constants = require './config/constants' module.exports = class Application extends Chaplin.Application password: null constructor: (options) -> @password = options.password super start: -> @_initLocale() @_initAppModules() @_fetchData() super _initLocale: -> moment.locale(navigator.language) _initAppModules: -> @_initStorageManager() @_initDataBinding() @_initNotificationManager() _initStorageManager: -> new StorageManager host: constants.storage.host database: constants.storage.database username: constants.storage.username password: @password _initDataBinding: -> new DataBindingManager _initNotificationManager: -> new NotificationManager _fetchData: -> mediator.charges.fetch() mediator.months.fetch startkey: moment().startOf('month').toJSON() endkey: moment().endOf('month').toJSON() limit: 1 success: (months, response, options) => if months.length is 1 monthId = months.at(0).get('_id') mediator.resume.set('_id', "$resume::#{monthId}") mediator.resume.fetch() initMediator: -> # gastos generales mediator.charges = new Charges # gastos de este mes mediator.monthCharges = new MonthCharges # mes actual mediator.months = new Months # resume actual mediator.resume = new Resume # Seal the mediator super
192849
StorageManager = require './storage/storage-manager' NotificationManager = require 'lib/notification-manager' DataBindingManager = require 'lib/data-binding-manager' mediator = require 'mediator' Charges = require './storage/models/charges' MonthCharges = require './storage/models/month-charges' Months = require './storage/models/months' Resume = require './storage/models/resume' constants = require './config/constants' module.exports = class Application extends Chaplin.Application password: <PASSWORD> constructor: (options) -> @password = options.password super start: -> @_initLocale() @_initAppModules() @_fetchData() super _initLocale: -> moment.locale(navigator.language) _initAppModules: -> @_initStorageManager() @_initDataBinding() @_initNotificationManager() _initStorageManager: -> new StorageManager host: constants.storage.host database: constants.storage.database username: constants.storage.username password: <PASSWORD> _initDataBinding: -> new DataBindingManager _initNotificationManager: -> new NotificationManager _fetchData: -> mediator.charges.fetch() mediator.months.fetch startkey: moment().startOf('month').toJSON() endkey: moment().endOf('month').toJSON() limit: 1 success: (months, response, options) => if months.length is 1 monthId = months.at(0).get('_id') mediator.resume.set('_id', "$resume::#{monthId}") mediator.resume.fetch() initMediator: -> # gastos generales mediator.charges = new Charges # gastos de este mes mediator.monthCharges = new MonthCharges # mes actual mediator.months = new Months # resume actual mediator.resume = new Resume # Seal the mediator super
true
StorageManager = require './storage/storage-manager' NotificationManager = require 'lib/notification-manager' DataBindingManager = require 'lib/data-binding-manager' mediator = require 'mediator' Charges = require './storage/models/charges' MonthCharges = require './storage/models/month-charges' Months = require './storage/models/months' Resume = require './storage/models/resume' constants = require './config/constants' module.exports = class Application extends Chaplin.Application password: PI:PASSWORD:<PASSWORD>END_PI constructor: (options) -> @password = options.password super start: -> @_initLocale() @_initAppModules() @_fetchData() super _initLocale: -> moment.locale(navigator.language) _initAppModules: -> @_initStorageManager() @_initDataBinding() @_initNotificationManager() _initStorageManager: -> new StorageManager host: constants.storage.host database: constants.storage.database username: constants.storage.username password: PI:PASSWORD:<PASSWORD>END_PI _initDataBinding: -> new DataBindingManager _initNotificationManager: -> new NotificationManager _fetchData: -> mediator.charges.fetch() mediator.months.fetch startkey: moment().startOf('month').toJSON() endkey: moment().endOf('month').toJSON() limit: 1 success: (months, response, options) => if months.length is 1 monthId = months.at(0).get('_id') mediator.resume.set('_id', "$resume::#{monthId}") mediator.resume.fetch() initMediator: -> # gastos generales mediator.charges = new Charges # gastos de este mes mediator.monthCharges = new MonthCharges # mes actual mediator.months = new Months # resume actual mediator.resume = new Resume # Seal the mediator super
[ { "context": "ams:netconf:base:1.0</capability>\\n'\n if @chkframing\n @ncs.write ' <capability>urn:ietf:para", "end": 3413, "score": 0.6865941286087036, "start": 3406, "tag": "USERNAME", "value": "framing" }, { "context": "ams:netconf:base:1.1</capability>\\n'\n ...
lib/ncclient.coffee
nokia/atom-netconf
15
### ncclient.coffee Copyright (c) 2016-2021 Nokia Note: This file is part of the netconf package for the ATOM Text Editor. Licensed under the MIT license See LICENSE.md delivered with this project for more information. ### {EventEmitter} = require 'events' url = require 'url' ssh2 = require 'ssh2' stream = require 'stream' xmltools = require './xmltools' module.exports = class ncclient extends EventEmitter constructor: -> @debugging = atom.config.get 'atom-netconf.debug._ncclient', false atom.config.observe 'atom-netconf.debug._ncclient', @updateDebug.bind(this) console.debug '::constructor()' if @debugging console.log process.versions if @debugging @callbacks = {} @formating = {} @connected = false @nokiaSROS = false @base_1_1 = false @locked = false @ncs = undefined @ssh = undefined @rawbuf = "" @msgbuf = "" @bytes = 0 debugSSH: -> if atom.config.get 'atom-netconf.debug._ssh', false console.debug.apply(console, arguments) updateDebug: (newValue) => console.log "netconf debug enabled" if newValue console.log "netconf debug disabled" unless newValue @debugging = newValue msgTimeout: (msgid) => if @callbacks[msgid]? @emit 'rpc-timeout', msgid console.log "timeout for rpc-request message-id=#{msgid}" if @debugging delete @callbacks[msgid] delete @formating[msgid] @emit 'idle' if (Object.getOwnPropertyNames(@callbacks).length == 0) msgHandler: (msg) => console.debug "::msgHandler()" if @debugging # convert multi-byte unicode back to utf-8 single byte characters msg = msg.replace(/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, (c) -> # convert 3 byte characters cc = (c.charCodeAt(0) & 0x0f) << 12 | (c.charCodeAt(1) & 0x3f) << 6 | c.charCodeAt(2) & 0x3f String.fromCharCode cc ).replace(/[\u00c0-\u00df][\u0080-\u00bf]/g, (c) -> # convert 2 byte characters cc = (c.charCodeAt(0) & 0x1f) << 6 | c.charCodeAt(1) & 0x3f String.fromCharCode cc ) xmldom = (new DOMParser).parseFromString msg, "text/xml" if xmldom==null @emit 'warning', 'netconf error: xml parser failed with rpc-reply received', msg else if xmldom.firstElementChild.localName == "hello" console.log "hello message received" if @debugging @nokiaSROS = false @nokiaPSS = false for capability in xmldom.getElementsByTagName('capability') if capability.firstChild.data.startsWith("urn:nokia.com:sros:ns:yang:sr:conf?") @nokiaSROS = true @emit 'Nokia SROS' if capability.firstChild.data.startsWith("http://nokia.com/yang/nokia-security?module=nokia-security") @nokiaPSS = true if capability.firstChild.data.startsWith("urn:ietf:params:netconf:capability:validate:1") @emit 'support:validate' if capability.firstChild.data == 'urn:ietf:params:netconf:capability:candidate:1.0' @emit 'support:candidate' if capability.firstChild.data == 'urn:ietf:params:netconf:base:1.1' @base_1_1 = @chkframing @ncs.write '<?xml version="1.0" encoding="UTF-8"?>\n' @ncs.write '<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">\n' @ncs.write ' <capabilities>\n' @ncs.write ' <capability>urn:ietf:params:netconf:base:1.0</capability>\n' if @chkframing @ncs.write ' <capability>urn:ietf:params:netconf:base:1.1</capability>\n' if @nokiaPSS for capability in xmldom.getElementsByTagName('capability') if capability.firstChild.data.indexOf("?module=") != -1 @ncs.write (new XMLSerializer()).serializeToString(capability) @ncs.write ' </capabilities>\n' @ncs.write '</hello>\n' @ncs.write ']]>]]>' @connected = true mode = atom.config.get 'atom-netconf.behavior.xmlProcessor' if mode == 'prettify' @emit 'connected', xmltools.prettify(xmldom) else if mode == 'minify' @emit 'connected', xmltools.minify(xmldom) else @emit 'connected', msg else if xmldom.firstElementChild.localName == "rpc-reply" console.log "rpc-reply message received" if @debugging msgid = xmldom.firstElementChild.getAttribute('message-id') if (msgid) if @callbacks[msgid]? console.log "callback found for message-id=#{msgid}" if @debugging if xmldom.getElementsByTagName('rpc-error').length >= 1 @emit 'rpc-error', msgid, xmldom else nodes = xmldom.firstElementChild.childNodes if nodes.length==1 and nodes[0].localName=="ok" and nodes[0].nodeType==1 # Just emit OK, but skip the callback @emit 'rpc-ok', msgid else if @formating[msgid] == 'prettify' @callbacks[msgid] msgid, xmltools.prettify(xmldom) else if @formating[msgid] == 'minify' @callbacks[msgid] msgid, xmltools.minify(xmldom) else if @formating[msgid] == 'data' @callbacks[msgid] msgid, xmltools.data_node(xmldom) else if @formating[msgid] == 'sros' @callbacks[msgid] msgid, xmltools.sros_config(xmldom) else @callbacks[msgid] msgid, msg delete @callbacks[msgid] delete @formating[msgid] @emit 'idle' if (Object.getOwnPropertyNames(@callbacks).length == 0) else @emit 'warning', "netconf error: unexpected rpc-reply with message-id #{msgid} received" else @emit 'warning', 'netconf error: rpc-reply w/o message-id received', msg else if xmldom.firstElementChild.localName == "notification" console.log "notification message received" if @debugging @emit 'notification', xmldom else # current version of ncclient only support hello, rpc-reply and notification @emit 'warning', 'netconf error: unsupported message received', msg base10Parser: (callback) => if @rawbuf.match("]]>]]>") msgs = @rawbuf.split("]]>]]>") @rawbuf = msgs.pop() msgs.forEach (msg) => @msgHandler(msg) callback() base11Parser: (callback) => pos = 0 while (pos+3<@rawbuf.length) if @rawbuf[pos...pos+4] == "\n##\n" if @msgbuf.length>0 @msgHandler(@msgbuf) @msgbuf = "" pos = pos+4 else if @rawbuf[pos...pos+2] == "\n#" idx = @rawbuf.indexOf("\n", pos+2) if idx!=-1 bytes = Number(@rawbuf[pos+2...idx]) if idx+1+bytes <= @rawbuf.length @msgbuf += @rawbuf[idx+1...idx+1+bytes] pos = idx+1+bytes else break # need to wait for more bytes to come else break # need to wait for more bytes to come else @rawbuf = "" @msgbuf = "" pos = 0 @emit 'error', 'base_1_1 error', 'chunk start not found' callback(new Error('base_1_1 error: chunk start not found')) return if pos>0 # skip parts next time which are already copied to msgbuf @rawbuf = @rawbuf[pos...] callback() streamParser: (callback) => if @bytes > 100000000 @emit 'data', "#{@bytes>>20}MB" else @emit 'data', "#{@bytes>>10}KB" if @base_1_1 @base11Parser(callback) # BASE_1_1 CHUNK FRAMING else @base10Parser(callback) # BASE_1_0 EOM FRAMING # --- ncclient public methods ---------------------------------------------- loadkeyfile: (filename) => console.debug "::loadkeyfile(#{filename})" if @debugging if filename != "" @privkey = require('fs').readFileSync(filename).toString('utf-8') console.log @privkey else @privkey = undefined connect: (uri) => console.debug "::connect(#{uri})" if @debugging # usage: # client.connect 'netconf://netconf:netconf@localhost:8300/' @emit 'busy' @ssh = new ssh2.Client @callbacks = {} @formating = {} @ssh.on 'error', (err) => console.log err if @debugging @emit 'error', 'ssh error', err.toString() @ssh.on 'connect', -> console.log "ssh connect" if @debugging @ssh.on 'timeout', => console.log "ssh timeout" if @debugging @ssh.on 'close', => console.log "ssh close" if @debugging @connected = false @locked = false @callbacks = {} @formating = {} @emit 'locked', false @emit 'end' @ssh.on 'end', => console.log "ssh end" if @debugging @ssh.on 'banner', (msg) => console.log "banner:\n", msg @emit 'ssh-banner', msg @ssh.on 'greeting', (msg) => console.log "greeting:\n", msg @emit 'ssh-greeting', msg @ssh.on 'ready', => @ssh.subsys 'netconf', (err, ncstream) => if err @emit 'error', 'ssh error', err.toString() return console.log "subsys netconf is ready" if @debugging @base_1_1 = false @chkframing = atom.config.get 'atom-netconf.server.base11', true @ncs = ncstream @rawbuf = "" @msgbuf = "" @bytes = 0 ncWriter = new stream.Writable( highWaterMark: 1048576 write: (chunk, encoding, callback) => # convert utf-8 single byte to unicode multi-byte characters # required, as netconf base11 chunk-length is based on octets rawString = chunk.toString('utf-8').replace(/[\u0080-\u07ff]/g, (c) -> # convert 2 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xc0 | cc >> 6, 0x80 | cc & 0x3f ).replace(/[\u0800-\uffff]/g, (c) -> # convert 3 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f ) @rawbuf += rawString @bytes += rawString.length @streamParser(callback) writev: (chunks, callback) => for chunk in chunks # convert utf-8 single byte to unicode multi-byte characters # required, as netconf base11 chunk-length is based on octets rawString = chunk.toString('utf-8').replace(/[\u0080-\u07ff]/g, (c) -> # convert 2 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xc0 | cc >> 6, 0x80 | cc & 0x3f ).replace(/[\u0800-\uffff]/g, (c) -> # convert 3 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f ) @streamParser(callback) ) # End of ncWriter ncstream.pipe(ncWriter) ncstream.on 'error', (error) => console.log "netconf connection error: #{error}" if @debugging ncstream.on 'close', => console.log "netconf connection closed" if @debugging {protocol, hostname, port, auth} = url.parse(uri) if auth.indexOf(':') != -1 username = auth.split(':')[0] password = auth.split(':')[1] else username = auth password = undefined @ssh.connect host: hostname port: port username: username password: password tryKeyboard: true # algorithms: # kex: ["ecdh-sha2-nistp256","diffie-hellman-group-exchange-sha256","diffie-hellman-group14-sha1","diffie-hellman-group-exchange-sha1","diffie-hellman-group1-sha1"] # cipher: ["aes128-ctr","aes192-ctr","aes256-ctr","aes128-gcm","aes256-gcm","aes256-cbc","3des-cbc"] debug: @debugSSH privateKey: @privkey rpc: (request, format='default', timeout=300, callback) => console.debug "::rpc()" if @debugging if @connected if typeof request is 'string' parser = new DOMParser() reqDOM = parser.parseFromString request, "text/xml" nodeName = reqDOM.firstElementChild.localName if (nodeName == 'rpc') msgid = reqDOM.firstElementChild.getAttribute('message-id') if (msgid) if @callbacks[msgid]? @emit 'warning', 'netconf error', 'message-id is already in-use' else @emit 'busy' @callbacks[msgid] = callback setTimeout (=>@msgTimeout(msgid)), timeout*1000 if format=='default' @formating[msgid] = atom.config.get 'atom-netconf.behavior.xmlProcessor' else @formating[msgid] = format if @base_1_1 # convert utf-8 single byte to unicode multi-byte characters # required, as netconf base11 chunk-length is based on octets rawString = request.replace(/[\u0080-\u07ff]/g, (c) -> # convert 2 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xc0 | cc >> 6, 0x80 | cc & 0x3f ).replace(/[\u0800-\uffff]/g, (c) -> # convert 3 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f ) @ncs.write "\n##{rawString.length}\n" @ncs.write request @ncs.write '\n##\n' else @ncs.write request @ncs.write "]]>]]>" else @emit 'warning', 'netconf error', 'rpc-request requires message-id attribute' else @emit 'warning', 'netconf error: rpc required', "unsupported netconf operation #{nodeName}" else console.error 'ncclient only supports rpc-requests using type string' else @emit 'error', 'netconf error', 'Need to connect netconf client first.' disconnect: (callback) => console.debug "::disconnect()" if @debugging if @connected @emit 'busy' @callbacks['disconnect'] = => @ssh.end() @formating['disconnect'] = 'none' request = '<?xml version="1.0" encoding="UTF-8"?>\n<rpc message-id="disconnect" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><close-session/></rpc>' if @base_1_1 @ncs.write "\n##{request.length}\n" @ncs.write request @ncs.write '\n##\n' else @ncs.write request @ncs.write "]]>]]>" setTimeout (=>@ssh.end()), 1000 else @emit 'warning', 'netconf disconnect failed', 'already disconnected' lock: => console.debug "::lock()" if @debugging if @connected if not @locked xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="lock" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><lock><target><candidate/></target></lock></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'locked', true @locked = true else @emit 'warning', 'netconf lock failed', 'already locked' else @emit 'warning', 'netconf lock failed', 'need to connect first' unlock: => console.debug "::unlock()" if @debugging if @connected if @locked xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="unlock" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><unlock><target><candidate/></target></unlock></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'locked', false @locked = false else @emit 'warning', 'netconf unlock failed', 'already locked' else @emit 'warning', 'netconf unlock failed', 'need to connect first' commit: => console.debug "::commit()" if @debugging if @connected xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="commit" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><commit/></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'committed' discard: => console.debug "::discard()" if @debugging if @connected xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="discard" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><discard-changes/></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'discarded' validate: => console.debug "::validate()" if @debugging if @connected xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="validate" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><validate><source><candidate/></source></validate></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'validated' close: => console.debug "::close()" if @debugging @ssh.end() isNokiaSROS: => return @nokiaSROS isConnected: => return @connected isLocked: => return @locked # EOF
84263
### ncclient.coffee Copyright (c) 2016-2021 Nokia Note: This file is part of the netconf package for the ATOM Text Editor. Licensed under the MIT license See LICENSE.md delivered with this project for more information. ### {EventEmitter} = require 'events' url = require 'url' ssh2 = require 'ssh2' stream = require 'stream' xmltools = require './xmltools' module.exports = class ncclient extends EventEmitter constructor: -> @debugging = atom.config.get 'atom-netconf.debug._ncclient', false atom.config.observe 'atom-netconf.debug._ncclient', @updateDebug.bind(this) console.debug '::constructor()' if @debugging console.log process.versions if @debugging @callbacks = {} @formating = {} @connected = false @nokiaSROS = false @base_1_1 = false @locked = false @ncs = undefined @ssh = undefined @rawbuf = "" @msgbuf = "" @bytes = 0 debugSSH: -> if atom.config.get 'atom-netconf.debug._ssh', false console.debug.apply(console, arguments) updateDebug: (newValue) => console.log "netconf debug enabled" if newValue console.log "netconf debug disabled" unless newValue @debugging = newValue msgTimeout: (msgid) => if @callbacks[msgid]? @emit 'rpc-timeout', msgid console.log "timeout for rpc-request message-id=#{msgid}" if @debugging delete @callbacks[msgid] delete @formating[msgid] @emit 'idle' if (Object.getOwnPropertyNames(@callbacks).length == 0) msgHandler: (msg) => console.debug "::msgHandler()" if @debugging # convert multi-byte unicode back to utf-8 single byte characters msg = msg.replace(/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, (c) -> # convert 3 byte characters cc = (c.charCodeAt(0) & 0x0f) << 12 | (c.charCodeAt(1) & 0x3f) << 6 | c.charCodeAt(2) & 0x3f String.fromCharCode cc ).replace(/[\u00c0-\u00df][\u0080-\u00bf]/g, (c) -> # convert 2 byte characters cc = (c.charCodeAt(0) & 0x1f) << 6 | c.charCodeAt(1) & 0x3f String.fromCharCode cc ) xmldom = (new DOMParser).parseFromString msg, "text/xml" if xmldom==null @emit 'warning', 'netconf error: xml parser failed with rpc-reply received', msg else if xmldom.firstElementChild.localName == "hello" console.log "hello message received" if @debugging @nokiaSROS = false @nokiaPSS = false for capability in xmldom.getElementsByTagName('capability') if capability.firstChild.data.startsWith("urn:nokia.com:sros:ns:yang:sr:conf?") @nokiaSROS = true @emit 'Nokia SROS' if capability.firstChild.data.startsWith("http://nokia.com/yang/nokia-security?module=nokia-security") @nokiaPSS = true if capability.firstChild.data.startsWith("urn:ietf:params:netconf:capability:validate:1") @emit 'support:validate' if capability.firstChild.data == 'urn:ietf:params:netconf:capability:candidate:1.0' @emit 'support:candidate' if capability.firstChild.data == 'urn:ietf:params:netconf:base:1.1' @base_1_1 = @chkframing @ncs.write '<?xml version="1.0" encoding="UTF-8"?>\n' @ncs.write '<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">\n' @ncs.write ' <capabilities>\n' @ncs.write ' <capability>urn:ietf:params:netconf:base:1.0</capability>\n' if @chkframing @ncs.write ' <capability>urn:ietf:params:netconf:base:1.1</capability>\n' if @nokiaPSS for capability in xmldom.getElementsByTagName('capability') if capability.firstChild.data.indexOf("?module=") != -1 @ncs.write (new XMLSerializer()).serializeToString(capability) @ncs.write ' </capabilities>\n' @ncs.write '</hello>\n' @ncs.write ']]>]]>' @connected = true mode = atom.config.get 'atom-netconf.behavior.xmlProcessor' if mode == 'prettify' @emit 'connected', xmltools.prettify(xmldom) else if mode == 'minify' @emit 'connected', xmltools.minify(xmldom) else @emit 'connected', msg else if xmldom.firstElementChild.localName == "rpc-reply" console.log "rpc-reply message received" if @debugging msgid = xmldom.firstElementChild.getAttribute('message-id') if (msgid) if @callbacks[msgid]? console.log "callback found for message-id=#{msgid}" if @debugging if xmldom.getElementsByTagName('rpc-error').length >= 1 @emit 'rpc-error', msgid, xmldom else nodes = xmldom.firstElementChild.childNodes if nodes.length==1 and nodes[0].localName=="ok" and nodes[0].nodeType==1 # Just emit OK, but skip the callback @emit 'rpc-ok', msgid else if @formating[msgid] == 'prettify' @callbacks[msgid] msgid, xmltools.prettify(xmldom) else if @formating[msgid] == 'minify' @callbacks[msgid] msgid, xmltools.minify(xmldom) else if @formating[msgid] == 'data' @callbacks[msgid] msgid, xmltools.data_node(xmldom) else if @formating[msgid] == 'sros' @callbacks[msgid] msgid, xmltools.sros_config(xmldom) else @callbacks[msgid] msgid, msg delete @callbacks[msgid] delete @formating[msgid] @emit 'idle' if (Object.getOwnPropertyNames(@callbacks).length == 0) else @emit 'warning', "netconf error: unexpected rpc-reply with message-id #{msgid} received" else @emit 'warning', 'netconf error: rpc-reply w/o message-id received', msg else if xmldom.firstElementChild.localName == "notification" console.log "notification message received" if @debugging @emit 'notification', xmldom else # current version of ncclient only support hello, rpc-reply and notification @emit 'warning', 'netconf error: unsupported message received', msg base10Parser: (callback) => if @rawbuf.match("]]>]]>") msgs = @rawbuf.split("]]>]]>") @rawbuf = msgs.pop() msgs.forEach (msg) => @msgHandler(msg) callback() base11Parser: (callback) => pos = 0 while (pos+3<@rawbuf.length) if @rawbuf[pos...pos+4] == "\n##\n" if @msgbuf.length>0 @msgHandler(@msgbuf) @msgbuf = "" pos = pos+4 else if @rawbuf[pos...pos+2] == "\n#" idx = @rawbuf.indexOf("\n", pos+2) if idx!=-1 bytes = Number(@rawbuf[pos+2...idx]) if idx+1+bytes <= @rawbuf.length @msgbuf += @rawbuf[idx+1...idx+1+bytes] pos = idx+1+bytes else break # need to wait for more bytes to come else break # need to wait for more bytes to come else @rawbuf = "" @msgbuf = "" pos = 0 @emit 'error', 'base_1_1 error', 'chunk start not found' callback(new Error('base_1_1 error: chunk start not found')) return if pos>0 # skip parts next time which are already copied to msgbuf @rawbuf = @rawbuf[pos...] callback() streamParser: (callback) => if @bytes > 100000000 @emit 'data', "#{@bytes>>20}MB" else @emit 'data', "#{@bytes>>10}KB" if @base_1_1 @base11Parser(callback) # BASE_1_1 CHUNK FRAMING else @base10Parser(callback) # BASE_1_0 EOM FRAMING # --- ncclient public methods ---------------------------------------------- loadkeyfile: (filename) => console.debug "::loadkeyfile(#{filename})" if @debugging if filename != "" @privkey = require('fs').readFileSync(filename).toString('utf-8') console.log @privkey else @privkey = undefined connect: (uri) => console.debug "::connect(#{uri})" if @debugging # usage: # client.connect 'netconf://netconf:netconf@localhost:8300/' @emit 'busy' @ssh = new ssh2.Client @callbacks = {} @formating = {} @ssh.on 'error', (err) => console.log err if @debugging @emit 'error', 'ssh error', err.toString() @ssh.on 'connect', -> console.log "ssh connect" if @debugging @ssh.on 'timeout', => console.log "ssh timeout" if @debugging @ssh.on 'close', => console.log "ssh close" if @debugging @connected = false @locked = false @callbacks = {} @formating = {} @emit 'locked', false @emit 'end' @ssh.on 'end', => console.log "ssh end" if @debugging @ssh.on 'banner', (msg) => console.log "banner:\n", msg @emit 'ssh-banner', msg @ssh.on 'greeting', (msg) => console.log "greeting:\n", msg @emit 'ssh-greeting', msg @ssh.on 'ready', => @ssh.subsys 'netconf', (err, ncstream) => if err @emit 'error', 'ssh error', err.toString() return console.log "subsys netconf is ready" if @debugging @base_1_1 = false @chkframing = atom.config.get 'atom-netconf.server.base11', true @ncs = ncstream @rawbuf = "" @msgbuf = "" @bytes = 0 ncWriter = new stream.Writable( highWaterMark: 1048576 write: (chunk, encoding, callback) => # convert utf-8 single byte to unicode multi-byte characters # required, as netconf base11 chunk-length is based on octets rawString = chunk.toString('utf-8').replace(/[\u0080-\u07ff]/g, (c) -> # convert 2 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xc0 | cc >> 6, 0x80 | cc & 0x3f ).replace(/[\u0800-\uffff]/g, (c) -> # convert 3 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f ) @rawbuf += rawString @bytes += rawString.length @streamParser(callback) writev: (chunks, callback) => for chunk in chunks # convert utf-8 single byte to unicode multi-byte characters # required, as netconf base11 chunk-length is based on octets rawString = chunk.toString('utf-8').replace(/[\u0080-\u07ff]/g, (c) -> # convert 2 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xc0 | cc >> 6, 0x80 | cc & 0x3f ).replace(/[\u0800-\uffff]/g, (c) -> # convert 3 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f ) @streamParser(callback) ) # End of ncWriter ncstream.pipe(ncWriter) ncstream.on 'error', (error) => console.log "netconf connection error: #{error}" if @debugging ncstream.on 'close', => console.log "netconf connection closed" if @debugging {protocol, hostname, port, auth} = url.parse(uri) if auth.indexOf(':') != -1 username = auth.split(':')[0] password = auth.split(':')[1] else username = auth password = <PASSWORD> @ssh.connect host: hostname port: port username: username password: <PASSWORD> tryKeyboard: true # algorithms: # kex: ["ecdh-sha2-nistp256","diffie-hellman-group-exchange-sha256","diffie-hellman-group14-sha1","diffie-hellman-group-exchange-sha1","diffie-hellman-group1-sha1"] # cipher: ["aes128-ctr","aes192-ctr","aes256-ctr","aes128-gcm","aes256-gcm","aes256-cbc","3des-cbc"] debug: @debugSSH privateKey: @privkey rpc: (request, format='default', timeout=300, callback) => console.debug "::rpc()" if @debugging if @connected if typeof request is 'string' parser = new DOMParser() reqDOM = parser.parseFromString request, "text/xml" nodeName = reqDOM.firstElementChild.localName if (nodeName == 'rpc') msgid = reqDOM.firstElementChild.getAttribute('message-id') if (msgid) if @callbacks[msgid]? @emit 'warning', 'netconf error', 'message-id is already in-use' else @emit 'busy' @callbacks[msgid] = callback setTimeout (=>@msgTimeout(msgid)), timeout*1000 if format=='default' @formating[msgid] = atom.config.get 'atom-netconf.behavior.xmlProcessor' else @formating[msgid] = format if @base_1_1 # convert utf-8 single byte to unicode multi-byte characters # required, as netconf base11 chunk-length is based on octets rawString = request.replace(/[\u0080-\u07ff]/g, (c) -> # convert 2 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xc0 | cc >> 6, 0x80 | cc & 0x3f ).replace(/[\u0800-\uffff]/g, (c) -> # convert 3 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f ) @ncs.write "\n##{rawString.length}\n" @ncs.write request @ncs.write '\n##\n' else @ncs.write request @ncs.write "]]>]]>" else @emit 'warning', 'netconf error', 'rpc-request requires message-id attribute' else @emit 'warning', 'netconf error: rpc required', "unsupported netconf operation #{nodeName}" else console.error 'ncclient only supports rpc-requests using type string' else @emit 'error', 'netconf error', 'Need to connect netconf client first.' disconnect: (callback) => console.debug "::disconnect()" if @debugging if @connected @emit 'busy' @callbacks['disconnect'] = => @ssh.end() @formating['disconnect'] = 'none' request = '<?xml version="1.0" encoding="UTF-8"?>\n<rpc message-id="disconnect" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><close-session/></rpc>' if @base_1_1 @ncs.write "\n##{request.length}\n" @ncs.write request @ncs.write '\n##\n' else @ncs.write request @ncs.write "]]>]]>" setTimeout (=>@ssh.end()), 1000 else @emit 'warning', 'netconf disconnect failed', 'already disconnected' lock: => console.debug "::lock()" if @debugging if @connected if not @locked xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="lock" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><lock><target><candidate/></target></lock></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'locked', true @locked = true else @emit 'warning', 'netconf lock failed', 'already locked' else @emit 'warning', 'netconf lock failed', 'need to connect first' unlock: => console.debug "::unlock()" if @debugging if @connected if @locked xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="unlock" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><unlock><target><candidate/></target></unlock></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'locked', false @locked = false else @emit 'warning', 'netconf unlock failed', 'already locked' else @emit 'warning', 'netconf unlock failed', 'need to connect first' commit: => console.debug "::commit()" if @debugging if @connected xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="commit" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><commit/></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'committed' discard: => console.debug "::discard()" if @debugging if @connected xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="discard" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><discard-changes/></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'discarded' validate: => console.debug "::validate()" if @debugging if @connected xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="validate" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><validate><source><candidate/></source></validate></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'validated' close: => console.debug "::close()" if @debugging @ssh.end() isNokiaSROS: => return @nokiaSROS isConnected: => return @connected isLocked: => return @locked # EOF
true
### ncclient.coffee Copyright (c) 2016-2021 Nokia Note: This file is part of the netconf package for the ATOM Text Editor. Licensed under the MIT license See LICENSE.md delivered with this project for more information. ### {EventEmitter} = require 'events' url = require 'url' ssh2 = require 'ssh2' stream = require 'stream' xmltools = require './xmltools' module.exports = class ncclient extends EventEmitter constructor: -> @debugging = atom.config.get 'atom-netconf.debug._ncclient', false atom.config.observe 'atom-netconf.debug._ncclient', @updateDebug.bind(this) console.debug '::constructor()' if @debugging console.log process.versions if @debugging @callbacks = {} @formating = {} @connected = false @nokiaSROS = false @base_1_1 = false @locked = false @ncs = undefined @ssh = undefined @rawbuf = "" @msgbuf = "" @bytes = 0 debugSSH: -> if atom.config.get 'atom-netconf.debug._ssh', false console.debug.apply(console, arguments) updateDebug: (newValue) => console.log "netconf debug enabled" if newValue console.log "netconf debug disabled" unless newValue @debugging = newValue msgTimeout: (msgid) => if @callbacks[msgid]? @emit 'rpc-timeout', msgid console.log "timeout for rpc-request message-id=#{msgid}" if @debugging delete @callbacks[msgid] delete @formating[msgid] @emit 'idle' if (Object.getOwnPropertyNames(@callbacks).length == 0) msgHandler: (msg) => console.debug "::msgHandler()" if @debugging # convert multi-byte unicode back to utf-8 single byte characters msg = msg.replace(/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, (c) -> # convert 3 byte characters cc = (c.charCodeAt(0) & 0x0f) << 12 | (c.charCodeAt(1) & 0x3f) << 6 | c.charCodeAt(2) & 0x3f String.fromCharCode cc ).replace(/[\u00c0-\u00df][\u0080-\u00bf]/g, (c) -> # convert 2 byte characters cc = (c.charCodeAt(0) & 0x1f) << 6 | c.charCodeAt(1) & 0x3f String.fromCharCode cc ) xmldom = (new DOMParser).parseFromString msg, "text/xml" if xmldom==null @emit 'warning', 'netconf error: xml parser failed with rpc-reply received', msg else if xmldom.firstElementChild.localName == "hello" console.log "hello message received" if @debugging @nokiaSROS = false @nokiaPSS = false for capability in xmldom.getElementsByTagName('capability') if capability.firstChild.data.startsWith("urn:nokia.com:sros:ns:yang:sr:conf?") @nokiaSROS = true @emit 'Nokia SROS' if capability.firstChild.data.startsWith("http://nokia.com/yang/nokia-security?module=nokia-security") @nokiaPSS = true if capability.firstChild.data.startsWith("urn:ietf:params:netconf:capability:validate:1") @emit 'support:validate' if capability.firstChild.data == 'urn:ietf:params:netconf:capability:candidate:1.0' @emit 'support:candidate' if capability.firstChild.data == 'urn:ietf:params:netconf:base:1.1' @base_1_1 = @chkframing @ncs.write '<?xml version="1.0" encoding="UTF-8"?>\n' @ncs.write '<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">\n' @ncs.write ' <capabilities>\n' @ncs.write ' <capability>urn:ietf:params:netconf:base:1.0</capability>\n' if @chkframing @ncs.write ' <capability>urn:ietf:params:netconf:base:1.1</capability>\n' if @nokiaPSS for capability in xmldom.getElementsByTagName('capability') if capability.firstChild.data.indexOf("?module=") != -1 @ncs.write (new XMLSerializer()).serializeToString(capability) @ncs.write ' </capabilities>\n' @ncs.write '</hello>\n' @ncs.write ']]>]]>' @connected = true mode = atom.config.get 'atom-netconf.behavior.xmlProcessor' if mode == 'prettify' @emit 'connected', xmltools.prettify(xmldom) else if mode == 'minify' @emit 'connected', xmltools.minify(xmldom) else @emit 'connected', msg else if xmldom.firstElementChild.localName == "rpc-reply" console.log "rpc-reply message received" if @debugging msgid = xmldom.firstElementChild.getAttribute('message-id') if (msgid) if @callbacks[msgid]? console.log "callback found for message-id=#{msgid}" if @debugging if xmldom.getElementsByTagName('rpc-error').length >= 1 @emit 'rpc-error', msgid, xmldom else nodes = xmldom.firstElementChild.childNodes if nodes.length==1 and nodes[0].localName=="ok" and nodes[0].nodeType==1 # Just emit OK, but skip the callback @emit 'rpc-ok', msgid else if @formating[msgid] == 'prettify' @callbacks[msgid] msgid, xmltools.prettify(xmldom) else if @formating[msgid] == 'minify' @callbacks[msgid] msgid, xmltools.minify(xmldom) else if @formating[msgid] == 'data' @callbacks[msgid] msgid, xmltools.data_node(xmldom) else if @formating[msgid] == 'sros' @callbacks[msgid] msgid, xmltools.sros_config(xmldom) else @callbacks[msgid] msgid, msg delete @callbacks[msgid] delete @formating[msgid] @emit 'idle' if (Object.getOwnPropertyNames(@callbacks).length == 0) else @emit 'warning', "netconf error: unexpected rpc-reply with message-id #{msgid} received" else @emit 'warning', 'netconf error: rpc-reply w/o message-id received', msg else if xmldom.firstElementChild.localName == "notification" console.log "notification message received" if @debugging @emit 'notification', xmldom else # current version of ncclient only support hello, rpc-reply and notification @emit 'warning', 'netconf error: unsupported message received', msg base10Parser: (callback) => if @rawbuf.match("]]>]]>") msgs = @rawbuf.split("]]>]]>") @rawbuf = msgs.pop() msgs.forEach (msg) => @msgHandler(msg) callback() base11Parser: (callback) => pos = 0 while (pos+3<@rawbuf.length) if @rawbuf[pos...pos+4] == "\n##\n" if @msgbuf.length>0 @msgHandler(@msgbuf) @msgbuf = "" pos = pos+4 else if @rawbuf[pos...pos+2] == "\n#" idx = @rawbuf.indexOf("\n", pos+2) if idx!=-1 bytes = Number(@rawbuf[pos+2...idx]) if idx+1+bytes <= @rawbuf.length @msgbuf += @rawbuf[idx+1...idx+1+bytes] pos = idx+1+bytes else break # need to wait for more bytes to come else break # need to wait for more bytes to come else @rawbuf = "" @msgbuf = "" pos = 0 @emit 'error', 'base_1_1 error', 'chunk start not found' callback(new Error('base_1_1 error: chunk start not found')) return if pos>0 # skip parts next time which are already copied to msgbuf @rawbuf = @rawbuf[pos...] callback() streamParser: (callback) => if @bytes > 100000000 @emit 'data', "#{@bytes>>20}MB" else @emit 'data', "#{@bytes>>10}KB" if @base_1_1 @base11Parser(callback) # BASE_1_1 CHUNK FRAMING else @base10Parser(callback) # BASE_1_0 EOM FRAMING # --- ncclient public methods ---------------------------------------------- loadkeyfile: (filename) => console.debug "::loadkeyfile(#{filename})" if @debugging if filename != "" @privkey = require('fs').readFileSync(filename).toString('utf-8') console.log @privkey else @privkey = undefined connect: (uri) => console.debug "::connect(#{uri})" if @debugging # usage: # client.connect 'netconf://netconf:netconf@localhost:8300/' @emit 'busy' @ssh = new ssh2.Client @callbacks = {} @formating = {} @ssh.on 'error', (err) => console.log err if @debugging @emit 'error', 'ssh error', err.toString() @ssh.on 'connect', -> console.log "ssh connect" if @debugging @ssh.on 'timeout', => console.log "ssh timeout" if @debugging @ssh.on 'close', => console.log "ssh close" if @debugging @connected = false @locked = false @callbacks = {} @formating = {} @emit 'locked', false @emit 'end' @ssh.on 'end', => console.log "ssh end" if @debugging @ssh.on 'banner', (msg) => console.log "banner:\n", msg @emit 'ssh-banner', msg @ssh.on 'greeting', (msg) => console.log "greeting:\n", msg @emit 'ssh-greeting', msg @ssh.on 'ready', => @ssh.subsys 'netconf', (err, ncstream) => if err @emit 'error', 'ssh error', err.toString() return console.log "subsys netconf is ready" if @debugging @base_1_1 = false @chkframing = atom.config.get 'atom-netconf.server.base11', true @ncs = ncstream @rawbuf = "" @msgbuf = "" @bytes = 0 ncWriter = new stream.Writable( highWaterMark: 1048576 write: (chunk, encoding, callback) => # convert utf-8 single byte to unicode multi-byte characters # required, as netconf base11 chunk-length is based on octets rawString = chunk.toString('utf-8').replace(/[\u0080-\u07ff]/g, (c) -> # convert 2 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xc0 | cc >> 6, 0x80 | cc & 0x3f ).replace(/[\u0800-\uffff]/g, (c) -> # convert 3 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f ) @rawbuf += rawString @bytes += rawString.length @streamParser(callback) writev: (chunks, callback) => for chunk in chunks # convert utf-8 single byte to unicode multi-byte characters # required, as netconf base11 chunk-length is based on octets rawString = chunk.toString('utf-8').replace(/[\u0080-\u07ff]/g, (c) -> # convert 2 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xc0 | cc >> 6, 0x80 | cc & 0x3f ).replace(/[\u0800-\uffff]/g, (c) -> # convert 3 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f ) @streamParser(callback) ) # End of ncWriter ncstream.pipe(ncWriter) ncstream.on 'error', (error) => console.log "netconf connection error: #{error}" if @debugging ncstream.on 'close', => console.log "netconf connection closed" if @debugging {protocol, hostname, port, auth} = url.parse(uri) if auth.indexOf(':') != -1 username = auth.split(':')[0] password = auth.split(':')[1] else username = auth password = PI:PASSWORD:<PASSWORD>END_PI @ssh.connect host: hostname port: port username: username password: PI:PASSWORD:<PASSWORD>END_PI tryKeyboard: true # algorithms: # kex: ["ecdh-sha2-nistp256","diffie-hellman-group-exchange-sha256","diffie-hellman-group14-sha1","diffie-hellman-group-exchange-sha1","diffie-hellman-group1-sha1"] # cipher: ["aes128-ctr","aes192-ctr","aes256-ctr","aes128-gcm","aes256-gcm","aes256-cbc","3des-cbc"] debug: @debugSSH privateKey: @privkey rpc: (request, format='default', timeout=300, callback) => console.debug "::rpc()" if @debugging if @connected if typeof request is 'string' parser = new DOMParser() reqDOM = parser.parseFromString request, "text/xml" nodeName = reqDOM.firstElementChild.localName if (nodeName == 'rpc') msgid = reqDOM.firstElementChild.getAttribute('message-id') if (msgid) if @callbacks[msgid]? @emit 'warning', 'netconf error', 'message-id is already in-use' else @emit 'busy' @callbacks[msgid] = callback setTimeout (=>@msgTimeout(msgid)), timeout*1000 if format=='default' @formating[msgid] = atom.config.get 'atom-netconf.behavior.xmlProcessor' else @formating[msgid] = format if @base_1_1 # convert utf-8 single byte to unicode multi-byte characters # required, as netconf base11 chunk-length is based on octets rawString = request.replace(/[\u0080-\u07ff]/g, (c) -> # convert 2 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xc0 | cc >> 6, 0x80 | cc & 0x3f ).replace(/[\u0800-\uffff]/g, (c) -> # convert 3 byte characters cc = c.charCodeAt(0) String.fromCharCode 0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f ) @ncs.write "\n##{rawString.length}\n" @ncs.write request @ncs.write '\n##\n' else @ncs.write request @ncs.write "]]>]]>" else @emit 'warning', 'netconf error', 'rpc-request requires message-id attribute' else @emit 'warning', 'netconf error: rpc required', "unsupported netconf operation #{nodeName}" else console.error 'ncclient only supports rpc-requests using type string' else @emit 'error', 'netconf error', 'Need to connect netconf client first.' disconnect: (callback) => console.debug "::disconnect()" if @debugging if @connected @emit 'busy' @callbacks['disconnect'] = => @ssh.end() @formating['disconnect'] = 'none' request = '<?xml version="1.0" encoding="UTF-8"?>\n<rpc message-id="disconnect" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><close-session/></rpc>' if @base_1_1 @ncs.write "\n##{request.length}\n" @ncs.write request @ncs.write '\n##\n' else @ncs.write request @ncs.write "]]>]]>" setTimeout (=>@ssh.end()), 1000 else @emit 'warning', 'netconf disconnect failed', 'already disconnected' lock: => console.debug "::lock()" if @debugging if @connected if not @locked xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="lock" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><lock><target><candidate/></target></lock></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'locked', true @locked = true else @emit 'warning', 'netconf lock failed', 'already locked' else @emit 'warning', 'netconf lock failed', 'need to connect first' unlock: => console.debug "::unlock()" if @debugging if @connected if @locked xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="unlock" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><unlock><target><candidate/></target></unlock></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'locked', false @locked = false else @emit 'warning', 'netconf unlock failed', 'already locked' else @emit 'warning', 'netconf unlock failed', 'need to connect first' commit: => console.debug "::commit()" if @debugging if @connected xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="commit" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><commit/></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'committed' discard: => console.debug "::discard()" if @debugging if @connected xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="discard" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><discard-changes/></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'discarded' validate: => console.debug "::validate()" if @debugging if @connected xmlrpc = """<?xml version="1.0" encoding="UTF-8"?><rpc message-id="validate" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><validate><source><candidate/></source></validate></rpc>""" @rpc xmlrpc, 'default', 60, => @emit 'validated' close: => console.debug "::close()" if @debugging @ssh.end() isNokiaSROS: => return @nokiaSROS isConnected: => return @connected isLocked: => return @locked # EOF
[ { "context": "\" \" + time\n datetime_ms = Date.now()\n\n key = \"#{tagg.trail_index} #{time}: #{category} / #{type}\"\n crumb = {\n short: ", "end": 5312, "score": 0.9654455184936523, "start": 5280, "tag": "KEY", "value": "\"#{tagg.trail_index} #{time}: #{" } ]
source/06__test.coffee
davidchip/tagg
0
tagg.trail_index = 0 tagg.debug = { _all: {} _verbose: {} } tagg.wrapTest = (test, delay=10) -> return new Promise((testsFinished) => timeout = new Promise ((timeoutCompleted) => tagg.loaded.then(() => setTimeout (() => timeoutCompleted() ), delay ) ) timeout.then(() => url = window.location.pathname; filename = url.substring(url.lastIndexOf('/')+1) results = { passed: [] failed: [] filename: filename logs: tagg.debug } test(results) if results.failed.length is 0 msg = " %c PASSED" for space in [0..Math.ceil(Math.random() * 10)] msg = msg + " " console.log(msg, "color:blue;") else console.log("%c FAILED ", "background-color:red; color:white") console.log(results) testsFinished(results) ) ) tagg.testEvent = (category, eventName, eventDetails) -> testingObj = {} testingObj[category] = {} testingObj[category][eventName] = eventDetails return tagg.testObj(testingObj) tagg.testEvents = (events=[], delay=1000) -> testingObj = {} for event in events category = event[0] eventName = event[1] eventDetails = event[2] if not testingObj[category]? testingObj[category] = {} testingObj[category][eventName] = eventDetails return tagg.testObj(testingObj, delay) tagg.testEqual = (arg1, arg2, msg='', delay=100) -> return tagg.wrapTest((results) => if arg1 is arg2 results.passed.push("#{arg1} equals #{arg2} for test #{msg}") else results.failed.push("#{arg1} does not equal #{arg2} for test #{msg}") , delay) tagg.testAttr = (_tag, attrName, testVal, delay=100) -> return tagg.wrapTest((results) => attrVal = _tag.getAttribute(attrName) tagName = _tag.tagName.toLowerCase() if testVal is attrVal results.passed.push("attr #{attrName} for #{tagName} equals #{testVal}") else results.failed.push("attr #{attrName} for #{tagName} does not equal #{testVal}, it equals #{attrVal}") , delay) tagg.testProp = (_tag, propName, testVal, delay=100) -> return tagg.wrapTest((results) => tagName = _tag.tagName.toLowerCase() if _tag[propName] is testVal results.passed.push("prop #{propName} for #{tagName} equals #{testVal}") else results.failed.push("prop #{propName} for #{tagName} does not equal #{testVal}, equals #{_tag[propName]}") , delay) tagg.testObj = (testingObj={}, delay=1000) -> return tagg.wrapTest((results) => for category, tagCrumbs of testingObj if not tagg.debug[category]? results.failed.push("#{category} has had no events at all") else for eventType, eventTest of tagCrumbs event = tagg.debug[category][eventType] if not event? results.failed.push("#{category} has had no events of type #{eventType}") else if typeof eventTest is "object" for testKey, testValue of eventTest eventValue = event[testKey] if eventValue is testValue results.passed.push("#{category} had an event #{eventType} where #{testKey} equalled #{testValue}") else results.failed.push("#{category} had an event #{eventType} where #{testKey} equalled #{eventValue} instead of #{testValue}") else if typeof eventTest is "function" _eventTest = eventTest(event) if _eventTest is true results.passed.push("#{category} function for #{eventType} passed") else results.failed.push("#{category} function for #{eventType} failed") else if typeof eventTest is "number" if event["_length"] is eventTest testLength = results.passed.push("#{category} had #{eventTest} instance(s) of #{eventType} event(s)") else results.failed.push("#{category} had #{event["_length"]} instance(s) of #{eventType} being called, not #{eventTest}") , delay) tagg.log = (type, category, verbose, details={}) => """Add event regarding a category the central log. """ if not verbose? verbose = type category = "#{category}" category = category.toLowerCase() today = new Date() date = today.toLocaleDateString() time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds() + ":" + today.getMilliseconds() datetime = date + " " + time datetime_ms = Date.now() key = "#{tagg.trail_index} #{time}: #{category} / #{type}" crumb = { short: type verbose: verbose details: if typeof details is "array" then details.toString() else details datetime: datetime datetime_ms: datetime_ms category: category } ## track by tag if not tagg.debug[category]? tagg.debug[category] = {} tagg.debug[category]["_all"] = {} tagg.debug[category]["_verbose"] = {} if not tagg.debug[category][type]? tagg.debug[category][type] = {} tagg.debug[category][type]['_length'] = 0 tagg.debug[category][type][key] = crumb tagg.debug[category][type]['_length'] = Object.keys(tagg.debug[category][type]).length - 1 ## - 1 for _length property tagg.debug[category]["_all"][key] = crumb tagg.debug[category]["_verbose"][tagg.trail_index + " " + time] = verbose ## track by time tagg.debug["_all"][key] = crumb tagg.debug["_verbose"][tagg.trail_index + " " + time] = verbose tagg.trail_index++
132994
tagg.trail_index = 0 tagg.debug = { _all: {} _verbose: {} } tagg.wrapTest = (test, delay=10) -> return new Promise((testsFinished) => timeout = new Promise ((timeoutCompleted) => tagg.loaded.then(() => setTimeout (() => timeoutCompleted() ), delay ) ) timeout.then(() => url = window.location.pathname; filename = url.substring(url.lastIndexOf('/')+1) results = { passed: [] failed: [] filename: filename logs: tagg.debug } test(results) if results.failed.length is 0 msg = " %c PASSED" for space in [0..Math.ceil(Math.random() * 10)] msg = msg + " " console.log(msg, "color:blue;") else console.log("%c FAILED ", "background-color:red; color:white") console.log(results) testsFinished(results) ) ) tagg.testEvent = (category, eventName, eventDetails) -> testingObj = {} testingObj[category] = {} testingObj[category][eventName] = eventDetails return tagg.testObj(testingObj) tagg.testEvents = (events=[], delay=1000) -> testingObj = {} for event in events category = event[0] eventName = event[1] eventDetails = event[2] if not testingObj[category]? testingObj[category] = {} testingObj[category][eventName] = eventDetails return tagg.testObj(testingObj, delay) tagg.testEqual = (arg1, arg2, msg='', delay=100) -> return tagg.wrapTest((results) => if arg1 is arg2 results.passed.push("#{arg1} equals #{arg2} for test #{msg}") else results.failed.push("#{arg1} does not equal #{arg2} for test #{msg}") , delay) tagg.testAttr = (_tag, attrName, testVal, delay=100) -> return tagg.wrapTest((results) => attrVal = _tag.getAttribute(attrName) tagName = _tag.tagName.toLowerCase() if testVal is attrVal results.passed.push("attr #{attrName} for #{tagName} equals #{testVal}") else results.failed.push("attr #{attrName} for #{tagName} does not equal #{testVal}, it equals #{attrVal}") , delay) tagg.testProp = (_tag, propName, testVal, delay=100) -> return tagg.wrapTest((results) => tagName = _tag.tagName.toLowerCase() if _tag[propName] is testVal results.passed.push("prop #{propName} for #{tagName} equals #{testVal}") else results.failed.push("prop #{propName} for #{tagName} does not equal #{testVal}, equals #{_tag[propName]}") , delay) tagg.testObj = (testingObj={}, delay=1000) -> return tagg.wrapTest((results) => for category, tagCrumbs of testingObj if not tagg.debug[category]? results.failed.push("#{category} has had no events at all") else for eventType, eventTest of tagCrumbs event = tagg.debug[category][eventType] if not event? results.failed.push("#{category} has had no events of type #{eventType}") else if typeof eventTest is "object" for testKey, testValue of eventTest eventValue = event[testKey] if eventValue is testValue results.passed.push("#{category} had an event #{eventType} where #{testKey} equalled #{testValue}") else results.failed.push("#{category} had an event #{eventType} where #{testKey} equalled #{eventValue} instead of #{testValue}") else if typeof eventTest is "function" _eventTest = eventTest(event) if _eventTest is true results.passed.push("#{category} function for #{eventType} passed") else results.failed.push("#{category} function for #{eventType} failed") else if typeof eventTest is "number" if event["_length"] is eventTest testLength = results.passed.push("#{category} had #{eventTest} instance(s) of #{eventType} event(s)") else results.failed.push("#{category} had #{event["_length"]} instance(s) of #{eventType} being called, not #{eventTest}") , delay) tagg.log = (type, category, verbose, details={}) => """Add event regarding a category the central log. """ if not verbose? verbose = type category = "#{category}" category = category.toLowerCase() today = new Date() date = today.toLocaleDateString() time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds() + ":" + today.getMilliseconds() datetime = date + " " + time datetime_ms = Date.now() key = <KEY>category} / #{type}" crumb = { short: type verbose: verbose details: if typeof details is "array" then details.toString() else details datetime: datetime datetime_ms: datetime_ms category: category } ## track by tag if not tagg.debug[category]? tagg.debug[category] = {} tagg.debug[category]["_all"] = {} tagg.debug[category]["_verbose"] = {} if not tagg.debug[category][type]? tagg.debug[category][type] = {} tagg.debug[category][type]['_length'] = 0 tagg.debug[category][type][key] = crumb tagg.debug[category][type]['_length'] = Object.keys(tagg.debug[category][type]).length - 1 ## - 1 for _length property tagg.debug[category]["_all"][key] = crumb tagg.debug[category]["_verbose"][tagg.trail_index + " " + time] = verbose ## track by time tagg.debug["_all"][key] = crumb tagg.debug["_verbose"][tagg.trail_index + " " + time] = verbose tagg.trail_index++
true
tagg.trail_index = 0 tagg.debug = { _all: {} _verbose: {} } tagg.wrapTest = (test, delay=10) -> return new Promise((testsFinished) => timeout = new Promise ((timeoutCompleted) => tagg.loaded.then(() => setTimeout (() => timeoutCompleted() ), delay ) ) timeout.then(() => url = window.location.pathname; filename = url.substring(url.lastIndexOf('/')+1) results = { passed: [] failed: [] filename: filename logs: tagg.debug } test(results) if results.failed.length is 0 msg = " %c PASSED" for space in [0..Math.ceil(Math.random() * 10)] msg = msg + " " console.log(msg, "color:blue;") else console.log("%c FAILED ", "background-color:red; color:white") console.log(results) testsFinished(results) ) ) tagg.testEvent = (category, eventName, eventDetails) -> testingObj = {} testingObj[category] = {} testingObj[category][eventName] = eventDetails return tagg.testObj(testingObj) tagg.testEvents = (events=[], delay=1000) -> testingObj = {} for event in events category = event[0] eventName = event[1] eventDetails = event[2] if not testingObj[category]? testingObj[category] = {} testingObj[category][eventName] = eventDetails return tagg.testObj(testingObj, delay) tagg.testEqual = (arg1, arg2, msg='', delay=100) -> return tagg.wrapTest((results) => if arg1 is arg2 results.passed.push("#{arg1} equals #{arg2} for test #{msg}") else results.failed.push("#{arg1} does not equal #{arg2} for test #{msg}") , delay) tagg.testAttr = (_tag, attrName, testVal, delay=100) -> return tagg.wrapTest((results) => attrVal = _tag.getAttribute(attrName) tagName = _tag.tagName.toLowerCase() if testVal is attrVal results.passed.push("attr #{attrName} for #{tagName} equals #{testVal}") else results.failed.push("attr #{attrName} for #{tagName} does not equal #{testVal}, it equals #{attrVal}") , delay) tagg.testProp = (_tag, propName, testVal, delay=100) -> return tagg.wrapTest((results) => tagName = _tag.tagName.toLowerCase() if _tag[propName] is testVal results.passed.push("prop #{propName} for #{tagName} equals #{testVal}") else results.failed.push("prop #{propName} for #{tagName} does not equal #{testVal}, equals #{_tag[propName]}") , delay) tagg.testObj = (testingObj={}, delay=1000) -> return tagg.wrapTest((results) => for category, tagCrumbs of testingObj if not tagg.debug[category]? results.failed.push("#{category} has had no events at all") else for eventType, eventTest of tagCrumbs event = tagg.debug[category][eventType] if not event? results.failed.push("#{category} has had no events of type #{eventType}") else if typeof eventTest is "object" for testKey, testValue of eventTest eventValue = event[testKey] if eventValue is testValue results.passed.push("#{category} had an event #{eventType} where #{testKey} equalled #{testValue}") else results.failed.push("#{category} had an event #{eventType} where #{testKey} equalled #{eventValue} instead of #{testValue}") else if typeof eventTest is "function" _eventTest = eventTest(event) if _eventTest is true results.passed.push("#{category} function for #{eventType} passed") else results.failed.push("#{category} function for #{eventType} failed") else if typeof eventTest is "number" if event["_length"] is eventTest testLength = results.passed.push("#{category} had #{eventTest} instance(s) of #{eventType} event(s)") else results.failed.push("#{category} had #{event["_length"]} instance(s) of #{eventType} being called, not #{eventTest}") , delay) tagg.log = (type, category, verbose, details={}) => """Add event regarding a category the central log. """ if not verbose? verbose = type category = "#{category}" category = category.toLowerCase() today = new Date() date = today.toLocaleDateString() time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds() + ":" + today.getMilliseconds() datetime = date + " " + time datetime_ms = Date.now() key = PI:KEY:<KEY>END_PIcategory} / #{type}" crumb = { short: type verbose: verbose details: if typeof details is "array" then details.toString() else details datetime: datetime datetime_ms: datetime_ms category: category } ## track by tag if not tagg.debug[category]? tagg.debug[category] = {} tagg.debug[category]["_all"] = {} tagg.debug[category]["_verbose"] = {} if not tagg.debug[category][type]? tagg.debug[category][type] = {} tagg.debug[category][type]['_length'] = 0 tagg.debug[category][type][key] = crumb tagg.debug[category][type]['_length'] = Object.keys(tagg.debug[category][type]).length - 1 ## - 1 for _length property tagg.debug[category]["_all"][key] = crumb tagg.debug[category]["_verbose"][tagg.trail_index + " " + time] = verbose ## track by time tagg.debug["_all"][key] = crumb tagg.debug["_verbose"][tagg.trail_index + " " + time] = verbose tagg.trail_index++
[ { "context": "\n\n @setPublished = (id, published) ->\n key = \"published_#{id}\"\n @_set key, published\n\n @getPublished = (id) ", "end": 1207, "score": 0.9673157930374146, "start": 1191, "tag": "KEY", "value": "published_#{id}\"" }, { "context": ", published\n\n @getPubli...
server/api/page/page.model.coffee
EcomGems/tilda-site
13
'use strict' Q = require 'q' config = require '../../config/environment' redis = require '../../helpers/redis' Tilda = require '../../helpers/tilda' tilda = new Tilda config.tilda.api.public_key, config.tilda.api.secret_key Project = require '../project/project.model' Promises = require 'bluebird' md5 = require 'md5' liquid = require 'liquid-node' fs = require 'fs' Promises.promisifyAll(fs) CDNify = require '../../helpers/cdnify' class Page @_get = (key) -> def = Q.defer() redis .getAsync key .then (value) -> def.resolve value return .catch (err) -> def.reject err return def.promise @_set = (key, value) -> def = Q.defer() redis .setAsync key, value .then (value) -> def.resolve value return .catch (err) -> def.reject err return def.promise ### # Check if page # is still fresh ### @isPageFresh = (id, published) -> def = Q.defer() Page.getPublished(id) .then (value) -> if not value? or value < published def.resolve false else def.resolve true def.promise @setPublished = (id, published) -> key = "published_#{id}" @_set key, published @getPublished = (id) -> key = "published_#{id}" @_get key @setHtml = (path, html, protocol = 'http') -> key = "#{protocol}_#{md5(path)}" @_set key, html @getHtml = (path, protocol = 'http') -> key = "#{protocol}_#{md5(path)}" @_get key ### # Compile page # if that's necessary # to recompile it ### @compile = (page, overwrite = false) -> def = Q.defer() _page = null # Validate if # we need to # recompile # the page @isPageFresh page.id, page.published .then (isFresh) -> if isFresh and not overwrite # Return page # and cancel # the chain def.resolve page return Promises.cancel() else # Fetch complete # page data from # Tilda return tilda.page page.id .then (page) -> _page = page # Prepare content # for both HTTP and # HTTPS protocols Promises.all [ Page.prepareHtml(page, 'http'), Page.prepareHtml(page, 'https') ] .then (contents) -> httpContent = contents[0] httpsContent = contents[1] Promises.all [ Page.setHtml(_page.alias, httpContent, 'http') Page.setHtml(_page.alias, httpsContent, 'https') ] .then () -> Page.setPublished _page.id, _page.published .then () -> def.resolve _page .catch (err) -> def.reject err def.promise @initPages = (project, overwrite = false) -> console.log "Prepare Tilda Pages for #{project.title} project" def = Q.defer() tilda # Fetch info # about all pages # in the project .pages project.id # Compile all pages # we need to compile .then (pages) => promises = [] for page in pages promises.push Page.compile page, overwrite Promises.all promises # Resolve promise # to initialize # pages .then (pages) -> def.resolve pages # Sure try # to handle # any problems .catch (err) -> def.reject err return def.promise @prepareHtml = (page, protocol = 'http')-> def = Q.defer() templatePath = './template/page.liquid' fetchPartsPromises = [ fs.readFileAsync(templatePath, 'utf8') Project.get(config.tilda.api.project_id) ] Promises .all fetchPartsPromises .then (parts) -> content = parts[0] project = parts[1] engine = new liquid.Engine return engine.parseAndRender content, page: page config: config protocol: protocol project: project .then (html) -> return CDNify.content html .then (html) -> def.resolve html return .catch (err) -> def.reject err return def.promise module.exports = Page
101003
'use strict' Q = require 'q' config = require '../../config/environment' redis = require '../../helpers/redis' Tilda = require '../../helpers/tilda' tilda = new Tilda config.tilda.api.public_key, config.tilda.api.secret_key Project = require '../project/project.model' Promises = require 'bluebird' md5 = require 'md5' liquid = require 'liquid-node' fs = require 'fs' Promises.promisifyAll(fs) CDNify = require '../../helpers/cdnify' class Page @_get = (key) -> def = Q.defer() redis .getAsync key .then (value) -> def.resolve value return .catch (err) -> def.reject err return def.promise @_set = (key, value) -> def = Q.defer() redis .setAsync key, value .then (value) -> def.resolve value return .catch (err) -> def.reject err return def.promise ### # Check if page # is still fresh ### @isPageFresh = (id, published) -> def = Q.defer() Page.getPublished(id) .then (value) -> if not value? or value < published def.resolve false else def.resolve true def.promise @setPublished = (id, published) -> key = "<KEY> @_set key, published @getPublished = (id) -> key = "<KEY>id}" @_get key @setHtml = (path, html, protocol = 'http') -> key = <KEY> @_set key, html @getHtml = (path, protocol = 'http') -> key = <KEY> @_get key ### # Compile page # if that's necessary # to recompile it ### @compile = (page, overwrite = false) -> def = Q.defer() _page = null # Validate if # we need to # recompile # the page @isPageFresh page.id, page.published .then (isFresh) -> if isFresh and not overwrite # Return page # and cancel # the chain def.resolve page return Promises.cancel() else # Fetch complete # page data from # Tilda return tilda.page page.id .then (page) -> _page = page # Prepare content # for both HTTP and # HTTPS protocols Promises.all [ Page.prepareHtml(page, 'http'), Page.prepareHtml(page, 'https') ] .then (contents) -> httpContent = contents[0] httpsContent = contents[1] Promises.all [ Page.setHtml(_page.alias, httpContent, 'http') Page.setHtml(_page.alias, httpsContent, 'https') ] .then () -> Page.setPublished _page.id, _page.published .then () -> def.resolve _page .catch (err) -> def.reject err def.promise @initPages = (project, overwrite = false) -> console.log "Prepare Tilda Pages for #{project.title} project" def = Q.defer() tilda # Fetch info # about all pages # in the project .pages project.id # Compile all pages # we need to compile .then (pages) => promises = [] for page in pages promises.push Page.compile page, overwrite Promises.all promises # Resolve promise # to initialize # pages .then (pages) -> def.resolve pages # Sure try # to handle # any problems .catch (err) -> def.reject err return def.promise @prepareHtml = (page, protocol = 'http')-> def = Q.defer() templatePath = './template/page.liquid' fetchPartsPromises = [ fs.readFileAsync(templatePath, 'utf8') Project.get(config.tilda.api.project_id) ] Promises .all fetchPartsPromises .then (parts) -> content = parts[0] project = parts[1] engine = new liquid.Engine return engine.parseAndRender content, page: page config: config protocol: protocol project: project .then (html) -> return CDNify.content html .then (html) -> def.resolve html return .catch (err) -> def.reject err return def.promise module.exports = Page
true
'use strict' Q = require 'q' config = require '../../config/environment' redis = require '../../helpers/redis' Tilda = require '../../helpers/tilda' tilda = new Tilda config.tilda.api.public_key, config.tilda.api.secret_key Project = require '../project/project.model' Promises = require 'bluebird' md5 = require 'md5' liquid = require 'liquid-node' fs = require 'fs' Promises.promisifyAll(fs) CDNify = require '../../helpers/cdnify' class Page @_get = (key) -> def = Q.defer() redis .getAsync key .then (value) -> def.resolve value return .catch (err) -> def.reject err return def.promise @_set = (key, value) -> def = Q.defer() redis .setAsync key, value .then (value) -> def.resolve value return .catch (err) -> def.reject err return def.promise ### # Check if page # is still fresh ### @isPageFresh = (id, published) -> def = Q.defer() Page.getPublished(id) .then (value) -> if not value? or value < published def.resolve false else def.resolve true def.promise @setPublished = (id, published) -> key = "PI:KEY:<KEY>END_PI @_set key, published @getPublished = (id) -> key = "PI:KEY:<KEY>END_PIid}" @_get key @setHtml = (path, html, protocol = 'http') -> key = PI:KEY:<KEY>END_PI @_set key, html @getHtml = (path, protocol = 'http') -> key = PI:KEY:<KEY>END_PI @_get key ### # Compile page # if that's necessary # to recompile it ### @compile = (page, overwrite = false) -> def = Q.defer() _page = null # Validate if # we need to # recompile # the page @isPageFresh page.id, page.published .then (isFresh) -> if isFresh and not overwrite # Return page # and cancel # the chain def.resolve page return Promises.cancel() else # Fetch complete # page data from # Tilda return tilda.page page.id .then (page) -> _page = page # Prepare content # for both HTTP and # HTTPS protocols Promises.all [ Page.prepareHtml(page, 'http'), Page.prepareHtml(page, 'https') ] .then (contents) -> httpContent = contents[0] httpsContent = contents[1] Promises.all [ Page.setHtml(_page.alias, httpContent, 'http') Page.setHtml(_page.alias, httpsContent, 'https') ] .then () -> Page.setPublished _page.id, _page.published .then () -> def.resolve _page .catch (err) -> def.reject err def.promise @initPages = (project, overwrite = false) -> console.log "Prepare Tilda Pages for #{project.title} project" def = Q.defer() tilda # Fetch info # about all pages # in the project .pages project.id # Compile all pages # we need to compile .then (pages) => promises = [] for page in pages promises.push Page.compile page, overwrite Promises.all promises # Resolve promise # to initialize # pages .then (pages) -> def.resolve pages # Sure try # to handle # any problems .catch (err) -> def.reject err return def.promise @prepareHtml = (page, protocol = 'http')-> def = Q.defer() templatePath = './template/page.liquid' fetchPartsPromises = [ fs.readFileAsync(templatePath, 'utf8') Project.get(config.tilda.api.project_id) ] Promises .all fetchPartsPromises .then (parts) -> content = parts[0] project = parts[1] engine = new liquid.Engine return engine.parseAndRender content, page: page config: config protocol: protocol project: project .then (html) -> return CDNify.content html .then (html) -> def.resolve html return .catch (err) -> def.reject err return def.promise module.exports = Page
[ { "context": "###\nTilt the simulator\n\n@auther ho.s\n@date 2016.10.04\n###\nOrientationSimulator = {}\nOr", "end": 36, "score": 0.8351641297340393, "start": 32, "tag": "NAME", "value": "ho.s" } ]
360Viewer.framer/modules/OrientationSimulator.coffee
framer-modules/sensor
12
### Tilt the simulator @auther ho.s @date 2016.10.04 ### OrientationSimulator = {} OrientationSimulator.onTilt = (cb) -> return unless Utils.isDesktop() Events.Gamma = "OrientationSimulator.gamma" ry = 1 * 1.2 dx = 50 dz = -5 dScaleX = .96 guideDx = 30 # Set perspective Framer.Device.hands.perspective = 100 * 2 Framer.Device.hands.z = 100 # View _left = new Layer name: '.left' width: Framer.Device.background.width / 2, height: Framer.Device.background.height backgroundColor: 'rgba(0,0,0,0)' parent: Framer.Device.background _right = new Layer name: '.right' x: Framer.Device.background.width / 2 width: Framer.Device.background.width / 2, height: Framer.Device.background.height backgroundColor: 'rgba(0,0,0,0)' parent: Framer.Device.background _left.label = new Layer name: '.left.label' x: Align.right(-800 * Framer.Device.hands.scale), y: Align.center width: 500 html: "<strong>왼쪽</strong>으로<br/>기울이기" color: "rgba(0,0,0,.3)" style: { font: "300 100px/1 #{Utils.deviceFont()}", textAlign: "right", "-webkit-font-smoothing": "antialiased" } scale: Framer.Device.hands.scale, originX: 1 backgroundColor: "transparent" parent: _left _left.label.custom = { oX: _left.label.x } _right.label = new Layer name: '.right.label' x: Align.left(800 * Framer.Device.hands.scale), y: Align.center width: 500 html: "<strong>오른쪽</strong>으로<br/>기울이기" color: "rgba(0,0,0,.3)" style: { font: "300 100px/1 #{Utils.deviceFont()}", textAlign: "left", "-webkit-font-smoothing": "antialiased" } scale: Framer.Device.hands.scale, originX: 0 backgroundColor: "transparent" parent: _right _right.label.custom = { oX: _right.label.x } ### # Event :: Touch start Framer.Device.background.onTapStart -> centerX = Framer.Device.background.width / 2 if event.point.x < centerX Framer.Device.handsImageLayer.animate properties: { x: Align.center(dx), rotationY: -ry, z: dz, scaleX: dScaleX } Framer.Device.phone.animate properties: { x: Align.center(dx), rotationY: -ry, z: dz, scaleX: dScaleX } else Framer.Device.handsImageLayer.animate properties: { x: Align.center(-dx), rotationY: ry, z: dz, scaleX: dScaleX } Framer.Device.phone.animate properties: { x: Align.center(-dx), rotationY: ry, z: dz, scaleX: dScaleX } # Event :: Touch end Framer.Device.background.onTapEnd -> Framer.Device.handsImageLayer.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } Framer.Device.phone.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } ### Utils.interval .1, -> cb(Utils.modulate(Framer.Device.phone.rotationY, [-ry, ry], [-1, 1], true), @) ? cb # Event :: Change # Framer.Device.phone.on "change:rotationY", -> # Callback # cb(Utils.modulate(Framer.Device.phone.rotationY, [-ry, ry], [-1, 1], true), @) ? cb Framer.Device.background.on "change:size", -> _left.props = width: Framer.Device.background.width / 2, height: Framer.Device.background.height _right.props = x: Framer.Device.background.width / 2 width: Framer.Device.background.width / 2, height: Framer.Device.background.height _left.label.props = x: Align.right(-800 * Framer.Device.hands.scale), y: Align.center scale: Framer.Device.hands.scale _left.label.custom = { oX: _left.label.x } _right.label.props = x: Align.left(800 * Framer.Device.hands.scale), y: Align.center scale: Framer.Device.hands.scale _right.label.custom = { oX: _right.label.x } isLeftAni = isBackAni = isRightAni = false onMouseOver = -> if @name is ".left" then x = @children[0].custom.oX - guideDx else x = @children[0].custom.oX + guideDx @children[0].animate properties: { x: x } onMouseOut = -> @children[0].animate properties: { x: @children[0].custom.oX } if Framer.Device.phone.rotationY isnt 0 and !isBackAni isLeftAni = false isBackAni = true isRightAni = false Framer.Device.handsImageLayer.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } Framer.Device.phone.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } Framer.Device.phone.onAnimationEnd callback = -> isBackAni = false Framer.Device.phone.off Events.AnimationEnd, callback _left.onMouseOver onMouseOver _left.onMouseOut onMouseOut _right.onMouseOver onMouseOver _right.onMouseOut onMouseOut onTouchMove = (_dx, _ry) -> if Framer.Device.phone.rotationY isnt _ry and !(if _ry is -ry then isLeftAni else isRightAni) isLeftAni = isBackAni = isRightAni = false if _ry is -ry then isLeftAni = true else isRightAni = true Framer.Device.handsImageLayer.animate properties: { x: Align.center(_dx), rotationY: _ry, z: dz, scaleX: dScaleX } Framer.Device.phone.animate properties: { x: Align.center(_dx), rotationY: _ry, z: dz, scaleX: dScaleX } _left.onTouchMove -> onTouchMove(dx, -ry, isLeftAni) _right.onTouchMove -> onTouchMove(-dx, ry, isRightAni) module.exports = OrientationSimulator if module? Framer.OrientationSimulator = OrientationSimulator
27315
### Tilt the simulator @auther <NAME> @date 2016.10.04 ### OrientationSimulator = {} OrientationSimulator.onTilt = (cb) -> return unless Utils.isDesktop() Events.Gamma = "OrientationSimulator.gamma" ry = 1 * 1.2 dx = 50 dz = -5 dScaleX = .96 guideDx = 30 # Set perspective Framer.Device.hands.perspective = 100 * 2 Framer.Device.hands.z = 100 # View _left = new Layer name: '.left' width: Framer.Device.background.width / 2, height: Framer.Device.background.height backgroundColor: 'rgba(0,0,0,0)' parent: Framer.Device.background _right = new Layer name: '.right' x: Framer.Device.background.width / 2 width: Framer.Device.background.width / 2, height: Framer.Device.background.height backgroundColor: 'rgba(0,0,0,0)' parent: Framer.Device.background _left.label = new Layer name: '.left.label' x: Align.right(-800 * Framer.Device.hands.scale), y: Align.center width: 500 html: "<strong>왼쪽</strong>으로<br/>기울이기" color: "rgba(0,0,0,.3)" style: { font: "300 100px/1 #{Utils.deviceFont()}", textAlign: "right", "-webkit-font-smoothing": "antialiased" } scale: Framer.Device.hands.scale, originX: 1 backgroundColor: "transparent" parent: _left _left.label.custom = { oX: _left.label.x } _right.label = new Layer name: '.right.label' x: Align.left(800 * Framer.Device.hands.scale), y: Align.center width: 500 html: "<strong>오른쪽</strong>으로<br/>기울이기" color: "rgba(0,0,0,.3)" style: { font: "300 100px/1 #{Utils.deviceFont()}", textAlign: "left", "-webkit-font-smoothing": "antialiased" } scale: Framer.Device.hands.scale, originX: 0 backgroundColor: "transparent" parent: _right _right.label.custom = { oX: _right.label.x } ### # Event :: Touch start Framer.Device.background.onTapStart -> centerX = Framer.Device.background.width / 2 if event.point.x < centerX Framer.Device.handsImageLayer.animate properties: { x: Align.center(dx), rotationY: -ry, z: dz, scaleX: dScaleX } Framer.Device.phone.animate properties: { x: Align.center(dx), rotationY: -ry, z: dz, scaleX: dScaleX } else Framer.Device.handsImageLayer.animate properties: { x: Align.center(-dx), rotationY: ry, z: dz, scaleX: dScaleX } Framer.Device.phone.animate properties: { x: Align.center(-dx), rotationY: ry, z: dz, scaleX: dScaleX } # Event :: Touch end Framer.Device.background.onTapEnd -> Framer.Device.handsImageLayer.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } Framer.Device.phone.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } ### Utils.interval .1, -> cb(Utils.modulate(Framer.Device.phone.rotationY, [-ry, ry], [-1, 1], true), @) ? cb # Event :: Change # Framer.Device.phone.on "change:rotationY", -> # Callback # cb(Utils.modulate(Framer.Device.phone.rotationY, [-ry, ry], [-1, 1], true), @) ? cb Framer.Device.background.on "change:size", -> _left.props = width: Framer.Device.background.width / 2, height: Framer.Device.background.height _right.props = x: Framer.Device.background.width / 2 width: Framer.Device.background.width / 2, height: Framer.Device.background.height _left.label.props = x: Align.right(-800 * Framer.Device.hands.scale), y: Align.center scale: Framer.Device.hands.scale _left.label.custom = { oX: _left.label.x } _right.label.props = x: Align.left(800 * Framer.Device.hands.scale), y: Align.center scale: Framer.Device.hands.scale _right.label.custom = { oX: _right.label.x } isLeftAni = isBackAni = isRightAni = false onMouseOver = -> if @name is ".left" then x = @children[0].custom.oX - guideDx else x = @children[0].custom.oX + guideDx @children[0].animate properties: { x: x } onMouseOut = -> @children[0].animate properties: { x: @children[0].custom.oX } if Framer.Device.phone.rotationY isnt 0 and !isBackAni isLeftAni = false isBackAni = true isRightAni = false Framer.Device.handsImageLayer.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } Framer.Device.phone.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } Framer.Device.phone.onAnimationEnd callback = -> isBackAni = false Framer.Device.phone.off Events.AnimationEnd, callback _left.onMouseOver onMouseOver _left.onMouseOut onMouseOut _right.onMouseOver onMouseOver _right.onMouseOut onMouseOut onTouchMove = (_dx, _ry) -> if Framer.Device.phone.rotationY isnt _ry and !(if _ry is -ry then isLeftAni else isRightAni) isLeftAni = isBackAni = isRightAni = false if _ry is -ry then isLeftAni = true else isRightAni = true Framer.Device.handsImageLayer.animate properties: { x: Align.center(_dx), rotationY: _ry, z: dz, scaleX: dScaleX } Framer.Device.phone.animate properties: { x: Align.center(_dx), rotationY: _ry, z: dz, scaleX: dScaleX } _left.onTouchMove -> onTouchMove(dx, -ry, isLeftAni) _right.onTouchMove -> onTouchMove(-dx, ry, isRightAni) module.exports = OrientationSimulator if module? Framer.OrientationSimulator = OrientationSimulator
true
### Tilt the simulator @auther PI:NAME:<NAME>END_PI @date 2016.10.04 ### OrientationSimulator = {} OrientationSimulator.onTilt = (cb) -> return unless Utils.isDesktop() Events.Gamma = "OrientationSimulator.gamma" ry = 1 * 1.2 dx = 50 dz = -5 dScaleX = .96 guideDx = 30 # Set perspective Framer.Device.hands.perspective = 100 * 2 Framer.Device.hands.z = 100 # View _left = new Layer name: '.left' width: Framer.Device.background.width / 2, height: Framer.Device.background.height backgroundColor: 'rgba(0,0,0,0)' parent: Framer.Device.background _right = new Layer name: '.right' x: Framer.Device.background.width / 2 width: Framer.Device.background.width / 2, height: Framer.Device.background.height backgroundColor: 'rgba(0,0,0,0)' parent: Framer.Device.background _left.label = new Layer name: '.left.label' x: Align.right(-800 * Framer.Device.hands.scale), y: Align.center width: 500 html: "<strong>왼쪽</strong>으로<br/>기울이기" color: "rgba(0,0,0,.3)" style: { font: "300 100px/1 #{Utils.deviceFont()}", textAlign: "right", "-webkit-font-smoothing": "antialiased" } scale: Framer.Device.hands.scale, originX: 1 backgroundColor: "transparent" parent: _left _left.label.custom = { oX: _left.label.x } _right.label = new Layer name: '.right.label' x: Align.left(800 * Framer.Device.hands.scale), y: Align.center width: 500 html: "<strong>오른쪽</strong>으로<br/>기울이기" color: "rgba(0,0,0,.3)" style: { font: "300 100px/1 #{Utils.deviceFont()}", textAlign: "left", "-webkit-font-smoothing": "antialiased" } scale: Framer.Device.hands.scale, originX: 0 backgroundColor: "transparent" parent: _right _right.label.custom = { oX: _right.label.x } ### # Event :: Touch start Framer.Device.background.onTapStart -> centerX = Framer.Device.background.width / 2 if event.point.x < centerX Framer.Device.handsImageLayer.animate properties: { x: Align.center(dx), rotationY: -ry, z: dz, scaleX: dScaleX } Framer.Device.phone.animate properties: { x: Align.center(dx), rotationY: -ry, z: dz, scaleX: dScaleX } else Framer.Device.handsImageLayer.animate properties: { x: Align.center(-dx), rotationY: ry, z: dz, scaleX: dScaleX } Framer.Device.phone.animate properties: { x: Align.center(-dx), rotationY: ry, z: dz, scaleX: dScaleX } # Event :: Touch end Framer.Device.background.onTapEnd -> Framer.Device.handsImageLayer.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } Framer.Device.phone.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } ### Utils.interval .1, -> cb(Utils.modulate(Framer.Device.phone.rotationY, [-ry, ry], [-1, 1], true), @) ? cb # Event :: Change # Framer.Device.phone.on "change:rotationY", -> # Callback # cb(Utils.modulate(Framer.Device.phone.rotationY, [-ry, ry], [-1, 1], true), @) ? cb Framer.Device.background.on "change:size", -> _left.props = width: Framer.Device.background.width / 2, height: Framer.Device.background.height _right.props = x: Framer.Device.background.width / 2 width: Framer.Device.background.width / 2, height: Framer.Device.background.height _left.label.props = x: Align.right(-800 * Framer.Device.hands.scale), y: Align.center scale: Framer.Device.hands.scale _left.label.custom = { oX: _left.label.x } _right.label.props = x: Align.left(800 * Framer.Device.hands.scale), y: Align.center scale: Framer.Device.hands.scale _right.label.custom = { oX: _right.label.x } isLeftAni = isBackAni = isRightAni = false onMouseOver = -> if @name is ".left" then x = @children[0].custom.oX - guideDx else x = @children[0].custom.oX + guideDx @children[0].animate properties: { x: x } onMouseOut = -> @children[0].animate properties: { x: @children[0].custom.oX } if Framer.Device.phone.rotationY isnt 0 and !isBackAni isLeftAni = false isBackAni = true isRightAni = false Framer.Device.handsImageLayer.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } Framer.Device.phone.animate properties: { x: Align.center, rotationX: 0, rotationY: 0, z: 0, scaleX: 1 } Framer.Device.phone.onAnimationEnd callback = -> isBackAni = false Framer.Device.phone.off Events.AnimationEnd, callback _left.onMouseOver onMouseOver _left.onMouseOut onMouseOut _right.onMouseOver onMouseOver _right.onMouseOut onMouseOut onTouchMove = (_dx, _ry) -> if Framer.Device.phone.rotationY isnt _ry and !(if _ry is -ry then isLeftAni else isRightAni) isLeftAni = isBackAni = isRightAni = false if _ry is -ry then isLeftAni = true else isRightAni = true Framer.Device.handsImageLayer.animate properties: { x: Align.center(_dx), rotationY: _ry, z: dz, scaleX: dScaleX } Framer.Device.phone.animate properties: { x: Align.center(_dx), rotationY: _ry, z: dz, scaleX: dScaleX } _left.onTouchMove -> onTouchMove(dx, -ry, isLeftAni) _right.onTouchMove -> onTouchMove(-dx, ry, isRightAni) module.exports = OrientationSimulator if module? Framer.OrientationSimulator = OrientationSimulator
[ { "context": "sted workaround for #365 ###\n swap.author = 'director' if csl.type in [ 'motion_picture', 'broadcast']\n", "end": 1289, "score": 0.9707790613174438, "start": 1281, "tag": "NAME", "value": "director" } ]
resource/translators/betterCSL.coffee
edwinksl/zotero-better-bibtex
0
doExport = -> items = [] while item = Zotero.nextItem() continue if item.itemType == 'note' || item.itemType == 'attachment' cached = Zotero.BetterBibTeX.cache.fetch(item.itemID, Translator.header) if cached csl = cached.bibtex else Zotero.BetterBibTeX.keymanager.extract(item, 'nextItem') fields = Translator.extractFields(item) csl = Zotero.Utilities.itemToCSLJSON(item) csl.issued = Zotero.BetterBibTeX.parseDateToArray(item.date) if csl.issued && item.date for name, value of fields continue unless value.format == 'csl' switch Translator.CSLVariables[name].type when 'date' csl[name] = Zotero.BetterBibTeX.parseDateToArray(value.value) when 'creator' creators = [] for creator in value.value creator = {family: creator.lastName || '', given: creator.firstName || ''} Zotero.BetterBibTeX.CSL.parseParticles(creator) creators.push(creator) csl[name] = creators else csl[name] = value.value swap = { shortTitle: 'title-short' journalAbbreviation: 'container-title-short' } ### ham-fisted workaround for #365 ### swap.author = 'director' if csl.type in [ 'motion_picture', 'broadcast'] for k, v of swap [csl[k], csl[v]] = [csl[v], csl[k]] citekey = csl.id = Zotero.BetterBibTeX.keymanager.get(item, 'on-export').citekey csl = serialize(csl) Zotero.BetterBibTeX.cache.store(item.itemID, Translator.header, citekey, csl) items.push(csl) Zotero.write(flush(items))
59238
doExport = -> items = [] while item = Zotero.nextItem() continue if item.itemType == 'note' || item.itemType == 'attachment' cached = Zotero.BetterBibTeX.cache.fetch(item.itemID, Translator.header) if cached csl = cached.bibtex else Zotero.BetterBibTeX.keymanager.extract(item, 'nextItem') fields = Translator.extractFields(item) csl = Zotero.Utilities.itemToCSLJSON(item) csl.issued = Zotero.BetterBibTeX.parseDateToArray(item.date) if csl.issued && item.date for name, value of fields continue unless value.format == 'csl' switch Translator.CSLVariables[name].type when 'date' csl[name] = Zotero.BetterBibTeX.parseDateToArray(value.value) when 'creator' creators = [] for creator in value.value creator = {family: creator.lastName || '', given: creator.firstName || ''} Zotero.BetterBibTeX.CSL.parseParticles(creator) creators.push(creator) csl[name] = creators else csl[name] = value.value swap = { shortTitle: 'title-short' journalAbbreviation: 'container-title-short' } ### ham-fisted workaround for #365 ### swap.author = '<NAME>' if csl.type in [ 'motion_picture', 'broadcast'] for k, v of swap [csl[k], csl[v]] = [csl[v], csl[k]] citekey = csl.id = Zotero.BetterBibTeX.keymanager.get(item, 'on-export').citekey csl = serialize(csl) Zotero.BetterBibTeX.cache.store(item.itemID, Translator.header, citekey, csl) items.push(csl) Zotero.write(flush(items))
true
doExport = -> items = [] while item = Zotero.nextItem() continue if item.itemType == 'note' || item.itemType == 'attachment' cached = Zotero.BetterBibTeX.cache.fetch(item.itemID, Translator.header) if cached csl = cached.bibtex else Zotero.BetterBibTeX.keymanager.extract(item, 'nextItem') fields = Translator.extractFields(item) csl = Zotero.Utilities.itemToCSLJSON(item) csl.issued = Zotero.BetterBibTeX.parseDateToArray(item.date) if csl.issued && item.date for name, value of fields continue unless value.format == 'csl' switch Translator.CSLVariables[name].type when 'date' csl[name] = Zotero.BetterBibTeX.parseDateToArray(value.value) when 'creator' creators = [] for creator in value.value creator = {family: creator.lastName || '', given: creator.firstName || ''} Zotero.BetterBibTeX.CSL.parseParticles(creator) creators.push(creator) csl[name] = creators else csl[name] = value.value swap = { shortTitle: 'title-short' journalAbbreviation: 'container-title-short' } ### ham-fisted workaround for #365 ### swap.author = 'PI:NAME:<NAME>END_PI' if csl.type in [ 'motion_picture', 'broadcast'] for k, v of swap [csl[k], csl[v]] = [csl[v], csl[k]] citekey = csl.id = Zotero.BetterBibTeX.keymanager.get(item, 'on-export').citekey csl = serialize(csl) Zotero.BetterBibTeX.cache.store(item.itemID, Translator.header, citekey, csl) items.push(csl) Zotero.write(flush(items))
[ { "context": "# Copyright (C) 2013 John Judnich\n# Released under The MIT License - see \"LICENSE\" ", "end": 33, "score": 0.9998758435249329, "start": 21, "tag": "NAME", "value": "John Judnich" } ]
shaders/PlanetFarMeshShader.coffee
anandprabhakar0507/Kosmos
46
# Copyright (C) 2013 John Judnich # Released under The MIT License - see "LICENSE" file for details. frag = """ precision mediump float; varying vec3 vNormal; varying vec2 vUV; uniform vec3 lightVec; uniform sampler2D sampler; uniform vec3 planetColor1; uniform vec3 planetColor2; uniform float alpha; vec3 computeLighting(float globalDot, float diffuse, float ambient, vec3 color) { /*float nightBlend = clamp(0.5 - globalDot * 4.0, 0.0, 1.0); float nightLight = clamp(0.2 / sqrt(camDist) - 0.001, 0.0, 1.0); float ambientNight = nightBlend * (ambient * ambient * 0.14 + 0.02) * nightLight; float grayColor = (color.r + color.g + color.b) / 3.0; vec3 nightColor = vec3(grayColor * 0.4, grayColor * 0.1, grayColor * 1.0);*/ return color * diffuse;// + nightColor * ambientNight; } vec3 computeColor(float height, float ambient) { float selfShadowing = 1.00 - dot(planetColor1, vec3(1,1,1)/3.0); vec3 color = vec3(1,1,1); float edge = mix(1.0, ambient, selfShadowing); color *= mix(planetColor2, vec3(1,1,1) * edge, clamp(abs(height - 0.0) / 1.5, 0.0, 1.0)); color *= mix(planetColor1, vec3(1,1,1) * edge, clamp(abs(height - 0.5) / 2.5, 0.0, 1.0)); color *= height * 0.25 + 1.00; return color; } void main(void) { // extract terrain info vec4 tex = texture2D(sampler, vUV); vec3 norm = normalize(tex.xyz * 2.0 - 1.0); // compute terrain shape features values float globalDot = dot(lightVec, vNormal); float diffuse = clamp(dot(lightVec, norm), 0.0, 1.0); float ambient = clamp(1.0 - 2.0 * acos(dot(norm, normalize(vNormal))), 0.0, 1.0); float height = tex.a; // compute color based on terrain features vec3 color = computeColor(height, ambient); gl_FragColor.xyz = computeLighting(globalDot, diffuse, ambient, color); gl_FragColor.w = alpha; } """ vert = """ attribute vec3 aPos; attribute vec2 aUV; uniform mat4 projMat; uniform mat4 modelViewMat; varying vec3 vNormal; varying vec2 vUV; void main(void) { vNormal = aPos; vUV = aUV; vec4 pos = vec4(aPos, 1.0); pos = modelViewMat * pos; gl_Position = projMat * pos; } """ xgl.addProgram("planetFarMesh", vert, frag)
44612
# Copyright (C) 2013 <NAME> # Released under The MIT License - see "LICENSE" file for details. frag = """ precision mediump float; varying vec3 vNormal; varying vec2 vUV; uniform vec3 lightVec; uniform sampler2D sampler; uniform vec3 planetColor1; uniform vec3 planetColor2; uniform float alpha; vec3 computeLighting(float globalDot, float diffuse, float ambient, vec3 color) { /*float nightBlend = clamp(0.5 - globalDot * 4.0, 0.0, 1.0); float nightLight = clamp(0.2 / sqrt(camDist) - 0.001, 0.0, 1.0); float ambientNight = nightBlend * (ambient * ambient * 0.14 + 0.02) * nightLight; float grayColor = (color.r + color.g + color.b) / 3.0; vec3 nightColor = vec3(grayColor * 0.4, grayColor * 0.1, grayColor * 1.0);*/ return color * diffuse;// + nightColor * ambientNight; } vec3 computeColor(float height, float ambient) { float selfShadowing = 1.00 - dot(planetColor1, vec3(1,1,1)/3.0); vec3 color = vec3(1,1,1); float edge = mix(1.0, ambient, selfShadowing); color *= mix(planetColor2, vec3(1,1,1) * edge, clamp(abs(height - 0.0) / 1.5, 0.0, 1.0)); color *= mix(planetColor1, vec3(1,1,1) * edge, clamp(abs(height - 0.5) / 2.5, 0.0, 1.0)); color *= height * 0.25 + 1.00; return color; } void main(void) { // extract terrain info vec4 tex = texture2D(sampler, vUV); vec3 norm = normalize(tex.xyz * 2.0 - 1.0); // compute terrain shape features values float globalDot = dot(lightVec, vNormal); float diffuse = clamp(dot(lightVec, norm), 0.0, 1.0); float ambient = clamp(1.0 - 2.0 * acos(dot(norm, normalize(vNormal))), 0.0, 1.0); float height = tex.a; // compute color based on terrain features vec3 color = computeColor(height, ambient); gl_FragColor.xyz = computeLighting(globalDot, diffuse, ambient, color); gl_FragColor.w = alpha; } """ vert = """ attribute vec3 aPos; attribute vec2 aUV; uniform mat4 projMat; uniform mat4 modelViewMat; varying vec3 vNormal; varying vec2 vUV; void main(void) { vNormal = aPos; vUV = aUV; vec4 pos = vec4(aPos, 1.0); pos = modelViewMat * pos; gl_Position = projMat * pos; } """ xgl.addProgram("planetFarMesh", vert, frag)
true
# Copyright (C) 2013 PI:NAME:<NAME>END_PI # Released under The MIT License - see "LICENSE" file for details. frag = """ precision mediump float; varying vec3 vNormal; varying vec2 vUV; uniform vec3 lightVec; uniform sampler2D sampler; uniform vec3 planetColor1; uniform vec3 planetColor2; uniform float alpha; vec3 computeLighting(float globalDot, float diffuse, float ambient, vec3 color) { /*float nightBlend = clamp(0.5 - globalDot * 4.0, 0.0, 1.0); float nightLight = clamp(0.2 / sqrt(camDist) - 0.001, 0.0, 1.0); float ambientNight = nightBlend * (ambient * ambient * 0.14 + 0.02) * nightLight; float grayColor = (color.r + color.g + color.b) / 3.0; vec3 nightColor = vec3(grayColor * 0.4, grayColor * 0.1, grayColor * 1.0);*/ return color * diffuse;// + nightColor * ambientNight; } vec3 computeColor(float height, float ambient) { float selfShadowing = 1.00 - dot(planetColor1, vec3(1,1,1)/3.0); vec3 color = vec3(1,1,1); float edge = mix(1.0, ambient, selfShadowing); color *= mix(planetColor2, vec3(1,1,1) * edge, clamp(abs(height - 0.0) / 1.5, 0.0, 1.0)); color *= mix(planetColor1, vec3(1,1,1) * edge, clamp(abs(height - 0.5) / 2.5, 0.0, 1.0)); color *= height * 0.25 + 1.00; return color; } void main(void) { // extract terrain info vec4 tex = texture2D(sampler, vUV); vec3 norm = normalize(tex.xyz * 2.0 - 1.0); // compute terrain shape features values float globalDot = dot(lightVec, vNormal); float diffuse = clamp(dot(lightVec, norm), 0.0, 1.0); float ambient = clamp(1.0 - 2.0 * acos(dot(norm, normalize(vNormal))), 0.0, 1.0); float height = tex.a; // compute color based on terrain features vec3 color = computeColor(height, ambient); gl_FragColor.xyz = computeLighting(globalDot, diffuse, ambient, color); gl_FragColor.w = alpha; } """ vert = """ attribute vec3 aPos; attribute vec2 aUV; uniform mat4 projMat; uniform mat4 modelViewMat; varying vec3 vNormal; varying vec2 vUV; void main(void) { vNormal = aPos; vUV = aUV; vec4 pos = vec4(aPos, 1.0); pos = modelViewMat * pos; gl_Position = projMat * pos; } """ xgl.addProgram("planetFarMesh", vert, frag)
[ { "context": "\n###\nTest CSV - Copyright David Worms <open@adaltas.com> (BSD Licensed)\n###\n\nfs = requi", "end": 37, "score": 0.9998608827590942, "start": 26, "tag": "NAME", "value": "David Worms" }, { "context": "\n###\nTest CSV - Copyright David Worms <open@adaltas.com> (BSD Lic...
node_modules/csvtojson/node_modules/csv/test/eof.coffee
thomjoy/sydney-buses
1
### Test CSV - Copyright David Worms <open@adaltas.com> (BSD Licensed) ### fs = require 'fs' should = require 'should' csv = if process.env.CSV_COV then require '../lib-cov' else require '../src' describe 'eof', -> it 'should work with `to.string`', (next) -> string = "a,b,c\n1,2,3" csv() .from.string(string) .to.string (data) -> data.should.eql "a,b,c\n1,2,3\n" next() , eof: true
50857
### Test CSV - Copyright <NAME> <<EMAIL>> (BSD Licensed) ### fs = require 'fs' should = require 'should' csv = if process.env.CSV_COV then require '../lib-cov' else require '../src' describe 'eof', -> it 'should work with `to.string`', (next) -> string = "a,b,c\n1,2,3" csv() .from.string(string) .to.string (data) -> data.should.eql "a,b,c\n1,2,3\n" next() , eof: true
true
### Test CSV - Copyright PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (BSD Licensed) ### fs = require 'fs' should = require 'should' csv = if process.env.CSV_COV then require '../lib-cov' else require '../src' describe 'eof', -> it 'should work with `to.string`', (next) -> string = "a,b,c\n1,2,3" csv() .from.string(string) .to.string (data) -> data.should.eql "a,b,c\n1,2,3\n" next() , eof: true
[ { "context": "EGIN PGP PRIVATE KEY BLOCK-----\nVersion: GnuPG v2\n\nlNYEVcxnrxMJKyQDAwIIAQELAwMEUJgB6OlAqOFOsLsW1kG9NbqVZyPITd5H1dvX\nquD399rUXy16WKTCOBv8Rtk8pJMfLoyPQfN4BbysZTOYYp1Uw3gBQV2KahVxokyx\nTXo5DqramOvTpdXK8aALac3nxUWP/gcDAkMjTh8avKR10UNX9QpHiyZqQROwLYEI\nnhRW18mK5LO/AiH+0mpxK4rMbVAGy4FJAvt6JDaM7/mDbB...
test/files/brainpool384.iced
samkenxstream/kbpgp
464
{KeyManager} = require '../../lib/main' {do_message} = require '../../lib/openpgp/processor' {burn} = require '../../lib/openpgp/burner' km = null top = require '../../lib/main' #================================================================= exports.import_brainpool384_key_with_private_gen_by_gnupg = (T, cb) -> key = """-----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v2 lNYEVcxnrxMJKyQDAwIIAQELAwMEUJgB6OlAqOFOsLsW1kG9NbqVZyPITd5H1dvX quD399rUXy16WKTCOBv8Rtk8pJMfLoyPQfN4BbysZTOYYp1Uw3gBQV2KahVxokyx TXo5DqramOvTpdXK8aALac3nxUWP/gcDAkMjTh8avKR10UNX9QpHiyZqQROwLYEI nhRW18mK5LO/AiH+0mpxK4rMbVAGy4FJAvt6JDaM7/mDbBaAMiY6sV9b38o1Wtnv uqVfwx6jSsbaSKtkVE+5LZuAbN699xrLtCdUZXN0IEJyYWlucG9vbCAzODQgPDM4 NEBicmFpbnBvb2wudGVzdD6ImQQTEwkAIQUCVcxnrwIbAwULCQgHAgYVCAkKCwIE FgIDAQIeAQIXgAAKCRA6fAaeW5nT4aBsAX92gkhndQfkRkYnuC60EziSYgMGBTZy 8SpkXknpqbWO9T+oKVrkyKki57mSItYSeYwBfigPprgIH2KLk2Il+A4+BeqRSl+B AQdzeD0eF/QnfG9+yq4KsMZ0Z9yRh4W0gGoPaJzaBFXMZ68SCSskAwMCCAEBCwMD BBn/EkKMcC9krkjgDlX+5tW2hiZ2WZm67lg4HnupledTswaduRGC/rLTgCpGdXbC 7yzVl4XNQ98r9Ekfxw1S0D02wWTg0IJDGFNPHoPR+NRbmO0KN/6KXkDdlhCBRQtD NwMBCQn+BwMCOzl83dZLYYnR5NmFFm1bsHF+ENgmQhiUXcHv2GRNOirxlRAdevwU 1RFsoYnnmI0qhqAEGiWDjzzgNIBROsa6/s7a+yA2G4xtzDYYKc2chtW+8Onmdu2G 9uGaoQ2HNeyIgQQYEwkACQUCVcxnrwIbDAAKCRA6fAaeW5nT4S/bAXwI8fgkDlME fjm5TWDPqN9n6/zbuhyqaHBXfoPjHgEbPYV4mX4xOALakgbDELhUtkEBf1FbYONg EQ5OkgXBM+G54PL6nWmABbb08ZoZ6TZc1epnVv39+OSKom828SEyGjsdaA== =4K/l -----END PGP PRIVATE KEY BLOCK-----""" await KeyManager.import_from_armored_pgp { raw : key }, defer err, tmp, warnings T.no_error err T.assert tmp?, "a key manager returned" T.assert (warnings.warnings().length is 0), "didn't get any warnings" km = tmp cb() #================================================================= exports.unlock_private_brainpool384 = (T,cb) -> T.assert km.has_pgp_private(), "has a private key" await km.unlock_pgp { passphrase : '384' }, defer err T.no_error err cb() #================================================================= exports.decrypt_brainpool384 = (T,cb) -> msg = """-----BEGIN PGP MESSAGE----- Version: GnuPG v2 hJ4DZABmfiqEGAcSAwMEf4K2BzfsqaF/teXLF4l1vuUP6EMyPx4Cibsmh41DmdDR bpqqf2143HA6tIAK1GcPCNcBe8R44SGBa1mAeEEgmx6voxkLr+gF3f+0Jb4tuUci dEH0y3I05Fo0ZGIRl569MHG/3ClOfGJMYanw5b1gwrAlhq8iWCfo9+eZ6p2vroIh 8iRxXRcoFK3Px8cT+ZZaAdJhAbIg07NzK4N3Me4oL4h1Pi0IjwqhV8Nck9SbXAWy E3jcPzLTn4PgLhSew70QrbhTyr7nR9TlgDfz+aKYqSbqYf4OiGzeuYRpQ1n4shKH Gwhg5h7s7T5VJDrC6GwdRfL7gA== =SZA+ -----END PGP MESSAGE-----""" await do_message { armored : msg, keyfetch : km }, defer err, msg T.no_error err T.equal msg[0].toString(), "hello world (Brainpool 384)\n", "got the right plaintext" cb() #================================================================= exports.roundtrip_brainpool384 = (T,cb) -> plaintext = """ The Aquarium is gone. Everywhere, giant finned cars nose forward like fish; a savage servility slides by on grease. """ await burn { msg : plaintext, encrypt_for : km }, defer err, aout, raw T.no_error err await do_message { armored : aout, keyfetch : km }, defer err, msg T.no_error err T.equal plaintext, msg[0].toString(), "roundtrip worked!" cb() #================================================================= roundtrip_sig_crypt_brainpool384 = (T,km,cb) -> plaintext = """ The Aquarium is gone. Everywhere, giant finned cars nose forward like fish; a savage servility slides by on grease. """ await burn { msg : plaintext, encrypt_for : km, sign_with : km }, defer err, aout, raw T.no_error err await do_message { armored : aout, keyfetch : km }, defer err, msg T.no_error err T.equal plaintext, msg[0].toString(), "roundtrip worked!" T.assert (msg[0].get_data_signer()?), "was signed!" sign_fp = msg[0].get_data_signer().sig.key_manager.get_pgp_fingerprint() start_fp = km.get_pgp_fingerprint() T.equal sign_fp.toString('hex'), start_fp.toString('hex'), "signed by the right person" cb() #====================================================================== exports.roundtrip_sig_crypt_brainpool384 = (T,cb) -> roundtrip_sig_crypt_brainpool384 T, km, cb #=================================================================
29938
{KeyManager} = require '../../lib/main' {do_message} = require '../../lib/openpgp/processor' {burn} = require '../../lib/openpgp/burner' km = null top = require '../../lib/main' #================================================================= exports.import_brainpool384_key_with_private_gen_by_gnupg = (T, cb) -> key = """-----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v2 <KEY> -----END PGP PRIVATE KEY BLOCK-----""" await KeyManager.import_from_armored_pgp { raw : key }, defer err, tmp, warnings T.no_error err T.assert tmp?, "a key manager returned" T.assert (warnings.warnings().length is 0), "didn't get any warnings" km = tmp cb() #================================================================= exports.unlock_private_brainpool384 = (T,cb) -> T.assert km.has_pgp_private(), "has a private key" await km.unlock_pgp { passphrase : '<PASSWORD>' }, defer err T.no_error err cb() #================================================================= exports.decrypt_brainpool384 = (T,cb) -> msg = """-----BEGIN PGP MESSAGE----- Version: GnuPG v2 <KEY> -----END PGP MESSAGE-----""" await do_message { armored : msg, keyfetch : km }, defer err, msg T.no_error err T.equal msg[0].toString(), "hello world (Brainpool 384)\n", "got the right plaintext" cb() #================================================================= exports.roundtrip_brainpool384 = (T,cb) -> plaintext = """ The Aquarium is gone. Everywhere, giant finned cars nose forward like fish; a savage servility slides by on grease. """ await burn { msg : plaintext, encrypt_for : km }, defer err, aout, raw T.no_error err await do_message { armored : aout, keyfetch : km }, defer err, msg T.no_error err T.equal plaintext, msg[0].toString(), "roundtrip worked!" cb() #================================================================= roundtrip_sig_crypt_brainpool384 = (T,km,cb) -> plaintext = """ The Aquarium is gone. Everywhere, giant finned cars nose forward like fish; a savage servility slides by on grease. """ await burn { msg : plaintext, encrypt_for : km, sign_with : km }, defer err, aout, raw T.no_error err await do_message { armored : aout, keyfetch : km }, defer err, msg T.no_error err T.equal plaintext, msg[0].toString(), "roundtrip worked!" T.assert (msg[0].get_data_signer()?), "was signed!" sign_fp = msg[0].get_data_signer().sig.key_manager.get_pgp_fingerprint() start_fp = km.get_pgp_fingerprint() T.equal sign_fp.toString('hex'), start_fp.toString('hex'), "signed by the right person" cb() #====================================================================== exports.roundtrip_sig_crypt_brainpool384 = (T,cb) -> roundtrip_sig_crypt_brainpool384 T, km, cb #=================================================================
true
{KeyManager} = require '../../lib/main' {do_message} = require '../../lib/openpgp/processor' {burn} = require '../../lib/openpgp/burner' km = null top = require '../../lib/main' #================================================================= exports.import_brainpool384_key_with_private_gen_by_gnupg = (T, cb) -> key = """-----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v2 PI:KEY:<KEY>END_PI -----END PGP PRIVATE KEY BLOCK-----""" await KeyManager.import_from_armored_pgp { raw : key }, defer err, tmp, warnings T.no_error err T.assert tmp?, "a key manager returned" T.assert (warnings.warnings().length is 0), "didn't get any warnings" km = tmp cb() #================================================================= exports.unlock_private_brainpool384 = (T,cb) -> T.assert km.has_pgp_private(), "has a private key" await km.unlock_pgp { passphrase : 'PI:PASSWORD:<PASSWORD>END_PI' }, defer err T.no_error err cb() #================================================================= exports.decrypt_brainpool384 = (T,cb) -> msg = """-----BEGIN PGP MESSAGE----- Version: GnuPG v2 PI:KEY:<KEY>END_PI -----END PGP MESSAGE-----""" await do_message { armored : msg, keyfetch : km }, defer err, msg T.no_error err T.equal msg[0].toString(), "hello world (Brainpool 384)\n", "got the right plaintext" cb() #================================================================= exports.roundtrip_brainpool384 = (T,cb) -> plaintext = """ The Aquarium is gone. Everywhere, giant finned cars nose forward like fish; a savage servility slides by on grease. """ await burn { msg : plaintext, encrypt_for : km }, defer err, aout, raw T.no_error err await do_message { armored : aout, keyfetch : km }, defer err, msg T.no_error err T.equal plaintext, msg[0].toString(), "roundtrip worked!" cb() #================================================================= roundtrip_sig_crypt_brainpool384 = (T,km,cb) -> plaintext = """ The Aquarium is gone. Everywhere, giant finned cars nose forward like fish; a savage servility slides by on grease. """ await burn { msg : plaintext, encrypt_for : km, sign_with : km }, defer err, aout, raw T.no_error err await do_message { armored : aout, keyfetch : km }, defer err, msg T.no_error err T.equal plaintext, msg[0].toString(), "roundtrip worked!" T.assert (msg[0].get_data_signer()?), "was signed!" sign_fp = msg[0].get_data_signer().sig.key_manager.get_pgp_fingerprint() start_fp = km.get_pgp_fingerprint() T.equal sign_fp.toString('hex'), start_fp.toString('hex'), "signed by the right person" cb() #====================================================================== exports.roundtrip_sig_crypt_brainpool384 = (T,cb) -> roundtrip_sig_crypt_brainpool384 T, km, cb #=================================================================
[ { "context": "edit-name'\n view.$(click).click()\n value = 'Peter Bishop' if value is null\n view.$(field).text value\n ", "end": 518, "score": 0.9996376037597656, "start": 506, "tag": "NAME", "value": "Peter Bishop" }, { "context": "d not be tracked globally\n view.$(fi...
mixins/views/editable-callbacks.spec.coffee
kpunith8/gringotts
0
import Chaplin from 'chaplin' import ValidateModelMock from '../../lib/mocks/validate-model-mock' import EditableViewMock from '../../lib/mocks/editable-view-mock' describe 'Editable callbacks', -> sandbox = null model = null view = null patch = null enter = null field = null click = null value = null event = null # TODO: this is a duplicate from editable-test setupEditableBefore = -> field ||= '.name-field' click ||= '.edit-name' view.$(click).click() value = 'Peter Bishop' if value is null view.$(field).text value e = if event is null then enter else event view.$(field).trigger e setupEditableAfter = -> # FIXME: since error state is tracked globally it has to be reset after # each test. it should not be tracked globally view.$(field).text('Peter Bishop').trigger enter click = null field = null beforeEach -> sandbox = sinon.createSandbox useFakeServer: yes sandbox.stub document, 'execCommand' model = new ValidateModelMock name: 'Olivia Dunham' email: 'odunham@effbeeeye.com' url: 'http://dunham.com' view = new EditableViewMock {model} view.errorCallback = sinon.spy() view.cleanCallback = sinon.spy() view.setupEditable '.edit-name', '.name-field', { patch saveMessage: 'Model updated' success: view.genericSave delayedSave: true error: (error, opts) -> @errorCallback error, opts clean: (opts) -> @cleanCallback opts } view.setupEditable '.edit-email', '.email-field', saveMessage: 'Model updated' success: view.genericSave delayedSave: true enter = $.Event 'keydown', keyCode: 13 afterEach -> sandbox.restore() view.dispose() model.dispose() describe 'editing a field', -> beforeEach -> sinon.spy view, 'publishEvent' sinon.spy model, 'save' beforeEach setupEditableBefore afterEach setupEditableAfter describe 'then pressing enter', -> it 'calls success and publishes a notification', -> expect(view.publishEvent).to.have.been.calledWith 'notify' describe 'success callback', -> beforeEach -> sandbox.server.respondWith JSON.stringify domain_name: 'Peter Bishop' view.publishEvent.lastCall.args[2].success() it 'saves the model', -> expect(model.save).to.have.been.calledWith 'name', value it 'sets the value on model', -> expect(model.get 'name').to.equal value describe 'with patch', -> before -> patch = yes after -> patch = null it 'uses patch to save', -> opts = model.save.lastCall.args[2] expect(opts).to.have.property 'patch', yes describe 'with a second editable', -> beforeEach -> view.$('.edit-email').click() view.$('.email-field').text 'peter@bishop.com' view.$('.email-field').trigger enter it 'can edit both', -> expect(view.publishEvent).to.have.been.calledTwice expect(view.$ '.name-field').to.contain 'Peter Bishop' expect(view.$ '.email-field').to.contain 'peter@bishop.com' describe 'after success', -> beforeEach -> view.publishEvent.lastCall.args[2].success() it 'has saved both times', -> expect(model.save).to.have.been.calledTwice describe 'after undo', -> beforeEach -> view.publishEvent.lastCall.args[2].undo() it 'reverts the last change', -> email = 'odunham@effbeeeye.com' expect(view.$ '.email-field').to.contain email it 'leaves the first change', -> expect(view.$ '.name-field').to.contain 'Peter Bishop' describe 'undo callback', -> beforeEach -> view.publishEvent.lastCall.args[2].undo() it 'reverts the text', -> expect(view.$(field)).to.contain 'Olivia Dunham' describe 'on a link', -> before -> click = '.edit-email' field = '.email-field' value = 'peter@bishop.org' after -> value = null field = null click = null it 'reverts the href', -> expect(view.$ '.email-field').to.have.attr('href') .and.to.equal 'mailto:odunham@effbeeeye.com' it 'becomes editable again', -> expect(view.$(field)).to.have.attr 'contenteditable' describe 'with an invalid value', -> before -> value = '' after -> value = null it 'calls the error callback', -> expect(view.errorCallback).to.have.been.called describe 'without changing the value', -> before -> value = 'Olivia Dunham' after -> value = null it 'calls the clean callback', -> expect(view.cleanCallback).to.have.been.called
217928
import Chaplin from 'chaplin' import ValidateModelMock from '../../lib/mocks/validate-model-mock' import EditableViewMock from '../../lib/mocks/editable-view-mock' describe 'Editable callbacks', -> sandbox = null model = null view = null patch = null enter = null field = null click = null value = null event = null # TODO: this is a duplicate from editable-test setupEditableBefore = -> field ||= '.name-field' click ||= '.edit-name' view.$(click).click() value = '<NAME>' if value is null view.$(field).text value e = if event is null then enter else event view.$(field).trigger e setupEditableAfter = -> # FIXME: since error state is tracked globally it has to be reset after # each test. it should not be tracked globally view.$(field).text('<NAME>').trigger enter click = null field = null beforeEach -> sandbox = sinon.createSandbox useFakeServer: yes sandbox.stub document, 'execCommand' model = new ValidateModelMock name: '<NAME>' email: '<EMAIL>' url: 'http://dunham.com' view = new EditableViewMock {model} view.errorCallback = sinon.spy() view.cleanCallback = sinon.spy() view.setupEditable '.edit-name', '.name-field', { patch saveMessage: 'Model updated' success: view.genericSave delayedSave: true error: (error, opts) -> @errorCallback error, opts clean: (opts) -> @cleanCallback opts } view.setupEditable '.edit-email', '.email-field', saveMessage: 'Model updated' success: view.genericSave delayedSave: true enter = $.Event 'keydown', keyCode: 13 afterEach -> sandbox.restore() view.dispose() model.dispose() describe 'editing a field', -> beforeEach -> sinon.spy view, 'publishEvent' sinon.spy model, 'save' beforeEach setupEditableBefore afterEach setupEditableAfter describe 'then pressing enter', -> it 'calls success and publishes a notification', -> expect(view.publishEvent).to.have.been.calledWith 'notify' describe 'success callback', -> beforeEach -> sandbox.server.respondWith JSON.stringify domain_name: '<NAME>' view.publishEvent.lastCall.args[2].success() it 'saves the model', -> expect(model.save).to.have.been.calledWith 'name', value it 'sets the value on model', -> expect(model.get 'name').to.equal value describe 'with patch', -> before -> patch = yes after -> patch = null it 'uses patch to save', -> opts = model.save.lastCall.args[2] expect(opts).to.have.property 'patch', yes describe 'with a second editable', -> beforeEach -> view.$('.edit-email').click() view.$('.email-field').text '<EMAIL>' view.$('.email-field').trigger enter it 'can edit both', -> expect(view.publishEvent).to.have.been.calledTwice expect(view.$ '.name-field').to.contain '<NAME>' expect(view.$ '.email-field').to.contain '<EMAIL>' describe 'after success', -> beforeEach -> view.publishEvent.lastCall.args[2].success() it 'has saved both times', -> expect(model.save).to.have.been.calledTwice describe 'after undo', -> beforeEach -> view.publishEvent.lastCall.args[2].undo() it 'reverts the last change', -> email = '<EMAIL>' expect(view.$ '.email-field').to.contain email it 'leaves the first change', -> expect(view.$ '.name-field').to.contain '<NAME>' describe 'undo callback', -> beforeEach -> view.publishEvent.lastCall.args[2].undo() it 'reverts the text', -> expect(view.$(field)).to.contain '<NAME>' describe 'on a link', -> before -> click = '.edit-email' field = '.email-field' value = '<EMAIL>' after -> value = null field = null click = null it 'reverts the href', -> expect(view.$ '.email-field').to.have.attr('href') .and.to.equal 'mailto:<EMAIL>' it 'becomes editable again', -> expect(view.$(field)).to.have.attr 'contenteditable' describe 'with an invalid value', -> before -> value = '' after -> value = null it 'calls the error callback', -> expect(view.errorCallback).to.have.been.called describe 'without changing the value', -> before -> value = '<NAME>' after -> value = null it 'calls the clean callback', -> expect(view.cleanCallback).to.have.been.called
true
import Chaplin from 'chaplin' import ValidateModelMock from '../../lib/mocks/validate-model-mock' import EditableViewMock from '../../lib/mocks/editable-view-mock' describe 'Editable callbacks', -> sandbox = null model = null view = null patch = null enter = null field = null click = null value = null event = null # TODO: this is a duplicate from editable-test setupEditableBefore = -> field ||= '.name-field' click ||= '.edit-name' view.$(click).click() value = 'PI:NAME:<NAME>END_PI' if value is null view.$(field).text value e = if event is null then enter else event view.$(field).trigger e setupEditableAfter = -> # FIXME: since error state is tracked globally it has to be reset after # each test. it should not be tracked globally view.$(field).text('PI:NAME:<NAME>END_PI').trigger enter click = null field = null beforeEach -> sandbox = sinon.createSandbox useFakeServer: yes sandbox.stub document, 'execCommand' model = new ValidateModelMock name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' url: 'http://dunham.com' view = new EditableViewMock {model} view.errorCallback = sinon.spy() view.cleanCallback = sinon.spy() view.setupEditable '.edit-name', '.name-field', { patch saveMessage: 'Model updated' success: view.genericSave delayedSave: true error: (error, opts) -> @errorCallback error, opts clean: (opts) -> @cleanCallback opts } view.setupEditable '.edit-email', '.email-field', saveMessage: 'Model updated' success: view.genericSave delayedSave: true enter = $.Event 'keydown', keyCode: 13 afterEach -> sandbox.restore() view.dispose() model.dispose() describe 'editing a field', -> beforeEach -> sinon.spy view, 'publishEvent' sinon.spy model, 'save' beforeEach setupEditableBefore afterEach setupEditableAfter describe 'then pressing enter', -> it 'calls success and publishes a notification', -> expect(view.publishEvent).to.have.been.calledWith 'notify' describe 'success callback', -> beforeEach -> sandbox.server.respondWith JSON.stringify domain_name: 'PI:NAME:<NAME>END_PI' view.publishEvent.lastCall.args[2].success() it 'saves the model', -> expect(model.save).to.have.been.calledWith 'name', value it 'sets the value on model', -> expect(model.get 'name').to.equal value describe 'with patch', -> before -> patch = yes after -> patch = null it 'uses patch to save', -> opts = model.save.lastCall.args[2] expect(opts).to.have.property 'patch', yes describe 'with a second editable', -> beforeEach -> view.$('.edit-email').click() view.$('.email-field').text 'PI:EMAIL:<EMAIL>END_PI' view.$('.email-field').trigger enter it 'can edit both', -> expect(view.publishEvent).to.have.been.calledTwice expect(view.$ '.name-field').to.contain 'PI:NAME:<NAME>END_PI' expect(view.$ '.email-field').to.contain 'PI:EMAIL:<EMAIL>END_PI' describe 'after success', -> beforeEach -> view.publishEvent.lastCall.args[2].success() it 'has saved both times', -> expect(model.save).to.have.been.calledTwice describe 'after undo', -> beforeEach -> view.publishEvent.lastCall.args[2].undo() it 'reverts the last change', -> email = 'PI:EMAIL:<EMAIL>END_PI' expect(view.$ '.email-field').to.contain email it 'leaves the first change', -> expect(view.$ '.name-field').to.contain 'PI:NAME:<NAME>END_PI' describe 'undo callback', -> beforeEach -> view.publishEvent.lastCall.args[2].undo() it 'reverts the text', -> expect(view.$(field)).to.contain 'PI:NAME:<NAME>END_PI' describe 'on a link', -> before -> click = '.edit-email' field = '.email-field' value = 'PI:EMAIL:<EMAIL>END_PI' after -> value = null field = null click = null it 'reverts the href', -> expect(view.$ '.email-field').to.have.attr('href') .and.to.equal 'mailto:PI:EMAIL:<EMAIL>END_PI' it 'becomes editable again', -> expect(view.$(field)).to.have.attr 'contenteditable' describe 'with an invalid value', -> before -> value = '' after -> value = null it 'calls the error callback', -> expect(view.errorCallback).to.have.been.called describe 'without changing the value', -> before -> value = 'PI:NAME:<NAME>END_PI' after -> value = null it 'calls the clean callback', -> expect(view.cleanCallback).to.have.been.called
[ { "context": " @polyglot.t(\"hi_name_welcome_to_place\", {name: \"Spike\", place: \"the webz\"}).should.equal(\"Hi, Spike, we", "end": 630, "score": 0.9253809452056885, "start": 625, "tag": "NAME", "value": "Spike" }, { "context": " @polyglot.t(\"name_your_name_is_name\", {name: ...
test/main.coffee
zeke/polyglot.js
1
Polyglot = require("../lib/polyglot") should = require('should') describe "t", -> phrases = "hello": "Hello" "hi_name_welcome_to_place": "Hi, %{name}, welcome to %{place}!" "name_your_name_is_name": "%{name}, your name is %{name}!" "empty_string": "" beforeEach -> @polyglot = new Polyglot({phrases:phrases}) it "should translate a simple string", -> @polyglot.t("hello").should.equal("Hello") it "should return the key if translation not found", -> @polyglot.t("bogus_key").should.equal("bogus_key") it "should interpolate", -> @polyglot.t("hi_name_welcome_to_place", {name: "Spike", place: "the webz"}).should.equal("Hi, Spike, welcome to the webz!") it "should interpolate the same placeholder multiple times", -> @polyglot.t("name_your_name_is_name", {name: "Spike"}).should.equal("Spike, your name is Spike!") it "should allow you to supply default values", -> @polyglot.t("can_i_call_you_name", _: "Can I call you %{name}?" name: "Robert" ).should.equal "Can I call you Robert?" it "should return the non-interpolated key if not initialized with allowMissing and translation not found", -> @polyglot.t("Welcome %{name}", name: "Robert" ).should.equal "Welcome %{name}" it "should return an interpolated key if initialized with allowMissing and translation not found", -> @polyglot = new Polyglot({phrases:phrases,allowMissing:true}) @polyglot.t("Welcome %{name}", name: "Robert" ).should.equal "Welcome Robert" it "should return the translation even if it is an empty string", -> @polyglot = new Polyglot({phrases:phrases}) @polyglot.t("empty_string").should.equal("") it "should return the default value even if it is an empty string", -> @polyglot = new Polyglot({phrases:phrases}) @polyglot.t("bogus_key", { _: "" }).should.equal("") it "should handle dollar signs in the substitution value", -> @polyglot = new Polyglot({phrases: phrases}) @polyglot.t("hi_name_welcome_to_place", { name: '$abc $0' place: '$1 $&' }).should.equal("Hi, $abc $0, welcome to $1 $&!") it "should support nested phrase objects", -> nestedPhrases = nav: presentations: "Presentations" hi_user: "Hi, %{user}." cta: join_now: "Join now!" 'header.sign_in': "Sign In" @polyglot = new Polyglot({phrases: nestedPhrases}) @polyglot.t("nav.presentations").should.equal "Presentations" @polyglot.t("nav.hi_user", user: "Raph").should.equal "Hi, Raph." @polyglot.t("nav.cta.join_now").should.equal "Join now!" @polyglot.t("header.sign_in").should.equal "Sign In" describe "pluralize", -> phrases = "count_name": "%{smart_count} Name |||| %{smart_count} Names" beforeEach -> @polyglot = new Polyglot({phrases:phrases, locale:'en'}) it "should support pluralization with an integer", -> @polyglot.t("count_name", smart_count: 0).should.equal("0 Names") @polyglot.t("count_name", smart_count: 1).should.equal("1 Name") @polyglot.t("count_name", smart_count: 2).should.equal("2 Names") @polyglot.t("count_name", smart_count: 3).should.equal("3 Names") it "should accept a number as a shortcut to pluralize a word", -> @polyglot.t("count_name", 0).should.equal "0 Names" @polyglot.t("count_name", 1).should.equal "1 Name" @polyglot.t("count_name", 2).should.equal "2 Names" @polyglot.t("count_name", 3).should.equal "3 Names" describe "locale", -> beforeEach -> @polyglot = new Polyglot() it "should default to 'en'", -> @polyglot.locale().should.equal "en" it "should get and set locale", -> @polyglot.locale("es") @polyglot.locale().should.equal "es" @polyglot.locale("fr") @polyglot.locale().should.equal "fr" describe "extend", -> beforeEach -> @polyglot = new Polyglot() it "should support multiple extends, overriding old keys", -> @polyglot.extend({aKey: 'First time'}) @polyglot.extend({aKey: 'Second time'}) @polyglot.t('aKey').should.equal 'Second time' it "shouldn't forget old keys", -> @polyglot.extend({firstKey: 'Numba one', secondKey: 'Numba two'}) @polyglot.extend({secondKey: 'Numero dos'}) @polyglot.t('firstKey').should.equal 'Numba one' it "should support optional `prefix` argument", -> @polyglot.extend({click: 'Click', hover: 'Hover'}, 'sidebar') @polyglot.phrases['sidebar.click'].should.equal 'Click' @polyglot.phrases['sidebar.hover'].should.equal 'Hover' should.not.exist(@polyglot.phrases['click']) it "should support nested object", -> @polyglot.extend({ sidebar: click: 'Click' hover: 'Hover' nav: header: log_in: 'Log In' }) @polyglot.phrases['sidebar.click'].should.equal 'Click' @polyglot.phrases['sidebar.hover'].should.equal 'Hover' @polyglot.phrases['nav.header.log_in'].should.equal 'Log In' should.not.exist(@polyglot.phrases['click']) should.not.exist(@polyglot.phrases['header.log_in']) should.not.exist(@polyglot.phrases['log_in']) describe "clear", -> beforeEach -> @polyglot = new Polyglot() it "should wipe out old phrases", -> @polyglot.extend {hiFriend: "Hi, Friend."} @polyglot.clear() @polyglot.t("hiFriend").should.equal "hiFriend" describe "replace", -> beforeEach -> @polyglot = new Polyglot() it "should wipe out old phrases and replace with new phrases", -> @polyglot.extend {hiFriend: "Hi, Friend.", byeFriend: "Bye, Friend."} @polyglot.replace {hiFriend: "Hi, Friend."} @polyglot.t("hiFriend").should.equal "Hi, Friend." @polyglot.t("byeFriend").should.equal "byeFriend" describe "unset", -> beforeEach -> @polyglot = new Polyglot() it "should unset a key based on a string", -> @polyglot.extend { test_key: "test_value"} @polyglot.has("test_key").should.equal true @polyglot.unset("test_key") @polyglot.has("test_key").should.equal false it "should unset a key based on an object hash", -> @polyglot.extend { test_key: "test_value", foo: "bar" } @polyglot.has("test_key").should.equal true @polyglot.has("foo").should.equal true @polyglot.unset { test_key: "test_value", foo: "bar" } @polyglot.has("test_key").should.equal false @polyglot.has("foo").should.equal false it "should unset nested objects using recursive prefix call", -> @polyglot.extend { foo: { bar: "foobar" }} @polyglot.has("foo.bar").should.equal true @polyglot.unset { foo: { bar: "foobar" }} @polyglot.has("foo.bar").should.equal false
163937
Polyglot = require("../lib/polyglot") should = require('should') describe "t", -> phrases = "hello": "Hello" "hi_name_welcome_to_place": "Hi, %{name}, welcome to %{place}!" "name_your_name_is_name": "%{name}, your name is %{name}!" "empty_string": "" beforeEach -> @polyglot = new Polyglot({phrases:phrases}) it "should translate a simple string", -> @polyglot.t("hello").should.equal("Hello") it "should return the key if translation not found", -> @polyglot.t("bogus_key").should.equal("bogus_key") it "should interpolate", -> @polyglot.t("hi_name_welcome_to_place", {name: "<NAME>", place: "the webz"}).should.equal("Hi, Spike, welcome to the webz!") it "should interpolate the same placeholder multiple times", -> @polyglot.t("name_your_name_is_name", {name: "<NAME>"}).should.equal("Spike, your name is Spi<NAME>!") it "should allow you to supply default values", -> @polyglot.t("can_i_call_you_name", _: "Can I call you %{name}?" name: "<NAME>" ).should.equal "Can I call you <NAME>?" it "should return the non-interpolated key if not initialized with allowMissing and translation not found", -> @polyglot.t("Welcome %{name}", name: "<NAME>" ).should.equal "Welcome %{name}" it "should return an interpolated key if initialized with allowMissing and translation not found", -> @polyglot = new Polyglot({phrases:phrases,allowMissing:true}) @polyglot.t("Welcome %{name}", name: "<NAME>" ).should.equal "Welcome <NAME>" it "should return the translation even if it is an empty string", -> @polyglot = new Polyglot({phrases:phrases}) @polyglot.t("empty_string").should.equal("") it "should return the default value even if it is an empty string", -> @polyglot = new Polyglot({phrases:phrases}) @polyglot.t("bogus_key", { _: "" }).should.equal("") it "should handle dollar signs in the substitution value", -> @polyglot = new Polyglot({phrases: phrases}) @polyglot.t("hi_name_welcome_to_place", { name: '$abc $0' place: '$1 $&' }).should.equal("Hi, $abc $0, welcome to $1 $&!") it "should support nested phrase objects", -> nestedPhrases = nav: presentations: "Presentations" hi_user: "Hi, %{user}." cta: join_now: "Join now!" 'header.sign_in': "Sign In" @polyglot = new Polyglot({phrases: nestedPhrases}) @polyglot.t("nav.presentations").should.equal "Presentations" @polyglot.t("nav.hi_user", user: "<NAME>").should.equal "Hi, <NAME>." @polyglot.t("nav.cta.join_now").should.equal "Join now!" @polyglot.t("header.sign_in").should.equal "Sign In" describe "pluralize", -> phrases = "count_name": "%{smart_count} Name |||| %{smart_count} Names" beforeEach -> @polyglot = new Polyglot({phrases:phrases, locale:'en'}) it "should support pluralization with an integer", -> @polyglot.t("count_name", smart_count: 0).should.equal("0 Names") @polyglot.t("count_name", smart_count: 1).should.equal("1 Name") @polyglot.t("count_name", smart_count: 2).should.equal("2 Names") @polyglot.t("count_name", smart_count: 3).should.equal("3 Names") it "should accept a number as a shortcut to pluralize a word", -> @polyglot.t("count_name", 0).should.equal "0 Names" @polyglot.t("count_name", 1).should.equal "1 Name" @polyglot.t("count_name", 2).should.equal "2 Names" @polyglot.t("count_name", 3).should.equal "3 Names" describe "locale", -> beforeEach -> @polyglot = new Polyglot() it "should default to 'en'", -> @polyglot.locale().should.equal "en" it "should get and set locale", -> @polyglot.locale("es") @polyglot.locale().should.equal "es" @polyglot.locale("fr") @polyglot.locale().should.equal "fr" describe "extend", -> beforeEach -> @polyglot = new Polyglot() it "should support multiple extends, overriding old keys", -> @polyglot.extend({aKey: 'First time'}) @polyglot.extend({aKey: 'Second time'}) @polyglot.t('aKey').should.equal 'Second time' it "shouldn't forget old keys", -> @polyglot.extend({firstKey: 'Num<KEY>', secondKey: '<KEY>'}) @polyglot.extend({secondKey: 'Numero <KEY>'}) @polyglot.t('firstKey').should.equal 'Numba one' it "should support optional `prefix` argument", -> @polyglot.extend({click: 'Click', hover: 'Hover'}, 'sidebar') @polyglot.phrases['sidebar.click'].should.equal 'Click' @polyglot.phrases['sidebar.hover'].should.equal 'Hover' should.not.exist(@polyglot.phrases['click']) it "should support nested object", -> @polyglot.extend({ sidebar: click: 'Click' hover: 'Hover' nav: header: log_in: 'Log In' }) @polyglot.phrases['sidebar.click'].should.equal 'Click' @polyglot.phrases['sidebar.hover'].should.equal 'Hover' @polyglot.phrases['nav.header.log_in'].should.equal 'Log In' should.not.exist(@polyglot.phrases['click']) should.not.exist(@polyglot.phrases['header.log_in']) should.not.exist(@polyglot.phrases['log_in']) describe "clear", -> beforeEach -> @polyglot = new Polyglot() it "should wipe out old phrases", -> @polyglot.extend {hiFriend: "Hi, Friend."} @polyglot.clear() @polyglot.t("hiFriend").should.equal "hiFriend" describe "replace", -> beforeEach -> @polyglot = new Polyglot() it "should wipe out old phrases and replace with new phrases", -> @polyglot.extend {hiFriend: "Hi, Friend.", byeFriend: "Bye, Friend."} @polyglot.replace {hiFriend: "Hi, Friend."} @polyglot.t("hiFriend").should.equal "Hi, Friend." @polyglot.t("byeFriend").should.equal "byeFriend" describe "unset", -> beforeEach -> @polyglot = new Polyglot() it "should unset a key based on a string", -> @polyglot.extend { test_key: "test_value"} @polyglot.has("test_key").should.equal true @polyglot.unset("test_key") @polyglot.has("test_key").should.equal false it "should unset a key based on an object hash", -> @polyglot.extend { test_key: "test_<KEY>", foo: "bar" } @polyglot.has("test_key").should.equal true @polyglot.has("foo").should.equal true @polyglot.unset { test_key: "<KEY>", foo: "bar" } @polyglot.has("test_key").should.equal false @polyglot.has("foo").should.equal false it "should unset nested objects using recursive prefix call", -> @polyglot.extend { foo: { bar: "foobar" }} @polyglot.has("foo.bar").should.equal true @polyglot.unset { foo: { bar: "foobar" }} @polyglot.has("foo.bar").should.equal false
true
Polyglot = require("../lib/polyglot") should = require('should') describe "t", -> phrases = "hello": "Hello" "hi_name_welcome_to_place": "Hi, %{name}, welcome to %{place}!" "name_your_name_is_name": "%{name}, your name is %{name}!" "empty_string": "" beforeEach -> @polyglot = new Polyglot({phrases:phrases}) it "should translate a simple string", -> @polyglot.t("hello").should.equal("Hello") it "should return the key if translation not found", -> @polyglot.t("bogus_key").should.equal("bogus_key") it "should interpolate", -> @polyglot.t("hi_name_welcome_to_place", {name: "PI:NAME:<NAME>END_PI", place: "the webz"}).should.equal("Hi, Spike, welcome to the webz!") it "should interpolate the same placeholder multiple times", -> @polyglot.t("name_your_name_is_name", {name: "PI:NAME:<NAME>END_PI"}).should.equal("Spike, your name is SpiPI:NAME:<NAME>END_PI!") it "should allow you to supply default values", -> @polyglot.t("can_i_call_you_name", _: "Can I call you %{name}?" name: "PI:NAME:<NAME>END_PI" ).should.equal "Can I call you PI:NAME:<NAME>END_PI?" it "should return the non-interpolated key if not initialized with allowMissing and translation not found", -> @polyglot.t("Welcome %{name}", name: "PI:NAME:<NAME>END_PI" ).should.equal "Welcome %{name}" it "should return an interpolated key if initialized with allowMissing and translation not found", -> @polyglot = new Polyglot({phrases:phrases,allowMissing:true}) @polyglot.t("Welcome %{name}", name: "PI:NAME:<NAME>END_PI" ).should.equal "Welcome PI:NAME:<NAME>END_PI" it "should return the translation even if it is an empty string", -> @polyglot = new Polyglot({phrases:phrases}) @polyglot.t("empty_string").should.equal("") it "should return the default value even if it is an empty string", -> @polyglot = new Polyglot({phrases:phrases}) @polyglot.t("bogus_key", { _: "" }).should.equal("") it "should handle dollar signs in the substitution value", -> @polyglot = new Polyglot({phrases: phrases}) @polyglot.t("hi_name_welcome_to_place", { name: '$abc $0' place: '$1 $&' }).should.equal("Hi, $abc $0, welcome to $1 $&!") it "should support nested phrase objects", -> nestedPhrases = nav: presentations: "Presentations" hi_user: "Hi, %{user}." cta: join_now: "Join now!" 'header.sign_in': "Sign In" @polyglot = new Polyglot({phrases: nestedPhrases}) @polyglot.t("nav.presentations").should.equal "Presentations" @polyglot.t("nav.hi_user", user: "PI:NAME:<NAME>END_PI").should.equal "Hi, PI:NAME:<NAME>END_PI." @polyglot.t("nav.cta.join_now").should.equal "Join now!" @polyglot.t("header.sign_in").should.equal "Sign In" describe "pluralize", -> phrases = "count_name": "%{smart_count} Name |||| %{smart_count} Names" beforeEach -> @polyglot = new Polyglot({phrases:phrases, locale:'en'}) it "should support pluralization with an integer", -> @polyglot.t("count_name", smart_count: 0).should.equal("0 Names") @polyglot.t("count_name", smart_count: 1).should.equal("1 Name") @polyglot.t("count_name", smart_count: 2).should.equal("2 Names") @polyglot.t("count_name", smart_count: 3).should.equal("3 Names") it "should accept a number as a shortcut to pluralize a word", -> @polyglot.t("count_name", 0).should.equal "0 Names" @polyglot.t("count_name", 1).should.equal "1 Name" @polyglot.t("count_name", 2).should.equal "2 Names" @polyglot.t("count_name", 3).should.equal "3 Names" describe "locale", -> beforeEach -> @polyglot = new Polyglot() it "should default to 'en'", -> @polyglot.locale().should.equal "en" it "should get and set locale", -> @polyglot.locale("es") @polyglot.locale().should.equal "es" @polyglot.locale("fr") @polyglot.locale().should.equal "fr" describe "extend", -> beforeEach -> @polyglot = new Polyglot() it "should support multiple extends, overriding old keys", -> @polyglot.extend({aKey: 'First time'}) @polyglot.extend({aKey: 'Second time'}) @polyglot.t('aKey').should.equal 'Second time' it "shouldn't forget old keys", -> @polyglot.extend({firstKey: 'NumPI:KEY:<KEY>END_PI', secondKey: 'PI:KEY:<KEY>END_PI'}) @polyglot.extend({secondKey: 'Numero PI:KEY:<KEY>END_PI'}) @polyglot.t('firstKey').should.equal 'Numba one' it "should support optional `prefix` argument", -> @polyglot.extend({click: 'Click', hover: 'Hover'}, 'sidebar') @polyglot.phrases['sidebar.click'].should.equal 'Click' @polyglot.phrases['sidebar.hover'].should.equal 'Hover' should.not.exist(@polyglot.phrases['click']) it "should support nested object", -> @polyglot.extend({ sidebar: click: 'Click' hover: 'Hover' nav: header: log_in: 'Log In' }) @polyglot.phrases['sidebar.click'].should.equal 'Click' @polyglot.phrases['sidebar.hover'].should.equal 'Hover' @polyglot.phrases['nav.header.log_in'].should.equal 'Log In' should.not.exist(@polyglot.phrases['click']) should.not.exist(@polyglot.phrases['header.log_in']) should.not.exist(@polyglot.phrases['log_in']) describe "clear", -> beforeEach -> @polyglot = new Polyglot() it "should wipe out old phrases", -> @polyglot.extend {hiFriend: "Hi, Friend."} @polyglot.clear() @polyglot.t("hiFriend").should.equal "hiFriend" describe "replace", -> beforeEach -> @polyglot = new Polyglot() it "should wipe out old phrases and replace with new phrases", -> @polyglot.extend {hiFriend: "Hi, Friend.", byeFriend: "Bye, Friend."} @polyglot.replace {hiFriend: "Hi, Friend."} @polyglot.t("hiFriend").should.equal "Hi, Friend." @polyglot.t("byeFriend").should.equal "byeFriend" describe "unset", -> beforeEach -> @polyglot = new Polyglot() it "should unset a key based on a string", -> @polyglot.extend { test_key: "test_value"} @polyglot.has("test_key").should.equal true @polyglot.unset("test_key") @polyglot.has("test_key").should.equal false it "should unset a key based on an object hash", -> @polyglot.extend { test_key: "test_PI:KEY:<KEY>END_PI", foo: "bar" } @polyglot.has("test_key").should.equal true @polyglot.has("foo").should.equal true @polyglot.unset { test_key: "PI:KEY:<KEY>END_PI", foo: "bar" } @polyglot.has("test_key").should.equal false @polyglot.has("foo").should.equal false it "should unset nested objects using recursive prefix call", -> @polyglot.extend { foo: { bar: "foobar" }} @polyglot.has("foo.bar").should.equal true @polyglot.unset { foo: { bar: "foobar" }} @polyglot.has("foo.bar").should.equal false
[ { "context": "ownloader\n username: program.username\n password: program.password\n session: program.session\n extension: program.e", "end": 888, "score": 0.9987758994102478, "start": 872, "tag": "PASSWORD", "value": "program.password" } ]
lib/download.coffee
kaikash/yandex-contest-downloader
1
packageFile = require '../package.json' program = require 'commander' Downloader = require './components/downloader.coffee' program .version packageFile.version, '-v, --version' .option '-e, --extension [extension]', 'Specify file extension', 'py' .option '-u, --username [username]', 'Specify yandex contest username' .option '-p, --password [password]', 'Specify yandex contest password' .option '-s, --session [session]', 'Specify yandex contest session' .option '-i, --id [n]', 'Specify yandex contest number' .option '-R, --no-readme', 'Do not create readme files' .option '-d, --domain [domain]', 'Yandex contest domain', 'official.contest.yandex.ru' .option '-o, --outputDir [dirname]', 'Output dirname' .option '-T, --no-tests', 'Do not create tests' .parse process.argv downloader = new Downloader username: program.username password: program.password session: program.session extension: program.extension contestId: program.id readme: program.readme tests: program.tests domain: program.domain outputDir: program.outputDir do downloader.run
159257
packageFile = require '../package.json' program = require 'commander' Downloader = require './components/downloader.coffee' program .version packageFile.version, '-v, --version' .option '-e, --extension [extension]', 'Specify file extension', 'py' .option '-u, --username [username]', 'Specify yandex contest username' .option '-p, --password [password]', 'Specify yandex contest password' .option '-s, --session [session]', 'Specify yandex contest session' .option '-i, --id [n]', 'Specify yandex contest number' .option '-R, --no-readme', 'Do not create readme files' .option '-d, --domain [domain]', 'Yandex contest domain', 'official.contest.yandex.ru' .option '-o, --outputDir [dirname]', 'Output dirname' .option '-T, --no-tests', 'Do not create tests' .parse process.argv downloader = new Downloader username: program.username password: <PASSWORD> session: program.session extension: program.extension contestId: program.id readme: program.readme tests: program.tests domain: program.domain outputDir: program.outputDir do downloader.run
true
packageFile = require '../package.json' program = require 'commander' Downloader = require './components/downloader.coffee' program .version packageFile.version, '-v, --version' .option '-e, --extension [extension]', 'Specify file extension', 'py' .option '-u, --username [username]', 'Specify yandex contest username' .option '-p, --password [password]', 'Specify yandex contest password' .option '-s, --session [session]', 'Specify yandex contest session' .option '-i, --id [n]', 'Specify yandex contest number' .option '-R, --no-readme', 'Do not create readme files' .option '-d, --domain [domain]', 'Yandex contest domain', 'official.contest.yandex.ru' .option '-o, --outputDir [dirname]', 'Output dirname' .option '-T, --no-tests', 'Do not create tests' .parse process.argv downloader = new Downloader username: program.username password: PI:PASSWORD:<PASSWORD>END_PI session: program.session extension: program.extension contestId: program.id readme: program.readme tests: program.tests domain: program.domain outputDir: program.outputDir do downloader.run
[ { "context": "y = config.oauth.tokenQueryParam\n tokenKey ?= 'access_token'\n\n qs:\n \"#{tokenKey}\": config.oauth", "end": 426, "score": 0.7447997331619263, "start": 420, "tag": "KEY", "value": "access" } ]
src/models/request-formatter.coffee
octoblu/channel-proxy-service
0
_ = require 'lodash' url = require 'url' class RequestFormatter BasicAuthStrategy: (config) => auth: username: config.oauth.access_token password: config.oauth.access_token_secret NoAuthStrategy: => {} AccessTokenBearerStrategy: (config) => auth: bearer: config.oauth.access_token AccessTokenQueryStrategy: (config) => tokenKey = config.oauth.tokenQueryParam tokenKey ?= 'access_token' qs: "#{tokenKey}": config.oauth.access_token AccessTokenBearerAndApiKeyStrategy: (config) => auth: bearer: config.oauth.access_token qs: api_key: config.oauth.api_key ApiKeyStrategy: (config) => tokenKey = config.authHeaderKey headers: "#{tokenKey}": config.apikey AuthTokenStrategy: (config) => tokenKey = config.oauth.tokenQueryParam tokenKey ?= 'token' headers: "Authorization": "#{tokenKey} #{config.oauth.access_token}" HeaderApiKeyAuthStrategy: (config) => tokenKey = config.oauth.headerParam tokenKey ?= 'Access-Token' headers: "#{tokenKey}": config.oauth.access_token SignedOAuthStrategy: (config) => oauth: consumer_key: config.oauth.key consumer_secret: config.oauth.secret token: config.oauth.access_token token_secret: config.oauth.access_token_secret getStrategy: (tokenMethod) => strategies = 'access_token_bearer': @AccessTokenBearerStrategy 'access_token_query': @AccessTokenQueryStrategy 'access_token_bearer_and_api_key': @AccessTokenBearerAndApiKeyStrategy 'basic': @BasicAuthStrategy 'apikey-basic': @BasicAuthStrategy 'apikey-dummypass-basic': @BasicAuthStrategy 'meshblu': @BasicAuthStrategy 'oauth_signed': @SignedOAuthStrategy 'echosign': @HeaderApiKeyAuthStrategy 'header': @HeaderApiKeyAuthStrategy 'auth_token': @AuthTokenStrategy 'apikey': @ApiKeyStrategy strategies[tokenMethod] ? @NoAuthStrategy buildRequestParameters: (config) => config = _.cloneDeep config _.defaults config, defaultParams: {} dynamicParams: {} hiddenBodyParams = _.filter config.hiddenParams, style: 'body' hiddenQueryParams = _.filter config.hiddenParams, style: 'query' urlParams = _.extend {}, config.defaultParams, config.urlParams headerParams = _.cloneDeep config.headerParams bodyParams = {} uri = @_replaceParams config.url, urlParams if config.method != 'GET' _.each config.bodyParams, (value, key) => _.set bodyParams, key, value _.each hiddenBodyParams, (param) -> _.set bodyParams, param.name, param.value if config.bodyParam? and bodyParams[config.bodyParam]? bodyParams = bodyParams[config.bodyParam] requestParams = @_generateRequestParams uri, config, bodyParams requestParams.qs ?= {} _.each hiddenQueryParams, (param) -> _.set requestParams.qs, param.name, param.value requestParams.headers = _.extend {}, requestParams.headers, headerParams strategyMethod = @getStrategy config.oauth?.tokenMethod strategyParams = strategyMethod config, _.cloneDeep(requestParams) return _.defaultsDeep {}, strategyParams, requestParams format: (config) => @buildRequestParameters config _generateRequestParams: (uri, config, bodyParams, body) => # clean up querystring and place it in the queryParams parsedUri = url.parse(uri, true) parsedUri.search = '' parsedUri.query = '' uri = url.format(parsedUri) queryParams = _.extend {}, parsedUri.query _.each config.queryParams, (value, key) => _.set queryParams, key, value requestParams = headers: 'Accept': 'application/json' 'User-Agent': 'Octoblu/1.0.0' 'x-li-format': 'json' uri: uri method: config.method followAllRedirects: config.followAllRedirects ? true qs: queryParams requestParams.strictSSL = false if config.skipVerifySSL if config.uploadData buf = new Buffer config.uploadData, 'base64' requestParams.body = buf requestParams.encoding = null requestParams.headers['Content-Type'] = 'text/plain' delete requestParams.headers['Accept'] else if config.bodyFormat == 'json' requestParams.json = @_omitEmptyObjects bodyParams else requestParams.form = bodyParams requestParams _replaceParams: (path, params) => _.each params, (value, key) => re = new RegExp(key, 'g') path = path.replace(re, value) return path _omitEmptyObjects: (object) => _.omit object, (value) => _.isObject(value) && _.isEmpty(value) module.exports = RequestFormatter
14245
_ = require 'lodash' url = require 'url' class RequestFormatter BasicAuthStrategy: (config) => auth: username: config.oauth.access_token password: config.oauth.access_token_secret NoAuthStrategy: => {} AccessTokenBearerStrategy: (config) => auth: bearer: config.oauth.access_token AccessTokenQueryStrategy: (config) => tokenKey = config.oauth.tokenQueryParam tokenKey ?= '<KEY>_token' qs: "#{tokenKey}": config.oauth.access_token AccessTokenBearerAndApiKeyStrategy: (config) => auth: bearer: config.oauth.access_token qs: api_key: config.oauth.api_key ApiKeyStrategy: (config) => tokenKey = config.authHeaderKey headers: "#{tokenKey}": config.apikey AuthTokenStrategy: (config) => tokenKey = config.oauth.tokenQueryParam tokenKey ?= 'token' headers: "Authorization": "#{tokenKey} #{config.oauth.access_token}" HeaderApiKeyAuthStrategy: (config) => tokenKey = config.oauth.headerParam tokenKey ?= 'Access-Token' headers: "#{tokenKey}": config.oauth.access_token SignedOAuthStrategy: (config) => oauth: consumer_key: config.oauth.key consumer_secret: config.oauth.secret token: config.oauth.access_token token_secret: config.oauth.access_token_secret getStrategy: (tokenMethod) => strategies = 'access_token_bearer': @AccessTokenBearerStrategy 'access_token_query': @AccessTokenQueryStrategy 'access_token_bearer_and_api_key': @AccessTokenBearerAndApiKeyStrategy 'basic': @BasicAuthStrategy 'apikey-basic': @BasicAuthStrategy 'apikey-dummypass-basic': @BasicAuthStrategy 'meshblu': @BasicAuthStrategy 'oauth_signed': @SignedOAuthStrategy 'echosign': @HeaderApiKeyAuthStrategy 'header': @HeaderApiKeyAuthStrategy 'auth_token': @AuthTokenStrategy 'apikey': @ApiKeyStrategy strategies[tokenMethod] ? @NoAuthStrategy buildRequestParameters: (config) => config = _.cloneDeep config _.defaults config, defaultParams: {} dynamicParams: {} hiddenBodyParams = _.filter config.hiddenParams, style: 'body' hiddenQueryParams = _.filter config.hiddenParams, style: 'query' urlParams = _.extend {}, config.defaultParams, config.urlParams headerParams = _.cloneDeep config.headerParams bodyParams = {} uri = @_replaceParams config.url, urlParams if config.method != 'GET' _.each config.bodyParams, (value, key) => _.set bodyParams, key, value _.each hiddenBodyParams, (param) -> _.set bodyParams, param.name, param.value if config.bodyParam? and bodyParams[config.bodyParam]? bodyParams = bodyParams[config.bodyParam] requestParams = @_generateRequestParams uri, config, bodyParams requestParams.qs ?= {} _.each hiddenQueryParams, (param) -> _.set requestParams.qs, param.name, param.value requestParams.headers = _.extend {}, requestParams.headers, headerParams strategyMethod = @getStrategy config.oauth?.tokenMethod strategyParams = strategyMethod config, _.cloneDeep(requestParams) return _.defaultsDeep {}, strategyParams, requestParams format: (config) => @buildRequestParameters config _generateRequestParams: (uri, config, bodyParams, body) => # clean up querystring and place it in the queryParams parsedUri = url.parse(uri, true) parsedUri.search = '' parsedUri.query = '' uri = url.format(parsedUri) queryParams = _.extend {}, parsedUri.query _.each config.queryParams, (value, key) => _.set queryParams, key, value requestParams = headers: 'Accept': 'application/json' 'User-Agent': 'Octoblu/1.0.0' 'x-li-format': 'json' uri: uri method: config.method followAllRedirects: config.followAllRedirects ? true qs: queryParams requestParams.strictSSL = false if config.skipVerifySSL if config.uploadData buf = new Buffer config.uploadData, 'base64' requestParams.body = buf requestParams.encoding = null requestParams.headers['Content-Type'] = 'text/plain' delete requestParams.headers['Accept'] else if config.bodyFormat == 'json' requestParams.json = @_omitEmptyObjects bodyParams else requestParams.form = bodyParams requestParams _replaceParams: (path, params) => _.each params, (value, key) => re = new RegExp(key, 'g') path = path.replace(re, value) return path _omitEmptyObjects: (object) => _.omit object, (value) => _.isObject(value) && _.isEmpty(value) module.exports = RequestFormatter
true
_ = require 'lodash' url = require 'url' class RequestFormatter BasicAuthStrategy: (config) => auth: username: config.oauth.access_token password: config.oauth.access_token_secret NoAuthStrategy: => {} AccessTokenBearerStrategy: (config) => auth: bearer: config.oauth.access_token AccessTokenQueryStrategy: (config) => tokenKey = config.oauth.tokenQueryParam tokenKey ?= 'PI:KEY:<KEY>END_PI_token' qs: "#{tokenKey}": config.oauth.access_token AccessTokenBearerAndApiKeyStrategy: (config) => auth: bearer: config.oauth.access_token qs: api_key: config.oauth.api_key ApiKeyStrategy: (config) => tokenKey = config.authHeaderKey headers: "#{tokenKey}": config.apikey AuthTokenStrategy: (config) => tokenKey = config.oauth.tokenQueryParam tokenKey ?= 'token' headers: "Authorization": "#{tokenKey} #{config.oauth.access_token}" HeaderApiKeyAuthStrategy: (config) => tokenKey = config.oauth.headerParam tokenKey ?= 'Access-Token' headers: "#{tokenKey}": config.oauth.access_token SignedOAuthStrategy: (config) => oauth: consumer_key: config.oauth.key consumer_secret: config.oauth.secret token: config.oauth.access_token token_secret: config.oauth.access_token_secret getStrategy: (tokenMethod) => strategies = 'access_token_bearer': @AccessTokenBearerStrategy 'access_token_query': @AccessTokenQueryStrategy 'access_token_bearer_and_api_key': @AccessTokenBearerAndApiKeyStrategy 'basic': @BasicAuthStrategy 'apikey-basic': @BasicAuthStrategy 'apikey-dummypass-basic': @BasicAuthStrategy 'meshblu': @BasicAuthStrategy 'oauth_signed': @SignedOAuthStrategy 'echosign': @HeaderApiKeyAuthStrategy 'header': @HeaderApiKeyAuthStrategy 'auth_token': @AuthTokenStrategy 'apikey': @ApiKeyStrategy strategies[tokenMethod] ? @NoAuthStrategy buildRequestParameters: (config) => config = _.cloneDeep config _.defaults config, defaultParams: {} dynamicParams: {} hiddenBodyParams = _.filter config.hiddenParams, style: 'body' hiddenQueryParams = _.filter config.hiddenParams, style: 'query' urlParams = _.extend {}, config.defaultParams, config.urlParams headerParams = _.cloneDeep config.headerParams bodyParams = {} uri = @_replaceParams config.url, urlParams if config.method != 'GET' _.each config.bodyParams, (value, key) => _.set bodyParams, key, value _.each hiddenBodyParams, (param) -> _.set bodyParams, param.name, param.value if config.bodyParam? and bodyParams[config.bodyParam]? bodyParams = bodyParams[config.bodyParam] requestParams = @_generateRequestParams uri, config, bodyParams requestParams.qs ?= {} _.each hiddenQueryParams, (param) -> _.set requestParams.qs, param.name, param.value requestParams.headers = _.extend {}, requestParams.headers, headerParams strategyMethod = @getStrategy config.oauth?.tokenMethod strategyParams = strategyMethod config, _.cloneDeep(requestParams) return _.defaultsDeep {}, strategyParams, requestParams format: (config) => @buildRequestParameters config _generateRequestParams: (uri, config, bodyParams, body) => # clean up querystring and place it in the queryParams parsedUri = url.parse(uri, true) parsedUri.search = '' parsedUri.query = '' uri = url.format(parsedUri) queryParams = _.extend {}, parsedUri.query _.each config.queryParams, (value, key) => _.set queryParams, key, value requestParams = headers: 'Accept': 'application/json' 'User-Agent': 'Octoblu/1.0.0' 'x-li-format': 'json' uri: uri method: config.method followAllRedirects: config.followAllRedirects ? true qs: queryParams requestParams.strictSSL = false if config.skipVerifySSL if config.uploadData buf = new Buffer config.uploadData, 'base64' requestParams.body = buf requestParams.encoding = null requestParams.headers['Content-Type'] = 'text/plain' delete requestParams.headers['Accept'] else if config.bodyFormat == 'json' requestParams.json = @_omitEmptyObjects bodyParams else requestParams.form = bodyParams requestParams _replaceParams: (path, params) => _.each params, (value, key) => re = new RegExp(key, 'g') path = path.replace(re, value) return path _omitEmptyObjects: (object) => _.omit object, (value) => _.isObject(value) && _.isEmpty(value) module.exports = RequestFormatter
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9991069436073303, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-fs-realpath.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. # something like "C:\\" # On Windows, creating symlinks requires admin privileges. # We'll only try to run symlink test if we have enough privileges. # better safe than sorry tmp = (p) -> path.join common.tmpDir, p asynctest = (testBlock, args, callback, assertBlock) -> async_expected++ testBlock.apply testBlock, args.concat((err) -> ignoreError = false if assertBlock try ignoreError = assertBlock.apply(assertBlock, arguments) catch e err = e async_completed++ callback (if ignoreError then null else err) return ) return # sub-tests: test_simple_error_callback = (cb) -> ncalls = 0 fs.realpath "/this/path/does/not/exist", (err, s) -> assert err assert not s ncalls++ cb() return process.on "exit", -> assert.equal ncalls, 1 return return test_simple_relative_symlink = (callback) -> console.log "test_simple_relative_symlink" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() entry = common.tmpDir + "/symlink" expected = common.tmpDir + "/cycles/root.js" [[ entry "../tmp/cycles/root.js" ]].forEach (t) -> try fs.unlinkSync t[0] console.log "fs.symlinkSync(%j, %j, %j)", t[1], t[0], "file" fs.symlinkSync t[1], t[0], "file" unlink.push t[0] return result = fs.realpathSync(entry) assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) return return test_simple_absolute_symlink = (callback) -> console.log "test_simple_absolute_symlink" # this one should still run, even if skipSymlinks is set, # because it uses a junction. type = (if skipSymlinks then "junction" else "dir") console.log "using type=%s", type entry = tmpAbsDir + "/symlink" expected = fixturesAbsDir + "/nested-index/one" [[ entry expected ]].forEach (t) -> try fs.unlinkSync t[0] console.error "fs.symlinkSync(%j, %j, %j)", t[1], t[0], type fs.symlinkSync t[1], t[0], type unlink.push t[0] return result = fs.realpathSync(entry) assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) return return test_deep_relative_file_symlink = (callback) -> console.log "test_deep_relative_file_symlink" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() expected = path.join(common.fixturesDir, "cycles", "root.js") linkData1 = "../../cycles/root.js" linkPath1 = path.join(common.fixturesDir, "nested-index", "one", "symlink1.js") try fs.unlinkSync linkPath1 fs.symlinkSync linkData1, linkPath1, "file" linkData2 = "../one/symlink1.js" entry = path.join(common.fixturesDir, "nested-index", "two", "symlink1-b.js") try fs.unlinkSync entry fs.symlinkSync linkData2, entry, "file" unlink.push linkPath1 unlink.push entry assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) return return test_deep_relative_dir_symlink = (callback) -> console.log "test_deep_relative_dir_symlink" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() expected = path.join(common.fixturesDir, "cycles", "folder") linkData1b = "../../cycles/folder" linkPath1b = path.join(common.fixturesDir, "nested-index", "one", "symlink1-dir") try fs.unlinkSync linkPath1b fs.symlinkSync linkData1b, linkPath1b, "dir" linkData2b = "../one/symlink1-dir" entry = path.join(common.fixturesDir, "nested-index", "two", "symlink12-dir") try fs.unlinkSync entry fs.symlinkSync linkData2b, entry, "dir" unlink.push linkPath1b unlink.push entry assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) return return test_cyclic_link_protection = (callback) -> console.log "test_cyclic_link_protection" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() entry = common.tmpDir + "/cycles/realpath-3a" [ [ entry "../cycles/realpath-3b" ] [ common.tmpDir + "/cycles/realpath-3b" "../cycles/realpath-3c" ] [ common.tmpDir + "/cycles/realpath-3c" "../cycles/realpath-3a" ] ].forEach (t) -> try fs.unlinkSync t[0] fs.symlinkSync t[1], t[0], "dir" unlink.push t[0] return assert.throws -> fs.realpathSync entry return asynctest fs.realpath, [entry], callback, (err, result) -> assert.ok err and true true return test_cyclic_link_overprotection = (callback) -> console.log "test_cyclic_link_overprotection" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() cycles = common.tmpDir + "/cycles" expected = fs.realpathSync(cycles) folder = cycles + "/folder" link = folder + "/cycles" testPath = cycles i = 0 while i < 10 testPath += "/folder/cycles" i++ try fs.unlinkSync link fs.symlinkSync cycles, link, "dir" unlink.push link assert.equal fs.realpathSync(testPath), path.resolve(expected) asynctest fs.realpath, [testPath], callback, (er, res) -> assert.equal res, path.resolve(expected) return return test_relative_input_cwd = (callback) -> console.log "test_relative_input_cwd" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() # we need to get the relative path to the tmp dir from cwd. # When the test runner is running it, that will be .../node/test # but it's more common to run `./node test/.../`, so detect it here. entrydir = process.cwd() entry = common.tmpDir.substr(entrydir.length + 1) + "/cycles/realpath-3a" expected = common.tmpDir + "/cycles/root.js" [ [ entry "../cycles/realpath-3b" ] [ common.tmpDir + "/cycles/realpath-3b" "../cycles/realpath-3c" ] [ common.tmpDir + "/cycles/realpath-3c" "root.js" ] ].forEach (t) -> fn = t[0] console.error "fn=%j", fn try fs.unlinkSync fn b = path.basename(t[1]) type = ((if b is "root.js" then "file" else "dir")) console.log "fs.symlinkSync(%j, %j, %j)", t[1], fn, type fs.symlinkSync t[1], fn, "file" unlink.push fn return origcwd = process.cwd() process.chdir entrydir assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> process.chdir origcwd assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) true return test_deep_symlink_mix = (callback) -> console.log "test_deep_symlink_mix" if isWindows # This one is a mix of files and directories, and it's quite tricky # to get the file/dir links sorted out correctly. console.log "skipping symlink test (no way to work on windows)" return runNextTest() # todo: check to see that common.fixturesDir is not rooted in the # same directory as our test symlink. # # /tmp/node-test-realpath-f1 -> ../tmp/node-test-realpath-d1/foo # /tmp/node-test-realpath-d1 -> ../node-test-realpath-d2 # /tmp/node-test-realpath-d2/foo -> ../node-test-realpath-f2 # /tmp/node-test-realpath-f2 # -> /node/test/fixtures/nested-index/one/realpath-c # /node/test/fixtures/nested-index/one/realpath-c # -> /node/test/fixtures/nested-index/two/realpath-c # /node/test/fixtures/nested-index/two/realpath-c -> ../../cycles/root.js # /node/test/fixtures/cycles/root.js (hard) # entry = tmp("node-test-realpath-f1") try fs.unlinkSync tmp("node-test-realpath-d2/foo") try fs.rmdirSync tmp("node-test-realpath-d2") fs.mkdirSync tmp("node-test-realpath-d2"), 0700 try [ [ entry "../tmp/node-test-realpath-d1/foo" ] [ tmp("node-test-realpath-d1") "../tmp/node-test-realpath-d2" ] [ tmp("node-test-realpath-d2/foo") "../node-test-realpath-f2" ] [ tmp("node-test-realpath-f2") fixturesAbsDir + "/nested-index/one/realpath-c" ] [ fixturesAbsDir + "/nested-index/one/realpath-c" fixturesAbsDir + "/nested-index/two/realpath-c" ] [ fixturesAbsDir + "/nested-index/two/realpath-c" "../../../tmp/cycles/root.js" ] ].forEach (t) -> #common.debug('setting up '+t[0]+' -> '+t[1]); try fs.unlinkSync t[0] fs.symlinkSync t[1], t[0] unlink.push t[0] return finally unlink.push tmp("node-test-realpath-d2") expected = tmpAbsDir + "/cycles/root.js" assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) true return test_non_symlinks = (callback) -> console.log "test_non_symlinks" entrydir = path.dirname(tmpAbsDir) entry = tmpAbsDir.substr(entrydir.length + 1) + "/cycles/root.js" expected = tmpAbsDir + "/cycles/root.js" origcwd = process.cwd() process.chdir entrydir assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> process.chdir origcwd assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) true return test_escape_cwd = (cb) -> console.log "test_escape_cwd" asynctest fs.realpath, [".."], cb, (er, uponeActual) -> assert.equal upone, uponeActual, "realpath(\"..\") expected: " + path.resolve(upone) + " actual:" + uponeActual return return # going up with .. multiple times # . # `-- a/ # |-- b/ # | `-- e -> .. # `-- d -> .. # realpath(a/b/e/d/a/b/e/d/a) ==> a test_up_multiple = (cb) -> cleanup = -> [ "a/b" "a" ].forEach (folder) -> try fs.rmdirSync tmp(folder) return return setup = -> cleanup() return console.error "test_up_multiple" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() setup() fs.mkdirSync tmp("a"), 0755 fs.mkdirSync tmp("a/b"), 0755 fs.symlinkSync "..", tmp("a/d"), "dir" unlink.push tmp("a/d") fs.symlinkSync "..", tmp("a/b/e"), "dir" unlink.push tmp("a/b/e") abedabed = tmp("abedabed".split("").join("/")) abedabed_real = tmp("") abedabeda = tmp("abedabeda".split("").join("/")) abedabeda_real = tmp("a") assert.equal fs.realpathSync(abedabeda), abedabeda_real assert.equal fs.realpathSync(abedabed), abedabed_real fs.realpath abedabeda, (er, real) -> throw er if er assert.equal abedabeda_real, real fs.realpath abedabed, (er, real) -> throw er if er assert.equal abedabed_real, real cb() cleanup() return return return # absolute symlinks with children. # . # `-- a/ # |-- b/ # | `-- c/ # | `-- x.txt # `-- link -> /tmp/node-test-realpath-abs-kids/a/b/ # realpath(root+'/a/link/c/x.txt') ==> root+'/a/b/c/x.txt' test_abs_with_kids = (cb) -> # this one should still run, even if skipSymlinks is set, # because it uses a junction. cleanup = -> [ "/a/b/c/x.txt" "/a/link" ].forEach (file) -> try fs.unlinkSync root + file return [ "/a/b/c" "/a/b" "/a" "" ].forEach (folder) -> try fs.rmdirSync root + folder return return setup = -> cleanup() [ "" "/a" "/a/b" "/a/b/c" ].forEach (folder) -> console.log "mkdir " + root + folder fs.mkdirSync root + folder, 0700 return fs.writeFileSync root + "/a/b/c/x.txt", "foo" fs.symlinkSync root + "/a/b", root + "/a/link", type return console.log "test_abs_with_kids" type = (if skipSymlinks then "junction" else "dir") console.log "using type=%s", type root = tmpAbsDir + "/node-test-realpath-abs-kids" setup() linkPath = root + "/a/link/c/x.txt" expectPath = root + "/a/b/c/x.txt" actual = fs.realpathSync(linkPath) # console.log({link:linkPath,expect:expectPath,actual:actual},'sync'); assert.equal actual, path.resolve(expectPath) asynctest fs.realpath, [linkPath], cb, (er, actual) -> # console.log({link:linkPath,expect:expectPath,actual:actual},'async'); assert.equal actual, path.resolve(expectPath) cleanup() return return test_lying_cache_liar = (cb) -> n = 2 # this should not require *any* stat calls, since everything # checked by realpath will be found in the cache. console.log "test_lying_cache_liar" cache = "/foo/bar/baz/bluff": "/foo/bar/bluff" "/1/2/3/4/5/6/7": "/1" "/a": "/a" "/a/b": "/a/b" "/a/b/c": "/a/b" "/a/b/d": "/a/b/d" if isWindows wc = {} Object.keys(cache).forEach (k) -> wc[path.resolve(k)] = path.resolve(cache[k]) return cache = wc bluff = path.resolve("/foo/bar/baz/bluff") rps = fs.realpathSync(bluff, cache) assert.equal cache[bluff], rps nums = path.resolve("/1/2/3/4/5/6/7") called = false # no sync cb calling! fs.realpath nums, cache, (er, rp) -> called = true assert.equal cache[nums], rp cb() if --n is 0 return assert called is false test = path.resolve("/a/b/c/d") expect = path.resolve("/a/b/d") actual = fs.realpathSync(test, cache) assert.equal expect, actual fs.realpath test, cache, (er, actual) -> assert.equal expect, actual cb() if --n is 0 return return # ---------------------------------------------------------------------------- runNextTest = (err) -> throw err if err test = tests.shift() return console.log(numtests + " subtests completed OK for fs.realpath") unless test testsRun++ test runNextTest return runTest = -> tmpDirs = [ "cycles" "cycles/folder" ] tmpDirs.forEach (t) -> t = tmp(t) s = undefined try s = fs.statSync(t) return if s fs.mkdirSync t, 0700 return fs.writeFileSync tmp("cycles/root.js"), "console.error('roooot!');" console.error "start tests" runNextTest() return common = require("../common") assert = require("assert") fs = require("fs") path = require("path") exec = require("child_process").exec async_completed = 0 async_expected = 0 unlink = [] isWindows = process.platform is "win32" skipSymlinks = false root = "/" if isWindows root = process.cwd().substr(0, 3) try exec "whoami /priv", (err, o) -> skipSymlinks = true if err or o.indexOf("SeCreateSymbolicLinkPrivilege") is -1 runTest() return catch er skipSymlinks = true process.nextTick runTest else process.nextTick runTest fixturesAbsDir = common.fixturesDir tmpAbsDir = common.tmpDir console.error "absolutes\n%s\n%s", fixturesAbsDir, tmpAbsDir upone = path.join(process.cwd(), "..") uponeActual = fs.realpathSync("..") assert.equal upone, uponeActual, "realpathSync(\"..\") expected: " + path.resolve(upone) + " actual:" + uponeActual tests = [ test_simple_error_callback test_simple_relative_symlink test_simple_absolute_symlink test_deep_relative_file_symlink test_deep_relative_dir_symlink test_cyclic_link_protection test_cyclic_link_overprotection test_relative_input_cwd test_deep_symlink_mix test_non_symlinks test_escape_cwd test_abs_with_kids test_lying_cache_liar test_up_multiple ] numtests = tests.length testsRun = 0 assert.equal root, fs.realpathSync("/") fs.realpath "/", (err, result) -> assert.equal null, err assert.equal root, result return process.on "exit", -> assert.equal numtests, testsRun unlink.forEach (path) -> try fs.unlinkSync path return assert.equal async_completed, async_expected return
97626
# 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. # something like "C:\\" # On Windows, creating symlinks requires admin privileges. # We'll only try to run symlink test if we have enough privileges. # better safe than sorry tmp = (p) -> path.join common.tmpDir, p asynctest = (testBlock, args, callback, assertBlock) -> async_expected++ testBlock.apply testBlock, args.concat((err) -> ignoreError = false if assertBlock try ignoreError = assertBlock.apply(assertBlock, arguments) catch e err = e async_completed++ callback (if ignoreError then null else err) return ) return # sub-tests: test_simple_error_callback = (cb) -> ncalls = 0 fs.realpath "/this/path/does/not/exist", (err, s) -> assert err assert not s ncalls++ cb() return process.on "exit", -> assert.equal ncalls, 1 return return test_simple_relative_symlink = (callback) -> console.log "test_simple_relative_symlink" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() entry = common.tmpDir + "/symlink" expected = common.tmpDir + "/cycles/root.js" [[ entry "../tmp/cycles/root.js" ]].forEach (t) -> try fs.unlinkSync t[0] console.log "fs.symlinkSync(%j, %j, %j)", t[1], t[0], "file" fs.symlinkSync t[1], t[0], "file" unlink.push t[0] return result = fs.realpathSync(entry) assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) return return test_simple_absolute_symlink = (callback) -> console.log "test_simple_absolute_symlink" # this one should still run, even if skipSymlinks is set, # because it uses a junction. type = (if skipSymlinks then "junction" else "dir") console.log "using type=%s", type entry = tmpAbsDir + "/symlink" expected = fixturesAbsDir + "/nested-index/one" [[ entry expected ]].forEach (t) -> try fs.unlinkSync t[0] console.error "fs.symlinkSync(%j, %j, %j)", t[1], t[0], type fs.symlinkSync t[1], t[0], type unlink.push t[0] return result = fs.realpathSync(entry) assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) return return test_deep_relative_file_symlink = (callback) -> console.log "test_deep_relative_file_symlink" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() expected = path.join(common.fixturesDir, "cycles", "root.js") linkData1 = "../../cycles/root.js" linkPath1 = path.join(common.fixturesDir, "nested-index", "one", "symlink1.js") try fs.unlinkSync linkPath1 fs.symlinkSync linkData1, linkPath1, "file" linkData2 = "../one/symlink1.js" entry = path.join(common.fixturesDir, "nested-index", "two", "symlink1-b.js") try fs.unlinkSync entry fs.symlinkSync linkData2, entry, "file" unlink.push linkPath1 unlink.push entry assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) return return test_deep_relative_dir_symlink = (callback) -> console.log "test_deep_relative_dir_symlink" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() expected = path.join(common.fixturesDir, "cycles", "folder") linkData1b = "../../cycles/folder" linkPath1b = path.join(common.fixturesDir, "nested-index", "one", "symlink1-dir") try fs.unlinkSync linkPath1b fs.symlinkSync linkData1b, linkPath1b, "dir" linkData2b = "../one/symlink1-dir" entry = path.join(common.fixturesDir, "nested-index", "two", "symlink12-dir") try fs.unlinkSync entry fs.symlinkSync linkData2b, entry, "dir" unlink.push linkPath1b unlink.push entry assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) return return test_cyclic_link_protection = (callback) -> console.log "test_cyclic_link_protection" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() entry = common.tmpDir + "/cycles/realpath-3a" [ [ entry "../cycles/realpath-3b" ] [ common.tmpDir + "/cycles/realpath-3b" "../cycles/realpath-3c" ] [ common.tmpDir + "/cycles/realpath-3c" "../cycles/realpath-3a" ] ].forEach (t) -> try fs.unlinkSync t[0] fs.symlinkSync t[1], t[0], "dir" unlink.push t[0] return assert.throws -> fs.realpathSync entry return asynctest fs.realpath, [entry], callback, (err, result) -> assert.ok err and true true return test_cyclic_link_overprotection = (callback) -> console.log "test_cyclic_link_overprotection" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() cycles = common.tmpDir + "/cycles" expected = fs.realpathSync(cycles) folder = cycles + "/folder" link = folder + "/cycles" testPath = cycles i = 0 while i < 10 testPath += "/folder/cycles" i++ try fs.unlinkSync link fs.symlinkSync cycles, link, "dir" unlink.push link assert.equal fs.realpathSync(testPath), path.resolve(expected) asynctest fs.realpath, [testPath], callback, (er, res) -> assert.equal res, path.resolve(expected) return return test_relative_input_cwd = (callback) -> console.log "test_relative_input_cwd" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() # we need to get the relative path to the tmp dir from cwd. # When the test runner is running it, that will be .../node/test # but it's more common to run `./node test/.../`, so detect it here. entrydir = process.cwd() entry = common.tmpDir.substr(entrydir.length + 1) + "/cycles/realpath-3a" expected = common.tmpDir + "/cycles/root.js" [ [ entry "../cycles/realpath-3b" ] [ common.tmpDir + "/cycles/realpath-3b" "../cycles/realpath-3c" ] [ common.tmpDir + "/cycles/realpath-3c" "root.js" ] ].forEach (t) -> fn = t[0] console.error "fn=%j", fn try fs.unlinkSync fn b = path.basename(t[1]) type = ((if b is "root.js" then "file" else "dir")) console.log "fs.symlinkSync(%j, %j, %j)", t[1], fn, type fs.symlinkSync t[1], fn, "file" unlink.push fn return origcwd = process.cwd() process.chdir entrydir assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> process.chdir origcwd assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) true return test_deep_symlink_mix = (callback) -> console.log "test_deep_symlink_mix" if isWindows # This one is a mix of files and directories, and it's quite tricky # to get the file/dir links sorted out correctly. console.log "skipping symlink test (no way to work on windows)" return runNextTest() # todo: check to see that common.fixturesDir is not rooted in the # same directory as our test symlink. # # /tmp/node-test-realpath-f1 -> ../tmp/node-test-realpath-d1/foo # /tmp/node-test-realpath-d1 -> ../node-test-realpath-d2 # /tmp/node-test-realpath-d2/foo -> ../node-test-realpath-f2 # /tmp/node-test-realpath-f2 # -> /node/test/fixtures/nested-index/one/realpath-c # /node/test/fixtures/nested-index/one/realpath-c # -> /node/test/fixtures/nested-index/two/realpath-c # /node/test/fixtures/nested-index/two/realpath-c -> ../../cycles/root.js # /node/test/fixtures/cycles/root.js (hard) # entry = tmp("node-test-realpath-f1") try fs.unlinkSync tmp("node-test-realpath-d2/foo") try fs.rmdirSync tmp("node-test-realpath-d2") fs.mkdirSync tmp("node-test-realpath-d2"), 0700 try [ [ entry "../tmp/node-test-realpath-d1/foo" ] [ tmp("node-test-realpath-d1") "../tmp/node-test-realpath-d2" ] [ tmp("node-test-realpath-d2/foo") "../node-test-realpath-f2" ] [ tmp("node-test-realpath-f2") fixturesAbsDir + "/nested-index/one/realpath-c" ] [ fixturesAbsDir + "/nested-index/one/realpath-c" fixturesAbsDir + "/nested-index/two/realpath-c" ] [ fixturesAbsDir + "/nested-index/two/realpath-c" "../../../tmp/cycles/root.js" ] ].forEach (t) -> #common.debug('setting up '+t[0]+' -> '+t[1]); try fs.unlinkSync t[0] fs.symlinkSync t[1], t[0] unlink.push t[0] return finally unlink.push tmp("node-test-realpath-d2") expected = tmpAbsDir + "/cycles/root.js" assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) true return test_non_symlinks = (callback) -> console.log "test_non_symlinks" entrydir = path.dirname(tmpAbsDir) entry = tmpAbsDir.substr(entrydir.length + 1) + "/cycles/root.js" expected = tmpAbsDir + "/cycles/root.js" origcwd = process.cwd() process.chdir entrydir assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> process.chdir origcwd assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) true return test_escape_cwd = (cb) -> console.log "test_escape_cwd" asynctest fs.realpath, [".."], cb, (er, uponeActual) -> assert.equal upone, uponeActual, "realpath(\"..\") expected: " + path.resolve(upone) + " actual:" + uponeActual return return # going up with .. multiple times # . # `-- a/ # |-- b/ # | `-- e -> .. # `-- d -> .. # realpath(a/b/e/d/a/b/e/d/a) ==> a test_up_multiple = (cb) -> cleanup = -> [ "a/b" "a" ].forEach (folder) -> try fs.rmdirSync tmp(folder) return return setup = -> cleanup() return console.error "test_up_multiple" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() setup() fs.mkdirSync tmp("a"), 0755 fs.mkdirSync tmp("a/b"), 0755 fs.symlinkSync "..", tmp("a/d"), "dir" unlink.push tmp("a/d") fs.symlinkSync "..", tmp("a/b/e"), "dir" unlink.push tmp("a/b/e") abedabed = tmp("abedabed".split("").join("/")) abedabed_real = tmp("") abedabeda = tmp("abedabeda".split("").join("/")) abedabeda_real = tmp("a") assert.equal fs.realpathSync(abedabeda), abedabeda_real assert.equal fs.realpathSync(abedabed), abedabed_real fs.realpath abedabeda, (er, real) -> throw er if er assert.equal abedabeda_real, real fs.realpath abedabed, (er, real) -> throw er if er assert.equal abedabed_real, real cb() cleanup() return return return # absolute symlinks with children. # . # `-- a/ # |-- b/ # | `-- c/ # | `-- x.txt # `-- link -> /tmp/node-test-realpath-abs-kids/a/b/ # realpath(root+'/a/link/c/x.txt') ==> root+'/a/b/c/x.txt' test_abs_with_kids = (cb) -> # this one should still run, even if skipSymlinks is set, # because it uses a junction. cleanup = -> [ "/a/b/c/x.txt" "/a/link" ].forEach (file) -> try fs.unlinkSync root + file return [ "/a/b/c" "/a/b" "/a" "" ].forEach (folder) -> try fs.rmdirSync root + folder return return setup = -> cleanup() [ "" "/a" "/a/b" "/a/b/c" ].forEach (folder) -> console.log "mkdir " + root + folder fs.mkdirSync root + folder, 0700 return fs.writeFileSync root + "/a/b/c/x.txt", "foo" fs.symlinkSync root + "/a/b", root + "/a/link", type return console.log "test_abs_with_kids" type = (if skipSymlinks then "junction" else "dir") console.log "using type=%s", type root = tmpAbsDir + "/node-test-realpath-abs-kids" setup() linkPath = root + "/a/link/c/x.txt" expectPath = root + "/a/b/c/x.txt" actual = fs.realpathSync(linkPath) # console.log({link:linkPath,expect:expectPath,actual:actual},'sync'); assert.equal actual, path.resolve(expectPath) asynctest fs.realpath, [linkPath], cb, (er, actual) -> # console.log({link:linkPath,expect:expectPath,actual:actual},'async'); assert.equal actual, path.resolve(expectPath) cleanup() return return test_lying_cache_liar = (cb) -> n = 2 # this should not require *any* stat calls, since everything # checked by realpath will be found in the cache. console.log "test_lying_cache_liar" cache = "/foo/bar/baz/bluff": "/foo/bar/bluff" "/1/2/3/4/5/6/7": "/1" "/a": "/a" "/a/b": "/a/b" "/a/b/c": "/a/b" "/a/b/d": "/a/b/d" if isWindows wc = {} Object.keys(cache).forEach (k) -> wc[path.resolve(k)] = path.resolve(cache[k]) return cache = wc bluff = path.resolve("/foo/bar/baz/bluff") rps = fs.realpathSync(bluff, cache) assert.equal cache[bluff], rps nums = path.resolve("/1/2/3/4/5/6/7") called = false # no sync cb calling! fs.realpath nums, cache, (er, rp) -> called = true assert.equal cache[nums], rp cb() if --n is 0 return assert called is false test = path.resolve("/a/b/c/d") expect = path.resolve("/a/b/d") actual = fs.realpathSync(test, cache) assert.equal expect, actual fs.realpath test, cache, (er, actual) -> assert.equal expect, actual cb() if --n is 0 return return # ---------------------------------------------------------------------------- runNextTest = (err) -> throw err if err test = tests.shift() return console.log(numtests + " subtests completed OK for fs.realpath") unless test testsRun++ test runNextTest return runTest = -> tmpDirs = [ "cycles" "cycles/folder" ] tmpDirs.forEach (t) -> t = tmp(t) s = undefined try s = fs.statSync(t) return if s fs.mkdirSync t, 0700 return fs.writeFileSync tmp("cycles/root.js"), "console.error('roooot!');" console.error "start tests" runNextTest() return common = require("../common") assert = require("assert") fs = require("fs") path = require("path") exec = require("child_process").exec async_completed = 0 async_expected = 0 unlink = [] isWindows = process.platform is "win32" skipSymlinks = false root = "/" if isWindows root = process.cwd().substr(0, 3) try exec "whoami /priv", (err, o) -> skipSymlinks = true if err or o.indexOf("SeCreateSymbolicLinkPrivilege") is -1 runTest() return catch er skipSymlinks = true process.nextTick runTest else process.nextTick runTest fixturesAbsDir = common.fixturesDir tmpAbsDir = common.tmpDir console.error "absolutes\n%s\n%s", fixturesAbsDir, tmpAbsDir upone = path.join(process.cwd(), "..") uponeActual = fs.realpathSync("..") assert.equal upone, uponeActual, "realpathSync(\"..\") expected: " + path.resolve(upone) + " actual:" + uponeActual tests = [ test_simple_error_callback test_simple_relative_symlink test_simple_absolute_symlink test_deep_relative_file_symlink test_deep_relative_dir_symlink test_cyclic_link_protection test_cyclic_link_overprotection test_relative_input_cwd test_deep_symlink_mix test_non_symlinks test_escape_cwd test_abs_with_kids test_lying_cache_liar test_up_multiple ] numtests = tests.length testsRun = 0 assert.equal root, fs.realpathSync("/") fs.realpath "/", (err, result) -> assert.equal null, err assert.equal root, result return process.on "exit", -> assert.equal numtests, testsRun unlink.forEach (path) -> try fs.unlinkSync path return assert.equal async_completed, async_expected 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. # something like "C:\\" # On Windows, creating symlinks requires admin privileges. # We'll only try to run symlink test if we have enough privileges. # better safe than sorry tmp = (p) -> path.join common.tmpDir, p asynctest = (testBlock, args, callback, assertBlock) -> async_expected++ testBlock.apply testBlock, args.concat((err) -> ignoreError = false if assertBlock try ignoreError = assertBlock.apply(assertBlock, arguments) catch e err = e async_completed++ callback (if ignoreError then null else err) return ) return # sub-tests: test_simple_error_callback = (cb) -> ncalls = 0 fs.realpath "/this/path/does/not/exist", (err, s) -> assert err assert not s ncalls++ cb() return process.on "exit", -> assert.equal ncalls, 1 return return test_simple_relative_symlink = (callback) -> console.log "test_simple_relative_symlink" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() entry = common.tmpDir + "/symlink" expected = common.tmpDir + "/cycles/root.js" [[ entry "../tmp/cycles/root.js" ]].forEach (t) -> try fs.unlinkSync t[0] console.log "fs.symlinkSync(%j, %j, %j)", t[1], t[0], "file" fs.symlinkSync t[1], t[0], "file" unlink.push t[0] return result = fs.realpathSync(entry) assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) return return test_simple_absolute_symlink = (callback) -> console.log "test_simple_absolute_symlink" # this one should still run, even if skipSymlinks is set, # because it uses a junction. type = (if skipSymlinks then "junction" else "dir") console.log "using type=%s", type entry = tmpAbsDir + "/symlink" expected = fixturesAbsDir + "/nested-index/one" [[ entry expected ]].forEach (t) -> try fs.unlinkSync t[0] console.error "fs.symlinkSync(%j, %j, %j)", t[1], t[0], type fs.symlinkSync t[1], t[0], type unlink.push t[0] return result = fs.realpathSync(entry) assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(expected) return return test_deep_relative_file_symlink = (callback) -> console.log "test_deep_relative_file_symlink" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() expected = path.join(common.fixturesDir, "cycles", "root.js") linkData1 = "../../cycles/root.js" linkPath1 = path.join(common.fixturesDir, "nested-index", "one", "symlink1.js") try fs.unlinkSync linkPath1 fs.symlinkSync linkData1, linkPath1, "file" linkData2 = "../one/symlink1.js" entry = path.join(common.fixturesDir, "nested-index", "two", "symlink1-b.js") try fs.unlinkSync entry fs.symlinkSync linkData2, entry, "file" unlink.push linkPath1 unlink.push entry assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) return return test_deep_relative_dir_symlink = (callback) -> console.log "test_deep_relative_dir_symlink" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() expected = path.join(common.fixturesDir, "cycles", "folder") linkData1b = "../../cycles/folder" linkPath1b = path.join(common.fixturesDir, "nested-index", "one", "symlink1-dir") try fs.unlinkSync linkPath1b fs.symlinkSync linkData1b, linkPath1b, "dir" linkData2b = "../one/symlink1-dir" entry = path.join(common.fixturesDir, "nested-index", "two", "symlink12-dir") try fs.unlinkSync entry fs.symlinkSync linkData2b, entry, "dir" unlink.push linkPath1b unlink.push entry assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) return return test_cyclic_link_protection = (callback) -> console.log "test_cyclic_link_protection" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() entry = common.tmpDir + "/cycles/realpath-3a" [ [ entry "../cycles/realpath-3b" ] [ common.tmpDir + "/cycles/realpath-3b" "../cycles/realpath-3c" ] [ common.tmpDir + "/cycles/realpath-3c" "../cycles/realpath-3a" ] ].forEach (t) -> try fs.unlinkSync t[0] fs.symlinkSync t[1], t[0], "dir" unlink.push t[0] return assert.throws -> fs.realpathSync entry return asynctest fs.realpath, [entry], callback, (err, result) -> assert.ok err and true true return test_cyclic_link_overprotection = (callback) -> console.log "test_cyclic_link_overprotection" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() cycles = common.tmpDir + "/cycles" expected = fs.realpathSync(cycles) folder = cycles + "/folder" link = folder + "/cycles" testPath = cycles i = 0 while i < 10 testPath += "/folder/cycles" i++ try fs.unlinkSync link fs.symlinkSync cycles, link, "dir" unlink.push link assert.equal fs.realpathSync(testPath), path.resolve(expected) asynctest fs.realpath, [testPath], callback, (er, res) -> assert.equal res, path.resolve(expected) return return test_relative_input_cwd = (callback) -> console.log "test_relative_input_cwd" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() # we need to get the relative path to the tmp dir from cwd. # When the test runner is running it, that will be .../node/test # but it's more common to run `./node test/.../`, so detect it here. entrydir = process.cwd() entry = common.tmpDir.substr(entrydir.length + 1) + "/cycles/realpath-3a" expected = common.tmpDir + "/cycles/root.js" [ [ entry "../cycles/realpath-3b" ] [ common.tmpDir + "/cycles/realpath-3b" "../cycles/realpath-3c" ] [ common.tmpDir + "/cycles/realpath-3c" "root.js" ] ].forEach (t) -> fn = t[0] console.error "fn=%j", fn try fs.unlinkSync fn b = path.basename(t[1]) type = ((if b is "root.js" then "file" else "dir")) console.log "fs.symlinkSync(%j, %j, %j)", t[1], fn, type fs.symlinkSync t[1], fn, "file" unlink.push fn return origcwd = process.cwd() process.chdir entrydir assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> process.chdir origcwd assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) true return test_deep_symlink_mix = (callback) -> console.log "test_deep_symlink_mix" if isWindows # This one is a mix of files and directories, and it's quite tricky # to get the file/dir links sorted out correctly. console.log "skipping symlink test (no way to work on windows)" return runNextTest() # todo: check to see that common.fixturesDir is not rooted in the # same directory as our test symlink. # # /tmp/node-test-realpath-f1 -> ../tmp/node-test-realpath-d1/foo # /tmp/node-test-realpath-d1 -> ../node-test-realpath-d2 # /tmp/node-test-realpath-d2/foo -> ../node-test-realpath-f2 # /tmp/node-test-realpath-f2 # -> /node/test/fixtures/nested-index/one/realpath-c # /node/test/fixtures/nested-index/one/realpath-c # -> /node/test/fixtures/nested-index/two/realpath-c # /node/test/fixtures/nested-index/two/realpath-c -> ../../cycles/root.js # /node/test/fixtures/cycles/root.js (hard) # entry = tmp("node-test-realpath-f1") try fs.unlinkSync tmp("node-test-realpath-d2/foo") try fs.rmdirSync tmp("node-test-realpath-d2") fs.mkdirSync tmp("node-test-realpath-d2"), 0700 try [ [ entry "../tmp/node-test-realpath-d1/foo" ] [ tmp("node-test-realpath-d1") "../tmp/node-test-realpath-d2" ] [ tmp("node-test-realpath-d2/foo") "../node-test-realpath-f2" ] [ tmp("node-test-realpath-f2") fixturesAbsDir + "/nested-index/one/realpath-c" ] [ fixturesAbsDir + "/nested-index/one/realpath-c" fixturesAbsDir + "/nested-index/two/realpath-c" ] [ fixturesAbsDir + "/nested-index/two/realpath-c" "../../../tmp/cycles/root.js" ] ].forEach (t) -> #common.debug('setting up '+t[0]+' -> '+t[1]); try fs.unlinkSync t[0] fs.symlinkSync t[1], t[0] unlink.push t[0] return finally unlink.push tmp("node-test-realpath-d2") expected = tmpAbsDir + "/cycles/root.js" assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) true return test_non_symlinks = (callback) -> console.log "test_non_symlinks" entrydir = path.dirname(tmpAbsDir) entry = tmpAbsDir.substr(entrydir.length + 1) + "/cycles/root.js" expected = tmpAbsDir + "/cycles/root.js" origcwd = process.cwd() process.chdir entrydir assert.equal fs.realpathSync(entry), path.resolve(expected) asynctest fs.realpath, [entry], callback, (err, result) -> process.chdir origcwd assert.equal result, path.resolve(expected), "got " + common.inspect(result) + " expected " + common.inspect(path.resolve(expected)) true return test_escape_cwd = (cb) -> console.log "test_escape_cwd" asynctest fs.realpath, [".."], cb, (er, uponeActual) -> assert.equal upone, uponeActual, "realpath(\"..\") expected: " + path.resolve(upone) + " actual:" + uponeActual return return # going up with .. multiple times # . # `-- a/ # |-- b/ # | `-- e -> .. # `-- d -> .. # realpath(a/b/e/d/a/b/e/d/a) ==> a test_up_multiple = (cb) -> cleanup = -> [ "a/b" "a" ].forEach (folder) -> try fs.rmdirSync tmp(folder) return return setup = -> cleanup() return console.error "test_up_multiple" if skipSymlinks console.log "skipping symlink test (no privs)" return runNextTest() setup() fs.mkdirSync tmp("a"), 0755 fs.mkdirSync tmp("a/b"), 0755 fs.symlinkSync "..", tmp("a/d"), "dir" unlink.push tmp("a/d") fs.symlinkSync "..", tmp("a/b/e"), "dir" unlink.push tmp("a/b/e") abedabed = tmp("abedabed".split("").join("/")) abedabed_real = tmp("") abedabeda = tmp("abedabeda".split("").join("/")) abedabeda_real = tmp("a") assert.equal fs.realpathSync(abedabeda), abedabeda_real assert.equal fs.realpathSync(abedabed), abedabed_real fs.realpath abedabeda, (er, real) -> throw er if er assert.equal abedabeda_real, real fs.realpath abedabed, (er, real) -> throw er if er assert.equal abedabed_real, real cb() cleanup() return return return # absolute symlinks with children. # . # `-- a/ # |-- b/ # | `-- c/ # | `-- x.txt # `-- link -> /tmp/node-test-realpath-abs-kids/a/b/ # realpath(root+'/a/link/c/x.txt') ==> root+'/a/b/c/x.txt' test_abs_with_kids = (cb) -> # this one should still run, even if skipSymlinks is set, # because it uses a junction. cleanup = -> [ "/a/b/c/x.txt" "/a/link" ].forEach (file) -> try fs.unlinkSync root + file return [ "/a/b/c" "/a/b" "/a" "" ].forEach (folder) -> try fs.rmdirSync root + folder return return setup = -> cleanup() [ "" "/a" "/a/b" "/a/b/c" ].forEach (folder) -> console.log "mkdir " + root + folder fs.mkdirSync root + folder, 0700 return fs.writeFileSync root + "/a/b/c/x.txt", "foo" fs.symlinkSync root + "/a/b", root + "/a/link", type return console.log "test_abs_with_kids" type = (if skipSymlinks then "junction" else "dir") console.log "using type=%s", type root = tmpAbsDir + "/node-test-realpath-abs-kids" setup() linkPath = root + "/a/link/c/x.txt" expectPath = root + "/a/b/c/x.txt" actual = fs.realpathSync(linkPath) # console.log({link:linkPath,expect:expectPath,actual:actual},'sync'); assert.equal actual, path.resolve(expectPath) asynctest fs.realpath, [linkPath], cb, (er, actual) -> # console.log({link:linkPath,expect:expectPath,actual:actual},'async'); assert.equal actual, path.resolve(expectPath) cleanup() return return test_lying_cache_liar = (cb) -> n = 2 # this should not require *any* stat calls, since everything # checked by realpath will be found in the cache. console.log "test_lying_cache_liar" cache = "/foo/bar/baz/bluff": "/foo/bar/bluff" "/1/2/3/4/5/6/7": "/1" "/a": "/a" "/a/b": "/a/b" "/a/b/c": "/a/b" "/a/b/d": "/a/b/d" if isWindows wc = {} Object.keys(cache).forEach (k) -> wc[path.resolve(k)] = path.resolve(cache[k]) return cache = wc bluff = path.resolve("/foo/bar/baz/bluff") rps = fs.realpathSync(bluff, cache) assert.equal cache[bluff], rps nums = path.resolve("/1/2/3/4/5/6/7") called = false # no sync cb calling! fs.realpath nums, cache, (er, rp) -> called = true assert.equal cache[nums], rp cb() if --n is 0 return assert called is false test = path.resolve("/a/b/c/d") expect = path.resolve("/a/b/d") actual = fs.realpathSync(test, cache) assert.equal expect, actual fs.realpath test, cache, (er, actual) -> assert.equal expect, actual cb() if --n is 0 return return # ---------------------------------------------------------------------------- runNextTest = (err) -> throw err if err test = tests.shift() return console.log(numtests + " subtests completed OK for fs.realpath") unless test testsRun++ test runNextTest return runTest = -> tmpDirs = [ "cycles" "cycles/folder" ] tmpDirs.forEach (t) -> t = tmp(t) s = undefined try s = fs.statSync(t) return if s fs.mkdirSync t, 0700 return fs.writeFileSync tmp("cycles/root.js"), "console.error('roooot!');" console.error "start tests" runNextTest() return common = require("../common") assert = require("assert") fs = require("fs") path = require("path") exec = require("child_process").exec async_completed = 0 async_expected = 0 unlink = [] isWindows = process.platform is "win32" skipSymlinks = false root = "/" if isWindows root = process.cwd().substr(0, 3) try exec "whoami /priv", (err, o) -> skipSymlinks = true if err or o.indexOf("SeCreateSymbolicLinkPrivilege") is -1 runTest() return catch er skipSymlinks = true process.nextTick runTest else process.nextTick runTest fixturesAbsDir = common.fixturesDir tmpAbsDir = common.tmpDir console.error "absolutes\n%s\n%s", fixturesAbsDir, tmpAbsDir upone = path.join(process.cwd(), "..") uponeActual = fs.realpathSync("..") assert.equal upone, uponeActual, "realpathSync(\"..\") expected: " + path.resolve(upone) + " actual:" + uponeActual tests = [ test_simple_error_callback test_simple_relative_symlink test_simple_absolute_symlink test_deep_relative_file_symlink test_deep_relative_dir_symlink test_cyclic_link_protection test_cyclic_link_overprotection test_relative_input_cwd test_deep_symlink_mix test_non_symlinks test_escape_cwd test_abs_with_kids test_lying_cache_liar test_up_multiple ] numtests = tests.length testsRun = 0 assert.equal root, fs.realpathSync("/") fs.realpath "/", (err, result) -> assert.equal null, err assert.equal root, result return process.on "exit", -> assert.equal numtests, testsRun unlink.forEach (path) -> try fs.unlinkSync path return assert.equal async_completed, async_expected return
[ { "context": "# Copyright 2012 Joshua Carver \n# \n# Licensed under the Apache License, Versio", "end": 30, "score": 0.9998713731765747, "start": 17, "tag": "NAME", "value": "Joshua Carver" } ]
src/coffeescript/charts/index_chart_options.coffee
jcarver989/raphy-charts
5
# Copyright 2012 Joshua Carver # # 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. # @import base_chart_options.coffee class IndexChartOptions extends BaseChartOptions @DEFAULTS: { bar_margin: 30 bar_bg_color: "#bdced3" bar1_color: "90-#2f5e78-#4284a8" bar2_color: "90-#173e53-#225d7c" raw_value_bar_color: "#9eb7bf" x_padding: 160 x_padding_right: 100 y_padding: 50 bg_bar_padding: 14 rounding: 3 dash_width: 3 label_size: 14 font_family: "Helvetica, Arial, sans-serif" } constructor: (options) -> return super(options, IndexChartOptions.DEFAULTS)
171334
# Copyright 2012 <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. # @import base_chart_options.coffee class IndexChartOptions extends BaseChartOptions @DEFAULTS: { bar_margin: 30 bar_bg_color: "#bdced3" bar1_color: "90-#2f5e78-#4284a8" bar2_color: "90-#173e53-#225d7c" raw_value_bar_color: "#9eb7bf" x_padding: 160 x_padding_right: 100 y_padding: 50 bg_bar_padding: 14 rounding: 3 dash_width: 3 label_size: 14 font_family: "Helvetica, Arial, sans-serif" } constructor: (options) -> return super(options, IndexChartOptions.DEFAULTS)
true
# Copyright 2012 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. # @import base_chart_options.coffee class IndexChartOptions extends BaseChartOptions @DEFAULTS: { bar_margin: 30 bar_bg_color: "#bdced3" bar1_color: "90-#2f5e78-#4284a8" bar2_color: "90-#173e53-#225d7c" raw_value_bar_color: "#9eb7bf" x_padding: 160 x_padding_right: 100 y_padding: 50 bg_bar_padding: 14 rounding: 3 dash_width: 3 label_size: 14 font_family: "Helvetica, Arial, sans-serif" } constructor: (options) -> return super(options, IndexChartOptions.DEFAULTS)
[ { "context": "get: (which)->\n if this.available\n key = \"hex-bot-#{which}\"\n return localStorage.getItem(key)\n return", "end": 660, "score": 0.9806398749351501, "start": 643, "tag": "KEY", "value": "hex-bot-#{which}\"" }, { "context": "which, code)->\n if this....
src/coffee/view/Persistence.coffee
retroverse/hex-redux
0
class Persistence available: false getAvailable: (type)-> try storage = window[type] x = '__storage_test__' storage.setItem x, x storage.removeItem x return true catch e return e instanceof DOMException and ( e.code is 22 or e.code is 1014 or e.name is 'QuotaExceededError' or e.name is 'NS_ERROR_DOM_QUOTA_REACHED') and storage.length isnt 0 init: -> this.available = this.getAvailable('localStorage') clear: (which)-> if this.available localStorage.removeItem("hex-bot-#{which}") get: (which)-> if this.available key = "hex-bot-#{which}" return localStorage.getItem(key) return undefined save: (which, code)-> if this.available key = "hex-bot-#{which}" localStorage.setItem(key, code) ##Export module.exports = Persistence
34774
class Persistence available: false getAvailable: (type)-> try storage = window[type] x = '__storage_test__' storage.setItem x, x storage.removeItem x return true catch e return e instanceof DOMException and ( e.code is 22 or e.code is 1014 or e.name is 'QuotaExceededError' or e.name is 'NS_ERROR_DOM_QUOTA_REACHED') and storage.length isnt 0 init: -> this.available = this.getAvailable('localStorage') clear: (which)-> if this.available localStorage.removeItem("hex-bot-#{which}") get: (which)-> if this.available key = "<KEY> return localStorage.getItem(key) return undefined save: (which, code)-> if this.available key = "<KEY> localStorage.setItem(key, code) ##Export module.exports = Persistence
true
class Persistence available: false getAvailable: (type)-> try storage = window[type] x = '__storage_test__' storage.setItem x, x storage.removeItem x return true catch e return e instanceof DOMException and ( e.code is 22 or e.code is 1014 or e.name is 'QuotaExceededError' or e.name is 'NS_ERROR_DOM_QUOTA_REACHED') and storage.length isnt 0 init: -> this.available = this.getAvailable('localStorage') clear: (which)-> if this.available localStorage.removeItem("hex-bot-#{which}") get: (which)-> if this.available key = "PI:KEY:<KEY>END_PI return localStorage.getItem(key) return undefined save: (which, code)-> if this.available key = "PI:KEY:<KEY>END_PI localStorage.setItem(key, code) ##Export module.exports = Persistence
[ { "context": "his,is, a,test '\n author:\n name: 'Doe'\n\n response =\n locals: {}\n\n cb = ->\n ", "end": 1020, "score": 0.9997056722640991, "start": 1017, "tag": "NAME", "value": "Doe" }, { "context": "']\n expect(form.author.name.value).to.equal 'D...
test/form.middleware.spec.coffee
nrako/formal
2
### global describe, it, beforeEach ### chai = require 'chai' expect = chai.expect Form = require '../lib/form' describe 'Form route-middleware', -> it 'supports form.middleware', (done) -> middleware = Form title: type: String trim: true required: true attributes: placeholder: 'Title' publishOn: Date explicitContent: type: Number min: 6 max: 18 author: name: String email: type: String required: true tags: type: [String] set: (val) -> splits = val.split ',' splits.forEach (val, i, ar) -> ar[i] = val.trim() return splits category: type: String enum: ['CatA', 'CatB'] public: type: Boolean required: true request = body: title: '' publishOn: new Date # TODO should be a string tags: 'this,is, a,test ' author: name: 'Doe' response = locals: {} cb = -> form = response.locals.form expect(form.errors.length).to.equal 3 expect(form.title.data.attributes.placeholder).to.equal 'Title' expect(form.title.error).to.be.a 'string' expect(form.tags.value).to.deep.equal ['this','is','a','test'] expect(form.author.name.value).to.equal 'Doe' done() # app.post('/url', form.express, function (req, res) {...}) middleware request, response, cb
8722
### global describe, it, beforeEach ### chai = require 'chai' expect = chai.expect Form = require '../lib/form' describe 'Form route-middleware', -> it 'supports form.middleware', (done) -> middleware = Form title: type: String trim: true required: true attributes: placeholder: 'Title' publishOn: Date explicitContent: type: Number min: 6 max: 18 author: name: String email: type: String required: true tags: type: [String] set: (val) -> splits = val.split ',' splits.forEach (val, i, ar) -> ar[i] = val.trim() return splits category: type: String enum: ['CatA', 'CatB'] public: type: Boolean required: true request = body: title: '' publishOn: new Date # TODO should be a string tags: 'this,is, a,test ' author: name: '<NAME>' response = locals: {} cb = -> form = response.locals.form expect(form.errors.length).to.equal 3 expect(form.title.data.attributes.placeholder).to.equal 'Title' expect(form.title.error).to.be.a 'string' expect(form.tags.value).to.deep.equal ['this','is','a','test'] expect(form.author.name.value).to.equal '<NAME>' done() # app.post('/url', form.express, function (req, res) {...}) middleware request, response, cb
true
### global describe, it, beforeEach ### chai = require 'chai' expect = chai.expect Form = require '../lib/form' describe 'Form route-middleware', -> it 'supports form.middleware', (done) -> middleware = Form title: type: String trim: true required: true attributes: placeholder: 'Title' publishOn: Date explicitContent: type: Number min: 6 max: 18 author: name: String email: type: String required: true tags: type: [String] set: (val) -> splits = val.split ',' splits.forEach (val, i, ar) -> ar[i] = val.trim() return splits category: type: String enum: ['CatA', 'CatB'] public: type: Boolean required: true request = body: title: '' publishOn: new Date # TODO should be a string tags: 'this,is, a,test ' author: name: 'PI:NAME:<NAME>END_PI' response = locals: {} cb = -> form = response.locals.form expect(form.errors.length).to.equal 3 expect(form.title.data.attributes.placeholder).to.equal 'Title' expect(form.title.error).to.be.a 'string' expect(form.tags.value).to.deep.equal ['this','is','a','test'] expect(form.author.name.value).to.equal 'PI:NAME:<NAME>END_PI' done() # app.post('/url', form.express, function (req, res) {...}) middleware request, response, cb
[ { "context": "t de plecare.\"\n century_skills_quote4_author: \"Joey, clasa a 10-a\"\n century_skills_subtitle4: \"Com", "end": 3473, "score": 0.9998112320899963, "start": 3469, "tag": "NAME", "value": "Joey" }, { "context": "de scriere a codului.\"\n quotes_quote5_author: \...
app/locale/ro.coffee
georgyana/codecombat
0
module.exports = nativeDescription: "Română", englishDescription: "Romanian", translation: new_home: title: "CodeCombat - Învăța Python și Javascript prin jocuri de programare" meta_keywords: "CodeCombat, python, javascript, jocuri de programare" meta_description: "Învață să scrii cod printr-un joc de programare. Învață Python, Javascript, și HTML ca și când ai rezolva puzzle-uri și învață să îți faci propriile jocuri și site-uri web." meta_og_url: "https://codecombat.com" become_investor: "pentru a devi un investitor în CodeCombat" built_for_teachers_title: "Un joc de programare dezvoltat cu gândul la profesori." built_for_teachers_blurb: "Învățarea copiilor să scrie cod poate fi copleșitoare câteodată. CodeCombat îi ajută pe instructori să-i învețe pe elevi cum să scrie cod în Javascript sau în Python, două din cele mai populare limbaje de programare. Cu o curiculă completă incluzând șase unități care consolidează învățarea prin unități de dezvoltare a jocurilor bazată pe proiecte și a celor de dezvoltare web, copiii vor progresa de-a lungul unei călătorii de la sintaxa de bază până la recursivitate!" built_for_teachers_subtitle1: "Informatică" built_for_teachers_subblurb1: "Începând de la cursul nostru gratuit de Introducere în informatică, studenții își însușesc concepte de bază în programare, cum ar fi bucle while/for, funcții și algoritmi." built_for_teachers_subtitle2: "Dezvoltare de jocuri" built_for_teachers_subblurb2: "Cursanții construiesc labirinturi și utilizează elemente de bază despre manipularea intrărilor ca să programeze propriile jocuri care pot fi partajate mai apoi cu prietenii și familia." built_for_teachers_subtitle3: "Dezvoltare web" built_for_teachers_subblurb3: "Utilizând HTML, CSS și jQuery, cursanții își antrenează mușchii creativității prin programarea propriilor pagini web cu un URL propriu ce poate fi partajat cu colegii de clasă." century_skills_title: "Abilități pentru secolul 21" century_skills_blurb1: "Elevii nu își vor dezvolta doar eroul, se vor dezvolta pe ei înșiși" century_skills_quote1: "Ai greșit ... deci te vei gândi la toate posibilitățile să repari greșeala, iar apoi încerci din nou. Nu aș putea să ajung aici dacă nu aș încerca din greu." century_skills_subtitle1: "Gândire critică" century_skills_subblurb1: "Prin scrierea de cod pentru puzzle-urile încorporate în nivelurile din ce în ce mai incitante, jocurile de programare ale CodeCombat se asigură că gândirea critică este mereu exerseată de copii." century_skills_quote2: "Toată lumea făcea labirinturi, atunci m-am gândit, ‘capturează steagul’ și asta am făcut." century_skills_subtitle2: "Creativitate" century_skills_subblurb2: "CodeCombat încurajează elevii să își arate creativitatea construind și partajând propriile jocuri și pagini web." century_skills_quote3: "Dacă m-am blocat la un nivel. Voi lucra cu persoanele de lângă mine până ce toți ne vom da seama cum să mergem mai departe." century_skills_subtitle3: "Colaborare" century_skills_subblurb3: "În timpul jocului, există oportunități pentru elevi să colaboreze atunci când s-au blocat și să lucreze împreună utilizând ghidul nostru de programare în perechi." century_skills_quote4: "Tot mereu am avut aspirații pentru proiectarea de jocuri video și învățarea programării ... acesta îmi oferă un punct important de plecare." century_skills_quote4_author: "Joey, clasa a 10-a" century_skills_subtitle4: "Comunicare" century_skills_subblurb4: "scrierea de cod le solicită copiilor să exerseze noi forme de comunicare, inclusiv comunicarea cu calculatorul dar și transmiterea ideilor lor printr-un cod eficient." classroom_in_box_title: "Ne străduim să:" classroom_in_box_blurb1: "Antrenăm fiecare elev astfel încât el să creadă că programarea este pentru el." classroom_in_box_blurb2: "Permitem oricărui instructor să fie confident atunci când predă programare." classroom_in_box_blurb3: "Inspirăm toți liderii din școli pentru a crea un program internațional de informatică." classroom_in_box_blurb4: "" click_here: "Apasă aici" creativity_rigor_title: "Unde creativitatea întâlnește rigoarea" creativity_rigor_subtitle1: "Facem programarea distractivă și învățăm abilități necesare lumii actuale" creativity_rigor_blurb1: "Elevii vor scrie cod real de Python și Javascript în timp ce se joacă care încurajează încercările și erorile, gândirea critică și creativitatea. elevii aplică mai apoi abilitățile de programare învățate dezvoltând propriile jocuri și site-uri web în cursuri bazate pe proiecte." creativity_rigor_subtitle2: "Accesibil tuturor elevilor indiferent de nivel" creativity_rigor_blurb2: "Fiecare nivel CodeCombat este construit pe baza a milioane de date și optimizat să se poată adapta fiecărui cursant. Nivelurile de practică și indiciile îi ajută pe elevi atunci când aceștia se blochează, iar nivelurile tip provocare evaluează ceea ce au învățat elevii prin joc." creativity_rigor_subtitle3: "Construit pentru profesori, indiferent de experiența lor" creativity_rigor_blurb3: "CodeCombat poate fi urmat într-un ritm propriu, curicula aliniată la standarde permite învățarea informaticii de către toată lumea. CodeCombat echipează profesorii cu resursele de învățare necesare și cu un suport dedicat care să îi ajute să fie confidenți și să aibă succes în clasă." featured_partners_title1: "Prezentat în" featured_partners_title2: "Premii & Parteneri" featured_partners_blurb1: "Parteneri ingenioși" featured_partners_blurb2: "Cel mai creativ instrument pentru elevi" featured_partners_blurb3: "Alegerea de top pentru învățare" featured_partners_blurb4: "Partener oficial Code.org" featured_partners_blurb5: "Membru oficial CSforAll" featured_partners_blurb6: "Partener activități Hour of Code" for_leaders_title: "Pentru liderii din școli" for_leaders_blurb: "Un program de informatică cuprinzător și aliniat standardelor" for_leaders_subtitle1: "Implementare ușoară" for_leaders_subblurb1: "Un program bazat pe web care nu necesită suport IT. Pentru a începe aveți nevoie de mai puțin de 5 minute, utilizând Google sau Clever Single Sign-On (SSO)." for_leaders_subtitle2: "Curiculă completă de programare" for_leaders_subblurb2: "O curiculă aliniată standardelor cu resurse de pregătire și de dezvoltare profesională care permit oricărui profesor să predea informatică." for_leaders_subtitle3: "Modalități de utilizare flexibilă" for_leaders_subblurb3: "Indiferent dacă vrei să construiești un cerc de programare la școala generală, o curriculă de pregătire a carierei tehnice sau vrei să predai elemente de introducere în informatică la clasă, CodeCombat este pregătit să se adapteze nevoilor tale." for_leaders_subtitle4: "Abilități din lumea reală" for_leaders_subblurb4: "Elevii prind curaj și își dezvoltă modul de gândire prin provocări de programare care îi pregătește pentru cele 500K+ locuri de muncă disponibile în domeniul IT." for_teachers_title: "Pentru profesori" for_teachers_blurb: "Instrumente pentru descoperirea potențialului elevilor" for_teachers_subtitle1: "Învățare bazată pe proiecte" for_teachers_subblurb1: "Promovează creativitatea, rezolvarea problemelor și încrederea în forțele proprii prin cursuri orientate pe proiecte în care elevii își dezvoltă propriile jocuri și pagini web." for_teachers_subtitle2: "Panoul de lucru al profesorului" for_teachers_subblurb2: "Vizualizează date despre progresul elevilor, descoperă resurse care susțin curicula și accesează suportul în timp real pentru a susține procesul de învățare al elevilor." for_teachers_subtitle3: "Evaluări încorporate" for_teachers_subblurb3: "Personalizează instrucțiunile și asigură-te că elevii înțeleg conceptele de bază cu evaluări formative și sumative." for_teachers_subtitle4: "Diferențiere automată" for_teachers_subblurb4: "Implică toți cursanții dintr-o clasă mixtă în niveluri practice care se adaptează nevoilor de învățare specifice." game_based_blurb: "CodeCombat este un program de informatică bazat pe jocuri în care elevii scriu cod real și își pot urmării personajele în timp real." get_started: "Să începem" global_title: "Alătură-te comunității noastre globale de cursanți și instructori" global_subtitle1: "Cursanți" global_subtitle2: "Linii de cod" global_subtitle3: "Profesori" global_subtitle4: "Țări" go_to_my_classes: "Către clasele mele" go_to_my_courses: "Către cursurile mele" quotes_quote1: "Numește orice program online, eu deja l-am încercat. Nici unul dintre ele nu se compară cu CodeCombat & Ozaria. Orice profesor care vrea să își învețe elevii cum să scrie cod ... să înceapă aici!" quotes_quote2: " Am fost surprins să văd cât de simplu și intuitiv face învățarea informaticii CodeCombat. Notele la examenele AP au fost mai mari decât m-am așteptat și cred că CodeCombat este cel responsabilde acest lucru." quotes_quote3: "CodeCombat a fost cel mai util în învpțarea elevilor mei capabilități de scriere a codului real. Soțul meu este inginer software și mi-a testat toate programele mele. A fost prioritatea lui principală." quotes_quote4: "Părerile … au fost atât de pozitive încât construim o clasă de informatică în jurul CodeCombat. Programul îi antrenează cu adevărat pe elevi cu o platformă de tipul celor de jocuri care este este amuzantă și instructivă în același timp. Continuați cu treaba bine făcută, CodeCombat!" quotes_quote5: "Deși clasa începe în fiecare sâmbătă la ora 7am, fiul meu este atât de încântat încât se trezește înaintea mea! CodeCombat creează o cale pentru fiul meu ca acesta să își îmbunătățească abilitățile de scriere a codului." quotes_quote5_author: "Latthaphon Pohpon, părinte" see_example: "Vezi exemplul" slogan: "Cel mai antrenat mod de a învăța informatică" slogan_power_of_play: "Învață să programezi prin puterea jocului" teach_cs1_free: "Predă informatică gratuit" teachers_love_codecombat_title: "Profesorii iubesc CodeCombat" teachers_love_codecombat_blurb1: "Raportează că elevii lor îndrăgesc utilizarea CodeCombat pentru învățarea programării" teachers_love_codecombat_blurb2: "Recomandă CodeCombat altor profesori de informatică" teachers_love_codecombat_blurb3: "Spun că CodeCombat îi ajută să sprijine elevii cu abilitățile de rezolvare a problemelor" teachers_love_codecombat_subblurb: "În parteneriat cu McREL International, un lider în îndrumarea și evaluarea bazată pe cercetare a tehnologiilor educaționale." top_banner_blurb: "Părinți, dați-i copilului vostru darul programării și a instruirii personalizate cu profesorii noștri!" top_banner_summer_camp: "Înscrierile sunt acum deschise pentru taberele de vară de programare – întreabă-ne despre sesiunile virtuale de o săptămână începând doar de la $199." top_banner_blurb_funding: "Nou: Ghidul de resurse de finațare CARES Act pentru fondurile ESSER și GEER pentru programele tale de CS." try_the_game: "Încearcă jocul" classroom_edition: "Ediția pentru clasă:" learn_to_code: "Învață să scrii cod:" play_now: "Joacă acum" im_a_parent: "Sunt părinte" im_an_educator: "Sunt instructor" im_a_teacher: "Sunt profesor" im_a_student: "Sunt elev" learn_more: "Aflați mai multe" classroom_in_a_box: "O clasă „la cutie„ pentru a preda informatica." codecombat_is: "CodeCombat este o platformă <strong>pentru elevi</strong> să învețe informatică în timp ce se joacă un joc real." our_courses: "Cursurile noastre au fost testate în mod special <strong>pentru a excela în clasă</strong>, chiar și pentru profesorii cu puțină sau fără experiență prealabilă în informatică." watch_how: "Privește cum CodeCombat transformă modul în care oamenii învață informatică." top_screenshots_hint: "Elevii scriu cod și văd modificările lor actualizate în timp real" designed_with: "Proiectat cu gândul la profesori" real_code: "Cod scris, real" from_the_first_level: "de la primul nivel" getting_students: "Ajungerea elevilor la nivelul de a scrie cod cât mai repede posibil este critică în învățarea sinatxei programării și a structurii corecte." educator_resources: "Resurse pentru instructori" course_guides: "și ghiduri de curs" teaching_computer_science: "Predarea informaticii nu necesită o diplomă costisitoare, deoarece furnizăm unelte care să suțină profesori din toate mediile." accessible_to: "Accesibil pentru" everyone: "toată lumea" democratizing: "Democrația procesului de învățare a programării stă la baza filozofiei noastre. Toată lumea ar trebui să poată să învețe programare." forgot_learning: "Eu cred că ei de fapt au uitat că învață ceva." wanted_to_do: " scrierea de cod este ceva ce întotdeauna mi-am dorit să fac, și niciodată nu m-am gândit că aș putea să învăț în școală." builds_concepts_up: "Îmi place cum CodeCombat construiește conceptele. Este foarte ușor să înțelegi și amuzant să îți dai seama." why_games: "De ce este importantă învățarea prin jocuri?" games_reward: "Jocul răsplătește efortul productiv." encourage: "Jocul este un mediu care încurajează interacțiunea, descoperirea, și încercarea-și-eroarea. Un joc bun provoacă jucătorul să își îmbunătățească abilitățile în timp, care este un proces similar cu al elevilor când învață." excel: "Jocul este mai mult decât plin de satisfacții" struggle: "efort productiv" kind_of_struggle: "tipul de efort care rezultă din procesul de învățare care este antrenant și" motivating: "motivant" not_tedious: "nu plictisitor." gaming_is_good: "Studiile sugerează că jocurile sunt bune pentru creierul copiilor. (E adevarat!)" game_based: "Când sistemele de învățare bazate pe joc sunt" compared: "comparate" conventional: "metodele de evaluare convenționale, diferența este clară: jocurile sunt mai bune să ajute elevii să rețină cunoștințe, să se concentreze și" perform_at_higher_level: "să performeze la un nivel mai înalt" feedback: "Jocurile furnizează de asemenea un feedback în timp real care le permite elevilor să-și ajusteze calea către soluție și să înțeleagă concepte mai holistic, în loc să fie limitați doar la răspunsuri “corect” sau “incorect”." real_game: "Un joc real, jucat cu programare reală." great_game: "Un joc bun este mai mult decât insigne și realizări - este despre călătoria unui jucător, puzzle-uri bine făcute și abilitatea de abordare a provocărilor prin acțiune și încredere." agency: "CodeCombat este un joc care dă jucătorilor acea putere de a acționa și încredere prin intermediul motorului nostru de scriere cod, care îi ajută pe elevii începători și avansați deopotrică să scrie cod corect și valid." request_demo_title: "Pune-i pe elevii tăi să înceapă astăzi!" request_demo_subtitle: "Cere un demo și pune-i pe elevii tăi să înceapă în mai puțin de o oră." get_started_title: "Creează clasa azi" get_started_subtitle: "Creează o clasă, adaugă elevii și monitorizează progresul lor în timp ce ei învață informatică." request_demo: "Cere o demonstrație" request_quote: "Cere o ofertă de preț" setup_a_class: "Creează o clasă" have_an_account: "Aveți un cont?" logged_in_as: "În prezent sunteți conectat(ă) ca" computer_science: "Cursurile în ritm personal acoperă de la sintaxa de bază până la concepte avansate" ffa: "Gratuit pentru toți elevii" coming_soon: "Mai multe vor apărea în curând!" courses_available_in: "Cursurile sunt disponibile în Javascript și Python. Cursurile de Dezvoltare web utilizează HTML, CSS și jQuery." boast: "Se laudă cu ghicitori care sunt suficient de complexe să fascineze jucătorii și programatorii deopotrivă." winning: "O combinație câștigătoare de joc RPG și temă la programare care conduce la o educație prietenoasă și cu adevărat distractivă pentru copii." run_class: "Tot ceea ce ai nevoie pentru a ține clasa de informatică în școala ta astăzi, nu este nevoie de cunoștințe în CS." goto_classes: "Vezi clasa mea" view_profile: "Vezi profilul meu" view_progress: "Vezi progres" go_to_courses: "Vezi cursurile mele" want_coco: "Vrei CodeCombat în școala ta?" educator: "Instructor" student: "Elev" our_coding_programs: "Programele noastre de programare" codecombat: "CodeCombat" ozaria: "Ozaria" codecombat_blurb: "Jocul nostru de scriere cod original. Recomndat pentru părinți, persoane, instructori și elevi care doresc să experimenteze unul dintre jocurile de programare cel mai iubit din lume." ozaria_blurb: "Un joc de aventură și program de informatică unde elevii stăpânesc magia pierdută a codului pentru a salva lumea. Recomndat pentru instructori și elevi." try_codecombat: "Încearcă CodeCombat" try_ozaria: "Încearcă Ozaria" explore_codecombat: "Explorează CodeCombat" explore_ai_league: "Explorează liga IA" explore_ozaria: "Explorează Ozaria" explore_online_classes: "Explorează clasele online" explore_pd: "Explorează dezvoltarea profesională" new_adventure_game_blurb: "Ozaria este noul nostru joc de aventură nou-nouț și soluția ta la cheie pentru predare informaticii. Notele noastre pentru elevi __slides__ și pentru profesori fac ca planificarea și prezentarea lecțiilor să fie ușoară și rapidă." lesson_slides: "fișe lecții" pd_blurb: "Învață abilitățile necesare pentru predarea efectivă a informaticiicu cursul nostru de dezvoltare profesională auto-direcționat și acreditat CSTA. Obține 40 de ore în credite în orice moment, de pe orice dispozitiv. Face pereche bună cu clasele Ozaria." ai_league_blurb: "scrierea de cod în mediu competitiv nu a fost niciodată mai eroică cu aceste ligi educaționale de e-sport, care sunt în același timp niște simulatoare de lupă IA unice cât și motoare de joc pentru a învățarea scrierii de cod real." codecombat_live_online_classes: "Clase online în timp real CodeCombat" learning_technology_blurb: "Jocul nostru original învață aptitudini din lumea reală prin puterea jocului. Curicula bine construită construiește în mod sistematic experiența și cunoștințele elevului în timp ce ei progresează." learning_technology_blurb_short: "Tehnologia noastră inovativă bazată pe joc a transformat modul în care elevii învață să scrie cod." online_classes_blurb: "Clasele noastre online de sciere cod combină puterea jocului și instrucțiunile personalizate pentru o experiență pe care copilul tău nu o va îndrăgi. Cu cele două opțiuni disponibile, private sau de grup, acestea sunt sistemele de învățare la distanță care merg." for_educators: "Pentru instructori" for_parents: "Pentru părinți" for_everyone: "Pentru toată lumea" what_our_customers_are_saying: "Ce zic clienții noștri" game_based_learning: "Învățare pe bază de joc" unique_approach_blurb: "Cu abordarea noastră unică, elevii adoptă învățarea în timp ce joacă și scriu cod încă de la începutul aventurii lor, promovând învățarea activă și îmbunătățirea modului de a gândi." text_based_coding: "Programare pe bază de text" custom_code_engine_blurb: "Motorul și interpretorul nostru personalizat este proiectat pentru începători, pentru învățarea limbajelor de programare reale Python, Javascript și C++ utilizând termeni umani, prietenoase cu începătorii." student_impact: "Impact asupra elevilor" help_enjoy_learning_blurb: "Produsele noastre au ajutat peste 20 de milioane de elevi care s-au bucurat să învețe informatică, învățându-i să fie elevi critici, confidenți și creativi. Noi îi implicăm pe toți elevii, indiferent de experiență, ajutându-i să-și construiască o cale de succes în informatică." global_community: "Alătură-te comunității globale" million: "__num__ milioane" billion: "__num__ bilioane" nav: educators: "Instructori" follow_us: "Urmăriți-ne" general: "General" map: "Hartă" play: "Niveluri" # The top nav bar entry where players choose which levels to play community: "Communitate" courses: "Cursuri" blog: "Blog" forum: "Forum" account: "Cont" my_account: "Contul meu" profile: "Profil" home: "Acasă" contribute: "Contribuie" legal: "Confidențialitate și termeni" privacy: "Notă de confidențialitate" about: "Despre" impact: "Impact" contact: "Contact" twitter_follow: "Urmărește" my_classrooms: "Clasa mea" my_courses: "Cursurile mele" my_teachers: "Profesorii mei" careers: "Cariere" facebook: "Facebook" twitter: "Twitter" create_a_class: "Creează o clasă" other: "Altele" learn_to_code: "Învață să scrii cod!" toggle_nav: "Schimbare navigație" schools: "Școli" get_involved: "Implică-te" open_source: "Open source (GitHub)" support: "Suport" faqs: "Întrebări" copyright_prefix: "Copyright" copyright_suffix: "Toate drepturile rezervate." help_pref: "Ai nevoie de ajutor? Email" help_suff: "și vom lua legătura cu tine!" resource_hub: "Zona de resurse" apcsp: "Principiile AP CS" parent: "Părinți" esports: "E-sporturi" browser_recommendation: "Pentru cea mai bună experință vă recomandăm să utilizați ultima versiune de Chrome. Descarcă navigatorul web de aici!" ozaria_classroom: "Clasa Ozaria" codecombat_classroom: "Clasa CodeCombat" ozaria_dashboard: "Panou de lucru Ozaria" codecombat_dashboard: "Panou de lucru CodeCombat" professional_development: "Dezvoltare profesională" new: "Nou!" admin: "Admin" api_dashboard: "Panou de lucru API" funding_resources_guide: "Ghid resurse de finanțare" modal: close: "Închide" okay: "Okay" cancel: "Anulează" not_found: page_not_found: "Pagina nu a fost gasită" diplomat_suggestion: title: "Ajută la traducrea CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Avem nevoie de abilitățile tale lingvistice." pitch_body: "CodeCombat este dezvoltat în limba engleza, dar deja avem jucători din toate colțurile lumii. Mulți dintre ei vor să joace în română și nu vorbesc engleză. Dacă poți vorbi ambele limbi te rugăm să te gândești dacă ai dori să devi un Diplomat și să ne ajuți să traducem atât jocul cât și site-ul." missing_translations: "Până când nu putem traduce totul în română, vei vedea limba engleză acolo unde limba română nu este displonibilă." learn_more: "Află mai multe despre cum să fi un Diplomat" subscribe_as_diplomat: "Înscrie-te ca Diplomat" new_home_faq: what_programming_languages: "Ce limbaje de programare sunt disponibile?" python_and_javascript: "În prezent lucrăm cu Python și Javascript." why_python: "De ce să alegi Python?" why_python_blurb: "Python este prietenos pentru începători dar este în prezent utilizat de majoritatea corporațiilor (cum este Google). Dacă aveți cursanți mai tineri sau începători, vă recomandăm cu încredere Python." why_javascript: "De ce să alegi Javascript?" why_javascript_blurb: "Javascript este limbajul web și este utilizat în aproape toate site-urile web. Vei prefera să alegi Javascript dacă ai în plan se studiezi dezvoltarea web. Am făcut deasemenea ca tranziția elevilor de la Python la dezvoltarea web pe bază de Javascript să fie ușoară." javascript_versus_python: "Sintaxa Javascript este un pic mai dificilă pentru începători decât cea Python, de aceea dacă nu te poți decide între cele două, noi îți recomandăm Python." how_do_i_get_started: "Cum pot să încep?" getting_started_1: "Creează un cont de profesor" getting_started_2: "Creează o clasă" getting_started_3: "Addaugă elevi" getting_started_4: "Stai și observă elevii cum se delectează învățând să scrie cod" main_curriculum: "Pot utliza CodeCombat sau Ozaria ca și curiculă de bază?" main_curriculum_blurb: "Absolut! Am alocat timp consultațiilor cu specialiștii în educație pentru a dezvola curicule pentru clasă și materiale special concepute pentru profesorii care utilizează CodeCombat sau Ozaria fără ca aceștia să aibă cunoștințe prealabile de informatică. Multe școli implementează CodeCombat și/sau Ozaria ca și curiculă de bază pentru informatică." clever_instant_login: "CodeCombat și Ozaria au suport pentru Clever Instant Login?" clever_instant_login_blurb: "Da! Verifică __clever__ pentru mai multe detalii cum să începi." clever_integration_faq: "Întrebări despre integrarea Clever" google_classroom: "Dar Google Classroom?" google_classroom_blurb1: "Da! Fi sigur că utilizezi Google Single Sign-On (SSO) Modal pentru a te înregistra în contul tău de profesor. Dacă deja ai un cont pe care îl utilizezi pentru Google email, utilizează Google SSO modal pentru a te autentifica următoarea dată. În Creează Class modal, vei găsi o opțiune să faci legătura cu Google Classroom. În prezent avem suport numai pentru Google Classroom rostering." google_classroom_blurb2: "Notă: trebuie să utilizezi Google SSO să te autentifici sau să te autentifici măcar o dată pentru a vedea opțiunile de integrare Google Classroom." how_much_does_it_cost: "Cât de mult costă să acesez toate cursurile și resursele disponibile?" how_much_does_it_cost_blurb: "Personalizăm soluțiile pentru școli și districte și vom lucra cu tine pentru a înțelege cerința de utilizare, contextul și bugetul. __contact__ pentru mai multe detalii! Vezi de asemenea __funding__ pentru informații cu privire la accesarea surselor de finanțare CARES Act cum sunt ESSER și GEER." recommended_systems: "Există o recomandare cu privire la navigatorul web și la sistemul de operare?" recommended_systems_blurb: "CodeCombat și Ozaria rulează cel mai bine pe calculatoare cu cel puțin 4GB de RAM, pe navigatoare web moderne cum sunt Chrome, Safari, Firefox sau Edge. Chromebooks cu 2GB de RAM pot avea probleme minore de grafică în cursurile mai avansate. Un minim de 200 Kbps lățime de bandă pentru fiecare elev este necesară, deși este recomandat 1+ Mbps." other_questions: "Dacă ai și alte întrebări, te rog __contact__." play: title: "Joacă nivelele CodeCombat - Învață Python, Javascript și HTML" meta_description: "Învață programare cu un joc de scris cod pentru începători. Învață Python și Javascript în timp ce rezolvi labirinturi, Creează propriile jocuri și crește-ți nivelul. Provoacă prietenii în nivelurile din arena multi-utilizator!" level_title: "__level__ - Învață să scrii cod în Python, Javascript, HTML" video_title: "__video__ | Nivel video" game_development_title: "__level__ | Dezvoltare jocuri" web_development_title: "__level__ | Dezvoltare web" anon_signup_title_1: "CodeCombat are o" anon_signup_title_2: "versiune pentru clasă!" anon_signup_enter_code: "Introdu codul de clasă:" anon_signup_ask_teacher: "Nu ai unul? întreabă profesorul!" anon_signup_create_class: "Vrei să creezi o clasă?" anon_signup_setup_class: "Creează o clasă, adaugă elevii și monitorizează progresul!" anon_signup_create_teacher: "Creează un cont de profesor gratuit" play_as: "Joacă ca" # Ladder page get_course_for_class: "Alocă Dezvoltarea de jocuri și altele la clasa ta!" request_licenses: "Contactează specialiștii noștri școlari pentru detalii." compete: "Concurează!" # Course details page spectate: "Spectator" # Ladder page simulate_all: "Simulează totul" players: "jucători" # Hover over a level on /play hours_played: "ore jucate" # Hover over a level on /play items: "Articole" # Tooltip on item shop button from /play unlock: "Deblochează" # For purchasing items and heroes confirm: "Confirmă" owned: "Deținute" # For items you own locked: "Blocate" available: "Disponibile" skills_granted: "Abilități acordate" # Property documentation details heroes: "Eroi" # Tooltip on hero shop button from /play achievements: "Realizări" # Tooltip on achievement list button from /play settings: "Setări" # Tooltip on settings button from /play poll: "Sondaj" # Tooltip on poll button from /play next: "Următorul" # Go from choose hero to choose inventory before playing a level change_hero: "Schimbă eroul" # Go back from choose inventory to choose hero change_hero_or_language: "Schimbă eroul sau limba" buy_gems: "Cumpără pietre prețioase" subscribers_only: "Doar pentru abonați!" subscribe_unlock: "Pentru deblocare abonează-te!" subscriber_heroes: "Abonează-te azi pentru a debloca imediat Amara, Hushbaum și Hattori!" subscriber_gems: "Abonează-te azi pentru a cumpăra acest erou cu pietre prețioase!" anonymous: "Jucător anonim" level_difficulty: "Dificultate: " awaiting_levels_adventurer_prefix: "Lansăm niveluri noi în fiecare săptămână." awaiting_levels_adventurer: "Înscrie-te ca aventurier " awaiting_levels_adventurer_suffix: "pentru a fi primul care joacă nivele noi." adjust_volume: "Reglează volumul" campaign_multiplayer: "Arene multi-jucător" campaign_multiplayer_description: "... în care lupți cot-la-cot contra altor jucători." brain_pop_done: "Ai înfrânt căpcăunii cu codul tău! Ai învins!" brain_pop_challenge: "Ca și provocare joacă din nou utilizând un limbaj de programare diferit!" replay: "Joacă din nou" back_to_classroom: "Înapoi la clasă" teacher_button: "Pentru profesori" get_more_codecombat: "Mai mult CodeCombat" code: if: "dacă" # Keywords--these translations show up on hover, so please translate them all, even if it's kind of long. (In the code editor, they will still be in English.) else: "altfel" elif: "altfel dacă" while: "atăta timp cât" loop: "buclă" for: "pentru" break: "oprește" continue: "continuă" pass: "pass" return: "întoarce" then: "atunci" do: "execută" end: "sfârșit" function: "funcție" def: "definește" var: "variabilă" self: "se referă la el însuși" hero: "erou" this: "acesta (aceasta)" or: "sau" "||": "sau" and: "și" "&&": "și" not: "not (negație)" "!": "not (negație)" "=": "atribuie" "==": "egal cu" "===": "strict egal cu" "!=": "nu este egal cu" "!==": "nu este strict egal cu" ">": "mai mare decât" ">=": "mai mare sau egal decât" "<": "mai mic decât" "<=": "mai mic sau egal cu" "*": "înmulțit cu" "/": "împărțit la" "+": "plus" "-": "minus" "+=": "adaugă și atribuie" "-=": "scade și atribuie" True: "Adevărat" true: "adevărat" False: "Fals" false: "fals" undefined: "nedefinit" null: "Zero/Fără valoare cand nu este obiect" nil: "Zero/Fără valoare pentru obiecte" None: "Nici unul/una" share_progress_modal: blurb: "Faci progrese mari! Spune-le părinților cât de mult ai învățat cu CodeCombat." email_invalid: "Adresă email invalidă." form_blurb: "Introdu adresa email al unui părinte mai jos și le vom arăta!" form_label: "Adresă email" placeholder: "adresă email" title: "Excelentă treabă, ucenicule" login: sign_up: "Creează cont" email_or_username: "Email sau nume de utilizator" log_in: "Conectare" logging_in: "Se conectează" log_out: "Deconectare" forgot_password: "Ai uitat parola?" finishing: "Terminare" sign_in_with_facebook: "Conectează-te cu Facebook" sign_in_with_gplus: "Conectează-te cu Google" signup_switch: "Dorești să creezi un cont?" accounts_merge_confirmation: "Există un cont asociat cu adresa de email a acestui cont Google. Vrei să unim aceste conturi?" signup: complete_subscription: "Completează abonamentul" create_student_header: "Creează cont elev" create_teacher_header: "Creează cont profesor" create_individual_header: "Creează cont individual" email_announcements: "Primește anunțuri despre niveluri și îmbunătățiri ale CodeCombat!" sign_in_to_continue: "Conectează-te sau creează un cont pentru a continua" create_account_to_submit_multiplayer: "Creează un cont gratuit pentru a-ți clasifica IA multi-jucător și explorează tot jocul!" teacher_email_announcements: "Înformează-mă cu noutățile despre noi resurse pentru profesori, curicule și coursuri!" creating: "Se creează contul..." sign_up: "Înscrie-te" log_in: "conectează-te cu parolă" login: "Conectare" required: "Trebuie să te înregistrezi înaite să mergi mai departe." login_switch: "Ai deja un cont?" optional: "opțional" connected_gplus_header: "Te-ai conectat cu succes cu Google+!" connected_gplus_p: "Termină înregistrarea pentru a te putea autentifica cu contul Google+." connected_facebook_header: "Te-ai conectat cu succes cu Facebook!" connected_facebook_p: "Termină înregistrarea pentru a te putea autentifica cu contul Facebook." hey_students: "Elevi, introduceți codul clasei dat de profesor." birthday: "Ziua de naștere" parent_email_blurb: "Știm că abia aștepți să înveți programare &mdash; și noi suntem nerăbdători! Părinții tăi vor primi un email cu detalii despre cum să îți creeze un cont. Trimite email {{email_link}} dacă ai întrebări." classroom_not_found: "Nu există clase cu acest cod de clasă. Verifică ceea ce ai scris sau întreabă profesorul pentru ajutor." checking: "Verificare..." account_exists: "Acest e-mail este deja utilizat:" sign_in: "Autentificare" email_good: "Email-ul arată bine!" name_taken: "Nume de utilizator deja folosit! Încearcă {{suggestedName}}?" name_available: "Nume utilizator disponibil!" name_is_email: "Nume de utilizator nu poate fi o adresă email" choose_type: "Alege tipul de cont:" teacher_type_1: "Predă programare utilizând CodeCombat!" teacher_type_2: "Creează clasa" teacher_type_3: "Instrucțiuni accesare curs" teacher_type_4: "Vezi progresul elevilor" signup_as_teacher: "Autentificare profesor" student_type_1: "Învață să programezi în timp ce joci un joc captivant!" student_type_2: "Joacă cu clasa ta" student_type_3: "Concurează în arenă" student_type_4: "Alege eroul!" student_type_5: "Pregătește codul de clasă!" signup_as_student: "Autentificare ca elev" individuals_or_parents: "Persoane & Părinți" individual_type: "Pentru jucători care învață să scrie cod în afara unei clase. Părinții trebuie să se înregistreze pentru un cont aici." signup_as_individual: "Înregistrare persoană" enter_class_code: "Introdu codul de clasă" enter_birthdate: "Introdu data nașterii:" parent_use_birthdate: "Părinți, utilizați data dvs de naștere." ask_teacher_1: "Întreabă profesorul despre codul de clasă." ask_teacher_2: "Nu ești parte dintr-o clasă? Creează un" ask_teacher_3: "cont individual" ask_teacher_4: " în loc." about_to_join: "Ești pe cale să te alături:" enter_parent_email: "Introdu adresa de email a părintelui dvs .:" parent_email_error: "Ceva a mers greșit când am încercat să trimitem email. Verifică adresa de email și mai încearcă o dată." parent_email_sent: "Am trimis un email cu instrucțiuni cum să creezi un cont. Roagă părinții să-și verifice căsuța de email." account_created: "Cont creat!" confirm_student_blurb: "Notează pe ceva informațiile pentru a nu le uita. Profesorul tău te poate ajuta să îți resetezi parola în orice moment." confirm_individual_blurb: "Notează pe ceva informațiile de autentificare în caz că vei avea nevoie de ele mai târziu. Verifică căsuța de email ca să îți poți recupera contul dacă îți vei uita parola - verifică căsuța de email!" write_this_down: "Notează asta:" start_playing: "Începe jocul!" sso_connected: "Conectare reușită cu:" select_your_starting_hero: "Alege eroul de început:" you_can_always_change_your_hero_later: "Poți schimba eroul mai târziu." finish: "Termină" teacher_ready_to_create_class: "Ești gata să creezi prima ta clasă!" teacher_students_can_start_now: "Elevii vor putea să înceapă să joace primul curs, Introducere în informatică, immediat." teacher_list_create_class: "În următorul ecran vei putea crea o nouă clasă." teacher_list_add_students: "Adaugă elevi la clasă la link-ul Vezi clasă, apoi trimite elevilor codul de clasă sau URL-ul. Poți de asemenea să îi inviți prin email dacă aceștia au adrese de email." teacher_list_resource_hub_1: "Verifică" teacher_list_resource_hub_2: "Ghidurile de curs" teacher_list_resource_hub_3: "pentru soluțiile fiecărui nivel și " teacher_list_resource_hub_4: "Zona de resurse " teacher_list_resource_hub_5: "pentru ghiduri privind curicula, activitățile și altele!" teacher_additional_questions: "Asta e tot! Dacă ai nevoie de mai mult ajutor sau ai întrebări, contactează-ne la __supportEmail__." dont_use_our_email_silly: "Nu scrie adresa noastră de email aici! Pune adresa de email a unui părinte." want_codecombat_in_school: "Vrei să joci CodeCombat tot timpul?" eu_confirmation: "Sunt de acord să permit CodeCombat să stocheze datele mele pe un server din SUA." eu_confirmation_place_of_processing: "Află mai multe despre riscuri posibile." eu_confirmation_student: "Dacă nu ești sigur, întreabă-ți profesorul." eu_confirmation_individual: "Dacă nu vrei să îți păstrăm datele pe serverele din SUA, poți juca tot timpul în mod anonim fără salvarea codului scris." password_requirements: "de la 8 până la 64 de caractere fără repetare" invalid: "Invalid" invalid_password: "Parolă invalidă" with: "cu" want_to_play_codecombat: "Nu, nu am una dar vreau să joc CodeCombat!" have_a_classcode: "Ai un cod de clasă?" yes_i_have_classcode: "Da, am un cod de clasă!" enter_it_here: "Introdu codul aici:" recover: recover_account_title: "Recuperează cont" send_password: "Trimite parolă de recuperare" recovery_sent: "Email de recuperare trimis." items: primary: "Primar" secondary: "Secundar" armor: "Armură" accessories: "Accesorii" misc: "Diverse" books: "Cărți" common: default_title: "CodeCombat - Jocuri de scris cod pentru a învăța Python și Javascript" default_meta_description: "Învață să scrii cod prin programarea unui joc. Învață Python, Javascript și HTML ca și când ai rezolva puzzle-uri și învață să îți faci propriile jocuri și site-uri web." back: "Înapoi" # When used as an action verb, like "Navigate backward" coming_soon: "în curând!" continue: "Continuă" # When used as an action verb, like "Continue forward" next: "Următor" default_code: "Cod implicit" loading: "Se încarcă..." overview: "Prezentare generală" processing: "Procesare..." solution: "Soluţie" table_of_contents: "Cuprins" intro: "Introducere" saving: "Se salvează..." sending: "Se trimite..." send: "Trimite" sent: "Trimis" cancel: "Anulează" save: "Salvează" publish: "Publică" create: "Creează" fork: "Fork" play: "Joacă" # When used as an action verb, like "Play next level" retry: "Reîncearcă" actions: "Acţiuni" info: "Info" help: "Ajutor" watch: "Urmărește" unwatch: "Nu mai urmări" submit_patch: "Trimite patch" submit_changes: "Trimite modificări" save_changes: "Salvează modificări" required_field: "obligatoriu" submit: "Transmite" replay: "Rejoacă" complete: "Complet" pick_image: "Alege imagine" general: and: "și" name: "Nume" date: "Dată" body: "Corp" version: "Versiune" pending: "În așteptare" accepted: "Acceptat" rejected: "Respins" withdrawn: "Retras" accept: "Acceptă" accept_and_save: "Acceptă și salvează" reject: "Respinge" withdraw: "Retrage" submitter: "Expeditor" submitted: "Expediat" commit_msg: "Înregistrează mesajul" version_history: "Istoricul versiunilor" version_history_for: "Istoricul versiunilor pentru: " select_changes: "Selectați două schimbări de mai jos pentru a vedea diferenţa." undo_prefix: "Undo" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Redo" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Joaca previzualizarea nivelului curent" result: "Rezultat" results: "Rezultate" description: "Descriere" or: "sau" subject: "Subiect" email: "Email" password: "Parolă" confirm_password: "Confirmă parola" message: "Mesaj" code: "Cod" ladder: "Clasament" when: "când" opponent: "oponent" rank: "Rang" score: "Scor" win: "Victorie" loss: "Înfrângere" tie: "Remiză" easy: "Ușor" medium: "Mediu" hard: "Greu" player: "Jucător" player_level: "Nivel" # Like player level 5, not like level: Dungeons of Kithgard warrior: "Războinic" ranger: "Arcaș" wizard: "Vrăjitor" first_name: "Prenume" last_name: "Nume" last_initial: "Inițială nume" username: "Nume de utilizator" contact_us: "Contactează-ne" close_window: "Închide fereastra" learn_more: "Află mai mult" more: "Mai mult" fewer: "Mai puțin" with: "cu" chat: "Chat" chat_with_us: "Vorbește cu noi" email_us: "Trimite-ne email" sales: "Vânzări" support: "Suport" here: "aici" units: second: "secundă" seconds: "secunde" sec: "sec" minute: "minut" minutes: "minute" hour: "oră" hours: "ore" day: "zi" days: "zile" week: "săptămână" weeks: "săptămâni" month: "lună" months: "luni" year: "an" years: "ani" play_level: back_to_map: "Înapoi la hartă" directions: "Direcții" edit_level: "Modifică nivel" keep_learning: "Continuă să înveți" explore_codecombat: "Explorează CodeCombat" finished_hoc: "Am terminat Hour of Code" get_certificate: "Obține certificatul!" level_complete: "Nivel terminat" completed_level: "Nivel terminat:" course: "Curs:" done: "Terminat" next_level: "Următorul nivel" combo_challenge: "Provocare combinată" concept_challenge: "Provocare concept" challenge_unlocked: "Provocare deblocată" combo_challenge_unlocked: "Provocare combinată deblocată" concept_challenge_unlocked: "Provocare concept deblocată" concept_challenge_complete: "Provocare concept terminată!" combo_challenge_complete: "Provocare combinată terminată!" combo_challenge_complete_body: "Foarte bine, se pare că stai foarte bine în înțelegerea __concept__!" replay_level: "Joacă din nou nivelul" combo_concepts_used: "__complete__/__total__ concepte utilizate" combo_all_concepts_used: "Ai utilizat toate conceptele posibile pentru a rezolva provocarea. Foarte bine!" combo_not_all_concepts_used: "Ai utilizat __complete__ din __total__ concepte posibile pentru a rezolva provocarea. Încearcă să utilizezi toate cele __total__ concepte următoarea dată!" start_challenge: "Start provocare" next_game: "Următorul joc" languages: "Limbi" programming_language: "Limbaj de programare" show_menu: "Arată meniul jocului" home: "Acasă" # Not used any more, will be removed soon. level: "Nivel" # Like "Level: Dungeons of Kithgard" skip: "Sări peste" game_menu: "Meniul Jocului" restart: "Restart" goals: "Obiective" goal: "Obiectiv" challenge_level_goals: "Obiectivele nivelului tip provocare" challenge_level_goal: "Obiectivul nivelului tip provocare" concept_challenge_goals: "Obiectivele provocării concept" combo_challenge_goals: "Obiectivele provocării combinate" concept_challenge_goal: "Obiectivul provocării concept" combo_challenge_goal: "Obiectivul provocării combinate" running: "Rulează..." success: "Success!" incomplete: "Incomplet" timed_out: "Ai rămas fără timp" failing: "Eşec" reload: "Reîncarcă" reload_title: "Reîncarcă tot codul?" reload_really: "Ești sigur că vrei să reîncarci nivelul de la început?" reload_confirm: "Reîncarca tot" restart_really: "Ești sigur că vrei să joci din nou nivelul? Vei pierde tot codul pe care l-ai scris." restart_confirm: "Da, joc din nou" test_level: "Nivel de test" victory: "Victorie" victory_title_prefix: "" victory_title_suffix: " Terminat" victory_sign_up: "Înscrie-te pentru a salva progresul" victory_sign_up_poke: "Vrei să-ți salvezi codul? Creează un cont gratuit!" victory_rate_the_level: "Cât de amuzant a fost acest nivel?" victory_return_to_ladder: "Înapoi la clasament" victory_saving_progress: "Salvează progresul" victory_go_home: "Mergi acasă" victory_review: "Spune-ne mai multe!" victory_review_placeholder: "Cum a fost nivelul?" victory_hour_of_code_done: "Ai terminat?" victory_hour_of_code_done_yes: "Da, am terminat Hour of Code™!" victory_experience_gained: "Ai câștigat XP" victory_gems_gained: "Ai câștigat pietre prețioase" victory_new_item: "Articol nou" victory_new_hero: "Erou nou" victory_viking_code_school: "Oau, acesta a fost un nivel greu! Daca nu ești deja un dezvoltator de software, ar trebui să fi. Tocmai ai fost selectat pentru acceptare în Viking Code School, unde poți să îți dezvolți abilitățile la nivelul următor și să devi un dezvoltator web profesionist în 14 săptămâni." victory_become_a_viking: "Devin-o Viking" victory_no_progress_for_teachers: "Progresul nu este salvat pentru profesori. Dar, poți adăuga un cont de elev la clasa ta pentru tine." tome_cast_button_run: "Execută" tome_cast_button_running: "În execuție" tome_cast_button_ran: "S-a executat" tome_cast_button_update: "Actualizare" tome_submit_button: "Trimite" tome_reload_method: "Reîncarcă codul original pentru a restarta nivelul" tome_your_skills: "Abilitățile tale" hints: "Indicii" videos: "Filme" hints_title: "Indiciul {{number}}" code_saved: "Cod salvat" skip_tutorial: "Sări peste (esc)" keyboard_shortcuts: "Scurtături tastatură" loading_start: "Începe nivel" loading_start_combo: "Începe provocarea combinată" loading_start_concept: "Începe provocarea concept" problem_alert_title: "Repară codul" time_current: "Acum:" time_total: "Max:" time_goto: "Mergi la:" non_user_code_problem_title: "Imposibil de încărcat nivel" infinite_loop_title: "Buclă infinită detectată" infinite_loop_description: "Codul inițial pentru a construi lumea nu a terminat de rulat niciodată. Este probabil foarte lent sau are o buclă infinită. Sau ar putea fi o eroare de programare. Poți încerca să executați acest cod din nou sau să resetezi codul la starea implicită. Dacă nu se remediază, te rog să ne anunți." check_dev_console: "Puteți deschide, de asemenea, consola de dezvoltator pentru a vedea ce ar putea merge greșit." check_dev_console_link: "(instrucțiuni)" infinite_loop_try_again: "Încearcă din nou" infinite_loop_reset_level: "Resetează nivelul" infinite_loop_comment_out: "Comentează codul meu" tip_toggle_play: "schimbă între joacă/pauză cu Ctrl+P." tip_scrub_shortcut: "Utilizează Ctrl+[ și Ctrl+] pentru a derula înapoi sau a da pe repede înainte." tip_guide_exists: "Apasă pe ghid, din meniul jocului (din partea de sus a paginii), pentru informații utile." tip_open_source: "CodeCombat este parte a comunității open source!" tip_tell_friends: "Îți place CodeCombat? Spune-le prietenilor tăi despre noi!" tip_beta_launch: "CodeCombat a fost lansat în format beta în Octombrie 2013." tip_think_solution: "Gândește-te la soluție, nu la problemă." tip_theory_practice: "Teoretic nu este nici o diferență înte teorie și practică. Dar în practică este. - Yogi Berra" tip_error_free: "Există doar două metode de a scrie un program fără erori; numai a treia funcționează. - Alan Perlis" tip_debugging_program: "Dacă a face depanare este procesul de a elimina erorile, atunci a programa este procesul de a introduce erori. - Edsger W. Dijkstra" tip_forums: "Mergi la forum și spune-ți părerea!" tip_baby_coders: "În vitor până și bebelușii vor fi Archmage." tip_morale_improves: "Încărcarea va continua până când moralul se va îmbunătăți." tip_all_species: "Noi credem în șanse egale pentru toate speciile pentru a învăța programare." tip_reticulating: "Re-articulăm coloane vertebrale." tip_harry: "Yer a Wizard, " tip_great_responsibility: "Cu o mare abilitate de programare vine și o mare responsabilitate de depanare." tip_munchkin: "Dacă nu iți mănânci legumele, un munchkin va veni după tine când dormi." tip_binary: "Sunt doar 10 tipuri de oameni în lume: cei ce înteleg sistemul binar și ceilalți." tip_commitment_yoda: "Un programator trebuie să aibă cel mai profund angajament, mintea cea mai serioasă. ~Yoda" tip_no_try: "A face. Sau a nu face. Nu există voi încerca. ~Yoda" tip_patience: "Să ai rabdare trebuie, tinere Padawan. ~Yoda" tip_documented_bug: "O eroare (bug) documentată nu e chiar o eroare; este o caracteristică." tip_impossible: "Mereu pare imposibil până când e gata. ~Nelson Mandela" tip_talk_is_cheap: "Vorbele sunt goale. Arată-mi codul. ~Linus Torvalds" tip_first_language: "Cel mai dezastruos lucru pe care poți să îl înveți este primul limbaj de programare. ~Alan Kay" tip_hardware_problem: "Întrebare: De câți programatori ai nevoie ca să schimbi un bec? Răspuns: Niciunul, e o problemă de hardware." tip_hofstadters_law: "Legea lui Hofstadter: Mereu durează mai mult decât te aștepți, chiar dacă iei în considerare Legea lui Hofstadter." tip_premature_optimization: "Optimizarea prematură este rădăcina tuturor răutăților. ~Donald Knuth" tip_brute_force: "Atunci cănd ești în dubii, folosește forța brută. ~Ken Thompson" tip_extrapolation: "Există doar două feluri de oameni: cei care pot extrapola din date incomplete..." tip_superpower: "Programarea este cel mai apropiat lucru de o superputere." tip_control_destiny: "În open source, ai dreptul de a-ți controla propiul destin. ~Linus Torvalds" tip_no_code: "Niciun cod nu e mai rapid decat niciun cod." tip_code_never_lies: "Codul nu minte niciodată, commenturile mai mint. ~Ron Jeffries" tip_reusable_software: "Înainte ca un software să fie reutilizabil, trebuie să fie mai întâi utilizabil." tip_optimization_operator: "Fiecare limbaj are un operator de optimizare. La majoritatea acela este '//'" tip_lines_of_code: "Măsurarea progresului în lini de cod este ca și măsurarea progresului de construcție a aeronavelor în greutate. ~Bill Gates" tip_source_code: "Vreau să schimb lumea dar nu îmi dă nimeni codul sursă." tip_javascript_java: "Java e pentru Javascript exact ce e o mașina pentru o carpetă. ~Chris Heilmann" tip_move_forward: "Orice ai face, mergi înainte. ~Martin Luther King Jr." tip_google: "Ai o problemă care nu o poți rezolva? Folosește Google!" tip_adding_evil: "Adaugăm un strop de răutate." tip_hate_computers: "Tocmai aia e problema celor care cred că urăsc calulatoarele. Ceea ce urăsc ei de fapt sunt programatorii nepricepuți. ~Larry Niven" tip_open_source_contribute: "Poți ajuta la îmbunătățirea jocului CodeCombat!" tip_recurse: "A itera este uman, recursiv este divin. ~L. Peter Deutsch" tip_free_your_mind: "Trebuie sa lași totul, Neo. Frica, îndoiala și necredința. Eliberează-ți mintea. ~Morpheus" tip_strong_opponents: "Și cei mai puternici dintre oponenți întodeauna au o slăbiciune. ~Itachi Uchiha" tip_paper_and_pen: "Înainte să începi să scrii cod, poți tot mereu să planific mai întâi pe o foaie de hârtie cu un creion." tip_solve_then_write: "Mai întâi, rezolvă problema. Apoi, scrie codul. - John Johnson" tip_compiler_ignores_comments: "Câteodată cred că compilatorul îmi ignoră comentariile." tip_understand_recursion: "Singura modalitate de a înțelege recursivitatea este să înțelegi recursivitatea." tip_life_and_polymorphism: "Open Source este ca o structură total polimorfică și eterogenă: Toate tipurile sun primite." tip_mistakes_proof_of_trying: "Greșelile din codul tău sunt dovezi că încerci." tip_adding_orgres: "Scurtăm niște căpcăuni." tip_sharpening_swords: "Ascuțim săbiile." tip_ratatouille: "Nu trebuie să lași pe nimeni să-ți definească limitele pe baza locului de unde vi. Singura ta limită este sufletul tău. - Gusteau, Ratatouille" tip_nemo: "Când viața te pune la pământ, vrei să ști ce trebuie să faci? Doar continuă să înoți, doar continuă să înoți. - Dory, Finding Nemo" tip_internet_weather: "Mută-te pe Internet, este minunat aici. Ajungem să trăim înauntru unde vremea este tot mereu frumoasă. - John Green" tip_nerds: "Tocilarilor le este permis să iubească lucruri, ca de exemplu sări-sus-și-jos-în-scaun-nu-te-poți-controla. - John Green" tip_self_taught: "M-am învățat singur 90% din ceea ce am învățat. Și așa e normal! - Hank Green" tip_luna_lovegood: "Nu-ți face griji, ești la fel de sănătos la minte ca și mine. - Luna Lovegood" tip_good_idea: "Modalitatea cea mai bună de a avea o idee bună este să ai multe idei. - Linus Pauling" tip_programming_not_about_computers: "În informatică nu mai este vorba doar despre calculatoare așa cum în astronomie nu e vorba doar despre telescoape. - Edsger Dijkstra" tip_mulan: "Crede că poți și atunci vei putea. - Mulan" project_complete: "Proiect terminat!" share_this_project: "Partajează acest proiect cu prietenii și familia:" ready_to_share: "Gata să îți publici proiectul?" click_publish: "Apasă \"Publică\" pentru a-l face să apară în galeria clasei, apoi verifică ce au făcut colegii! Te poți întoarce să continui să lucrezi la acest proiect. Orice schimbare viitoare va fi automat salvată și partajată cu colegii tăi." already_published_prefix: "Modificările tale au fost publicate în galeria clasei." already_published_suffix: "Continuă să experimentezi și să îmbunătățești acest proiect, sau vezi ceea ce au construit restul colegilor! Modificările tale vor fi automat salvate și partajate cu colegii tăi." view_gallery: "Vezi galeria" project_published_noty: "Nivelul tău a fost publicat!" keep_editing: "Continuă să modifici" learn_new_concepts: "Învață noi concepte" watch_a_video: "Urmărește un video despre __concept_name__" concept_unlocked: "Concept deblocat" use_at_least_one_concept: "Utilizează cel puțin un concept: " command_bank: "Banca de comenzi" learning_goals: "Obiectivele învățării" start: "Start" vega_character: "Personaj Vega" click_to_continue: "Apasă pentru a continua" fill_in_solution: "Completează cu soluția" play_as_humans: "Joacă ca om" play_as_ogres: "Joacă ca căpcăun" apis: methods: "Metode" events: "Evenimente" handlers: "Handler-e" properties: "Proprietăți" snippets: "Fragmente" spawnable: "Generabil" html: "HTML" math: "Mate" array: "Matrice" object: "Obiect" string: "Șir de caractere" function: "Funcție" vector: "Vector" date: "Dată" jquery: "jQuery" json: "JSON" number: "Număr" webjavascript: "Javascript" amazon_hoc: title: "Continuă să înveți cu Amazon!" congrats: "Felicitări în câștigarea provocărilor din Hour of Code!" educate_1: "Acum, continuă să înveți despre scrieres codului și despre cloud computing cu AWS Educate, un program gratuit și captivant de la Amazon atât pentru cursanți cât și pentru profesori. Cu AWS Educate, poți câștiga insigne virtuale când înveți despre noțiunile de bază din cloud și despre tehnologiile de ultimă generație cum sunt jocurile, realitatea virtuală și Alexa." educate_2: "Învață mai multe și înregistrează-te aici" future_eng_1: "Poți să încerci să construiești abilități noi pentru Alexa legate de fapte școlare" future_eng_2: "aici" future_eng_3: "(echipamentul nu este necesar). Această activitate cu Alexa este prezentată de" future_eng_4: "Amazon Future Engineer (Viitorii Ingineri Amazon)" future_eng_5: "un program care creează oportunități pentru învățare și munncă pentru toți elevii K-12 din Statele Unite care doresc să urmeze o carieră în informatică." live_class: title: "Mulțumesc!" content: "Uimitor! Tocmai am lansat clase on-line în timp real." link: "Ești pregătit să mergi mai departe cu programarea?" code_quest: great: "Minunat!" join_paragraph: "Alătură-te celui mai mare turneu internațional de programare Python IA pentru toate vârstele și concurează pentru a ajunge în vârful tabelei de scor! Această bătălie globală de o lună, începe pe 1 August și include premii în valoare de $5k și o ceremonie virtuală de decernare a premiilor unde vom anunța câștigătorii și vom recunoaște abilitățile voastre de a scrie cod." link: "Apasă aici pentru înregistrare și mai multe detalii" global_tournament: "Turneu global" register: "Înregistrare" date: "1 Aug - 31 Aug" play_game_dev_level: created_by: "Creat de {{name}}" created_during_hoc: "Creat în timpul Hour of Code" restart: "Reîncepe nivel" play: "Joacă nivel" play_more_codecombat: "Joacă mai mult CodeCombat" default_student_instructions: "Apasă pentru a controla eroul și a câștiga jocul!" goal_survive: "Supraviețuiește." goal_survive_time: "Supraviețuiește pentru __seconds__ secunde." goal_defeat: "Învinge toți inamicii." goal_defeat_amount: "Învinge __amount__ inamici." goal_move: "Mergi la toate marcajele cu X." goal_collect: "Colectează toate obiectele." goal_collect_amount: "Ai colectat __amount__ obiecte." game_menu: inventory_tab: "Inventar" save_load_tab: "Salvează/Încarcă" options_tab: "Opțiuni" guide_tab: "Ghid" guide_video_tutorial: "Tutorial Video" guide_tips: "Sfaturi" multiplayer_tab: "Multiplayer" auth_tab: "Înscriere" inventory_caption: "Echipează eroul" choose_hero_caption: "Alege eroul, limba" options_caption: "Configurare setări" guide_caption: "Documentație și sfaturi" multiplayer_caption: "Joacă cu prietenii!" auth_caption: "Salvează progresul." leaderboard: view_other_solutions: "Vezi tabelul de clasificare" scores: "Scoruri" top_players: "Top jucători după" day: "Azi" week: "Săptămâna aceasta" all: "Tot timpul" latest: "Ultimul" time: "Timp" damage_taken: "Vătămare primită" damage_dealt: "Vătămare oferită" difficulty: "Dificultate" gold_collected: "Aur colectat" survival_time: "Supraviețuit" defeated: "Inamici înfrânți" code_length: "Linii de cod" score_display: "__scoreType__: __score__" inventory: equipped_item: "Echipat" required_purchase_title: "Necesar" available_item: "Disponibil" restricted_title: "Restricționat" should_equip: "(dublu-click pentru echipare)" equipped: "(echipat)" locked: "(blocat)" restricted: "(restricționat în acest nivel)" equip: "Echipează" unequip: "Dezechipează" warrior_only: "Doar războinic" ranger_only: "Doar arcaș" wizard_only: "Doar vrăjitor" buy_gems: few_gems: "Căteva pietre prețioase" pile_gems: "Morman de pietre prețioase" chest_gems: "Cufăr cu pietre prețioase" purchasing: "Cumpărare..." declined: "Cardul tău a fost refuzat." retrying: "Eroare de server, reîncerc." prompt_title: "Nu sunt destule pietre prețioase." prompt_body: "Vrei să cumperi mai multe?" prompt_button: "Intră în magazin." recovered: "Pietre prețioase cumpărate anterior recuperate. Vă rugăm să reîncărcați pagina." price: "x{{gems}} / lună" buy_premium: "Cumpără premium" purchase: "Cumpără" purchased: "Cumpărat" subscribe_for_gems: prompt_title: "Pietre prețioase insuficiente!" prompt_body: "Abonează-te la Premium pentru a obține pietre prețioase și pentru a accesa chiar mai multe niveluri!" earn_gems: prompt_title: "Pietre prețioase insuficiente" prompt_body: "Continuă să joci pentru a câștiga mai multe!" subscribe: best_deal: "Cea mai bună afacere!" confirmation: "Felicitări! Acum ai abonament CodeCombat Premium!" premium_already_subscribed: "Ești deja abonat la Premium!" subscribe_modal_title: "CodeCombat Premium" comparison_blurb: "Devino un Master Coder - abonează-te la varianta <b>Premium</b> azi! " must_be_logged: "Trebuie să te conectezi mai întâi. Te rugăm să creezi un cont sau să te conectezi din meniul de mai sus." subscribe_title: "Abonare" # Actually used in subscribe buttons, too unsubscribe: "Dezabonare" confirm_unsubscribe: "Confirmă dezabonarea" never_mind: "Nu contează, eu tot te iubesc!" thank_you_months_prefix: "Mulțumesc pentru sprijinul acordat în aceste" thank_you_months_suffix: "luni." thank_you: "Mulțumim pentru susținerea CodeCombat!" sorry_to_see_you_go: "Ne pare rău că pleci! Te rugăm să ne spui ce am fi putut face mai bine." unsubscribe_feedback_placeholder: "Of, ce am făcut?" stripe_description: "Abonament lunar" stripe_yearly_description: "Abonament anual" buy_now: "Cumpără acum" subscription_required_to_play: "Ai nevoie de abonament ca să joci acest nivel." unlock_help_videos: "Abonează-te pentru deblocarea tuturor tutorialelor video." personal_sub: "Abonament personal" # Accounts Subscription View below loading_info: "Se încarcă informațile despre abonament..." managed_by: "Gestionat de" will_be_cancelled: "Va fi anulat pe" currently_free: "În prezent ai un abonament gratuit" currently_free_until: "În prezent ai un abonament până pe" free_subscription: "Abonament gratuit" was_free_until: "Ai avut un abonament gratuit până pe" managed_subs: "Abonamente Gestionate" subscribing: "Te abonăm..." current_recipients: "Recipienți curenți" unsubscribing: "Dezabonare..." subscribe_prepaid: "Apasă pe abonare pentru a folosi un cod preplătit" using_prepaid: "Foloseste cod preplătit pentru un abonament lunar" feature_level_access: "Accesează peste 500+ de nivele disponibile" feature_heroes: "Deblochează eroi exclusivi și animăluțe de companie" feature_learn: "Învață să creezi jocuri și site-uri web" feature_gems: "Primește __gems__ pietre prețioase pe lună" month_price: "$__price__" # {change} first_month_price: "Doar $__price__ pentru prima lună!" lifetime: "Acces pe viață" lifetime_price: "$__price__" year_subscription: "Abonament anual" year_price: "$__price__/an" # {change} support_part1: "Ai nevoie de ajutor cu plata sau preferi PayPal? Email" support_part2: "support@codecombat.com" announcement: now_available: "Acum disponibil pentru abonați!" subscriber: "abonat" cuddly_companions: "Animăluțe drăguțe!" # Pet Announcement Modal kindling_name: "Kindling Elemental" kindling_description: "Kindling Elemental-ii vor doar să îți țină de cald noaptea. Și în timpul zilei. Toto timpul, pe cuvânt." griffin_name: "Pui de grifon" griffin_description: "Grifonii sunt jumătate vultur, jumătate leu, foarte adorabili." raven_name: "Corb" raven_description: "Corbii sunt excelenți la adunarea sticluțelor pline cu poțiune de sănătate." mimic_name: "Mim" mimic_description: "Mimii pot aduna monede pentru tine. Pune-i peste monede pentru a crește provizia de aur." cougar_name: "Puma" cougar_description: "Pumelor le place să își ia PhD prin Purring Happily Daily.(joc de cuvinte)" fox_name: "Vulpea albastră" fox_description: "Vulpile albastre sunt foarte istețe și le place să sape în pământ și zăpadă!" pugicorn_name: "Pugicorn" pugicorn_description: "Pugicornii sunt cele mai rare creaturi care pot face vrăji!" wolf_name: "Pui de lup" wolf_description: "Puii de lup sunt foarte buni la vânătoare, culegere și fac un joc răutăcios de-a fața-ascunselea!" ball_name: "Minge roșie chițăitoare" ball_description: "ball.squeak()" collect_pets: "Adună animăluțe pentru eroul tău!" each_pet: "Fiecare animăluț are o abilitate unică de a te ajuta!" upgrade_to_premium: "Devino un {{subscriber}} pentru a echipa animăluțele." play_second_kithmaze: "Joacă {{the_second_kithmaze}} pentru a debloca puiul de lup!" the_second_kithmaze: "Al doilea Kithmaze" keep_playing: "Continuă să joci pentru a descoperi primul animăluț!" coming_soon: "În curând" ritic: "Ritic al frigului" # Ritic Announcement Modal ritic_description: "Ritic al frigului. Prins în capcana ghețarului Kelvintaph de nenumărați ani, este în sfârșit liber și pregătit să aibă grijă de căpcăunii care l-au închis." ice_block: "Un bloc de gheață" ice_description: "Pare să fie ceva prins în interior ..." blink_name: "Blink" blink_description: "Ritic dispare și apare într-o clipire de ochi, lăsând în urmă doar umbră." shadowStep_name: "Shadowstep" shadowStep_description: "Un assasin maestru care știe să umble printre umbre." tornado_name: "Tornado" tornado_description: "Este bine să ai un buton de reset când acoperirea cuiva este spulberată." wallOfDarkness_name: "Zidul Întunericului" wallOfDarkness_description: "Se ascunde în spatele unui zid de umbră pentru a evita privirile." avatar_selection: pick_an_avatar: "Alege un avatar care te reprezintă ca și jucător" premium_features: get_premium: "Cumpără<br>CodeCombat<br>Premium" # Fit into the banner on the /features page master_coder: "Devino un master al codului abonându-te azi!" paypal_redirect: "Vei fi redirecționat către PayPal pentru a finaliza procesul de abonare." subscribe_now: "Abonează-te acum" hero_blurb_1: "Obține acces la __premiumHeroesCount__ de eroi super dotați disponibili doar pentru abonați! Valorifică puterea de neoprit a lui Okar Stompfoot, precizia mortală a lu Naria of the Leaf, sau cheamă \"adorable\" scheleți cu Nalfar Cryptor." hero_blurb_2: "Luptătorii premium deblochează arte marțiale uimitoare ca Warcry, Stomp și Hurl Enemy. Sau, joacă ca și Arcaș, utilizând procedee ascunse și arcuri, aruncarea de cuțite, capcane! Încearcă-ți aptitudinile ca Vrăjitor și eliberează o serie de magii puternice ca Primordial, Necromantic sau Elemental!" hero_caption: "Noi eroi impresionanți!" pet_blurb_1: "Animăluțele nu sunt numai companioni adorabili, ei furnizează funcții și metode unice. Piul de grifon poate căra trupe prin aer, puiul de lup joacă prinselea cu săgeține inamicilor, pumei îi place să fugărească căpcăuni iar Mim-ul atrage monedele ca magnetul!" pet_blurb_2: "Adună toate animăluțele pentru a descoperi abilitățile lor unice!" pet_caption: "Adoptă animăluțe care să îl însoțească pe eroul tău!" game_dev_blurb: "Învață game scripting și construiește noi nivele pe care să le partajezi cu prietenii tăi! Pune obiectele pe care le dorești, scrie cod pentru unitatea logică și de comportament și vezi dacă prietenii pot să termine nivelul!" game_dev_caption: "Dezvoltă propriile jocuri pentru a-ți provoca prietenii!" everything_in_premium: "Tot ceea ce vei obține în CodeCombat Premium:" list_gems: "Primești pietre prețioase bonus pentru cumpărarea echipamentului, animaăluțelor și eroilor" list_levels: "Obții acces la __premiumLevelsCount__ alte niveluri" list_heroes: "Deblochează eroi exclusivi, care cuprind clasele Arcaș și Vrăjitor" list_game_dev: "Creează și partajează jocuri cu prietenii" list_web_dev: "Construiește site-uri web și aplicații interactive" list_items: "Echipează-te cu elemente specifice premium cum sunt animăluțele" list_support: "Primește suport de tip premium pentru a te ajuta să rezolvi situațiile încâlcite" list_clans: "Creează clanuri private în care să inviți prieteni și concurează într-un clasament de grup" choose_hero: choose_hero: "Alege eroul" programming_language: "Limbaj de programare" programming_language_description: "Ce limbaj de programare vrei să folosești?" default: "Implicit" experimental: "Experimental" python_blurb: "Simplu dar puternic, minunat atât pentru începători cât și pentru experți" javascript_blurb: "Limbajul web-ului. (Nu este același lucru ca Java.)" coffeescript_blurb: "Javascript cu o syntaxă mai placută!" lua_blurb: "Limbaj de scripting pentru jocuri." java_blurb: "(Numai pentru abonați) Android și pentru afaceri." cpp_blurb: "(Numai pentru abonați) Dezvoltare de jocuri și calcul de înaltă performanță." status: "Stare" weapons: "Armament" weapons_warrior: "Săbii - Distanță scurtă, Fără magie" weapons_ranger: "Arbalete, Pistoale - Distanță mare, Fără magie" weapons_wizard: "Baghete, Toiege - Distanță mare, Magie" attack: "Atac" # Can also translate as "Attack" health: "Viață" speed: "Viteză" regeneration: "Regenerare" range: "Rază" # As in "attack or visual range" blocks: "Blochează" # As in "this shield blocks this much damage" backstab: "Înjunghiere" # As in "this dagger does this much backstab damage" skills: "Abilități" attack_1: "Oferă" attack_2: "din cele listate" attack_3: "Vătămare cu arma." health_1: "Primește" health_2: "din cele listate" health_3: "Stare armură." speed_1: "Se deplasează cu" speed_2: "metri pe secundă." available_for_purchase: "Disponibil pentru cumpărare" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Nivel ce trebuie deblocat:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see) restricted_to_certain_heroes: "Numai anumiți eroi pot juca acest nivel." char_customization_modal: heading: "Personalizează eroul" body: "Corp" name_label: "Nume erou" hair_label: "Culoare păr" skin_label: "Culoare piele" skill_docs: function: "funcție" # skill types method: "metodă" snippet: "fragment" number: "număr" array: "matrice" object: "obiect" string: "șir de caractere" writable: "permisiuni de scriere" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "permisiuni doar de citire" action: "Acțiune" spell: "Vrajă" action_name: "nume" action_cooldown: "Durează" action_specific_cooldown: "Răcire" action_damage: "Vătămare" action_range: "Raza de acțiune" action_radius: "Raza" action_duration: "Durata" example: "Exemplu" ex: "ex" # Abbreviation of "example" current_value: "Valoare curentă" default_value: "Valoare implicită" parameters: "Parametrii" required_parameters: "Parametrii necesari" optional_parameters: "Parametrii opționali" returns: "Întoarce" granted_by: "Acordat de" still_undocumented: "Încă nedocumentat, ne pare rău." save_load: granularity_saved_games: "Salvate" granularity_change_history: "Istoric" options: general_options: "Opțiuni Generale" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volum" music_label: "Muzică" music_description: "Oprește/pornește muzica din fundal." editor_config_title: "Configurare editor" editor_config_livecompletion_label: "Autocompletare live" editor_config_livecompletion_description: "Afișează sugesti de autocompletare în timp ce scri." editor_config_invisibles_label: "Arată etichetele invizibile" editor_config_invisibles_description: "Arată spațiile și taburile invizibile." editor_config_indentguides_label: "Arată ghidul de indentare" editor_config_indentguides_description: "Arată linii verticale pentru a vedea mai bine indentarea." editor_config_behaviors_label: "Comportamente inteligente" editor_config_behaviors_description: "Completează automat parantezele, ghilimele etc." about: title: "Despre CodeCombat - Elevi pasionați, Profesori implicați, Creații inspirate" meta_description: "Misiunea noastră este să ridicăm nivelul informaticii prin învățarea bazată pe joc și să facem programarea accesibilă fiecărui elev. Noi credem că programarea este magică și vrem că le dăm elevilor puterea de a crea lucruri din imaginație." learn_more: "Află mai multe" main_title: "Dacă vrei să înveți să programezi, trebuie să scrii (foarte mult) cod." main_description: "La CodeCombat, rolul nostru este să ne asigurăm că vei face acest lucru cu zâmbetul pe față." mission_link: "Misiune" team_link: "Echipă" story_link: "Poveste" press_link: "Presă" mission_title: "Misiunea noastră: să facem programarea accesibilă fiecărui elev de pe Pământ." mission_description_1: "<strong>Programarea este magică</strong>. Este abilitatea de a creea lucruri din imaginație. Am pornit CodeCombat pentru a-i face pe cursanți să simtă că au puteri magice la degetul lor mic utilizând <strong>cod scris</strong>." mission_description_2: "Dupăc cum am văzut, acest lucru îi face să învețe să scrie cod mai repede. MULT MAI rapid. Este ca și când am avea o conversație în loc de a citi un manual. Vrem să aducem această conversație în fiecare școală și la <strong>fiecare elev</strong>, deoarece toată lumea ar trebui să aibă o șansă să învețe magia programării." team_title: "Întâlnește echipa CodeCombat" team_values: "Punem preș pe dialoguș deschis și respectuos, în care cea mai bună idee câștigă. Deciziile noastre sun bazate pe cercetarea consumatorilor iar procesul nostru pune accent pe livrarea resultatelor tangibile pentru ei. Toată lumea luCreează la asta, de la CEO la contributorii noștri GitHub, deoarece noi în echipa noastră punem valoare pe creștere și dezvoltare ." nick_title: "Co-fondator, CEO" # csr_title: "Customer Success Representative" # csm_title: "Customer Success Manager" # scsm_title: "Senior Customer Success Manager" # ae_title: "Account Executive" # sae_title: "Senior Account Executive" # sism_title: "Senior Inside Sales Manager" # shan_title: "Head of Marketing, CodeCombat Greater China" # run_title: "Head of Operations, CodeCombat Greater China" # lance_title: "Head of Technology, CodeCombat Greater China" # zhiran_title: "Head of Curriculum, CodeCombat Greater China" # yuqiang_title: "Head of Innovation, CodeCombat Greater China" swe_title: "Inginer software" sswe_title: "Infiner senior software" css_title: "Specialist suport clienți" css_qa_title: "Suport clienți / Specialis întrebări/răspunsuri" maya_title: "Dezvoltator senior de curiculă" bill_title: "Manager general, CodeCombat Greater China" pvd_title: "Designer vizual și de produs" spvd_title: "Designer senior vizual și de produs" daniela_title: "Manager de marketing" bobby_title: "Dezvoltator joc" brian_title: "Manager senior de dezvoltare joc" stephanie_title: "Specialist suport clienți" # sdr_title: "Sales Development Representative" retrostyle_title: "Ilustrator" retrostyle_blurb: "Jocuri în stil retro" community_title: "...și comunitatea noastră open-source" bryukh_title: "Dezvoltator Senior de joc" # oa_title: "Operations Associate" ac_title: "Coordonator administrativ" ea_title: "Asistent executiv" om_title: "Manager de operații" mo_title: "Manager, Operații" smo_title: "Manager senior, Operații" do_title: "Director de operații" scd_title: "Dezvoltator senior de curiculă" lcd_title: "Dezvoltator șef de curiculă" de_title: "Director de educație" vpm_title: "VP, Marketing" oi_title: "Instructor online " # bdm_title: "Business Development Manager" community_subtitle: "Peste 500 de colaboratori au ajutat la dezvoltarea CodeCombat, numărul acestora crescând în fiecare săptămână!" community_description_3: "CodeCombat este un" community_description_link_2: "proiect colectiv" community_description_1: "cu sute de jucători care se oferă voluntar să creeze noi niveluri, contribuie la codul nostru pentru a adauga componente, a repara erori, a testa jocuri și a traduce jocul în peste 50 de limbi până în prezent. Angajații, contribuabilii și câștigurile aduse de site prin partajarea ideilor dar și un efort comun, așa cum face comunitatea open-source în general. Site-ul este construit pe numeroase proiecte open-source, și suntem deschiși să dăm înapoi comunității și să furnizăm jucătorilor curioși în privința codului un proiect familiar de examinat și experimentat. Oricine se poate alătura comunității CodeCombat! Verifică" community_description_link: "pagina cu cei care au contribuit" community_description_2: "pentru mai multe informații." number_contributors: "Peste 450 contributori și-au adus suportul și timpul la acest proiect." story_title: "Povestea noastră până în prezent" story_subtitle: "Din 2013, CodeCombat a crescut de la un simplu set de schițe la un joc palpitan care continuă să crească." story_statistic_1a: "20,000,000+" story_statistic_1b: "de jucători" story_statistic_1c: "și-au început călătoria în lumea programării prin CodeCombat" story_statistic_2a: "Am tradus în peste 50 de limbi — asta a venit de la jucătorii noștri" story_statistic_2b: "190+ țări" story_statistic_3a: "Împreună, ei au scris" story_statistic_3b: "1 bilion de linii de cod care încă crește" story_statistic_3c: "în diferite limbaje de programare" story_long_way_1: "Cu toate că am parcurs un drum lung..." story_sketch_caption: "cu schița lui Nick care prezenta un joc de programare în acțiune." story_long_way_2: "încă mai avem multe de făcut până ne terminăm misiunea, de aceea..." jobs_title: "Vin-o să lucrezi cu noi și ajută la scrierea istoriei CodeCombat!" jobs_subtitle: """Nu vezi unde te-ai puta încadra dar ai dori să păstrăm legătura? Vezi lista \"Creează propria\".""" jobs_benefits: "Beneficiile angaților" jobs_benefit_4: "Vacanță nelimitată" jobs_benefit_5: "Suport pentru dezvoltare profesională și educație continuă – cărți gratuite și jocuri!" jobs_benefit_6: "Medical (gold), dental, oftamologic, navetist, 401K" jobs_benefit_7: "Birouri de lucru pentru toți" # jobs_benefit_9: "10-year option exercise window" # jobs_benefit_10: "Maternity leave: 12 weeks paid, next 6 @ 55% salary" # jobs_benefit_11: "Paternity leave: 12 weeks paid" # jobs_custom_title: "Create Your Own" jobs_custom_description: "ești un pasionat de CodeCombat dar nu vezi un job care să corespundă calificărilor tale? scrie-ne și arată-ne cum crezi tu că poți contribui la echipa noastră. Ne-ar face plăcere să auzim toate acestea!" jobs_custom_contact_1: "Trimite-ne o notă la" jobs_custom_contact_2: "cu prezentarea ta și poate vom lua legătura în viitor!" contact_title: "Presă & Contact" contact_subtitle: "Ai nevoie de mai multe informații? Ia legătura cu noi la" screenshots_title: "Capturi de ecran din joc" screenshots_hint: "(apasă să vezi în dimensiune maximă)" downloads_title: "Descarcă Download Assets & Information" about_codecombat: "Despre CodeCombat" logo: "Logo" screenshots: "Capturi de ecran" character_art: "Arta caracterului" download_all: "Descarcă tot" previous: "Anterior" location_title: "Suntem localizați în centrul SF:" teachers: licenses_needed: "Sunt necesare licențe" special_offer: special_offer: "Ofertă specială" project_based_title: "Cursuri bazate pe proiecte" project_based_description: "Cursuri de dezvoltare web și de jocuri cu posibilități de partajare a proiectelor finale." great_for_clubs_title: "Ideale pentru cluburi și grupuri școlare" great_for_clubs_description: "Profesorii pot cumpăra până la __maxQuantityStarterLicenses__ licențe de pornire." low_price_title: "Doar __starterLicensePrice__ de cursant" low_price_description: "Licențele de pornire sunt active pentru __starterLicenseLengthMonths__ de luni de la cumpărare." three_great_courses: "Trei cursuri deosebite sunt incluse în licența de pornire:" license_limit_description: "Profesorii pot cumpăra până la __maxQuantityStarterLicenses__ licențe de pornire. Ai cumpărat deja __quantityAlreadyPurchased__. Dacă dorești mai multe, contactează-ne la __supportEmail__. Licențele de pornire sunt valabile pentru __starterLicenseLengthMonths__ de luni." student_starter_license: "Licențe de pornire pentru cursanți" purchase_starter_licenses: "Cumpără licențe de pornire" purchase_starter_licenses_to_grant: "Cumpără licențe de pornire pentru a avea acces la __starterLicenseCourseList__" starter_licenses_can_be_used: "Licențele de pornire pot fi utilizate pentru asignarea de cursuri adiționale imediat după cumpărare." pay_now: "Plătește acum" we_accept_all_major_credit_cards: "Acceptăm marea majoritate a cardurilor de credit." cs2_description: "construite pe fundamentele obținute la cursul Introducere în informatică, cu accent pe instrucțiuni if, funcții, evenimete și altele." wd1_description: "introduce elemente de bază de HTML și CSS în timp ce pregătește abilitățile cursanților necesare pentru dezvoltarea propriei pagini web." gd1_description: "utilizează sintaxe cu care cursanții sunt deja familiarizați pentru a le arăta cum să construiască și să partajeze propriul nivel de joc." see_an_example_project: "vezi un exemplu de proiect" get_started_today: "Începe astăzi!" want_all_the_courses: "Vrei toate cursurile? Cere informații despre licențele complete." compare_license_types: "Compară licențele după tip:" cs: "Informatică" wd: "Dezvoltare web" wd1: "Dezvolare web 1" gd: "Dezvolatre de joc" gd1: "Dezvoltare de joc 1" maximum_students: "Număr maxim # de cursanți" unlimited: "Nelimitat" priority_support: "Suport prioritar" yes: "Da" price_per_student: "__price__ pe cursant" pricing: "Preț" free: "Gratuit" purchase: "Cumpără" courses_prefix: "Cursuri" courses_suffix: "" course_prefix: "Curs" course_suffix: "" teachers_quote: subtitle: "Învață mai multe despre CodeCombat cu un tur interactiv al produsului, al prețului și al implementării acestuia!" email_exists: "Există utilizator cu această adresă de email." phone_number: "Număr de telefon" phone_number_help: "Care este cel mai bun număr la care să te contactăm?" primary_role_label: "Rolul tău primar" role_default: "Alege rol" primary_role_default: "Selectează rol primar" purchaser_role_default: "Selectează rolul tău ca și cumpărător" tech_coordinator: "Coordonator tehnologic" advisor: "Specialist/Consilier de curiculă" principal: "Director" superintendent: "Administrator" parent: "Părinte" purchaser_role_label: "Rolul tău ca și cumpărător" influence_advocate: "Formator de opinii/Susținător" evaluate_recommend: "Evaluează/Recomandă" approve_funds: "Aprobare fonduri" no_purchaser_role: "Nici un rol în decizia de cumpărare" district_label: "județ" district_name: "Nume județ" district_na: "scrie N/A dacă nu se aplică" organization_label: "Școală" school_name: "Numele școlii" city: "Oraș" state: "Sat / Regiune" country: "Țară / Regiune" num_students_help: "Câți elevi vor utiliza CodeCombat?" num_students_default: "Selectează intervalul" education_level_label: "Nivelul de educație al elevilor" education_level_help: "Alege pe toate care se aplică." elementary_school: "Școala primară" high_school: "Liceu" please_explain: "(te rog explică)" middle_school: "Școala gimnazială" college_plus: "Facultate sau mai sus" referrer: "Cum ai auzit despre noi?" referrer_help: "De exemplu: de la un alt profesor, o conferință, elevi, Code.org etc." referrer_default: "Alege una" referrer_conference: "Conferință (ex. ISTE)" referrer_hoc: "Code.org/Hour of Code" referrer_teacher: "Un profesor" referrer_admin: "Un administrator" referrer_student: "Un student" referrer_pd: "Pregătire profesională/Grup de lucru" referrer_web: "Google" referrer_other: "Altele" anything_else: "Pentru ce clasă anticipezi că vei utiliza CodeCombat?" anything_else_helper: "" thanks_header: "Cerere primită!" thanks_sub_header: "Mulțumim de interesul arătat în utilizarea CodeCombat în școala ta." thanks_p: "Vă vom contacta curând! Dacă dorești să ne contacteză, poți ajunge la noi prin:" back_to_classes: "Înapoi la clase" finish_signup: "Contul tău de utilizator a fost creat:" finish_signup_p: "Creează un cont pentru a creea o clasă, adaugă elevii și monitorizează progresul acestora în timp ce aceștia învață informatică." signup_with: "Autentificare cu:" connect_with: "Connectare cu:" conversion_warning: "AVERIZARE: Contul tău curent este un <em>Cont de elev</em>. După ce transmiți acest formular, contul tău va fi transformat într-un cont de profesor." learn_more_modal: "Conturile de profesor din CodeCombat au posibilitatea de a monitoriza progresul elevilor, a aloca licențe și să administreze clase. Conturile de profesor nu pot fi parte dintr-o clasă - dacă sunteți deja parte dintr-o clasă cu acest cont, nu o veți mai putea accesa după ce îl transformați în cont de profesor." create_account: "Creează un cont de profesor" create_account_subtitle: "Obține acces la unelte specifice profesorilor pntru a utiliza CodeCombat în clasă. <strong>Creează o clasă</strong>, adaugă elevii și <strong>monitorizează progresul lor</strong>!" convert_account_title: "Transformă în cont de profesor" not: "Nu" full_name_required: "Numele și prenumele sunt obligatorii" versions: save_version_title: "Salvează noua versiune" new_major_version: "Versiune nouă majoră" submitting_patch: "Trimitere Patch..." cla_prefix: "Pentru a salva modificările mai intâi trebuie sa fiți de acord cu" cla_url: "CLA" cla_suffix: "." cla_agree: "SUNT DE ACORD" owner_approve: "Un proprietar va trebui să aprobe înainte ca modificările să devină vizibile." contact: contact_us: "Contact CodeCombat" welcome: "Folosiți acest formular pentru a ne trimite email. " forum_prefix: "Pentru orice altceva vă rugăm să încercați " forum_page: "forumul nostru" forum_suffix: " în schimb." faq_prefix: "Există și un" faq: "FAQ" subscribe_prefix: "Daca ai nevoie de ajutor ca să termini un nivel te rugăm să" subscribe: "cumperi un abonament CodeCombat" subscribe_suffix: "și vom fi bucuroși să te ajutăm cu codul." subscriber_support: "Din moment ce ești un abonat CodeCombat, adresa ta de email va primi sprijinul nostru prioritar." screenshot_included: "Screenshot-uri incluse." where_reply: "Unde ar trebui să răspundem?" send: "Trimite Feedback" account_settings: title: "Setări Cont" not_logged_in: "Loghează-te sau Creează un cont nou pentru a schimba setările." me_tab: "Eu" picture_tab: "Poză" delete_account_tab: "Șterge contul" wrong_email: "Email greșit" wrong_password: "parolă greșită" delete_this_account: "Ștergere permanetă a acestui cont" reset_progress_tab: "Resetare progres" reset_your_progress: "Șterge tot progresul și începe din nou" god_mode: "Mod Dumnezeu" emails_tab: "Email-uri" admin: "Admin" manage_subscription: "Apasă aici pentru a administra abonamentele." new_password: "Parolă nouă" new_password_verify: "Verifică" type_in_email: "scrie adresa de email ca să confirmi ștergerea" type_in_email_progress: "scrie adresa de email pentru a confirma ștergerea progresului." type_in_password: "De asemenea, scrie și parola." email_subscriptions: "Subscripție email" email_subscriptions_none: "Nu ai subscripții email." email_announcements: "Anunțuri" email_announcements_description: "Primește email-uri cu ultimele știri despre CodeCombat." email_notifications: "Notificări" email_notifications_summary: "Control pentru notificări email personalizate, legate de activitatea CodeCombat." email_any_notes: "Orice notificări" email_any_notes_description: "Dezactivați pentru a opri toate email-urile de notificare a activității." email_news: "Noutăți" email_recruit_notes: "Oportunități de angajare" email_recruit_notes_description: "Dacă joci foarte bine, este posibil sa te contactăm pentru obținerea unui loc (mai bun) de muncă." # contributor_emails: "Contributor Class Emails" contribute_prefix: "Căutăm oameni să se alăture distracției! Intră pe " contribute_page: "pagina de contribuție" contribute_suffix: " pentru a afla mai multe." email_toggle: "Alege tot" error_saving: "Salvare erori" saved: "Modificări salvate" password_mismatch: "Parola nu se potrivește." password_repeat: "Te rugăm să repeți parola." keyboard_shortcuts: keyboard_shortcuts: "Scurtături tastatură" space: "Space" enter: "Enter" press_enter: "apasă enter" escape: "Escape" shift: "Shift" run_code: "Rulează codul." run_real_time: "Rulează în timp real." # continue_script: "Continue past current script." skip_scripts: "Treci peste toate script-urile ce pot fi sărite." toggle_playback: "Comută play/pause." scrub_playback: "Mergi înainte și înapoi în timp." single_scrub_playback: "Mergi înainte și înapoi în timp cu un singur cadru." scrub_execution: "Mergi prin lista curentă de vrăji executate." toggle_debug: "Comută afișaj depanare." toggle_grid: "Comută afișaj grilă." toggle_pathfinding: "Comută afișaj pathfinding." beautify: "Înfrumusețează codul standardizând formatarea lui." maximize_editor: "Mărește/Minimizează editorul." cinematic: click_anywhere_continue: "apasă oriunde pentru a continua" community: main_title: "Comunitatea CodeCombat" introduction: "Vezi metode prin care poți să te implici și tu mai jos și decide să alegi ce ți se pare cel mai distractiv. De abia așteptăm să lucrăm împreună!" level_editor_prefix: "Folosește CodeCombat" level_editor_suffix: "Pentru a crea și a edita niveluri. Utilizatorii au creat niveluri pentru clasele lor, prieteni, hackathonuri, studenți și rude. Dacă crearea unui nivel nou ți se pare intimidant poți să modifici un nivel creat de noi!" thang_editor_prefix: "Numim unitățile din joc 'thangs'. Folosește" thang_editor_suffix: "pentru a modifica ilustrațile sursă CodeCombat. Permitele unităților să arunce proiectile, schimbă direcția unei animații, schimbă viața unei unități, sau încarcă propiile sprite-uri vectoriale." article_editor_prefix: "Vezi o greșeală în documentația noastă? Vrei să documentezi instrucțiuni pentru propiile creații? Vezi" article_editor_suffix: "și ajută jucătorii CodeCombat să obțină căt mai multe din timpul lor de joc." find_us: "Ne găsești pe aceste site-uri" social_github: "Vezi tot codul nostru pe GitHub" social_blog: "Citește blogul CodeCombat pe Sett" # {change} social_discource: "Alătură-te discuțiilor pe forumul Discourse" social_facebook: "Lasă un Like pentru CodeCombat pe facebook" social_twitter: "Urmărește CodeCombat pe Twitter" social_slack: "Vorbește cu noi pe canalul public de Slack CodeCombat" contribute_to_the_project: "Contribuie la proiect" clans: title: "Alătură-te clanurilor CodeCombat - Învață să scrii cod în Python, Javascript și HTML" clan_title: "__clan__ - Alătură-te clanurilor CodeCombat și învață să scrii cod" meta_description: "Alătură-te unui clan pentru a-ți construi propria comunitate de programatori. Joacă nivele multi-jucător în arenă și urcă nivelul eroului tău și al abilităților tale de programare." clan: "Clan" clans: "Clanuri" new_name: "Nume nou de clan" new_description: "Descrierea clanului nou" make_private: "Fă clanul privat" subs_only: "numai abonați" create_clan: "Creează un clan nou" private_preview: "Previzualizare" private_clans: "Clanuri private" public_clans: "Clanuri Publice" my_clans: "Clanurile mele" clan_name: "Numele Clanului" name: "Nume" chieftain: "Căpetenie" edit_clan_name: "Editează numele clanului" edit_clan_description: "Editează descrierea clanului" edit_name: "editează nume" edit_description: "editează descriere" private: "(privat)" summary: "Sumar" average_level: "Nivel mediu" average_achievements: "realizare medie" delete_clan: "Șterge Clan" leave_clan: "Pleacă din Clan" join_clan: "Intră în Clan" invite_1: "Invitație:" invite_2: "*Invită jucători în acest clan trimițând acest link." members: "Membri" progress: "Progres" not_started_1: "neînceput" started_1: "început" complete_1: "complet" exp_levels: "Extinde niveluri" rem_hero: "Șterge Eroul" status: "Stare" complete_2: "Complet" started_2: "Început" not_started_2: "Neînceput" view_solution: "Apasă pentru a vedea soluția." view_attempt: "Apasă pentru a vedea încercarea." latest_achievement: "Ultimile realizări" playtime: "Timp de joc" last_played: "Ultima oară când ai jucat" leagues_explanation: "Joacă într-o ligă împotriva altor membri de clan în aceste instanțe de arenă multi-jucător." track_concepts1: "Conceptele traseului" track_concepts2a: "învățat de fiecare elev" track_concepts2b: "învățat de fiecare membru" track_concepts3a: "Urmărește nivelurile completate de fiecare elev" track_concepts3b: "Urmărește nivelurile completate de fiecare membru" track_concepts4a: "Vezi soluțiile elevilor" # The text is too fragmented and it does not have sense in Romanian. I added track_concepts5 to this track_concepts4b: "Vezi soluțiile membrilor" # I added track_concepts5 to this track_concepts5: "" track_concepts6a: "Sortează elevii după nume sau progres" track_concepts6b: "Sortează membrii după nume sau progres" track_concepts7: "Necesită invitație" track_concepts8: "pentru a te alătura" private_require_sub: "Clanurile private necesită un abonament pentru a le creea sau a te alătura unuia." courses: create_new_class: "Creează o nouă clasă" hoc_blurb1: "Încearcă" hoc_blurb2: "scrie cod, Joacă, Partajează" hoc_blurb3: "ca și activități! Construiește patru mini-jocuri diferite pentru a învăța bazele dezvoltării jocurilor, apoi creează unul singur!" solutions_require_licenses: "Soluțiile nivelurilor sunt disponibile profesorilor care au licențe." unnamed_class: "Clasă fără nume" edit_settings1: "Modifică setările clasei" add_students: "Adaugă elevi" stats: "Statistici" student_email_invite_blurb: "Elevii tăi pot utiliza codul de clasă <strong>__classCode__</strong> când creează un cont de elevt, nu este necesară o adresă email." total_students: "Total elevi:" average_time: "Timpul mediu de joc pe nivel:" total_time: "Timpul total de joc:" average_levels: "Media nivelurilor terminate:" total_levels: "Total niveluri terminate:" students: "Elevi" concepts: "Concepte" play_time: "Timp de joc:" completed: "Terminate:" enter_emails: "Separați fiecare adresă de email printr-o linie nouă sau virgulă" send_invites: "Invită elevi" number_programming_students: "Număr de elevi care programează" number_total_students: "Total elevi în școală/Județ" enroll: "Înscriere" enroll_paid: "Înscrie elevi la cursuri plătite" get_enrollments: "Cumpără mai multe licențe" change_language: "Schimbă limba cursului" keep_using: "Continuă să utilizezi" switch_to: "Schimbă" greetings: "Salutări!" back_classrooms: "Înapoi la clasa mea" back_classroom: "Înapoi la clasă" back_courses: "Înapoi la cursurile mele" edit_details: "Modifică detaliile clasei" purchase_enrollments: "Cumpără licențe pentru elevi" remove_student: "șterge elevi" assign: "Alocă" to_assign: "pentru a aloca la cursurile plătite." student: "Elev" teacher: "Profesor" arena: "Arenă" available_levels: "Niveluri disponibile" started: "începute" complete: "terminate" practice: "încearcă" required: "obligatorii" welcome_to_courses: "Aventurier, bine ai venit la CodeCombat!" ready_to_play: "Ești gata să joci?" start_new_game: "Începe un joc nou" play_now_learn_header: "Joacă acum ca să înveți" play_now_learn_1: "sintaxa de bază utilizată la controlarea personajului" play_now_learn_2: "bucle while pentru a rezolva puzzle-uri dificile" play_now_learn_3: "șiruri de caractere & variabile pentru a personaliza acțiunile" play_now_learn_4: "cum să înfrângi un căpcăun (o abilitate importantă pentru viață!)" my_classes: "Clase curente" class_added: "Clasă adăugată cu succes!" view_map: "vezi harta" view_videos: "vezi filme" view_project_gallery: "vezi proiectele colegilor" join_class: "Alătură-te unei clase" join_class_2: "Alătură-te clasei" ask_teacher_for_code: "Întreabă profesorul dacă ai un cod de clasă CodeCombat! Dacă ai, scrie codul aici:" enter_c_code: "<scrie codul clasei>" join: "Alătură-te" joining: "intrare în clasă" course_complete: "Curs terminat" play_arena: "Joacă în arenă" view_project: "Vezi proiect" start: "Start" last_level: "Ultimul nivel jucat" not_you: "Nu ești tu?" continue_playing: "Continuă să joci" option1_header: "Invită elevi prin email" remove_student1: "Șterge elev" are_you_sure: "Ești sigur că vrei să ștergi acest elev din clasă?" remove_description1: "Elevul va pierde accesul la această clasă și la celelalte clase alocate. Progresul și jocurile făcute NU se pierd, iar elevul va putea fi adăugat la loc în clasă oricând." remove_description2: "Licențele plătite și activate nu pot fi returnate." license_will_revoke: "Licența acestui elev va fi revocată și va deveni disponibilă pentru alocarea unui alt elev." keep_student: "păstrează elev" removing_user: "Ștergere elev" subtitle: "Analizează prezentarea cursului și nivelurilor" # Flat style redesign select_language: "Alege limba" select_level: "Alege nivel" play_level: "Joacă nivel" concepts_covered: "Concepte acoperite" view_guide_online: "Prezentare nivel și soluții" lesson_slides: "Fișe lecție" grants_lifetime_access: "Permite accesul la toate cursurile." enrollment_credits_available: "licențe disponibile:" language_select: "Alege o limbă" # ClassroomSettingsModal language_cannot_change: "Limba nu mai poate fi schimbată după ce elevii se alătură unei clase." avg_student_exp_label: "Experiența de programare medie a elevului" avg_student_exp_desc: "Acest lucru ne ajută să înțelegem cum să stabilim mai bine ritmul cursului." avg_student_exp_select: "Alege opțiunea cea mai bună" avg_student_exp_none: "Fără experiență - puțină sau fără experiență" avg_student_exp_beginner: "Începător - oarecare expunere sau programare cu blocuri" avg_student_exp_intermediate: "Intermediar - oarecare experință cu scrierea de cod" avg_student_exp_advanced: "Avansat - experineță amplă cu scrierea de cod" avg_student_exp_varied: "Nivele variate de experiență" student_age_range_label: "Interval de vârstă al alevilor" student_age_range_younger: "Mai mici de 6" student_age_range_older: "Mai mari de 18" student_age_range_to: "la" estimated_class_dates_label: "Datele estimate a claselor" estimated_class_frequency_label: "Frecvența estimată a claselor" classes_per_week: "clase pe săptămână" minutes_per_class: "minute pe clasă" create_class: "Creează o clasă" class_name: "Nume clasă" teacher_account_restricted: "Contul tău este un cont de utilizator și nu poate accesa conținut specific elevilor." account_restricted: "Un cont de elev este necesar pentru a accesa această pagină." update_account_login_title: "Autentifică-te pentru a schimba contul" update_account_title: "Contul tău necesită atenție!" update_account_blurb: "Înainte de a accesa clasele, alege cum vei dori să utilizezi acest cont." update_account_current_type: "Tipul contului curent:" update_account_account_email: "Email cont/Utilizator:" update_account_am_teacher: "Sunt un profesor" update_account_keep_access: "Mențien accesul la clasele pe care le-am creat" update_account_teachers_can: "Conturile de profesor pot să:" update_account_teachers_can1: "Creeze/administreze/adauge clase" update_account_teachers_can2: "Aloce/înscrie elevi la cursuri" update_account_teachers_can3: "Deblocheze toate nivelurile de curs pentru încercări" update_account_teachers_can4: "Aceseze elemente noi specifice profesorulu atunci când le lansăm" update_account_teachers_warning: "Atenție: Vei fi șters din toate clasele la care te-ai alăturat anterior și nu vei mai putea juca ca și elev." update_account_remain_teacher: "Rămâi profesor" update_account_update_teacher: "Transformă în profesor" update_account_am_student: "Sunt elev" update_account_remove_access: "Șterge accesul la clasele pe care le-am creat" update_account_students_can: "Conturile de elev pot să:" update_account_students_can1: "Se alăture claselor" update_account_students_can2: "Joace printre cursuri ca elev și să își urmărească progresul" update_account_students_can3: "Concureze împotriva colegilor în arenă" update_account_students_can4: "Aceseze elemente noi specifice elevilor atunci când le lansăm" update_account_students_warning: "Atenție: Nu vei putea administra nici o clasă pe care ai creat-o anterior sau să creezi noi clase." unsubscribe_warning: "Atenție: Vei fi dezabonat de la abonamentul lunar." update_account_remain_student: "Rămâi elev" update_account_update_student: "Transformă în elev" need_a_class_code: "Vei avea nevoie de un cod de clasă pentru a te alătura unei clase:" update_account_not_sure: "Nu ști sigur ce să alegi? Email" update_account_confirm_update_student: "Ești sigur că vrei să transformi contul în unul de elev?" update_account_confirm_update_student2: "Nu vei putea administra nici o clasă pe care ai creat-o anterior sau să creezi noi clase. Clasele create anterior vor fi șterse din CodeCombat și nu mai pot fi recuperate." instructor: "Instructor: " youve_been_invited_1: "AI fost invitat să te alături " youve_been_invited_2: ", unde vei învăța " youve_been_invited_3: " cu colegii de clasă în CodeCombat." by_joining_1: "Dacă te alături " by_joining_2: "vei putea să îți resetezi parola dacă o vei pierde sau uita. Poți de asemenea să îți verifici adresa de email ca să îți resetei parola singur!" sent_verification: "Ți-am trimis un email de verificare la:" you_can_edit: "Poți să modifici adresa de email în " account_settings: "Setări cont" select_your_hero: "Alege eroul" select_your_hero_description: "Poți oricând să schimbi eroul din pagina de Cursuri apăsând \"Schimbă erou\"" select_this_hero: "Alege acest erou" current_hero: "Erou curent:" current_hero_female: "Erou curent:" web_dev_language_transition: "Toate clasele programează în HTML / Javascript la acest curs. Clasele care au utilizat Python vor începe cu niveluri suplimentare de Javascript pentru o tranziție mai ușoară. Clasele care deja utilizează Javascript vor sări peste nivelurile introductive." course_membership_required_to_play: "Trebuie să te alături unui curs pentru a juca acest nivel." license_required_to_play: "Cere profesorului tău să îți asocieze o licență pentru a putea continua să joci CodeCombat!" update_old_classroom: "Un nou an școlar, noi niveluri!" update_old_classroom_detail: "Pentru a fi sigur că ai acces la cele mai moi niveluri, creează o nouă clasă pentru acest semestru apăsând Creează clasă nouă în" teacher_dashboard: "Panou de lucru profesor" update_old_classroom_detail_2: "și dând elevilor noul cod de clasă care apare." view_assessments: "Vezi evaluări" view_challenges: "vezi niveluri tip provocare" challenge: "Provocare:" challenge_level: "Nivel tip provocare:" status: "Stare:" assessments: "Evaluări" challenges: "Provocări" level_name: "Nume nivel:" keep_trying: "Continuă să încerci" start_challenge: "Start provocare" locked: "Blocat" concepts_used: "Concepte utilizate:" show_change_log: "Arată modificările acestor niveluri de curs" hide_change_log: "Ascunde schimbările acestor nivele de curs" concept_videos: "Filme despre concept" concept: "Concept:" basic_syntax: "Sintaxa de bază" while_loops: "Bucle while" variables: "Variabile" basic_syntax_desc: "Sintaxa este despre cum să scrii cod. Așa cum sunt citirea și gramatica importanre în scrierea poveștilor și a esurilor, sintaxa este importantă când scriem cod. Oamenii sunt foarte buni în a înțelege ce înseamnă ceva, chiar și atunci când ceva nu este foarte corect, însă calculatoarele nu sunt atât de inteligente și au nevoie ca tu să scrii foarte foarte precis." while_loops_desc: "O buclă este o modalitate de a repeta acțiuni într-un program. Le poți utiliza pentru a nu scrie același cod de mai multe ori (repetitiv), iar atunci când nu ști de câte ori o acțiune se repetă pentru a îndeplini o sarcină." variables_desc: "Lucrul cu variabilele este ca și organizarea lucrurilor în cutii. Dăi unei cutii un nume, de exemplu \"Rechizite școlare\" și apoi vei pune în ea diverse lucruri. Conținutul exact al cutiei se poate schimba de-a lungul timpului, însă tot mereu ce este înăuntru se va numi \"Rechizite școlare\". În programare, variabilele sunt simboluri utilizate pentru a păstra date care se vor schimba pe timpul programului. Variabilele pot păstra o varietate de tipuri de date, inclusiv numere și șiruri de caractere." locked_videos_desc: "Continuă să joci pentru a debloca filmul conceptului __concept_name__." unlocked_videos_desc: "Examinează filmul conceptului __concept_name__ ." video_shown_before: "afișat înainte de __level__" link_google_classroom: "Conectare cu Google Classroom" select_your_classroom: "Alege clasa" no_classrooms_found: "Nu s-a găsit nici o clasă" create_classroom_manually: "Creează clasa manual" classes: "Clase" certificate_btn_print: "Tipărire" certificate_btn_toggle: "Schimbare" ask_next_course: "Vrei să joci mai mult? Întreabă profesorul pentru a accesa cursul următor." set_start_locked_level: "Nivelurile blocate încep la " no_level_limit: "-- (nici un nivel blocat)" ask_teacher_to_unlock: "Întreabă profesorul pentru deblocare" ask_teacher_to_unlock_instructions: "Pentru a juca nivelul următor, roagă profesorul să îl deblocheze din ecranul lor Progres curs" play_next_level: "Joacă următorul nivel" play_tournament: "Joacă în turneu" levels_completed: "Niveluri terminate: __count__" ai_league_team_rankings: "Clasamentul echipelor din Liga IA" view_standings: "Vezi clasările" view_winners: "Vezi câștigătorii classroom_announcement: "Anunțurile clasei" project_gallery: no_projects_published: "Fi primul care publică un proiect în acest curs!" view_project: "Vezi proiect" edit_project: "Modifică proiect" teacher: assigning_course: "Alocă curs" back_to_top: "Înapoi sus" click_student_code: "Apasă pe oprice nivel de mai jos, început sau terminat de un elev, pentru a vedea codul scris." code: "Codul lui __name__" complete_solution: "Soluția completă" course_not_started: "Elevul nu a început încă acest curs." hoc_happy_ed_week: "Săptămâna informaticii fericită!" hoc_blurb1: "Află despre activități gratuite de" hoc_blurb2: "scriere a codului, Joc, Partajare," hoc_blurb3: " descarcă un nou plan de lecție și spune-le elevilor să se autentifice pentru a se juca!" hoc_button_text: "Vezi activitate" no_code_yet: "Elevul nu a scis încă nici un cod pentru acest nivel." open_ended_level: "Nivel deschis-terminat" partial_solution: "Soluție parțială" capstone_solution: "Soluția cea mai bună" removing_course: "Șterge curs" solution_arena_blurb: "Elevii sunt încurajați să rezolve nivelurile din arenă în mod creativ. Soluția furnizată mai jos îndeplinește cerințele acestui nivel din arenă." solution_challenge_blurb: "Elevii sunt încurajați să rezolve nivelurile tip provocare deschise-terminate în mod creativ. O soluție posibilă este afișată mai jos." solution_project_blurb: "Elevii sunt încurajați să construiască proiecte creative în acest nivel. Vă rog să urmăriți liniile directoare din curiculă din Zona de resurse pentru informații despre cum să evaluați aceste proiecte." students_code_blurb: "O soluție corectă pentru fiecare nivel este furnizată acolo unde este cazul. În unele cazuri, este posibil ca un elev să rezoove un nivel utilizând alte linii de cod. Soluțiile nu sunt afișate pentru nivelurile pe care elevii nu le-au început." course_solution: "Soluție curs" level_overview_solutions: "Prezentare nivel și soluții" no_student_assigned: "Nici un elev nu este alocat acestui curs." paren_new: "(nou)" student_code: "Cod student pentru __name__" teacher_dashboard: "Panou de lucru profesor" # Navbar my_classes: "Clasele mele" courses: "Ghiduri curs" enrollments: "Licențe elevi" resources: "Resurse" help: "Ajutor" language: "Limba" edit_class_settings: "modifică setările clasei" access_restricted: "Actualizare cont necesară" teacher_account_required: "Un cont de profesor este necesar pentru a accesa acest conținut." create_teacher_account: "Creează cont profesor" what_is_a_teacher_account: "Ce este un cond de profesor?" teacher_account_explanation: "Un cont de profesor CodeCombat îți permite să creezi clase, să monitorizezi progresul elevilor de-a lungul cursurilor, să administrezi licențele și să accesezi resurse din curicula pe care vrei să o construiești." current_classes: "Clase curente" archived_classes: "Clase arhivate" archived_classes_blurb: "Clasele pot fi arhivate pentru referințe viitoare. Dezarhivează o clasă pentru a o putea vedea în lista de clase curente din nou." view_class: "vezi clasă" view_ai_league_team: "Vezi echipa din liga IA" archive_class: "arhivează clasă" unarchive_class: "dezarhivează clasă" unarchive_this_class: "Dezarhivează această clasă" no_students_yet: "Această clasă nu are încă elevi." no_students_yet_view_class: "Vezi clasa pentru a adăuga elevi." try_refreshing: "(Ar putea fi nevoie să reîncarci pagina)" create_new_class: "Creează o nouă clasă" class_overview: "Vezi pagina clasei" # View Class page avg_playtime: "Timpul mediu al nivelului" total_playtime: "Tmpul de joc total" avg_completed: "Numărul mediu de niveluri teminate" total_completed: "Total niveluri terminate" created: "Create" concepts_covered: "Concepte acoperite" earliest_incomplete: "Primul nivel necompletat" latest_complete: "Ultimul nivel completat" enroll_student: "Înscrie elevi" apply_license: "Adaugă licență" revoke_license: "Înlătură licență" revoke_licenses: "Înlătură toate licențele" course_progress: "Progresul cursului" not_applicable: "N/A" edit: "modifică" edit_2: "Modifică" remove: "șterge" latest_completed: "Ultimul terminat:" sort_by: "Sortează după" progress: "Progres" concepts_used: "Concepte utilizate de elev:" concept_checked: "Concepte verificate:" completed: "Terminat" practice: "Practică" started: "Început" no_progress: "Fără progres" not_required: "Nu este obligatoriu" view_student_code: "Apasă să vezi codul de elev" select_course: "Alege cursul dorit" progress_color_key: "Codul de culoare pentru propgres:" level_in_progress: "Nivel în progres" level_not_started: "Nivel neînceput" project_or_arena: "Proiect sau Arenă" students_not_assigned: "Elevi care nu au fost alocați la {{courseName}}" course_overview: "Prezentare curs" copy_class_code: "Copiază codul clasei" class_code_blurb: "Elevii pot să se alăture clasei utilizând acest cod de clasă. Nu este necesară o adresă de email când creezi un cont de elev cu acest cod de clasă." copy_class_url: "Copiază URL-ul clasei" class_join_url_blurb: "Poți să publici această adresă unică URL pe o pagină de web." add_students_manually: "Invită elevii prin email" bulk_assign: "Alege curs" assigned_msg_1: "{{numberAssigned}} studenți au fost alocați cursului {{courseName}}." assigned_msg_2: "{{numberEnrolled}} licențe au fost aplicate." assigned_msg_3: "Mai ai {{remainingSpots}} licențe disponibile." assign_course: "Alocă curs" removed_course_msg: "{{numberRemoved}} elevi au fost șterși de la cursul {{courseName}}." remove_course: "Șterge curs" not_assigned_msg_1: "Nu poți adăuga elevi la o instanță de curs până când ei nu sunt adăugați unui abonament care conține acest curs" not_assigned_modal_title: "Cursurile nu au fost alocate" not_assigned_modal_starter_body_1: "Acest curs necesită o licență de tip Starter. Nu ai suficiente licențe Starter disponibile pentru a le aloca acestui curs pentru __selected__ de elevi selectați." not_assigned_modal_starter_body_2: "Cumpără licențe Starter pentru a permite accesul la acest curs." not_assigned_modal_full_body_1: "Acest curs necesită licență completă. Nu aveți suficiente licențe complete disponibile pentru a le aloca acestui curs pentru __selected__ de elevi selectați." not_assigned_modal_full_body_2: "Mai aveți doar __numFullLicensesAvailable__ de licențe complete disponibile (__numStudentsWithoutFullLicenses__ elevi nu au o licență completă alocată)." not_assigned_modal_full_body_3: "Te rog să alegi mai puțini elevi, sau contactează-ne la adresa __supportEmail__ pentru asistență." assigned: "Alocate" enroll_selected_students: "Înscrie elevii selectați" no_students_selected: "Nici un student nu este selectat." show_students_from: "Arată elevii din" # Enroll students modal apply_licenses_to_the_following_students: "Alocă licențe acestor elevi" select_license_type: "Selectează tipul de licență de aplicat" students_have_licenses: "Acești elevi au deja licențe alocate:" all_students: "Toți elevii" apply_licenses: "Alocă licențele" not_enough_enrollments: "Licențe disponibile insuficiente." enrollments_blurb: "Elevii trebuie să aibă o licență pentru a accesa conținutul după primul curs." how_to_apply_licenses: "Cum să aloci licențe" export_student_progress: "Exportă progresul elevilor (CSV)" send_email_to: "Trimite email de recuperare parolă la:" email_sent: "Email trimis" send_recovery_email: "Trimite email de recuperare" enter_new_password_below: "Introdu parola mai jos:" change_password: "Schimbă parola" changed: "Schimbată" available_credits: "Licențe disponibile" pending_credits: "Licențe în așteptare" empty_credits: "Licențe epuizate" license_remaining: "licență rămasă" licenses_remaining: "licențe rămase" student_enrollment_history: "Istoricul înscrierilor elevilor" enrollment_explanation_1: "" # the definite article in Ro is placed at the end of the substantive enrollment_explanation_2: "Istoricul înscrierilor elevilor" enrollment_explanation_3: "afișează numărul total de elevi unici care au fost alocați de toți profesorii în toate clasele adăugate în panoul de lucru. Acesta include elevii atât din clasele arhivate cât și nearhivate dintr-o clasă creată între 1 iulie - 30 iunie din respectivul an școlar." enrollment_explanation_4: "Amintește-ți" enrollment_explanation_5: "clasele pot fi arhivate și licențele pot fi reutilizate de-a lungul anului școlar, ceea ce permite administratorilor să înțeleagă câți elevi au participat per ansamblu de fapt în program." one_license_used: "1 din __totalLicenses__ licențe au fost utilizate" num_licenses_used: "__numLicensesUsed__ out of __totalLicenses__ licențe au fost utilizate" starter_licenses: "licențe tip starter" start_date: "data început:" end_date: "data sfărșit:" get_enrollments_blurb: " Te vom ajuta să construiești o soluție care îndeplinește cerințele clasei tale, școlii sau districtului." see_also_our: "Vezi de asemenea" for_more_funding_resources: "pentru informații cu privire la accesarea surselor de finanțare CARES Act cum sunt ESSER și GEER." how_to_apply_licenses_blurb_1: "Când un profesor alocă un curs unui elev pentru prima dată, vom aplica o licență în mod automat. Utilizează lista de alocare în grup din clasa ta pentru a aloca un curs mai multor elevi selectați:" how_to_apply_licenses_blurb_2: "Pot să aplic o licență fără a aloca un curs?" how_to_apply_licenses_blurb_3: "Da — mergi la tabul Stare licențe din clasa ta și apasă \"Aplică licență\" pentru orice elev care nu are încă o licență activă." request_sent: "Cerere transmisă!" assessments: "Evaluări" license_status: "Stare licență" status_expired: "Expiră în {{date}}" status_not_enrolled: "Nu este înrolat" status_enrolled: "Expiră în {{date}}" select_all: "Selectează tot" project: "Proiect" project_gallery: "Galerie proiecte" view_project: "Vezi proiect" unpublished: "(nepublicat)" view_arena_ladder: "Vezi clasament arenă" resource_hub: "Zonă de resurse" pacing_guides: "Ghiduri parcurgere Clasa-în-cutie" pacing_guides_desc: "Învață cum să încorporezi toate resursele CodeCombat în planificarea anului tău școlar!" pacing_guides_elem: "Ghid parcurgere școala primară" pacing_guides_middle: "Ghid parcurgere școala generală" pacing_guides_high: "Ghid parcurgere liceu" getting_started: "Noțiuni de bază" educator_faq: "Întrebări instructori" educator_faq_desc: "Întrebări frecvente despre utilizarea CodeCombat în clasă sau în școală." teacher_getting_started: "Ghid de noțiuni generale pentru profesor" teacher_getting_started_desc: "Nou la CodeCombat? Descarcă acest ghid de noțiuni generale pentru profesori pentru a-ți creea contul, a creea prima ta clasă și a invita elevii la primul curs." student_getting_started: "Ghid rapid de pornire pentru elevi" student_getting_started_desc: "Poți distribui acest ghid elevilor tăi înainte de începerea CodeCombat astfel încât aceștia să se familiarizeze cu editorul de cod. Acest ghid poate fi utilizat atât pentru clasele de Python cât și cele de Javascript." standardized_curricula: "Curicula standardizată" ap_cs_principles: "Principiile AP ale informaticii" ap_cs_principles_desc: "Principiile AP ale informaticii le face elevilor o introducere extinsă asupra puterii, impactului și posibilităților informaticii. Cursul pune accent pe rezolvarea problemelor și gândirea algoritmică și logică în timp ce aceștia învață bazele programării." cs1: "Introducere în informatică" cs2: "Informatică 2" cs3: "Informatică 3" cs4: "Informatică 4" cs5: "Informatică 5" cs1_syntax_python: "Curs 1 - Ghid sinatxă Python" cs1_syntax_python_desc: "Foaie rezumat cu referințe către cele mai uzuale sintaxe Python pe care elevii le vor învăța în lecția Introducere în informatică." cs1_syntax_javascript: "Curs 1 - Ghid sinatxă Javascript" cs1_syntax_javascript_desc: "Foaie rezumat cu referințe către cele mai uzuale sintaxe Javascript syntax pe care elevii le vor învăța în lecția Introducere în informatică." coming_soon: "În curând mai multe ghiduri!" engineering_cycle_worksheet: "Foaie rezumat despre ciclul tehnologic" engineering_cycle_worksheet_desc: "Utilizează această foaie de lucru pentru a-i învăța pe elevi bazele ciclului tehnologic: Evaluare, Proiectare, Implementare și Depanare. Fă referire la fișa cu exemplu complet ca și ghid." engineering_cycle_worksheet_link: "Vezi exemplu" progress_journal: "Jurnal de progres" progress_journal_desc: "Încurajează elevii să-și urmărească progresul cu ajutorul jurnalului de progres." cs1_curriculum: "Introducere în informatică - Ghid de curiculă" cs1_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 1." arenas_curriculum: "Niveluri arenă - Ghid profesor" arenas_curriculum_desc: "Instrucțiuni despre rularea arenelor multi-jucător Wakka Maul, Cross Bones și Power Peak în clasă." assessments_curriculum: "Niveluri de evaluare - Ghid profesor" assessments_curriculum_desc: "Învață cum să utilizezi Nivelurile de provocare și nivelurile de provocare combo pentru a evalua rezultatele învățării." cs2_curriculum: "Informatică 2 - Ghid de curiculă" cs2_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 2." cs3_curriculum: "Informatică 3 - Ghid de curiculă" cs3_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 3." cs4_curriculum: "Informatică 4 - Ghid de curiculă" cs4_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 4." cs5_curriculum_js: "Informatică 5 - Ghid de curiculă (Javascript)" cs5_curriculum_desc_js: "Scop și secvențiere, planuri de lecții, activități și altele pentru clasele Cursului 5 de Javascript." cs5_curriculum_py: "Informatică 5 - Ghid de curiculă (Python)" cs5_curriculum_desc_py: "Scop și secvențiere, planuri de lecții, activități și altele pentru clasele Cursului 5 de Python." cs1_pairprogramming: "Activitate de programare pe echipe" cs1_pairprogramming_desc: "introduce elevii într-un exercițiu de programare pe echipe care îi va ajuta să fie mai buni la ascultat și la comunicat." gd1: "Dezvoltare joc 1" gd1_guide: "Dezvoltare joc 1 - Ghid de proiect" gd1_guide_desc: "Utilizează acest proiect să ghidezi elevii în crearea primului lor proiect de dezvoltare joc partajat pe parcursul a 5 zile." gd1_rubric: "Dezvoltare joc 1 - Fișă proiect" gd1_rubric_desc: "Utilizează această fișă să evaluezi proiectele elevilor la sfârșitul proiectului Dezvoltare joc 1." gd2: "Dezvoltare joc 2" gd2_curriculum: "Dezvoltare joc 2 - Ghid de curiculă" gd2_curriculum_desc: "Planuri de lecție pentru Dezvoltare joc 2." gd3: "Dezvoltare joc 3" gd3_curriculum: "Dezvoltare joc 3 - Ghid de curiculă" gd3_curriculum_desc: "Planuri de lecție pentru Dezvoltare joc 3." wd1: "Dezvoltare web 1" wd1_curriculum: "Dezvoltare web 1 - Ghid de curiculă" wd1_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul Dezvoltare web 1." wd1_headlines: "Activitate despre titluri și antete" wd1_headlines_example: "Vezi soluțiile date ca exemplu" wd1_headlines_desc: "De ce sunt marcajele de paragraf și antetele importante? Utilizează această activitate să arăți cât de ușor sunt de citit paginile cu antete bine alese. Sunt mai multe soluții corecte pentru acesta!" wd1_html_syntax: "Ghid de sintaxă HTML" wd1_html_syntax_desc: "Referință de o pagină pentru stilurile HTML pe care elevii le vor învăța în Dezvoltare web 1." wd1_css_syntax: "Ghid sinatxă CSS" wd1_css_syntax_desc: "Referință de o pagină pentru sintaxa stilurilor CSS pe care elevii le vor învăța în Dezvoltare web 1." wd2: "Dezvolatre web 2" wd2_jquery_syntax: "Ghid de sintaxă pentru funcțiile jQuery" wd2_jquery_syntax_desc: "Referință de o pagină pentru sintaxa funcțiilor jQuery pe care elevii le vor învăța în Dezvoltare web 2." wd2_quizlet_worksheet: "Fișă de lucru chestionar" wd2_quizlet_worksheet_instructions: "Vezi instrucțiuni și exemple" wd2_quizlet_worksheet_desc: "Înainte ca elevii să își construiască proiectul cu chestionarul despre personalitate de la sfârșitul cursului Dezvoltare web 2, ar trebui să își planifice mai întâi întrebările, rezultate și răspunsuri utilizând această fișă de lucru. Profesorii pot să distribuie aceste instrucțiuni și exemple ca elevii să poată face referire la acestea." student_overview: "Prezentare generală" student_details: "Detalii elev" student_name: "Nume elev" no_name: "Nu este furnizat un nume." no_username: "Nu este furnizat un nume de utilizator." no_email: "Elevul nu are adresă de email setată." student_profile: "Profil elev" playtime_detail: "Detalii despre timpul de joc" student_completed: "Terminate de elev" student_in_progress: "Elev în progress" class_average: "Media clasei" not_assigned: "nu au fost alocate următoarele cursuri" playtime_axis: "Timp de joc în secunde" levels_axis: "Niveluri în" student_state: "Cum se" student_state_2: "descurcă?" student_good: "se descurcă bine în" student_good_detail: "Acest elev ține pasul cu timpul mediu de terminare a nivelului de către clasă." student_warn: "poate avea nevoie de ajutor în" student_warn_detail: "Timpul mediu de terminare a acestui nivel pentru acest elev sugerează că ar putea avea nevoie de ajutor cu conceptele noi care au fost introduse în acest curs." student_great: "se descurcă foarte bine în" student_great_detail: "Acest elev ar putea fi un bun candidat să îi ajute pe ceilalți elevi în acest curs, pe baza timpilor medii de terminare a nivelului." full_license: "Licență completă" starter_license: "Licență începător" customized_license: "Licență personalizată" trial: "Încercare" hoc_welcome: "Săptămână a informaticii fericită" hoc_title: "Jocuri pentru Hour of Code - Activități gratuite pentru a învăța să scrii cod în limbaje de programare reale" hoc_meta_description: "Fă-ți propriul joc sau programează-ți ieșirea din temniță! CodeCombat are patru activități diferite pentru Hour of Code și peste 60 de niveluri să înveți să programezi, să te joci și să creezi." hoc_intro: "Există trei modalități ca și clasa ta să participe la Hour of Code cu CodeCombat" hoc_self_led: "Joc individual" hoc_self_led_desc: "Elevii se pot juca cu tutorialele CodeCombat pentru Hour of Code singuri" hoc_game_dev: "Dezvoltare de joc" hoc_and: "și" hoc_programming: "Programare Javascript/Python" hoc_teacher_led: "Lecții cu profesor" hoc_teacher_led_desc1: "Descarcă" hoc_teacher_led_link: "planurile noastre de lecție pentru Hour of Code" hoc_teacher_led_desc2: "pentru a prezenta elevilor concepte de programare utilizând activități offline" hoc_group: "Joc în grup" hoc_group_desc_1: "Profesorii pot utiliza lecțiile în conjuncție cu cursul Introducere în informatică ca să poată monitoriza progresul elevilor. Vezi" hoc_group_link: "Ghidul de noțiuni de bază" hoc_group_desc_2: "pentru mai multe detalii" hoc_additional_desc1: "Pentru resurse și activități educaționale CodeCombat, vezi" hoc_additional_desc2: "Întrebările" hoc_additional_contact: "Ține legătura" revoke_confirm: "Ești sigur că vrei să înlături licența completă de la {{student_name}}? Licența va deveni disponibilă să o aloci altui elev." revoke_all_confirm: "Ești sigur că vrei să înlături licențele complete de la toți elevii din clasa aceasta?" revoking: "Revocare..." unused_licenses: "Ai licențe neutilizate care îți permit să aloci elevilor cursuri plătite atunci când aceștia vor fi gata să învețe mai mult!" remember_new_courses: "Amintește-ți să aloci cursuri noi!" more_info: "Mai multe informații" how_to_assign_courses: "Cum să aloci cursuri" select_students: "Alege elevi" select_instructions: "Selectează căsuța din dreptul fiecărui elev pentru care vrei să adaugi cursuri." choose_course: "Alege curs" choose_instructions: "Alege cursul din lista derulantă care vrei să îl aloci, apoi apasă “Alocă elevilor selectați.”" push_projects: "recomandăm alocarea cursului Dezvoltare web 1 sau Dezvoltare joc 1 după ce elevii au terminat Introducere în informatică! Vezi {{resource_hub}} pentru mai multe detalii despre aceste cursuri." teacher_quest: "Aventura profesorului către succes" quests_complete: "Aventuri terminate" teacher_quest_create_classroom: "Creează clasă" teacher_quest_add_students: "Adaugă elevi" teacher_quest_teach_methods: "Ajută-i pe elevii tăi să învețe cum să `cheme metode`." teacher_quest_teach_methods_step1: "Obține 75% din primul nivel cu cel puțin o clasă la Dungeons of Kithgard" teacher_quest_teach_methods_step2: "Tipărește [Ghidul elevului de introducere rapidă](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) din Zona de resurse." teacher_quest_teach_strings: "Nu îți face elevii să meargă pe ață (string), învață-i despre șiruri de caractere - `strings`." teacher_quest_teach_strings_step1: "Obține 75% cu cel puțin o clasă la Nume adevărate (True Names)" teacher_quest_teach_strings_step2: "Utilizează Selectorul de nivel al profesorului în pagina [Ghiduri de cursuri](/teachers/courses) să vezi prezentare Nume adevărate." teacher_quest_teach_loops: "Ține-ți elevii aproape cu buclele - `loops`." teacher_quest_teach_loops_step1: "Obține 75% cu cel puțin o clasă la Focul dansator (Fire Dancing)." teacher_quest_teach_loops_step2: "Utilizează Activitatea despre bocle din [Ghidul de curiculă CS1](/teachers/resources/cs1) pentru a întări acest concept." teacher_quest_teach_variables: "Variaz-l un pic cu variabilele - `variables`." teacher_quest_teach_variables_step1: "Obține 75% ocu cel puțin o clasă la Inamicul cunoscut (Known Enemy)." teacher_quest_teach_variables_step2: "Încurajează colaborarer utilizând [Activitatea de programare în perechi](/teachers/resources/pair-programming)." teacher_quest_kithgard_gates_100: "Evadează din Porțile Kithgard(Kithgard Gates) cu clasa ta." teacher_quest_kithgard_gates_100_step1: "Obține 75% cu cel puțin o clasă la Porțile Kithgard." teacher_quest_kithgard_gates_100_step2: "Îndrumă elevi cum să gândească problemele complexe utilizând [Foaie rezumat despre ciclul tehnologic](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)." teacher_quest_wakka_maul_100: "Pregătește-te de duel în Wakka Maul." teacher_quest_wakka_maul_100_step1: "Obține 75% cu cel puțin o clasă la Wakka Maul." teacher_quest_wakka_maul_100_step2: "Vezi [Ghidul arenei](/teachers/resources/arenas) din [Zona de resurse](/teachers/resources) pentru sfaturi despre cum să desfășori cu succes o zi de arenă." teacher_quest_reach_gamedev: "Explorează nou lumi!" teacher_quest_reach_gamedev_step1: "[Cumpără licențe](/teachers/licenses) ca elevii tăi să poată explora noi lumi, ca Dezvoltare de joc și Dezvoltare web!" teacher_quest_done: "Vrei ca elevii tăi să învețe să scrie cod și mai mult? Ia legătura cu [specialiștii școlari](mailto:schools@codecombat.com) astăzi!" teacher_quest_keep_going: "Continuă! Iată ce poți face mai departe:" teacher_quest_more: "Vezi toate misiunile" teacher_quest_less: "Vezi mai puține misiuni" refresh_to_update: "(reîncarcă pagina să vezi noutățile)" view_project_gallery: "Vezi galeria de proiecte" office_hours: "Conferințe pentru profesori" office_hours_detail: "Învață cum să ți pasul cu elevii tăi în timp ce aceștia creează jocuri și se îmbarcă în aventura lor de scriere a codului! Vino și participă la" office_hours_link: "conferințe pentru profesori" office_hours_detail_2: "." #included in the previous line success: "Succes" in_progress: "În progres" not_started: "Nu a început" mid_course: "Curs la jumătate" end_course: "Curs terminat" none: "Nedetectat încă" explain_open_ended: "Notă: Elevii sunt încurajați să rezolve acest nivel în mod creativ — o soluție posibilă este dată mai jos." level_label: "Nivel:" time_played_label: "Timp jucat:" back_to_resource_hub: "Înapoi la Zona de resurse" back_to_course_guides: "Înapoi la Ghidurile de curs" print_guide: "Tipărește acest ghid" combo: "Combo" combo_explanation: "Elevi trec de nivelurile de provocare combo utilizând cel puțin unul din conceptele listate. Analizează codul elevului apăsând pe punctul de progres." concept: "Concept" sync_google_classroom: "Sincronizează Clasa Google" try_ozaria_footer: "Încearcă noul nostru joc de aventură, Ozaria!" try_ozaria_free: "Încearcă gratuit Ozaria" ozaria_intro: "Introducem noul nostru program de informatică" teacher_ozaria_encouragement_modal: title: "Dezvoltă-ți abilitățile de programare pentru a salva Ozaria" sub_title: "Ești invitat să încerci noul joc de aventură de la CodeCombat" cancel: "Înapoi la CodeCombat" accept: "Încearcă prima unitate gratuit" bullet1: "Aprofundați conexiunea elevului cu învățarea printr-o poveste epică și un joc captivant" bullet2: "Predă fundamentele informaticii, Python sau Javascript și alte abilități specifice secolului 21" bullet3: "Deblochează creativitatea prin proiecte personalizate" bullet4: "Instrucțiuni de suport prin resurse curiculare dedicate" you_can_return: "Poți oricând să te întorci la CodeCombat" educator_signup_ozaria_encouragement: recommended_for: "Recomandat pentru:" independent_learners: "Cursanți independenți" homeschoolers: "Elevii școlii de acasă" educators_continue_coco: "Instructorii care doresc să continue să utilizeze CodeCombat în clasa lor" continue_coco: "Continuă cu CodeCombat" ozaria_cta: title1: "Curicula de bază aliniată standardelor" description1: "Captivantă, povestea este bazată pe o curiculă care îndeplinește standardele CSTA pentru clasele 6-8." title2: "Planuri de lecție la cheie" description2: "Prezentare detaliată și foi de lucru pentru profesori pentru ghidarea elevilor printre obiectivele de învățare." title3: "Profesor nou & Panouri de administrare" # description3: "All the actionable insights educators need at a glance, such as student progress and concept understanding." share_licenses: share_licenses: "Partajează licențe" shared_by: "Partajat de:" add_teacher_label: "Introdu adresa de email exactă a profesorului:" add_teacher_button: "Adaugă profesor" subheader: "Poți să îți faci licențele disponibile altor profesori din organizația ta. Fiecare licență poate fi utilizată pentru un singur elev la un moment dat." teacher_not_found: "Profesor negăsit. Te rog verifică dacă acest profesor are deja un Cont de profesor." teacher_not_valid: "Acesta nu este un Cond de profesor valid. Numai conturile de profesor pot partaja licențe." already_shared: "Ai partajat deja aceste licențe cu acel profesor." have_not_shared: "Nu ai partajat aceste licente cu acel profesor." teachers_using_these: "Profesori care pot accesa aceste licențe:" footer: "Când profesorii înlătură licențele de la elevi, licențele vor fi returnate în setul partajat pentru ca alți profesori din acest grup să le poată utiliza." you: "(tu)" one_license_used: "(1 licență utilizată)" licenses_used: "(__licensesUsed__ licențe utilizate)" more_info: "Mai multe informații" sharing: game: "Jov" webpage: "Pagină web" your_students_preview: "Elevii tăi vor apăsa aici ca să își vadă proiectele finalizate! Nedisponibil în zona profesorului." unavailable: "Link-ul de partajare nu este disponibil în zona profesorului." share_game: "Partajează acest joc" share_web: "Partajează această pagină web" victory_share_prefix: "Partajează acest link ca să inviți prietenii și familia" victory_share_prefix_short: "Invită persoane să" victory_share_game: "joace nivelul tău de joc" victory_share_web: "vadă pagina ta web" victory_share_suffix: "." victory_course_share_prefix: "Acest link îi lasă pe prietenii & familia ta să" victory_course_share_game: "joace jocul" victory_course_share_web: "vadă pagina web" victory_course_share_suffix: "pe care l-ai creat/ai creat-o." copy_url: "Copiază URL" share_with_teacher_email: "trimite profesorului tău" share_ladder_link: "Partajează link multi-jucător" ladder_link_title: "Partajează link către meciul tău multi-jucător" ladder_link_blurb: "Partajează link-ul de luptă IA ca prietenii și familia să joace împotriva codului tău:" game_dev: creator: "Creator" web_dev: image_gallery_title: "Galeria cu imagini" select_an_image: "Alege o imagine pe care vrei să o utilizezi" scroll_down_for_more_images: "(Derulează în jos pentru mai multe imagini)" copy_the_url: "Copiază URL-ul de mai jos" copy_the_url_description: "Util dacă vrei să schimbi o imagine existentă." copy_the_img_tag: "Copiază marcajul <img>" copy_the_img_tag_description: "Util dacă vrei să schimbi o imagine nouă." copy_url: "Copiază URL" copy_img: "Copiază <img>" how_to_copy_paste: "Cum să Copiezi/Lipești" copy: "Copiază" paste: "Lipește" back_to_editing: "Înapoi la editare" classes: archmage_title: "Archmage" archmage_title_description: "(Programator)" archmage_summary: "Dacă ești un dezvoltator interesat să programezi jocuri educaționale, devino Archmage și ajută-ne să construim CodeCombat!" artisan_title: "Artizan" artisan_title_description: "(Creator de nivele)" artisan_summary: "Construiește și oferă nivele pentru tine și pentru prieteni tăi, ca să se joace. Devino Artisan și învață arta de a împărtăși cunoștințe despre programare." adventurer_title: "Aventurier" adventurer_title_description: "(Playtester de nivele)" adventurer_summary: "Primește nivelele noastre noi (chiar și cele pentru abonați) gratis cu o săptămână înainte și ajută-ne să reparăm erorile până la lansare." scribe_title: "scrib" scribe_title_description: "(Editor de articole)" scribe_summary: "Un cod bun are nevoie de o documentație bună. scrie, editează și improvizează documentația citită de milioane de jucători din întreaga lume." diplomat_title: "Diplomat" diplomat_title_description: "(Translator)" diplomat_summary: "CodeCombat e tradus în 45+ de limbi de Diplomații noștri. Ajută-ne și contribuie la traducere." ambassador_title: "Ambasador" ambassador_title_description: "(Suport)" ambassador_summary: "Îmblânzește utilizatorii de pe forumul nostru și oferă direcții pentru cei cu întrebări. Ambasadorii noștri reprezintă CodeCombat în fața lumii." teacher_title: "Profesor" editor: main_title: "Editori CodeCombat" article_title: "Editor de articole" thang_title: "Editor thang" level_title: "Editor niveluri" course_title: "Editor curs" achievement_title: "Editor realizări" poll_title: "Editor sondaje" back: "Înapoi" revert: "Revino la versiunea anterioară" revert_models: "Resetează Modelele" pick_a_terrain: "Alege terenul" dungeon: "Temniță" indoor: "Interior" desert: "Deșert" grassy: "Ierbos" mountain: "Munte" glacier: "Ghețar" small: "Mic" large: "Mare" fork_title: "Fork Versiune Nouă" fork_creating: "Creare Fork..." generate_terrain: "Generează teren" more: "Mai multe" wiki: "Wiki" live_chat: "Chat Live" thang_main: "Principal" thang_spritesheets: "Spritesheets" thang_colors: "Culori" level_some_options: "Opțiuni?" level_tab_thangs: "Thangs" level_tab_scripts: "script-uri" level_tab_components: "Componente" level_tab_systems: "Sisteme" level_tab_docs: "Documentație" level_tab_thangs_title: "Thangs actuali" level_tab_thangs_all: "Toate" level_tab_thangs_conditions: "Condiți inițiale" level_tab_thangs_add: "Adaugă thangs" level_tab_thangs_search: "Caută thangs" add_components: "Adaugă componente" component_configs: "Configurare componente" config_thang: "Dublu click pentru a configura un thang" delete: "Șterge" duplicate: "Duplică" stop_duplicate: "Oprește duplicarea" rotate: "Rotește" level_component_tab_title: "Componente actuale" level_component_btn_new: "Creează componentă nouă" level_systems_tab_title: "Sisteme actuale" level_systems_btn_new: "Creează sistem nou" level_systems_btn_add: "Adaugă sistem" level_components_title: "Înapoi la toți Thangs" level_components_type: "Tip" level_component_edit_title: "Editează componentă" level_component_config_schema: "Schema config" level_system_edit_title: "Editează sistem" create_system_title: "Creează sistem nou" new_component_title: "Creează componentă nouă" new_component_field_system: "Sistem" new_article_title: "Creează un articol nou" new_thang_title: "Creează un nou tip de Thang" new_level_title: "Creează un nivel nou" new_article_title_login: "Loghează-te pentru a crea un Articol Nou" new_thang_title_login: "Loghează-te pentru a crea un Thang de Tip Nou" new_level_title_login: "Loghează-te pentru a crea un Nivel Nou" new_achievement_title: "Creează o realizare nouă" new_achievement_title_login: "Loghează-te pentru a crea o realizare nouă" new_poll_title: "Creează un sondaj nou" new_poll_title_login: "Autentifică-te pentru a crea un sondaj nou" article_search_title: "Caută articole aici" thang_search_title: "Caută tipuri de Thang aici" level_search_title: "Caută niveluri aici" achievement_search_title: "Caută realizări" poll_search_title: "Caută sondaje" read_only_warning2: "Notă: nu poți salva editările aici, pentru că nu ești autentificat." no_achievements: "Nici-un achivement adăugat acestui nivel până acum." achievement_query_misc: "Realizări cheie din diverse" achievement_query_goals: "Realizări cheie din obiectivele nivelurilor" level_completion: "Finalizare nivel" pop_i18n: "Populează I18N" tasks: "Sarcini" clear_storage: "Șterge schimbările locale" add_system_title: "Adaugă sisteme la nivel" done_adding: "Terminat de adăugat" article: edit_btn_preview: "Preview" edit_article_title: "Editează articol" polls: priority: "Prioritate" contribute: page_title: "Contribuțtii" intro_blurb: "CodeCombat este 100% open source! Sute de jucători dedicați ne-au ajutat să transformăm jocul în cea ce este astăzi. Alătură-te și scrie următorul capitol din aventura CodeCombat pentru a ajuta lumea să învețe cod!" # {change} alert_account_message_intro: "Salutare!" alert_account_message: "Pentru a te abona la mesajele email ale clasei trebuie să fi autentificat." archmage_introduction: "Una dintre cele mai bune părți despre construirea unui joc este că sintetizează atât de multe lucruri diferite. Grafică, sunet, conectarea în timp real, rețelele sociale și desigur multe dintre aspectele comune ale programării, de la gestiunea de nivel scăzut a bazelor de date și administrarea serverelor până la construirea de interfețe. Este mult de muncă și dacă ești un programator cu experiență, cu un dor de a te arunca cu capul înainte în CodeCombat, această clasă ți se potrivește. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." class_attributes: "Atribute pe clase" archmage_attribute_1_pref: "Cunoștințe în " archmage_attribute_1_suf: ", sau o dorință de a învăța. Majoritatea codului este în acest limbaj. Dacă ești fan Ruby sau Python, te vei simți ca acasă. Este Javascript, dar cu o sintaxă mai frumoasă." archmage_attribute_2: "Ceva experiență în programare și inițiativă personală. Te vom ajuta să te orientezi, dar nu putem aloca prea mult timp pentru a te pregăti." how_to_join: "Cum să ni te alături" join_desc_1: "Oricine poate să ajute! Doar intrați pe " join_desc_2: "pentru a începe, bifați căsuța de dedesubt pentru a te marca ca un Archmage curajos și pentru a primi ultimele știri pe email. Vrei să discuți despre ce să faci sau cum să te implici mai mult? " join_desc_3: ", sau găsește-ne în " join_desc_4: "și pornim de acolo!" join_url_email: "Trimite-ne Email" join_url_slack: "canal public de Slack" archmage_subscribe_desc: "Primește email-uri despre noi oportunități de progrmare și anunțuri." artisan_introduction_pref: "Trebuie să construim nivele adiționale! Oamenii sunt nerăbdători pentru mai mult conținut, și noi putem face doar atât singuri. Momentan editorul de nivele abia este utilizabil până și de creatorii lui, așa că aveți grijă. Dacă ai viziuni cu campanii care cuprind bucle for pentru" artisan_introduction_suf: ", atunci aceasta ar fi clasa pentru tine." artisan_attribute_1: "Orice experiență în crearea de conținut ca acesta ar fi de preferat, precum folosirea editoarelor de nivele de la Blizzard. Dar nu este obligatoriu!" artisan_attribute_2: "Un chef de a face o mulțime de teste și iterări. Pentru a face nivele bune, trebuie să fie test de mai mulți oameni și să obțineți păreri și să fiți pregăți să reparați o mulțime de lucruri." artisan_attribute_3: "Pentru moment trebuie să ai nervi de oțel. Editorul nostru de nivele este abia la început și încă are multe probleme. Ai fost avertizat!" artisan_join_desc: "Folosiți editorul de nivele urmărind acești pași, mai mult sau mai puțin:" artisan_join_step1: "Citește documentația." artisan_join_step2: "Creează un nivel nou și explorează nivelurile deja existente." artisan_join_step3: "Găsește-ne pe chatul nostru de Hipchat pentru ajutor." artisan_join_step4: "Postează nivelurile tale pe forum pentru feedback." artisan_subscribe_desc: "Primește email-uri despre update-uri legate de Editorul de nivele și anunțuri." adventurer_introduction: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze niveluri noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura, atunci aceasta este clasa pentru tine." adventurer_attribute_1: "O sete de cunoaștere. Tu vrei să înveți cum să programezi și noi vrem să te învățăm. Cel mai probabil tu vei fi cel care va preda mai mult în acest caz." adventurer_attribute_2: "Carismatic. Formulează într-un mod clar ceea ce trebuie îmbunătățit și oferă sugestii." adventurer_join_pref: "Ori fă echipă (sau recrutează!) cu un Artizan și lucreează cu el, sau bifează căsuța de mai jos pentru a primi email când sunt noi niveluri de testat. De asemenea vom posta despre niveluri care trebuie revizuite pe rețelele noastre precum" adventurer_forum_url: "forumul nostru" adventurer_join_suf: "deci dacă preferi să fi înștiințat în acele moduri, înscrie-te acolo!" adventurer_subscribe_desc: "Primește email-uri când sunt noi niveluri de testat." scribe_introduction_pref: "CodeCombat nu o să fie doar o colecție de niveluri. Vor fi incluse resurse de cunoaștere, un wiki despre concepte de programare legate de fiecare nivel. În felul acesta fiecare Artisan nu trebuie să mai descrie în detaliu ce este un operator de comparație, ei pot să pună un link la un articol mai bine documentat. Ceva asemănător cu ce " scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: " a construit. Dacă idea ta de distracție este să articulezi conceptele de programare în formă Markdown, această clasă ți s-ar potrivi." scribe_attribute_1: "Un talent în cuvinte este tot ce îți trebuie. Nu numai gramatică și ortografie, trebuie să poți să explici ideii complicate celorlați." contact_us_url: "Contactați-ne" # {change} scribe_join_description: "spune-ne câte ceva despre tine, experiențele tale despre programare și despre ce fel de lucruri ți-ar place să scrid. Vom începe de acolo!." scribe_subscribe_desc: "Primește email-uri despre scrisul de articole." diplomat_introduction_pref: "Dacă ar fi un lucru care l-am învățat din " diplomat_introduction_url: "comunitatea open source" diplomat_introduction_suf: "acesta ar fi că: există un interes mare pentru CodeCombat și în alte țări! Încercăm să adunăm cât mai mulți traducători care sunt pregătiți să transforme un set de cuvinte intr-un alt set de cuvinte ca să facă CodeCombat cât mai accesibil în toată lumea. Dacă vrei să tragi cu ochiul la conțintul ce va apărea și să aduci niveluri cât mai repede pentru conaționalii tăi, această clasă ți se potrivește." diplomat_attribute_1: "Fluență în Engleză și limba în care vrei să traduci. Când explici idei complicate este important să înțelegi bine ambele limbi!" diplomat_i18n_page_prefix: "Poți începe să traduci nivele accesând" diplomat_i18n_page: "Pagina de traduceri" diplomat_i18n_page_suffix: ", sau interfața și site-ul web pe GitHub." diplomat_join_pref_github: "Găsește fișierul pentru limba ta " diplomat_github_url: "pe GitHub" diplomat_join_suf_github: ", editează-l online și trimite un pull request. Bifează căsuța de mai jos ca să fi up-to-date cu dezvoltările noastre internaționale!" diplomat_subscribe_desc: "Primește mail-uri despre dezvoltările i18n și niveluri de tradus." ambassador_introduction: "Aceasta este o comunitate pe care o construim, iar voi sunteți conexiunile. Avem forumuri, email-uri și rețele sociale cu mulți oameni cu care se poate vorbi despre joc și de la care se poate învăța. Dacă vrei să ajuți oameni să se implice și să se distreze această clasă este potrivită pentru tine." ambassador_attribute_1: "Abilități de comunicare. Abilitatea de a indentifica problemele pe care jucătorii le au si să îi poți ajuta. De asemenea, trebuie să ne informezi cu părerile jucătoriilor, ce le place și ce vor mai mult!" ambassador_join_desc: "spune-ne câte ceva despre tine, ce ai făcut și ce te interesează să faci. Vom porni de acolo!." ambassador_join_step1: "Citește documentația." ambassador_join_step2: "ne găsești pe canalul public de Slack." ambassador_join_step3: "Ajută pe alții din categoria Ambasador." ambassador_subscribe_desc: "Primește email-uri despre actualizările suport și dezvoltări multi-jucător." teacher_subscribe_desc: "Primește mesaje email pentru actualizări și anunțuri destinate profesorilor." changes_auto_save: "Modificările sunt salvate automat când apeși checkbox-uri." diligent_scribes: "scribii noștri:" powerful_archmages: "Bravii noștri Archmage:" creative_artisans: "Artizanii noștri creativi:" brave_adventurers: "Aventurierii noștri neînfricați:" translating_diplomats: "Diplomații noștri abili:" helpful_ambassadors: "Ambasadorii noștri de ajutor:" ladder: title: "Arene multi-jucător" arena_title: "__arena__ | Arenă multi-jucător" my_matches: "Jocurile mele" simulate: "Simulează" simulation_explanation: "Simulând jocuri poți afla poziția în clasament a jocului tău mai repede!" simulation_explanation_leagues: "Vei simula în principal jocuri pentru jucătorii aliați din clanul și cursurile tale." simulate_games: "Simulează Jocuri!" games_simulated_by: "Jocuri simulate de tine:" games_simulated_for: "Jocuri simulate pentru tine:" games_in_queue: "Jocuri aflate în prezent în așteptare:" games_simulated: "Jocuri simulate" games_played: "Jocuri jucate" ratio: "Rație" leaderboard: "Clasament" battle_as: "Luptă ca " summary_your: "Al tău " summary_matches: "Meciuri - " summary_wins: " Victorii, " summary_losses: " Înfrângeri" rank_no_code: "Nici un cod nou pentru Clasament" rank_my_game: "Plasează-mi jocul în Clasament!" rank_submitting: "Se trimite..." rank_submitted: "Se trimite pentru Clasament" rank_failed: "A eșuat plasarea în clasament" rank_being_ranked: "Jocul se plasează în Clasament" rank_last_submitted: "trimis " help_simulate: "Ne ajuți simulând jocuri?" code_being_simulated: "Codul tău este simulat de alți jucători pentru clasament. Se va actualiza cum apar meciuri." no_ranked_matches_pre: "Niciun meci de clasament pentru " no_ranked_matches_post: " echipă! Joacă împotriva unor concurenți și revino apoi aici pentru a-ți plasa meciul în clasament." choose_opponent: "Alege un adversar" select_your_language: "Alege limba!" tutorial_play: "Joacă tutorial-ul" tutorial_recommended: "Recomandat dacă nu ai mai jucat niciodată înainte" tutorial_skip: "Sări peste tutorial" tutorial_not_sure: "Nu ești sigur ce se întâmplă?" tutorial_play_first: "Joacă tutorial-ul mai întâi." simple_ai: "CPU simplu" # {change} warmup: "Încălzire" friends_playing: "Prieteni ce se joacă" log_in_for_friends: "Autentifică-te ca să joci cu prieteni tăi!" social_connect_blurb: "Conectează-te și joacă împotriva prietenilor tăi!" invite_friends_to_battle: "Invită-ți prietenii să se alăture bătăliei" fight: "Luptă!" # {change} watch_victory: "Vizualizează victoria" defeat_the: "Învinge" watch_battle: "Privește lupta" tournament_starts: "Turneul începe" tournament_started: ", a început" tournament_ends: "Turneul se termină" tournament_ended: "Turneul s-a terminat" tournament_results_published: ", rezultate publicate" tournament_rules: "Regulile turneului" tournament_blurb_criss_cross: "Caștigă pariuri, creează căi, păcălește-ți oponenți, strânge pietre prețioase și îmbunătățește-ți cariera în turneul Criss-Cross! Află detalii" tournament_blurb_zero_sum: "Dezlănțuie creativitatea de programare în strângerea de aur sau în tactici de bătălie în meciul în oglindă din munte dintre vrăjitorii roși și cei albaștri.Turneul începe Vineri, 27 Martie și se va desfăsura până Luni, 6 Aprilie la 5PM PDT. Află detalii" # tournament_blurb_ace_of_coders: "Battle it out in the frozen glacier in this domination-style mirror match! The tournament began on Wednesday, September 16 and will run until Wednesday, October 14 at 5PM PDT. Check out the details" tournament_blurb_blog: "pe blogul nostru" rules: "Reguli" winners: "Învingători" league: "Ligă" red_ai: "CPU Roșu" # "Red AI Wins", at end of multiplayer match playback blue_ai: "CPU Albastru" wins: "Victorii" # At end of multiplayer match playback losses: "Pierderi" win_num: "Victorii" loss_num: "Pierderi" win_rate: "Victorii %" humans: "Roșu" # Ladder page display team name ogres: "Albastru" tournament_end_desc: "Turneul este terminat, mulțumim că ați jucat" age: "Vârsta" age_bracket: "Intervalul de vârstă" bracket_0_11: "0-11" bracket_11_14: "11-14" bracket_14_18: "14-18" bracket_11_18: "11-18" bracket_open: "Deschis" user: user_title: "__name__ - Învață să scrii cod cu CodeCombat" stats: "Statistici" singleplayer_title: "Niveluri individuale" multiplayer_title: "Niveluri multi-jucător" achievements_title: "Realizări" last_played: "Ultima oară jucat" status: "Stare" status_completed: "Complet" status_unfinished: "Neterminat" no_singleplayer: "Niciun joc individual jucat." no_multiplayer: "Niciun joc multi-jucător jucat." no_achievements: "Nici o realizare obținută." favorite_prefix: "Limbaj preferat" favorite_postfix: "." not_member_of_clans: "Nu ești membrul unui clan." certificate_view: "vezi certificat" certificate_click_to_view: "apasă să vezi certificatul" certificate_course_incomplete: "curs incomplet" certificate_of_completion: "Certificat de participare" certificate_endorsed_by: "Aprobat de" certificate_stats: "Nivelul de curs" certificate_lines_of: "linii de" certificate_levels_completed: "niveluri terminate" certificate_for: "pentru" certificate_number: "Nr." achievements: last_earned: "Ultimul câștigat" amount_achieved: "Sumă" achievement: "Realizare" current_xp_prefix: "" current_xp_postfix: " în total" new_xp_prefix: "" new_xp_postfix: " câștigat" left_xp_prefix: "" left_xp_infix: " până la nivelul" left_xp_postfix: "" account: title: "Cont" settings_title: "Setări cont" unsubscribe_title: "Dezabonare" payments_title: "Plăți" subscription_title: "Abonament" invoices_title: "Facturi" prepaids_title: "Preplătite" payments: "Plăți" prepaid_codes: "Coduri preplătite" purchased: "Cumpărate" subscribe_for_gems: "Abonează-te pentru pietre" subscription: "Abonament" invoices: "Facturi" service_apple: "Apple" service_web: "Web" paid_on: "Plătit pe" service: "Service" price: "Preț" gems: "Pietre prețioase" active: "Activ" subscribed: "Abonat" unsubscribed: "Dezabonat" active_until: "Activ până la" cost: "Cost" next_payment: "Următoarea plată" card: "Card" status_unsubscribed_active: "Nu ești abonat și nu vei fi facturat, contul tău este activ deocamdată." status_unsubscribed: "Primește access la niveluri noi, eroi, articole și pietre prețioase bonus cu un abonament CodeCombat!" not_yet_verified: "Neverificat încă." resend_email: "Te rog să salvezi mai întâi apoi retrimite email" email_sent: "Email transmis! Verifică casuța de email." verifying_email: "Verificarea adresei de email..." successfully_verified: "Ai verificat cu succes căsuța de email!" verify_error: "ceva a mers rău la verificarea adresei tale de email :(" unsubscribe_from_marketing: "Dezabonează __email__ de la toate mesajele de marketing ale CodeCombat?" unsubscribe_button: "Da, dezabonează" unsubscribe_failed: "Eșuat" unsubscribe_success: "Succes" manage_billing: "Administrare facturi" account_invoices: amount: "Sumă in dolari US" declined: "Cardul tău a fost refuzat" invalid_amount: "Introdu o sumă în dolari US." not_logged_in: "Autentifică-te sau Creează un cont pentru a accesa facturile." pay: "Plată factură" purchasing: "Cumpăr..." retrying: "Eroare server, reîncerc." success: "Plătit cu success. Mulțumim!" account_prepaid: purchase_code: "Cumpără un cod de abonament" purchase_code1: "Codurile de abonament revendicate vor adăuga o perioadă de subscripție premium la unul sau mai multe conturi pentru versiunea Home a CodeCombat." purchase_code2: "Fiecare cont CodeCombat poate revendica un anumit cod de abonament o singură dată." purchase_code3: "Codurile lunare de abnament vor fi adăugate în cont la sfârsitul abonamentelor deja existente." purchase_code4: "Codurile de abonament sunt pentru conturile care au acces la versiunea Home a CodeCombat, ele nu pot fi utilizate ca licențe de elevi la versiunea Classroom." purchase_code5: "Pentru mai multe informații asupra licențelor de elevi, contactați-ne la" users: "Utilizatori" months: "luni" purchase_total: "Total" purchase_button: "Transmite cererea de cumpărare" your_codes: "Codurile tale" redeem_codes: "Revendicare cod de abonament" prepaid_code: "Cod pre-plătit" lookup_code: "Vezi coduri pre-plătite" apply_account: "Aplică contului tău" copy_link: "Poți copia link-ul de cod și îl poți transmite către o altă persoană." quantity: "Cantitate" redeemed: "Revendicate" no_codes: "Nici un cod încă!" you_can1: "Poți" you_can2: "cumpăra un cod pre-plătit" you_can3: "care poate fi aplicat contului tău sau poate fi dat altora." impact: hero_heading: "Construim o clasă de informatică la nivel global" hero_subheading: "Ajutăm profesorii implicați și inspirăm elevii din întreaga țară" featured_partner_story: "Experiențele partenerilor noștri" partner_heading: "Predarea cu succes a programării la Title I School" partner_school: "Școala gimanzială Bobby Duke" featured_teacher: "Scott Baily" teacher_title: "Profesor de tehnologie în Coachella, CA" implementation: "Implementare" grades_taught: "Predare la clasele" length_use: "Timp utilizare" length_use_time: "3 ani" students_enrolled: "Elevi înscriși anul acesta" students_enrolled_number: "130" courses_covered: "Cursuri acoperite" course1: "CompSci 1" course2: "CompSci 2" course3: "CompSci 3" course4: "CompSci 4" course5: "GameDev 1" fav_features: "Caracterisitici preferate" responsive_support: "Suport responsiv" immediate_engagement: "Angajare imediată" paragraph1: "Școala gimanzială Bobby Duke se află situată între munții Coachella Valley din California de sud în vest și est și la 33 mile de Salton Sea în sud, și are o pulație de 697 elevi în cadrul unei populații de 18,861 elevi din districtul Coachella Valley Unified." paragraph2: "Elevii școlii gimanziale Bobby Duke reflectă provocările socio-economice ale populației și elevilor din Valea Coachella. Cu peste 95% dintre copii din Școala gimnazială calaficându-se pentru programul de masă gratuit sau cu preț redus și peste 40% clasificați ca populație ce învață limba Engleză, importanța predării unor aptitudini ale secolului 21 a fost o prioritate de top a profesorului de tehnologie din Școala gimanziă Bobby Dukehool, Scott Baily." paragraph3: "Baily a știut că învățarea elevilor să scrie cod este o modalitate importantă pentru a creea o oportunitate în condițiile în care piața muncii prioritizează din ce în ce mai mult și necesită abilități în domeniul calculatoarelor. De aceea, s-a hotărât să își asume această provocare captivantă de creare și predare a singurei clase de programare din școală și găsirea unei soluții accesibile financiar, care răspunde rapid la păreri, și antrenantă pentru elevi cu diverse abilități și condiții de studiu." teacher_quote: "Când am pus mâna pe CodeCombat [și] elevii mei au început să îl folosească, am avut o revelație. Era diferit ca ziua de noapte față de alte programe pe care le-am utilizat. Nu se apropie nici măcar un pic." quote_attribution: "Scott Baily, Profesor de tehnologe" read_full_story: "Citește povestea întreagă" more_stories: "Mai multe experiențe ale partenerilor" partners_heading_1: "Sprijin pentru mai multe linii de învățare informatică într-o singură clasă" partners_school_1: "Liceul Preston" partners_heading_2: "Excelență în examenele de plasare - AP Exam" partners_school_2: "Liceul River Ridge" partners_heading_3: "Predare informaticăă fără o experiență prealabilă" partners_school_3: "Liceul Riverdale" download_study: "Descarcă studiul de cercetare" teacher_spotlight: "Profesor & Elev în lumina reflectoarelor" teacher_name_1: "Amanda Henry" teacher_title_1: "Instructor de reabilitare" teacher_location_1: "Morehead, Kentucky" spotlight_1: "Prin compasiunea ei și dorința de a ajuta pe cei ce au nevoie de a adoua șansă, Amanda Henry a ajutat la schimbarea vieții elevilor care au nevoie de modele pozitive în viață. Fără o experiență în informatică prealabilă, Henry și-a condus elevii pe calea succesului într-o competiție regională de programare." teacher_name_2: "Kaila, Elev" teacher_title_2: "Colegiul comunal & tehnologic Maysville" teacher_location_2: "Lexington, Kentucky" spotlight_2: "Kaila a fost o elevă care niciodată nu s-a gândit că va putea scrie linii de cod, nicidecum că va fi înscrisă la un colegiu care-i oferă o cale către un viitor luminos." teacher_name_3: "Susan Jones-Szabo" teacher_title_3: "Profesor bibliotecar" teacher_school_3: "Școala primară Ruby Bridges" teacher_location_3: "Alameda, CA" spotlight_3: "Susan Jones-Szabo promovează o atmosferă echitabilă în clasa ei unde toată lumea poate obține rezultate în ritmul său. Greșelile și strădania sunt binevenite deoarece toată lumea învață din provocări, chiar și profesorul." continue_reading_blog: "Continuă să citești pe blog..." loading_error: could_not_load: "Eroare la încărcarea de pe server. Încearcă să reîncarci pagina" connection_failure: "Conexiune eșuată." connection_failure_desc: "Nu pare să fi conectat la Internet! Verifică conexiunea de rețea și apoi reîncarcă pagina." login_required: "Autentificare necesară" login_required_desc: "Trebuie să te autentifici pentru a avea acces la această pagină." unauthorized: "Trebuie să te autentifici. Ai cookies dezactivate?" forbidden: "Nepermis." forbidden_desc: "Oh nu, nu este nimic de văzut aici! Fi sigur că te-ai conectat la contul potrivit, sau vizitează unul din link-urile de mai jos ca să te reîntorci la programare!" user_not_found: "Utilizatoul nu este găsit" not_found: "Nu a fost găsit." not_found_desc: "Hm, nu este nimci aici. Vizitează unul din link-urile următoare ca să te reîntorci la programare!" not_allowed: "Metodă nepermisă." timeout: "Serverul nu poate fi contactat." conflict: "Conflict de resurse." bad_input: "Date greșite." server_error: "Eroare Server." unknown: "Eroare necunoscută." error: "EROARE" general_desc: "Ceva nu a mers bine, și probabil este vina noastră. Încearcă să aștepți puțin și apoi reîncarcă pagina, sau vizitează unul din link-urile următoare ca să te reîntorci la programare!" too_many_login_failures: "Au fost prea multe încercări eșuate de autentificare. Te rog să încerci mai târziu." resources: level: "Nivel" patch: "Patch" patches: "Patch-uri" system: "Sistem" systems: "Sisteme" component: "Componentă" components: "Componente" hero: "Erou" campaigns: "Campanii" concepts: advanced_css_rules: "Reguli CSS avansate" advanced_css_selectors: "Selectori CSS avansați" advanced_html_attributes: "Atribute HTML avansate" advanced_html_tags: "Tag-uri HTML avansate" algorithm_average: "Algoritm Medie aritmetică" algorithm_find_minmax: "Algoritm Caută Min/Max" algorithm_search_binary: "Algoritm Căutare binară" algorithm_search_graph: "Algoritm Căutare în graf" algorithm_sort: "Algoritm Sortare" algorithm_sum: "Algoritm Suma" arguments: "Argumente" arithmetic: "Aritmetică" array_2d: "Matrice bi-dimensională" array_index: "Indexare matriceală" array_iterating: "Iterare prin matrici" array_literals: "Literele matricelor" array_searching: "Căutare în matrice" array_sorting: "Sortare în matrice" arrays: "Matrici" basic_css_rules: "Regulii CSS de bază" basic_css_selectors: "Selectori CSS de bază" basic_html_attributes: "Atribute HTML de bază" basic_html_tags: "Tag-uri HTML de bază" basic_syntax: "Sintaxă de bază" binary: "Binar" boolean_and: "Și boolean" boolean_inequality: "Ingalitatea booleană" boolean_equality: "Egalitatea booleană" boolean_greater_less: "Mai mare/mai mic boolean" boolean_logic_shortcircuit: "Scurtături logice booleene" boolean_not: "Nu boolean" boolean_operator_precedence: "Precedența operatorilor booleeni" boolean_or: "Sau boolean" boolean_with_xycoordinates: "Comparații de coordonate" bootstrap: "Bootstrap" # Can't be translate in Romanian, is used in English form break_statements: "Instrucțiuni de oprire" classes: "Clase" continue_statements: "Instrucțiuni de continuare" dom_events: "Evenimente DOM" dynamic_styling: "Stilizare dinamică" events: "Evenimente" event_concurrency: "Evenimente concurente" event_data: "Date pentru evenimente" event_handlers: "Manipulatori de eveniment" # event_spawn: "Spawn Event" for_loops: "Bucle for" for_loops_nested: "Bucle for îmbricate" for_loops_range: "Zona de aplicare a buclelor for" functions: "Funcții" functions_parameters: "Parametrii" functions_multiple_parameters: "Parametrii multiplii" game_ai: "Joc AI" game_goals: "Obiectivele jocului" # game_spawn: "Game Spawn" graphics: "Grafică" graphs: "Grafuri" heaps: "Stive" if_condition: "Instrucțiuni condiționale if" if_else_if: "Instrucțiuni If/Else/IF" if_else_statements: "Instrucțiuni If/Else" if_statements: "Instrucțiuni If" if_statements_nested: "Instrucțiuni if îmbricate" indexing: "Indexuri matriceale" input_handling_flags: "Manipulare intrări - Flag-uri" input_handling_keyboard: "Manipulare intrări - Tastatură" input_handling_mouse: "Manipulare intrări - Mouse" intermediate_css_rules: "Reguli CSS intermediare" intermediate_css_selectors: "Selectrori CSS intermediari" intermediate_html_attributes: "Atribute HTML intermediare" intermediate_html_tags: "Tag-uri HTML intermediare" jquery: "jQuery" jquery_animations: "Animații jQuery" jquery_filtering: "Filtrare elemente jQuery" jquery_selectors: "Selectori jQuery" length: "Lungime matrice" math_coordinates: "Calculare coordonate" math_geometry: "Geometrie" math_operations: "Librăria de operații matematice" math_proportions: "Proporții matematice" math_trigonometry: "Trigonometrie" # object_literals: "Object literals" parameters: "Parametrii" programs: "Programe" properties: "Proprietăți" property_access: "Accesare proprietăți" property_assignment: "Alocarea proprietăți" property_coordinate: "Proprietatea coordonate" queues: "Structuri de date - Cozi" reading_docs: "Citirea documentației" recursion: "Recursivitate" return_statements: "Instrucțiunea return" stacks: "Structuri de date - Stive" strings: "Șiruri de caractere" strings_concatenation: "Concatenare șiruri de caractere" strings_substrings: "Sub-șir de caractere" trees: "Structuri de date - Arbori" variables: "Variabile" vectors: "Vectori" while_condition_loops: "Bucle while cu condiționare" while_loops_simple: "Bucle while" while_loops_nested: "Bucle while îmbricate" xy_coordinates: "Perechi de coordonate" advanced_strings: "Șiruri de caractere avansate" # Rest of concepts are deprecated algorithms: "Algoritmi" boolean_logic: "Logică booleană" basic_html: "HTML de bază" basic_css: "CSS de bază" basic_web_scripting: "Programare web de bază" intermediate_html: "HTML intermediar" intermediate_css: "CSS intermediar" intermediate_web_scripting: "Programare web intermediar" advanced_html: "HTML avansat" advanced_css: "CSS avansat" advanced_web_scripting: "Programare web avansat" input_handling: "Manipulare intrări" while_loops: "Bucle while" place_game_objects: "Plasare obiecte de joc" construct_mazes: "Construcție labirinturi" create_playable_game: "Creează un proiect de joc pe care îl poți juca, partaja" alter_existing_web_pages: "Modifică pagini de web existente" create_sharable_web_page: "Creează o pagină web care poate fi partajată" basic_input_handling: "Manipulare de bază a intrărilor" basic_game_ai: "Joc IA de bază" basic_javascript: "Javascript de bază" basic_event_handling: "Manipulare de bază a evenimentelor" create_sharable_interactive_web_page: "Creează o pagină de web interactivă care poate fi partajată" anonymous_teacher: notify_teacher: "Anunță profesor" create_teacher_account: "Creează un cont de profesor gratuit" enter_student_name: "Numele tău:" enter_teacher_email: "Adresa de email de profesor:" teacher_email_placeholder: "profesor.email@example.com" student_name_placeholder: "scrie numele tău aici" teachers_section: "Profesori:" students_section: "Elevi:" teacher_notified: "Ți-am anunțat profesorul că vrei să joci mai mult CodeCombat în clasă!" delta: added: "Adăugat" modified: "Modificat" not_modified: "Nemodificat" deleted: "Șters" moved_index: "Index mutat" text_diff: "Diff text" merge_conflict_with: "COMBINĂ CONFLICTUL CU" no_changes: "Fară schimbări" legal: page_title: "Aspecte Legale" opensource_introduction: "CodeCombat este parte a comunității open source." opensource_description_prefix: "Vizitează " github_url: "pagina noastră de GitHub" opensource_description_center: "și ajută-ne dacă îți place! CodeCombat este construit dintr-o mulțime de proiecte open source, pe care noi le iubim. Vizitați" archmage_wiki_url: "Archmage wiki" opensource_description_suffix: "pentru o listă cu softul care face acest joc posibil." practices_title: "Convenții" practices_description: "Acestea sunt promisiunile noastre către tine, jucătorul, fără așa mulți termeni legali." privacy_title: "Confidenţialitate şi termeni" privacy_description: "Nu o să iți vindem datele personale." security_title: "Securitate" security_description: "Ne străduim să vă protejăm informațiile personale. Fiind un proiect open-source, site-ul nostru oferă oricui posibilitatea de a ne revizui și îmbunătăți sistemul de securitate." email_title: "Email" email_description_prefix: "Noi nu vă vom inunda cu spam. Prin" email_settings_url: "setările tale de email" email_description_suffix: " sau prin link-urile din email-urile care vi le trimitem, puteți să schimbați preferințele și să vâ dezabonați oricând." cost_title: "Cost" cost_description: "CodeCombat se poate juca gratuit în nivelurile introductive, cu un abonament de ${{price}} USD/lună pentru acces la niveluri suplimentare și {{gems}} pietre prețioase bonus pe lună. Poți să anulezi printr-un simplu clic și oferim banii înapoi garantat în proporție de 100%." copyrights_title: "Drepturi de autor și licențe" contributor_title: "Acord de licență Contributor" contributor_description_prefix: "Toți contribuitorii, atât pe site cât și pe GitHub-ul nostru, sunt supuși la" cla_url: "ALC" contributor_description_suffix: "la care trebuie să fi de accord înainte să poți contribui." code_title: "Code - MIT" # {change} client_code_description_prefix: "Tot codul pe partea de client al codecombat.com din depozitul public GitHub și din baza de date codecombat.com, este licențiat sub" mit_license_url: "licența MIT" code_description_suffix: "Asta include tot codul din Systems și Components care este oferit de către CodeCombat cu scopul de a creea nivelurile." art_title: "Artă/Muzică - Conținut comun " art_description_prefix: "Tot conținutul creativ/artistic este valabil sub" cc_license_url: "Creative Commons Attribution 4.0 International License" art_description_suffix: "Conținut comun este orice făcut general valabil de către CodeCombat cu scopul de a crea niveluri. Asta include:" art_music: "Muzică" art_sound: "Sunet" art_artwork: "Artwork" art_sprites: "Sprites" art_other: "Orice și toate celelalte creații non-cod care sunt disponibile când se creează niveluri." art_access: "Momentan nu există nici un sistem universal, ușor pentru preluarea acestor bunuri. În general, preluați-le din adresele URL așa cum sunt folosite de site-ul web, contactați-ne pentru asistență, sau ajutați-ne să extindem site-ul ca să facem aceste bunuri mai ușor accesibile." art_paragraph_1: "Pentru atribuire, vă rugăm denumiți și să faceți referire la codecombat.com aproape de locația unde este folosită sursa sau unde este adecvat pentru mediu. De exemplu:" use_list_1: "Dacă este folosit într-un film sau alt joc, includeți codecombat.com la credite." use_list_2: "Dacă este folosit pe un site, includeți un link în apropiere, de exemplu sub o imagine, sau în pagina generală de atribuiri unde menționați și alte bunuri creative și softul open source folosit pe site. Ceva care face referință explicit la CodeCombat, precum o postare pe un blog care menționează CodeCombat, nu trebuie să se facă o atribuire separată." art_paragraph_2: "Dacă conținutul folosit nu este creat de către CodeCombat ci de către un utilizator al codecombat.com,atunci faceți referință către el și urmăriți indicațiile de atribuire prevăzute în descrierea resursei, dacă aceasta există." rights_title: "Drepturi rezervate" rights_desc: "Toate drepturile sunt rezervate pentru nivelurile în sine. Asta include" rights_scripts: "script-uri" rights_unit: "Configurații de unități" rights_writings: "scrieri" rights_media: "Media (sunete, muzică) și orice alt conținut creativ dezvoltat special pentru un nivel și care nu sunt valabile în mod normal pentru creearea altor niveluri." rights_clarification: "Pentru a clarifica, orice este valabil în Editorul de Niveluri pentru scopul de a crea niveluri se află sub licențiere CC, pe când conținutul creat cu Editorul de Niveluri sau încărcat pentru a face niveluru nu se află sub aceasta." nutshell_title: "Pe scurt" nutshell_description: "Orice resurse vă punem la dispoziție în Editorul de Niveluri puteți folosi liber cum vreți pentru a crea niveluri. Dar ne rezervăm dreptul de a rezerva distribuția de niveluri în sine (care sunt create pe codecombat.com) astfel încât să se poată percepe o taxă pentru ele pe vitor, dacă se va ajunge la așa ceva." nutshell_see_also: "Vezi și:" canonical: "Versiunea în engleză a acestui document este cea definitivă, versiunea canonică. Dacă există orice discrepanțe între versiunea tradusă și cea originală, documentul în engleză are prioritate." third_party_title: "Servicii Third Party" third_party_description: "CodeCombat utilizează următoarele servicii third party (printre altele):" cookies_message: "CodeCombat utilizează câteva cookies esențiale și neesențaile." cookies_deny: "Refuză cookies neesențiale" cookies_allow: "Permite cookies" calendar: year: "An" day: "Zi" month: "Luna" january: "Ianuarie" february: "Februarie" march: "Martie" april: "Aprilie" may: "Mai" june: "Iunie" july: "Iulie" august: "August" september: "Septembrie" october: "Octombrie" november: "Noiembrie" december: "Decembrie" code_play_create_account_modal: title: "Ai reușit!" # This section is only needed in US, UK, Mexico, India, and Germany body: "Ești pe cale să devii un programator de top. Înregistrează-te ca să primești suplimentar <strong>100 pietre prețioase</strong> & vei intra de asemenea pentru o șansă de a <strong>câștiga $2,500 & alte premii Lenovo</strong>." sign_up: "Întregistrează-te & continuă să programezi ▶" victory_sign_up_poke: "Creează un cont gratuit ca să poți salva codul scris & o șansă să câștigi premii!" victory_sign_up: "Înregistrează-te & să intri să <strong>câștigi $2,500</strong>" server_error: email_taken: "Email deja utilizat" username_taken: "Cont de utilizator existent" easy_password: "Parola este prea ușor de ghicit" reused_password: "Parola nu poate fi reutilizată" esper: line_no: "Linia $1: " uncaught: "Ne detectat $1" # $1 will be an error type, eg "Uncaught SyntaxError" reference_error: "ReferenceError: " argument_error: "ArgumentError: " type_error: "TypeError: " syntax_error: "SyntaxError: " error: "Eroare: " x_not_a_function: "$1 nu este o funcție" x_not_defined: "$1 nu este definit" spelling_issues: "Verifică erori de scriere: ai vrut `$1` în loc de `$2`?" capitalization_issues: "Verifică modul de scriere cu literele mari/mici: `$1` trebuie să fie `$2`." py_empty_block: "$1 este gol. Pune 4 spații în fața instrucțiunilor în interiorul instrucțiunii $2." fx_missing_paren: "Dacă vrei să chemi `$1` ca și funcție, ai nevoie de `()`" unmatched_token: "`$1` fără pereche. Fiecare deschidere `$2` trebuie să aibă o încheiere `$3` ca și pereche." unterminated_string: "Șir de caractere neterminat. Adaugă perechea de `\"` la sfârșitul șirului de caractere." missing_semicolon: "Punct și virgulă (;) lipsește." missing_quotes: "Ghilimelele lipsesc. Încearcă `$1`" argument_type: "Argumentul lui`$1` este `$2` care trebuie să fie de tipul`$3`, dar are `$4`: `$5`." argument_type2: "Argumentul lui `$1` este `$2` care trebuie să fie de tipul `$3`, dar are `$4`." target_a_unit: "Țintește o unitate." attack_capitalization: "Atacă $1, nu $2. (Literele mari sunt importante.)" empty_while: "Instrucțiune while goală. Pune 4 spații în fața instrucțiunilor în interiorul instrucțiunii while." line_of_site: "Argumentul `$1` este `$2` și are o problemă. Este deja un inamic în linia ta vizuală?" need_a_after_while: "Ai nevoie de un `$1` după `$2`." too_much_indentation: "Prea multă indentare la începutul acestei linii." missing_hero: "Cuvântul cheie `$1` lipsește; ar trebui să fie `$2`." takes_no_arguments: "`$1` nu ia nici un argument." no_one_named: "Nu este nimeni cu numele \"$1\" ca și țintă." separated_by_comma: "Parametrii de chemare a funcțiilor ar trebui separați cu `,`" protected_property: "Nu pot citi proprietatea protejată: $1" need_parens_to_call: "Dacă vrei să chemi `$1` ca și funcție ai nevoie de `()`" expected_an_identifier: "Se asteaptă un identificator dar în loc este '$1'." unexpected_identifier: "Identificator neașteptat" unexpected_end_of: "Terminare intrare neașteptată" unnecessary_semicolon: "Punct și virgulă neașteptate." unexpected_token_expected: "Token neașteptat: se aștepta $1 dar s-a găsit $2 când s-a analizat $3" unexpected_token: "$1 este un token neașteptat" unexpected_token2: "Token neașteptat" unexpected_number: "Număr neașteptat" unexpected: "'$1' neașteptat." escape_pressed_code: "Tasta escape apăsată; cod întrerupt." target_an_enemy: "Țintește un inamic după nume, ca `$1`, nu șirul de caractere `$2`." target_an_enemy_2: "Țintește un inamic după nume, ca $1" cannot_read_property: "Proprietatea '$1' nu se poate citi de tip nedefinit" attempted_to_assign: "Încercare de alocare proprietate readonly (doar pentru cititre)." unexpected_early_end: "Sfârșit de program neașteptat." you_need_a_string: "Trebuie să construiești un șir de caractere; unul ca $1" unable_to_get_property: "Proprietatea '$1' de tip nedefinit nu poate fi accesată sau referință către null" # TODO: Do we translate undefined/null? code_never_finished_its: "Programul nu a terminat niciodată. Este fie foarte încet or are o buclă infinită." unclosed_string: "Șir de caractere neînchis." unmatched: "'$1' fără pereche." error_you_said_achoo: "Ai scris: $1, dar parola este: $2. (Literele mari sunt importante.)" indentation_error_unindent_does: "Eroare de indentare: neindentarea nu se potrivește cu nici una din nivelurile de indentare" indentation_error: "Eroare de identare." need_a_on_the: "Ai nevoie de `:` la sfârșitul liniei după `$1`." attempt_to_call_undefined: "încercare de chemare a '$1' (o valoare nil)" unterminated: "`$1` neterminat" target_an_enemy_variable: "Țintește o variabilă $1, nu șirul de caractere $2. (Încearcă $3.)" error_use_the_variable: "Utilizează numele de variabilă `$1` în loc de șirul de caractere `$2`" indentation_unindent_does_not: "Neindentarea nu se potrivește cu nici una din nivelurile de indentare" unclosed_paren_in_function_arguments: "$1 neînchis în argumentele funcției." unexpected_end_of_input: " Sfârșit de intrare neașteptat" there_is_no_enemy: "Nu există`$1`. Utilizează mai întâi `$2`." # Hints start here try_herofindnearestenemy: "Încearcă `$1`" there_is_no_function: "Nu există funcția `$1`, dar `$2` are metoda `$3`." attacks_argument_enemy_has: "Argumentul lui`$1` este `$2` și are o problemă." is_there_an_enemy: "Este deja un inamic în linia ta vizuală?" target_is_null_is: "Ținta este $1. Există tot mereu o țintă pe care să o ataci? (Utilizezi $2?)" hero_has_no_method: "`$1` nu are nici o metodă`$2`." there_is_a_problem: "Este o problemă cu codul tău." did_you_mean: "Ai vrut să scrii $1? Nu ești echipat cu un element care să aibă acea abilitate." missing_a_quotation_mark: "O pereche de ghilimele lipsesc. " missing_var_use_var: "`$1` lipsește. Utilizează `$2` să faci o nouă variabilă." you_do_not_have: "Nu ești echipat cu un element care să aibă abilitatea $1." put_each_command_on: "Pune fiecare comandă pe o linie separată" are_you_missing_a: "Îți lipsește '$1' după '$2'? " your_parentheses_must_match: "Parantezele tale trebuie să fie pereche." apcsp: title: "Principiile informaticii de plasare avansată (AP) | Aprobate de Comisia colegiilor" meta_description: "Curicula completă a CodeCombat și programul de dezvoltare profesională sunt tot ceea ce ai nevoie pentru a oferi elevilor un nou curs de informatică al Comisiei colegiilor." syllabus: "Programa cu principiile informaticii pentru AP" syllabus_description: "Utilizează această resursă pentru a planifica curicula CodeCombat pentru clasa de principiile informaticii pentru AP." computational_thinking_practices: "Practici de gândire computațională" learning_objectives: "Obiective de învățare" curricular_requirements: "Cerințe curiculare" unit_1: "Unitatea 1: Tehnologie creativă" unit_1_activity_1: "Activitate unitatea 1: Prezentare a utilității tehnologiei" unit_2: "Unitatea 2: Gândire computațională" unit_2_activity_1: "Activitate unitatea 2: Secvențe binare" unit_2_activity_2: "Activitate unitatea 2: Proiect de lecție pentru tehnică de calcul" unit_3: "Unitatea 3: Algoritmi" unit_3_activity_1: "Activitate unitatea 3: Algoritmi - Ghidul Hitchhiker" unit_3_activity_2: "Activitate unitatea 3: Simulare - Prădător & Pradă" unit_3_activity_3: "Activitate unitatea 3: Algoritmi - Programare și design în perechi" unit_4: "Unitatea 4: Programare" unit_4_activity_1: "Activitate unitatea 4: Abstractizare" unit_4_activity_2: "Activitate unitatea 4: Căutare & Sortare" unit_4_activity_3: "Activitate unitatea 4: Refactorizare" unit_5: "Unitatea 5: Internetul" unit_5_activity_1: "Activitate unitatea 5: Cum funcționează Internetul" unit_5_activity_2: "Activitate unitatea 5: Simulator Internet" unit_5_activity_3: "Activitate unitatea 5: Simulator de canal de chat" unit_5_activity_4: "Activitate unitatea 5: Cybersecurity" unit_6: "Unitatea 6: Data" unit_6_activity_1: "Activitate unitatea 6: Introducere în date" unit_6_activity_2: "Activitate unitatea 6: Big Data" unit_6_activity_3: "Activitate unitatea 6: Compresie cu pierderi & fără pierderi" unit_7: "Unitatea 7: Impact personal & global" unit_7_activity_1: "Activitate unitatea 7: Impact personal & global" unit_7_activity_2: "Activitate unitatea 7: Crowdsourcing" unit_8: "Unitatea 8: Proba de performanță" unit_8_description: "Pregătește elevii pentru Creează temă în care vor construi propriile lor jocuri și în care vor testa conceptele de bază." unit_8_activity_1: "Practica 1 - Creează temă: Dezvolatre joc 1" unit_8_activity_2: "Practica 2 - Creează temă: Dezvolatre joc 2" unit_8_activity_3: "Practica 3 - Creează temă: Dezvolatre joc 3" unit_9: "Unitatea 9: Prezentare generală AP" unit_10: "Unitatea 10: După AP" unit_10_activity_1: "Activitate unitatea 10: Chestionar web" parents_landing_2: splash_title: "Descoperă magia programării acasă." learn_with_instructor: "Învață cu un instructor" live_classes: "Clase online în timp real" live_classes_offered: "CodeCombat oferă acum clase online de informatică pentru elevii care fac școala acasă. Bun pentru elevii care lucreează bine 1:1 sau grupuri mici în care rezultatele învățării sunt adaptate nevoilor lor." live_class_details_1: "Grupuri mici sau lecții private" live_class_details_2: "Programare în Javascript și Python, plus concepte de bază în informatică" live_class_details_3: "Predat de instructori experți în programare" live_class_details_4: "Păreri individualizate și imediate" live_class_details_5: "Curicula beneficiază de încrederea a 80,000+ de educatori" try_free_class: "Încearcă o clasă gratuită de 60 minute" pricing_plans: "Planuri de preț" choose_plan: "Alege un plan" per_student: "pentru fiecare elev" sibling_discount: "15% reducere pentru frați!" small_group_classes: "Clase de programare în grupuri mici" small_group_classes_detail: "4 grupuri pe sesiune / lună." small_group_classes_price: "$159/lună" small_group_classes_detail_1: "4:1 este rația elevi-profesor" small_group_classes_detail_2: "Clase de 60 de minute" small_group_classes_detail_3: "Construiește proiecte și spune-ți părerea despre proiectele celorlalți" small_group_classes_detail_4: "Partajare ecran pentru a primi păreri în timp real și depanare cod" private_classes: "Clase de programare private" four_sessions_per_month: "4 sesiuni private / lună." eight_sessions_per_month: "8 sesiuni private / lună." four_private_classes_price: "$219/lună" eight_private_classes_price: "$399/lună" private_classes_detail: "4 sau 8 sesiuni private / lună." private_classes_price: "$219/lună sau $399/lună" private_classes_detail_1: "1:1 este rația elev-profesor" private_classes_detail_2: "Clase de 60 de minut" private_classes_detail_3: "Program flexibil adaptat nevoilor tale" private_classes_detail_4: "Planuri de lecție și păreri în timp real adaptate stilului de învățare al elevului, ritmului acestuia și nivelului de abilități" best_seller: "Cel mai bine vândut" best_value: "Cea mai bună valoare" codecombat_premium: "CodeCombat Premium" learn_at_own_pace: "Învață în ritmul tău" monthly_sub: "Abonament lunar" buy_now: "Cumpără acum" per_month: " / lună" lifetime_access: "Acces pe viață" premium_details_title: "Bun pentru cei ce învață singuri și doresc autonomie completă." premium_details_1: "Accesează eroi, animăluțe și aptitudini disponibile doar abonaților" premium_details_2: "Primește pietre prețioase bonus să cumperi echipament, animăluțe și mai mulți eroi" premium_details_3: "Deblochează detalii despre concepte de bază și abilități ca dezvoltarea web și de jocuri" premium_details_4: "Suport premium pentru cei abonați" premium_details_5: "Creează clanuri private să îți inviți prietenii pentru a concura în grup" premium_need_help: "Ai nevoie de ajutor sau preferi Paypal? Email <a href=\"mailto:support@codecombat.com\">support@codecombat.com</a>" not_sure_kid: "Nu ești sigur dacă CodeCombat este pentru copiii tăi? Întreabă-i!" share_trailer: "Arată-i filmul nostru de prezentare copilului tău și determină-l să își facă un cont pentru a începe." why_kids_love: "De ce iubesc copiii CodeCombat" learn_through_play: "Învață prin joacă" learn_through_play_detail: "Elevii își vor dezvolta abilitățile de a scrie cod și își vor utiliza abilitățile de rezolvare a problemelor pentru a progresa prin niveluri și a-și crește eroul." skills_they_can_share: "Abilități pe care le pot partaja" skills_they_can_share_details: "Elevii își dezvoltă abilități din lumea reală și creează proiecte, cum ar fi jocuri sau pagini web, pe care le pot partaja cu prietenii și familia." help_when_needed: "Ajută-i atunci când au nevoie" help_when_needed_detail: "Utilizând date, fiecare nivel a fost construit să îi incite, dar niciodată să îi descurajeze. Elevii sun ajutați cu indicii atunci când se blochează." book_first_class: "Rezervă-ți prima clasă" why_parents_love: "De ce părinții iubesc CodeCombat" most_engaging: "Cel mai antrenant mod să înveți să scrii cod" most_engaging_detail: "Copilul tău va avea tot ce are nevoie la degentul mic pentru a scrie algoritmi în Python sau Javascript, să dezvolte site-uri web sau chiar să-și proiecteze propriul joc, în timp ce învață materie aliniată la standardele de curiculă națională." critical_skills: "Dezvoltă abilități importante pentru secolul 21" critical_skills_detail: "Copilul tău va învăța să navigheze și să devină cetățean în lumea digitală. CodeCombat este o soluție care îi îmbunătățește copilului tău gândirea critică, creativitatea și reziliența, îmbunătățindu-le abilitățile de care au nevoie în orice domeniu." parent_support: "Susținuți de părinți ca tine" parent_support_detail: "La CodeCombat, noi suntem părinții. Noi suntem programatori. Suntem profesori. Dar în primul rând, suntem oameni care credem că îi dăm copilului tău oportunitatea să aibă succes în orice își doreste acesta să facă." everything_they_need: "Tot ceea ce au nevoie pentru a începe să scrie cod singuri" beginner_concepts: "Concepte pentru începători" beginner_concepts_1: "Sintaxa de bază" beginner_concepts_2: "Bucle while" beginner_concepts_3: "Argumente" beginner_concepts_4: "Șiruri de caractere" beginner_concepts_5: "Variabile" beginner_concepts_6: "Algoritmi" intermediate_concepts: "Concepte de nivel intermediar" intermediate_concepts_1: "Instrucțiunea if" intermediate_concepts_2: "Comparația booleană" intermediate_concepts_3: "Condiționale îmbricate" intermediate_concepts_4: "Funcții" intermediate_concepts_5: "Manipularea de bază a intrărilor" intermediate_concepts_6: "Inteligență artificială de bază pentru jocuri" advanced_concepts: "Concepte avansate" advanced_concepts_1: "Manipularea evenimentelor" advanced_concepts_2: "Bucle condiționale while" # advanced_concepts_3: "Object literals" advanced_concepts_4: "Parametri" advanced_concepts_5: "Vectori" advanced_concepts_6: "Librăria de operatori matematici" advanced_concepts_7: "Recursivitate" get_started: "Hai să începem" quotes_title: "Ce zic părinții și copiii despre CodeCombat" quote_1: "\"Acesta este următorul nivel de scriere cod pentru copii și este foarte amuzant. Voi învăța un lucru sau două din acesta.\"" quote_2: "\"Mi-a plăcut să învăț o nouă abilitate pe care înainte nu o aveam. Mi-a plăcut că atunci când am avut probleme, am putu să-mi stabilesc obiectivele. Mi-a mai plăcut să văd că codul scris de mine funcționează corect.\"" quote_3: "\"Python-ul lui Oliver începe să aibă sens. El utilizează CodeCombat să își facă jocuri video. M-a provocat să îi joc jocurile, apoi râde când pierd.\"" quote_4: "\"Acesta este unul din lucrurile pe care îmi place să le fac. În fiecare dimineață mă trezesc și joc CodeCombat. Dacă ar trebui să îi dau o notă pentru CodeCombat de la 1 la 10, i-aș da un 10!\"" parent: "Părinți" student: "Elev" grade: "Clasa" subscribe_error_user_type: "Se pare că deja te-ai înregistrat pentru un cont. Dacă ești interesat de CodeCombat Premium, te rog să ne contactezi la team@codecombat.com." subscribe_error_already_subscribed: "Deja ai un abonament pentru un cont premium." start_free_trial_today: "Începe gratuit de azi varianta de încercare" live_classes_title: "Clase de programare online de la CodeCombat!" live_class_booked_thank_you: "Clasa de online a fost programată, mulțumim!" book_your_class: "Programează-ți clasa" call_to_book: "Sună acum pentru programare" modal_timetap_confirmation: congratulations: "Felicitări!" paragraph_1: "Aventura elevilor tăi în lumea programării așteaptă." paragraph_2: "Copilul tău este înregistrat la o clasă online și abia așteptăm să îl întâlnim!" paragraph_3: "În curând ar trebui să primești un email de invitație cu detalii atât despre clasa programată cât și numele și datele de contact ale instructorului." paragraph_4: "Dacă, pentru orice motiv, dorești modificarea clasei alese, replanificare sau vrei să vorbești cu un specialist în relația cu clienții, trebuie doar să ne folosești datele de contact furnizate în mesajul email de invitație." paragraph_5: "Îți mulțumim că ai ales CodeCombat și îți urăm noroc în călătoria ta în informatică!" back_to_coco: "Înapoi la CodeCombat" hoc_2018: banner: "Bine ai venit la Hour of Code!" page_heading: "Elevii tăi vor învăța cum să își construiască propriul joc!" page_heading_ai_league: "Elevii tăi vor învăța cum să își construiască propriul joc IA multi-jucător!" step_1: "Pas 1: Urmărește video de prezentare" step_2: "Pas 2: Încearcă-l" step_3: "Pas 3: Descarcă planul de lecție" try_activity: "Încearcă activitatea" download_pdf: "Descarcă PDF" teacher_signup_heading: "Transformă Hour of Code în Year of Code" teacher_signup_blurb: "Tot ce ai nevoie să predai informatică, nu este necesară o experiență anterioară." teacher_signup_input_blurb: "Ia primul curs gratuit:" teacher_signup_input_placeholder: "Adresa de email a profesorului" teacher_signup_input_button: "Ia cursul CS1 gratuit" activities_header: "Mai multe activități Hour of Cod" activity_label_1: "Informatică nivel începător: Scapă din temniță!" activity_label_2: " Dezvoltare jocuri nivel începător: Construiește un joc!" activity_label_3: "Dezvoltare de jocuri nivel avansat: Construiește un joc tip arcadă!" activity_label_hoc_2018: "Dezvoltare de jocuri nivel intermediar: scrie cod, joacă, creează" activity_label_ai_league: "Informatică nivel începător: Calea către liga IA" activity_button_1: "Vezi lecția" about: "Despre CodeCombat" about_copy: "Un program de informatică bazat pe joc, aliniat standardelor care predă scriere de cod în Python și Javascript." point1: "✓ Punerea bazelor" point2: "✓ Diferențiere" point3: "✓ Evaluări" point4: "✓ Cursuri bazate pe proiecte" point5: "✓ Monitorizare elevi" point6: "✓ Planuri de lecție complete" title: "HOUR OF CODE" acronym: "HOC" hoc_2018_interstitial: welcome: "Bine ai venit la Hour of Code organizat de CodeCombat!" educator: "Sunt instructor" show_resources: "Arată-mi resursele profesorului!" student: "Sunt elev" ready_to_code: "Sunt gata să programez!" hoc_2018_completion: congratulations: "Felicitări că ai terminat <b>scrie cod, joacă, creează!</b>" send: "Trimite jocul tău Hour of Code prietenilor și familiei!" copy: "Copiază URL" get_certificate: "Descarcă o diplomă de participare pentru a sărbătorii cu clasa ta!" get_cert_btn: "Descarcă certificat" first_name: "Prenume" last_initial: "Nume de familie și inițiala" teacher_email: "Adresa de email a profesorului" school_administrator: title: "Panou de lucru al administratorului școlii" my_teachers: "Profesorii mei" last_login: "Ultima autentificare" licenses_used: "licențe utilizate" total_students: "total elevi" active_students: "elevi activi" projects_created: "proiecte create" other: "Altele" notice: "Următorii administratori de școală au acces numai de vizualizare la datele tale de clasă:" add_additional_teacher: "Trebuie să adaugi un alt profesor? Contactează-ți managerul de cont CodCombat sau trimite email la support@codecombat.com. " license_stat_description: "Conturile licențiate disponibile reprezintă numărul de licențe disponibile pentru profesori, incluzând licențele partajate." students_stat_description: "Numărul total de conturi de elevi reprezintă toți elevii din toate clasele, indiferent dacă aceștia au sau nu licențe aplicate." active_students_stat_description: "Conturi de elevi activi reprezintă numărul de elevi care s-au conectat la CodeCombat în ultimele 60 de zile." project_stat_description: "Proiectele create reprezintă numărul total de proiecte de dezvoltare web sau de jocuri care au fost create." no_teachers: "Nu aveți în administrare nici un profesor." totals_calculated: "Cum sunt aceste totaluri calculate?" totals_explanation_1: "Cum sunt aceste totaluri calculate?" totals_explanation_2: "Licențe utilizate" totals_explanation_3: "Reprezintă totalul licențelor aplicate elevilor din totalul de licențe disponibile." totals_explanation_4: "Total elevi" totals_explanation_5: "Reprezintă elevii din toate clasele active. Pentru a vedea totalul elevilor înrolați în clasele active și cele arhivate, mergi la pagina Licențe elevi." totals_explanation_6: "Elevi activi" totals_explanation_7: "Resprezintă toți elevii care au fost activi în ultimele 60 de zile." totals_explanation_8: "Proiecte create" totals_explanation_9: "Reprezintă toate proiectele de dezvoltare web sau jocuri create." date_thru_date: "de la __startDateRange__ până la __endDateRange__" interactives: phenomenal_job: "Te-ai descurcat fenomenal!" try_again: "Ups, încearcă din nou!" select_statement_left: "Ups, alege o afirmație din stânga înainte de a apăsa \"Transmite.\"" fill_boxes: "Ups, fi sigur că ai completat toate căsuțele înainte de a apăsa \"Transmite.\"" browser_recommendation: title: "CodeCombat funcționează cel mai bine pe Chrome!" pitch_body: "Pentru o experiență CodeCombat cât mai bună recomandăm să se utilizeze ultima versiune de Chrome. Descarcă ultima versiune de Chrome apăsând butonul de mai jos!" download: "Descarcă Chrome" ignore: "Ignoră" admin: license_type_full: "Cursuri complete" license_type_customize: "Personalizează cursuri" outcomes: school_admin: "Administrator de școală" school_network: "Rețea școlară" school_subnetwork: "Subrețea școlară" classroom: "Clasă" league: student_register_1: "Devino următorul campion IA!" student_register_2: "Înregistrează-te, creează-ți echipa ta sau alătură-te altor echipe pentru a începe să concurezi." student_register_3: "Furnizează informațiile de mai jos pentru a fi eligibil pentru premii." teacher_register_1: "Înregistrează-te pentru a accesa pagina de profil a ligii a clasei tale și pornește clasa." general_news: "Primește mesaje email despre utimele noutăți cu privire la Lgile IA și campionate." team: "echipă" how_it_works1: "Alătură-te __team__" seasonal_arena_tooltip: "Luptă împotriva membrilor de echipă sau alți membrii utilizând cele mai bune aptitudini de programare pe care le ai pentru a câștiga puncte și a te clasa cât mai sus în clasamentul ligii IA înainte de a concura în arena campionatului la sfârșitul sezonului." summary: "Liga IA CodeCombat este atât un simulator unic copetitiv de lupte IA dar și un mototr de jocuri pentru a învăța Python și Javascript." join_now: "Alătură-te acum" tagline: "Liga IA CodeCombat combină curicula aliniată la standarde bazată pe proiecte, programarea de jocuri captivante bazate pe aventură și campionatul anual de programare IA organizat într-o competiție academică anuală cum nu există alta." ladder_subheader: "Utilizează abilitățile tale de programare și strategiile de luptă pentru a urca în clasament!" earn_codepoints: "Câștigă CodePoints finalizând niveluri" codepoints: "CodePoints" free_1: "Accesează arene competitive cu concurenți multiplii, clasamente și campionatul global de programare" free_2: "Câștigă puncte pentru finalizarea nivelurilor de pregătire și concurând în meciuri cot-la-cot" free_3: "Alătură-te echipelor de programare competitive împreună cu prietenii, familia sau colegii de clasă" free_4: "Arată-ți abilitățile de programare și ia acasă premiile mari" compete_season: "Testează toate abilitățile învățate! Concurează împotriva elevilor și jucătorilor din întreaga lume în acest apogeu captivant al sezonului." season_subheading1: "pentru amândouă arenele, cea de Sezon și cea de Turneu, fiecare jucător își programează echipa de “Eroi IA” cu cod scris în Python, Javascript, C++, Lua sau Coffeescript." season_subheading2: "Codul va informa despre strategiile pe care Eroii IA îl vor executa în competițiile față-în-față împotriva altor competitori." team_derbezt: "Învață să scrii cod și câștigă premii sponsorizate de superstarul Mexicanv care este actor, comedian și creator de filme Eugenio Derbez." invite_link: "Invită jucători în această echipă trimițăndu-le acest link:" public_link: "Partajează acest clasament cu link-ul public:" end_to_end: "Diferite de alte platforme de e-sport utilizate de școli, noi deținem toată structura de sus până jos, ceea ce înseamnă că nu depindem de nici un dezvoltator de jocuri și nu avem probleme de licențiere. Asta înseamnă deasemenea că putem face modificări personalizate la jocuri pentru școala sau organizația ta." path_success: "Platforma jocului se încadrează în curicula de informatică standard, astfel încât în timp ce elevii se joacă nivelurile jocului, ei fac și muncă de completare a cunoștințelor. Elevii învață să scrie cod și informatică în timp ce se joacă, apoi utilizeză aceste abilități în bătăliile din arenă în timp ce fac practică și se joacă pe aceeași platformă." unlimited_potential: "Structura concursului nostru este adaptabilă oricărui mediu sau situație. Elevii pot participa la un anumit moment în timpul orelor normale de clasă, pot să se joace asincron de acasă sau să participe după bunul plac." edit_team: "Modifică echipa" start_team: "Pornește o echipă" leave_team: "Părăsește echipa" join_team: "Alătură-te echipei" view_team: "Vezi echipa" join_team_name: "Alătură-te echipei __name__" features: "Caracteristici" built_in: "Infrastructură competitivă încorporată" built_in_subheader: "Platforma noastră găzduiește fiecare element al procesului competițional, de la tabele de scor la platforma de joc, bunuri și premii de concurs." custom_dev: "Dezvoltare personalizată" custom_dev_subheader: "Elementele personalizate pentru școala sau organizația ta sunt incluse, plus opțiuni ca pagini de prezentare cu marcaj specific și personaje de joc." comprehensive_curr: "Curiculă completă" comprehensive_curr_subheader: "CodeCombat este o soluție CS aliniată standardelor care susțin profesorii în predarea programării în Javascript și Python, indiferent de experiența lor." # roster_management: "Roster Management Tools" roster_management_subheader: "Monitorizează performanța elevilor pe timpul curiculei și al jocului, și adaugă sau șterge elevi facil." share_flyer: "Partajează afișul nostru despre Liga IA cu instructorii, administratorii, părinții, antrenorii de e-sport sau alte persoane care pot fi interesate." download_flyer: "Descarcă afișul" championship_summary: "Arena campionatului __championshipArena__ este deschisă! Luptă acum în ea în cadrul lunii __championshipMonth__ pentru a câștiga premii în __championshipArena__ __championshipType__." play_arena_full: "Joacă în __arenaName__ __arenaType__" play_arena_short: "Joacă în __arenaName__" view_arena_winners: "Vezi câștigătorii din __arenaName__ __arenaType__ " arena_type_championship: "Arena campionatului" arena_type_regular: "Arena multi-jucător" blazing_battle: "Luptă aprinsă" infinite_inferno: "Infern infinit" mages_might: "Puterea magilor" sorcerers: "Vrăjitori" giants_gate: "Poarta giganților" colossus: "Colossus" cup: "Cupa" blitz: "Blitz" clash: "Încleștare" season2_announcement_1: "Este timpul să îți testezi abilitățile de a scrie cod în arena finală a sezonului 2. Vrăjitorul Blitz este viu și oferă o nouă provocare și o nouă tabelă de scor de urcat." season2_announcement_2: "Ai nevoie de mai multă practică? Rămâi la Arena mare a magilorpentru a-ți îmbunătății abilitățile. Ai timp până pe 31 August să joci în ambele arene. Notă: modificări de echilibrare a arenei pot apărea până pe 23 August." season2_announcement_3: "Premii deosebite sunt disponibile pentru jucătorii de top în Vrăjitorul Blitz:" season1_prize_1: "burse de $1,000" # season1_prize_2: "RESPAWN Gaming Chair" season1_prize_3: "Avatar CodeCombat personalizat" season1_prize_4: "Și mult mai multe!" season1_prize_hyperx: "Echipamente perfierice premium HyperX" codecombat_ai_league: "Liga IA CodeCombat" register: "Înregistrare" not_registered: "Neînregistrat" register_for_ai_league: "Înregistrare în Liga IA" world: "Lumea" quickstart_video: "Video de prezentare" arena_rankings: "Calificări arenă" arena_rankings_blurb: "Calificări arenă la liga globală IA" arena_rankings_title: "Clasamentul global al tuturor jucătorilor din această echipă la toate arenele Ligii IA din intervalul de vârstă nespecificat." competing: "Concurenți:" # Competing: 3 students count_student: "elev" # 1 elev count_students: "elevi" # 2 elevi top_student: "Top:" # Top: Jane D top_percent: "top" # - top 3%) top_of: "din" # (#8 of 35). Perhaps just use "/" if this doesn't translate naturally. arena_victories: "Victorii în Arenă" arena_victories_blurb: "Victoriile recente din Liga globală IA" arena_victories_title: "Victoriile sunt numărate în baza la ultimele 1000 de meciuri jucate asincron de fiecare jucător în fiecare arenă a Ligii IA din care fac parte." count_wins: "victorii" # 100+ wins or 974 wins codepoints_blurb: "1 CodePoint = 1 linie de cod scrisă" codepoints_title: "Un CodePoint este obținut pentru fiecare linie de cod care nu este goală utilizată pentru câștigarea nivelului. Fiecare nivel valorează același număr de CodePoints în concordanță cu soluția standard, indiferent dacă elevul a scris mai multe sau mai puține linii de cod." count_total: "Total:" # Total: 300 CodePoints, or Total: 300 wins join_teams_header: "Alătură-te echipelor & Primește chestii tari!" join_team_hyperx_title: "Alătură-te echipei HyperX și primești 10% reducere" join_team_hyperx_blurb: "30 de membri ai echipelor vor fi aleși aleator să câștige un mousepad de joc gratuit!" join_team_derbezt_title: "Alătură-te echipei DerBezt, și primește un erou unic" join_team_derbezt_blurb: "Deblochează eroul Armando Hoyos de la superstarul mexican Eugenio Derbez!" join_team_ned_title: "Alătură-te echipei Ned, și deblochează eroul lui Ned" join_team_ned_blurb: "Primește eroul unic mânuitor-de-spatulă de la starul YouTube, Încearcă Guy Ned Fulmer!" tournament: mini_tournaments: "Mini campionate" usable_ladders: "Toate scările posibile" make_tournament: "Creează un mini campionat" go_tournaments: "Mergi la mini campionat" class_tournaments: "Clasifică mini campionatele" no_tournaments_owner: "Nu există nici un campionat acum, te rog Creează unul" no_tournaments: "Nu există nici un campionat acum" edit_tournament: "Editează campionatul" create_tournament: "Creează campionatul" payments: student_licenses: "Licențe pentru elevi" computer_science: "Informatică" web_development: "Dezvoltare web" game_development: "Dezvoltare de jocuri" per_student: "per elev" just: "Doar" teachers_upto: "Profesorul poate cumpăra până la" great_courses: "Mai multe cursuri sunt incluse pentru" studentLicense_successful: "Felicitări! Licențele tale vor fi gata într-un minut. Apasă pe Ghidul de noțiuni de bază din zona de Resurse pentru a învăța cum să le prezinți elevilor." onlineClasses_successful: "Felicitări! Plata ta s-a efectuat cu succes. Echipa noastră te va contacta în pașii următori." homeSubscriptions_successful: "Felicitări! Plata ta s-a efectuat cu succes. Accesul de tip premium va fi disponibil în câteva minute." failed: "Plata ta a eșuat, te rog să încerci din nou" session_week_1: "1 sesiune/săptămână" session_week_2: "2 sesiuni/săptămână" month_1: "Lunar" month_3: "Trimestrial" month_6: "Bi-anual" year_1: "Anual" most_popular: "Cel mai popular" best_value: "Valoarea cea mai bună" purchase_licenses: "Cumpără licențe ușor pentru a avea acces la CodeCombat și Ozaria" homeschooling: "Licențe pentru școala făcută acasă" recurring: month_1: 'Facturare recurentă lunară' month_3: 'Facturare recurentă la 3 luni' month_6: 'Facturare recurentă la 6 luni' year_1: 'Facturare recurentă anuală' form_validation_errors: required: "Câmpul este obligatoriu" invalidEmail: "Email invalid" invalidPhone: "Număr de telefon invalid" emailExists: "Adresa de email există deja" numberGreaterThanZero: "Ar trebui să fie un număr mai mare decât 0"
39479
module.exports = nativeDescription: "Română", englishDescription: "Romanian", translation: new_home: title: "CodeCombat - Învăța Python și Javascript prin jocuri de programare" meta_keywords: "CodeCombat, python, javascript, jocuri de programare" meta_description: "Învață să scrii cod printr-un joc de programare. Învață Python, Javascript, și HTML ca și când ai rezolva puzzle-uri și învață să îți faci propriile jocuri și site-uri web." meta_og_url: "https://codecombat.com" become_investor: "pentru a devi un investitor în CodeCombat" built_for_teachers_title: "Un joc de programare dezvoltat cu gândul la profesori." built_for_teachers_blurb: "Învățarea copiilor să scrie cod poate fi copleșitoare câteodată. CodeCombat îi ajută pe instructori să-i învețe pe elevi cum să scrie cod în Javascript sau în Python, două din cele mai populare limbaje de programare. Cu o curiculă completă incluzând șase unități care consolidează învățarea prin unități de dezvoltare a jocurilor bazată pe proiecte și a celor de dezvoltare web, copiii vor progresa de-a lungul unei călătorii de la sintaxa de bază până la recursivitate!" built_for_teachers_subtitle1: "Informatică" built_for_teachers_subblurb1: "Începând de la cursul nostru gratuit de Introducere în informatică, studenții își însușesc concepte de bază în programare, cum ar fi bucle while/for, funcții și algoritmi." built_for_teachers_subtitle2: "Dezvoltare de jocuri" built_for_teachers_subblurb2: "Cursanții construiesc labirinturi și utilizează elemente de bază despre manipularea intrărilor ca să programeze propriile jocuri care pot fi partajate mai apoi cu prietenii și familia." built_for_teachers_subtitle3: "Dezvoltare web" built_for_teachers_subblurb3: "Utilizând HTML, CSS și jQuery, cursanții își antrenează mușchii creativității prin programarea propriilor pagini web cu un URL propriu ce poate fi partajat cu colegii de clasă." century_skills_title: "Abilități pentru secolul 21" century_skills_blurb1: "Elevii nu își vor dezvolta doar eroul, se vor dezvolta pe ei înșiși" century_skills_quote1: "Ai greșit ... deci te vei gândi la toate posibilitățile să repari greșeala, iar apoi încerci din nou. Nu aș putea să ajung aici dacă nu aș încerca din greu." century_skills_subtitle1: "Gândire critică" century_skills_subblurb1: "Prin scrierea de cod pentru puzzle-urile încorporate în nivelurile din ce în ce mai incitante, jocurile de programare ale CodeCombat se asigură că gândirea critică este mereu exerseată de copii." century_skills_quote2: "Toată lumea făcea labirinturi, atunci m-am gândit, ‘capturează steagul’ și asta am făcut." century_skills_subtitle2: "Creativitate" century_skills_subblurb2: "CodeCombat încurajează elevii să își arate creativitatea construind și partajând propriile jocuri și pagini web." century_skills_quote3: "Dacă m-am blocat la un nivel. Voi lucra cu persoanele de lângă mine până ce toți ne vom da seama cum să mergem mai departe." century_skills_subtitle3: "Colaborare" century_skills_subblurb3: "În timpul jocului, există oportunități pentru elevi să colaboreze atunci când s-au blocat și să lucreze împreună utilizând ghidul nostru de programare în perechi." century_skills_quote4: "Tot mereu am avut aspirații pentru proiectarea de jocuri video și învățarea programării ... acesta îmi oferă un punct important de plecare." century_skills_quote4_author: "<NAME>, clasa a 10-a" century_skills_subtitle4: "Comunicare" century_skills_subblurb4: "scrierea de cod le solicită copiilor să exerseze noi forme de comunicare, inclusiv comunicarea cu calculatorul dar și transmiterea ideilor lor printr-un cod eficient." classroom_in_box_title: "Ne străduim să:" classroom_in_box_blurb1: "Antrenăm fiecare elev astfel încât el să creadă că programarea este pentru el." classroom_in_box_blurb2: "Permitem oricărui instructor să fie confident atunci când predă programare." classroom_in_box_blurb3: "Inspirăm toți liderii din școli pentru a crea un program internațional de informatică." classroom_in_box_blurb4: "" click_here: "Apasă aici" creativity_rigor_title: "Unde creativitatea întâlnește rigoarea" creativity_rigor_subtitle1: "Facem programarea distractivă și învățăm abilități necesare lumii actuale" creativity_rigor_blurb1: "Elevii vor scrie cod real de Python și Javascript în timp ce se joacă care încurajează încercările și erorile, gândirea critică și creativitatea. elevii aplică mai apoi abilitățile de programare învățate dezvoltând propriile jocuri și site-uri web în cursuri bazate pe proiecte." creativity_rigor_subtitle2: "Accesibil tuturor elevilor indiferent de nivel" creativity_rigor_blurb2: "Fiecare nivel CodeCombat este construit pe baza a milioane de date și optimizat să se poată adapta fiecărui cursant. Nivelurile de practică și indiciile îi ajută pe elevi atunci când aceștia se blochează, iar nivelurile tip provocare evaluează ceea ce au învățat elevii prin joc." creativity_rigor_subtitle3: "Construit pentru profesori, indiferent de experiența lor" creativity_rigor_blurb3: "CodeCombat poate fi urmat într-un ritm propriu, curicula aliniată la standarde permite învățarea informaticii de către toată lumea. CodeCombat echipează profesorii cu resursele de învățare necesare și cu un suport dedicat care să îi ajute să fie confidenți și să aibă succes în clasă." featured_partners_title1: "Prezentat în" featured_partners_title2: "Premii & Parteneri" featured_partners_blurb1: "Parteneri ingenioși" featured_partners_blurb2: "Cel mai creativ instrument pentru elevi" featured_partners_blurb3: "Alegerea de top pentru învățare" featured_partners_blurb4: "Partener oficial Code.org" featured_partners_blurb5: "Membru oficial CSforAll" featured_partners_blurb6: "Partener activități Hour of Code" for_leaders_title: "Pentru liderii din școli" for_leaders_blurb: "Un program de informatică cuprinzător și aliniat standardelor" for_leaders_subtitle1: "Implementare ușoară" for_leaders_subblurb1: "Un program bazat pe web care nu necesită suport IT. Pentru a începe aveți nevoie de mai puțin de 5 minute, utilizând Google sau Clever Single Sign-On (SSO)." for_leaders_subtitle2: "Curiculă completă de programare" for_leaders_subblurb2: "O curiculă aliniată standardelor cu resurse de pregătire și de dezvoltare profesională care permit oricărui profesor să predea informatică." for_leaders_subtitle3: "Modalități de utilizare flexibilă" for_leaders_subblurb3: "Indiferent dacă vrei să construiești un cerc de programare la școala generală, o curriculă de pregătire a carierei tehnice sau vrei să predai elemente de introducere în informatică la clasă, CodeCombat este pregătit să se adapteze nevoilor tale." for_leaders_subtitle4: "Abilități din lumea reală" for_leaders_subblurb4: "Elevii prind curaj și își dezvoltă modul de gândire prin provocări de programare care îi pregătește pentru cele 500K+ locuri de muncă disponibile în domeniul IT." for_teachers_title: "Pentru profesori" for_teachers_blurb: "Instrumente pentru descoperirea potențialului elevilor" for_teachers_subtitle1: "Învățare bazată pe proiecte" for_teachers_subblurb1: "Promovează creativitatea, rezolvarea problemelor și încrederea în forțele proprii prin cursuri orientate pe proiecte în care elevii își dezvoltă propriile jocuri și pagini web." for_teachers_subtitle2: "Panoul de lucru al profesorului" for_teachers_subblurb2: "Vizualizează date despre progresul elevilor, descoperă resurse care susțin curicula și accesează suportul în timp real pentru a susține procesul de învățare al elevilor." for_teachers_subtitle3: "Evaluări încorporate" for_teachers_subblurb3: "Personalizează instrucțiunile și asigură-te că elevii înțeleg conceptele de bază cu evaluări formative și sumative." for_teachers_subtitle4: "Diferențiere automată" for_teachers_subblurb4: "Implică toți cursanții dintr-o clasă mixtă în niveluri practice care se adaptează nevoilor de învățare specifice." game_based_blurb: "CodeCombat este un program de informatică bazat pe jocuri în care elevii scriu cod real și își pot urmării personajele în timp real." get_started: "Să începem" global_title: "Alătură-te comunității noastre globale de cursanți și instructori" global_subtitle1: "Cursanți" global_subtitle2: "Linii de cod" global_subtitle3: "Profesori" global_subtitle4: "Țări" go_to_my_classes: "Către clasele mele" go_to_my_courses: "Către cursurile mele" quotes_quote1: "Numește orice program online, eu deja l-am încercat. Nici unul dintre ele nu se compară cu CodeCombat & Ozaria. Orice profesor care vrea să își învețe elevii cum să scrie cod ... să înceapă aici!" quotes_quote2: " Am fost surprins să văd cât de simplu și intuitiv face învățarea informaticii CodeCombat. Notele la examenele AP au fost mai mari decât m-am așteptat și cred că CodeCombat este cel responsabilde acest lucru." quotes_quote3: "CodeCombat a fost cel mai util în învpțarea elevilor mei capabilități de scriere a codului real. Soțul meu este inginer software și mi-a testat toate programele mele. A fost prioritatea lui principală." quotes_quote4: "Părerile … au fost atât de pozitive încât construim o clasă de informatică în jurul CodeCombat. Programul îi antrenează cu adevărat pe elevi cu o platformă de tipul celor de jocuri care este este amuzantă și instructivă în același timp. Continuați cu treaba bine făcută, CodeCombat!" quotes_quote5: "Deși clasa începe în fiecare sâmbătă la ora 7am, fiul meu este atât de încântat încât se trezește înaintea mea! CodeCombat creează o cale pentru fiul meu ca acesta să își îmbunătățească abilitățile de scriere a codului." quotes_quote5_author: "<NAME>, părinte" see_example: "Vezi exemplul" slogan: "Cel mai antrenat mod de a învăța informatică" slogan_power_of_play: "Învață să programezi prin puterea jocului" teach_cs1_free: "Predă informatică gratuit" teachers_love_codecombat_title: "Profesorii iubesc CodeCombat" teachers_love_codecombat_blurb1: "Raportează că elevii lor îndrăgesc utilizarea CodeCombat pentru învățarea programării" teachers_love_codecombat_blurb2: "Recomandă CodeCombat altor profesori de informatică" teachers_love_codecombat_blurb3: "Spun că CodeCombat îi ajută să sprijine elevii cu abilitățile de rezolvare a problemelor" teachers_love_codecombat_subblurb: "În parteneriat cu McREL International, un lider în îndrumarea și evaluarea bazată pe cercetare a tehnologiilor educaționale." top_banner_blurb: "Părinți, dați-i copilului vostru darul programării și a instruirii personalizate cu profesorii noștri!" top_banner_summer_camp: "Înscrierile sunt acum deschise pentru taberele de vară de programare – întreabă-ne despre sesiunile virtuale de o săptămână începând doar de la $199." top_banner_blurb_funding: "Nou: Ghidul de resurse de finațare CARES Act pentru fondurile ESSER și GEER pentru programele tale de CS." try_the_game: "Încearcă jocul" classroom_edition: "Ediția pentru clasă:" learn_to_code: "Învață să scrii cod:" play_now: "Joacă acum" im_a_parent: "Sunt părinte" im_an_educator: "Sunt instructor" im_a_teacher: "Sunt profesor" im_a_student: "Sunt elev" learn_more: "Aflați mai multe" classroom_in_a_box: "O clasă „la cutie„ pentru a preda informatica." codecombat_is: "CodeCombat este o platformă <strong>pentru elevi</strong> să învețe informatică în timp ce se joacă un joc real." our_courses: "Cursurile noastre au fost testate în mod special <strong>pentru a excela în clasă</strong>, chiar și pentru profesorii cu puțină sau fără experiență prealabilă în informatică." watch_how: "Privește cum CodeCombat transformă modul în care oamenii învață informatică." top_screenshots_hint: "Elevii scriu cod și văd modificările lor actualizate în timp real" designed_with: "Proiectat cu gândul la profesori" real_code: "Cod scris, real" from_the_first_level: "de la primul nivel" getting_students: "Ajungerea elevilor la nivelul de a scrie cod cât mai repede posibil este critică în învățarea sinatxei programării și a structurii corecte." educator_resources: "Resurse pentru instructori" course_guides: "și ghiduri de curs" teaching_computer_science: "Predarea informaticii nu necesită o diplomă costisitoare, deoarece furnizăm unelte care să suțină profesori din toate mediile." accessible_to: "Accesibil pentru" everyone: "toată lumea" democratizing: "Democrația procesului de învățare a programării stă la baza filozofiei noastre. Toată lumea ar trebui să poată să învețe programare." forgot_learning: "Eu cred că ei de fapt au uitat că învață ceva." wanted_to_do: " scrierea de cod este ceva ce întotdeauna mi-am dorit să fac, și niciodată nu m-am gândit că aș putea să învăț în școală." builds_concepts_up: "Îmi place cum CodeCombat construiește conceptele. Este foarte ușor să înțelegi și amuzant să îți dai seama." why_games: "De ce este importantă învățarea prin jocuri?" games_reward: "Jocul răsplătește efortul productiv." encourage: "Jocul este un mediu care încurajează interacțiunea, descoperirea, și încercarea-și-eroarea. Un joc bun provoacă jucătorul să își îmbunătățească abilitățile în timp, care este un proces similar cu al elevilor când învață." excel: "Jocul este mai mult decât plin de satisfacții" struggle: "efort productiv" kind_of_struggle: "tipul de efort care rezultă din procesul de învățare care este antrenant și" motivating: "motivant" not_tedious: "nu plictisitor." gaming_is_good: "Studiile sugerează că jocurile sunt bune pentru creierul copiilor. (E adevarat!)" game_based: "Când sistemele de învățare bazate pe joc sunt" compared: "comparate" conventional: "metodele de evaluare convenționale, diferența este clară: jocurile sunt mai bune să ajute elevii să rețină cunoștințe, să se concentreze și" perform_at_higher_level: "să performeze la un nivel mai înalt" feedback: "Jocurile furnizează de asemenea un feedback în timp real care le permite elevilor să-și ajusteze calea către soluție și să înțeleagă concepte mai holistic, în loc să fie limitați doar la răspunsuri “corect” sau “incorect”." real_game: "Un joc real, jucat cu programare reală." great_game: "Un joc bun este mai mult decât insigne și realizări - este despre călătoria unui jucător, puzzle-uri bine făcute și abilitatea de abordare a provocărilor prin acțiune și încredere." agency: "CodeCombat este un joc care dă jucătorilor acea putere de a acționa și încredere prin intermediul motorului nostru de scriere cod, care îi ajută pe elevii începători și avansați deopotrică să scrie cod corect și valid." request_demo_title: "Pune-i pe elevii tăi să înceapă astăzi!" request_demo_subtitle: "Cere un demo și pune-i pe elevii tăi să înceapă în mai puțin de o oră." get_started_title: "Creează clasa azi" get_started_subtitle: "Creează o clasă, adaugă elevii și monitorizează progresul lor în timp ce ei învață informatică." request_demo: "Cere o demonstrație" request_quote: "Cere o ofertă de preț" setup_a_class: "Creează o clasă" have_an_account: "Aveți un cont?" logged_in_as: "În prezent sunteți conectat(ă) ca" computer_science: "Cursurile în ritm personal acoperă de la sintaxa de bază până la concepte avansate" ffa: "Gratuit pentru toți elevii" coming_soon: "Mai multe vor apărea în curând!" courses_available_in: "Cursurile sunt disponibile în Javascript și Python. Cursurile de Dezvoltare web utilizează HTML, CSS și jQuery." boast: "Se laudă cu ghicitori care sunt suficient de complexe să fascineze jucătorii și programatorii deopotrivă." winning: "O combinație câștigătoare de joc RPG și temă la programare care conduce la o educație prietenoasă și cu adevărat distractivă pentru copii." run_class: "Tot ceea ce ai nevoie pentru a ține clasa de informatică în școala ta astăzi, nu este nevoie de cunoștințe în CS." goto_classes: "Vezi clasa mea" view_profile: "Vezi profilul meu" view_progress: "Vezi progres" go_to_courses: "Vezi cursurile mele" want_coco: "Vrei CodeCombat în școala ta?" educator: "Instructor" student: "<NAME>" our_coding_programs: "Programele noastre de programare" codecombat: "CodeCombat" ozaria: "Ozaria" codecombat_blurb: "Jocul nostru de scriere cod original. Recomndat pentru părinți, persoane, instructori și elevi care doresc să experimenteze unul dintre jocurile de programare cel mai iubit din lume." ozaria_blurb: "Un joc de aventură și program de informatică unde elevii stăpânesc magia pierdută a codului pentru a salva lumea. Recomndat pentru instructori și elevi." try_codecombat: "Încearcă CodeCombat" try_ozaria: "Încearcă Ozaria" explore_codecombat: "Explorează CodeCombat" explore_ai_league: "Explorează liga IA" explore_ozaria: "Explorează Ozaria" explore_online_classes: "Explorează clasele online" explore_pd: "Explorează dezvoltarea profesională" new_adventure_game_blurb: "Ozaria este noul nostru joc de aventură nou-nouț și soluția ta la cheie pentru predare informaticii. Notele noastre pentru elevi __slides__ și pentru profesori fac ca planificarea și prezentarea lecțiilor să fie ușoară și rapidă." lesson_slides: "fișe lecții" pd_blurb: "Învață abilitățile necesare pentru predarea efectivă a informaticiicu cursul nostru de dezvoltare profesională auto-direcționat și acreditat CSTA. Obține 40 de ore în credite în orice moment, de pe orice dispozitiv. Face pereche bună cu clasele Ozaria." ai_league_blurb: "scrierea de cod în mediu competitiv nu a fost niciodată mai eroică cu aceste ligi educaționale de e-sport, care sunt în același timp niște simulatoare de lupă IA unice cât și motoare de joc pentru a învățarea scrierii de cod real." codecombat_live_online_classes: "Clase online în timp real CodeCombat" learning_technology_blurb: "Jocul nostru original învață aptitudini din lumea reală prin puterea jocului. Curicula bine construită construiește în mod sistematic experiența și cunoștințele elevului în timp ce ei progresează." learning_technology_blurb_short: "Tehnologia noastră inovativă bazată pe joc a transformat modul în care elevii învață să scrie cod." online_classes_blurb: "Clasele noastre online de sciere cod combină puterea jocului și instrucțiunile personalizate pentru o experiență pe care copilul tău nu o va îndrăgi. Cu cele două opțiuni disponibile, private sau de grup, acestea sunt sistemele de învățare la distanță care merg." for_educators: "Pentru instructori" for_parents: "Pentru părinți" for_everyone: "Pentru toată lumea" what_our_customers_are_saying: "Ce zic clienții noștri" game_based_learning: "Învățare pe bază de joc" unique_approach_blurb: "Cu abordarea noastră unică, elevii adoptă învățarea în timp ce joacă și scriu cod încă de la începutul aventurii lor, promovând învățarea activă și îmbunătățirea modului de a gândi." text_based_coding: "Programare pe bază de text" custom_code_engine_blurb: "Motorul și interpretorul nostru personalizat este proiectat pentru începători, pentru învățarea limbajelor de programare reale Python, Javascript și C++ utilizând termeni umani, prietenoase cu începătorii." student_impact: "Impact asupra elevilor" help_enjoy_learning_blurb: "Produsele noastre au ajutat peste 20 de milioane de elevi care s-au bucurat să învețe informatică, învățându-i să fie elevi critici, confidenți și creativi. Noi îi implicăm pe toți elevii, indiferent de experiență, ajutându-i să-și construiască o cale de succes în informatică." global_community: "Alătură-te comunității globale" million: "__num__ milioane" billion: "__num__ bilioane" nav: educators: "Instructori" follow_us: "Urmăriți-ne" general: "General" map: "Hartă" play: "Niveluri" # The top nav bar entry where players choose which levels to play community: "Communitate" courses: "Cursuri" blog: "Blog" forum: "Forum" account: "Cont" my_account: "Contul meu" profile: "Profil" home: "Acasă" contribute: "Contribuie" legal: "Confidențialitate și termeni" privacy: "Notă de confidențialitate" about: "Despre" impact: "Impact" contact: "Contact" twitter_follow: "Urmărește" my_classrooms: "Clasa mea" my_courses: "Cursurile mele" my_teachers: "Profesorii mei" careers: "Cariere" facebook: "Facebook" twitter: "Twitter" create_a_class: "Creează o clasă" other: "Altele" learn_to_code: "Învață să scrii cod!" toggle_nav: "Schimbare navigație" schools: "Școli" get_involved: "Implică-te" open_source: "Open source (GitHub)" support: "Suport" faqs: "Întrebări" copyright_prefix: "Copyright" copyright_suffix: "Toate drepturile rezervate." help_pref: "Ai nevoie de ajutor? Email" help_suff: "și vom lua legătura cu tine!" resource_hub: "Zona de resurse" apcsp: "Principiile AP CS" parent: "Părinți" esports: "E-sporturi" browser_recommendation: "Pentru cea mai bună experință vă recomandăm să utilizați ultima versiune de Chrome. Descarcă navigatorul web de aici!" ozaria_classroom: "Clasa Ozaria" codecombat_classroom: "Clasa CodeCombat" ozaria_dashboard: "Panou de lucru Ozaria" codecombat_dashboard: "Panou de lucru CodeCombat" professional_development: "Dezvoltare profesională" new: "Nou!" admin: "Admin" api_dashboard: "Panou de lucru API" funding_resources_guide: "Ghid resurse de finanțare" modal: close: "Închide" okay: "Okay" cancel: "Anulează" not_found: page_not_found: "Pagina nu a fost gasită" diplomat_suggestion: title: "Ajută la traducrea CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Avem nevoie de abilitățile tale lingvistice." pitch_body: "CodeCombat este dezvoltat în limba engleza, dar deja avem jucători din toate colțurile lumii. Mulți dintre ei vor să joace în română și nu vorbesc engleză. Dacă poți vorbi ambele limbi te rugăm să te gândești dacă ai dori să devi un Diplomat și să ne ajuți să traducem atât jocul cât și site-ul." missing_translations: "Până când nu putem traduce totul în română, vei vedea limba engleză acolo unde limba română nu este displonibilă." learn_more: "Află mai multe despre cum să fi un Diplomat" subscribe_as_diplomat: "Înscrie-te ca Diplomat" new_home_faq: what_programming_languages: "Ce limbaje de programare sunt disponibile?" python_and_javascript: "În prezent lucrăm cu Python și Javascript." why_python: "De ce să alegi Python?" why_python_blurb: "Python este prietenos pentru începători dar este în prezent utilizat de majoritatea corporațiilor (cum este Google). Dacă aveți cursanți mai tineri sau începători, vă recomandăm cu încredere Python." why_javascript: "De ce să alegi Javascript?" why_javascript_blurb: "Javascript este limbajul web și este utilizat în aproape toate site-urile web. Vei prefera să alegi Javascript dacă ai în plan se studiezi dezvoltarea web. Am făcut deasemenea ca tranziția elevilor de la Python la dezvoltarea web pe bază de Javascript să fie ușoară." javascript_versus_python: "Sintaxa Javascript este un pic mai dificilă pentru începători decât cea Python, de aceea dacă nu te poți decide între cele două, noi îți recomandăm Python." how_do_i_get_started: "Cum pot să încep?" getting_started_1: "Creează un cont de profesor" getting_started_2: "Creează o clasă" getting_started_3: "Addaugă elevi" getting_started_4: "Stai și observă elevii cum se delectează învățând să scrie cod" main_curriculum: "Pot utliza CodeCombat sau Ozaria ca și curiculă de bază?" main_curriculum_blurb: "Absolut! Am alocat timp consultațiilor cu specialiștii în educație pentru a dezvola curicule pentru clasă și materiale special concepute pentru profesorii care utilizează CodeCombat sau Ozaria fără ca aceștia să aibă cunoștințe prealabile de informatică. Multe școli implementează CodeCombat și/sau Ozaria ca și curiculă de bază pentru informatică." clever_instant_login: "CodeCombat și Ozaria au suport pentru Clever Instant Login?" clever_instant_login_blurb: "Da! Verifică __clever__ pentru mai multe detalii cum să începi." clever_integration_faq: "Întrebări despre integrarea Clever" google_classroom: "Dar Google Classroom?" google_classroom_blurb1: "Da! Fi sigur că utilizezi Google Single Sign-On (SSO) Modal pentru a te înregistra în contul tău de profesor. Dacă deja ai un cont pe care îl utilizezi pentru Google email, utilizează Google SSO modal pentru a te autentifica următoarea dată. În Creează Class modal, vei găsi o opțiune să faci legătura cu Google Classroom. În prezent avem suport numai pentru Google Classroom rostering." google_classroom_blurb2: "Notă: trebuie să utilizezi Google SSO să te autentifici sau să te autentifici măcar o dată pentru a vedea opțiunile de integrare Google Classroom." how_much_does_it_cost: "Cât de mult costă să acesez toate cursurile și resursele disponibile?" how_much_does_it_cost_blurb: "Personalizăm soluțiile pentru școli și districte și vom lucra cu tine pentru a înțelege cerința de utilizare, contextul și bugetul. __contact__ pentru mai multe detalii! Vezi de asemenea __funding__ pentru informații cu privire la accesarea surselor de finanțare CARES Act cum sunt ESSER și GEER." recommended_systems: "Există o recomandare cu privire la navigatorul web și la sistemul de operare?" recommended_systems_blurb: "CodeCombat și Ozaria rulează cel mai bine pe calculatoare cu cel puțin 4GB de RAM, pe navigatoare web moderne cum sunt Chrome, Safari, Firefox sau Edge. Chromebooks cu 2GB de RAM pot avea probleme minore de grafică în cursurile mai avansate. Un minim de 200 Kbps lățime de bandă pentru fiecare elev este necesară, deși este recomandat 1+ Mbps." other_questions: "Dacă ai și alte întrebări, te rog __contact__." play: title: "Joacă nivelele CodeCombat - Învață Python, Javascript și HTML" meta_description: "Învață programare cu un joc de scris cod pentru începători. Învață Python și Javascript în timp ce rezolvi labirinturi, Creează propriile jocuri și crește-ți nivelul. Provoacă prietenii în nivelurile din arena multi-utilizator!" level_title: "__level__ - Învață să scrii cod în Python, Javascript, HTML" video_title: "__video__ | Nivel video" game_development_title: "__level__ | Dezvoltare jocuri" web_development_title: "__level__ | Dezvoltare web" anon_signup_title_1: "CodeCombat are o" anon_signup_title_2: "versiune pentru clasă!" anon_signup_enter_code: "Introdu codul de clasă:" anon_signup_ask_teacher: "Nu ai unul? întreabă profesorul!" anon_signup_create_class: "Vrei să creezi o clasă?" anon_signup_setup_class: "Creează o clasă, adaugă elevii și monitorizează progresul!" anon_signup_create_teacher: "Creează un cont de profesor gratuit" play_as: "Joacă ca" # Ladder page get_course_for_class: "Alocă Dezvoltarea de jocuri și altele la clasa ta!" request_licenses: "Contactează specialiștii noștri școlari pentru detalii." compete: "Concurează!" # Course details page spectate: "Spectator" # Ladder page simulate_all: "Simulează totul" players: "jucători" # Hover over a level on /play hours_played: "ore jucate" # Hover over a level on /play items: "Articole" # Tooltip on item shop button from /play unlock: "Deblochează" # For purchasing items and heroes confirm: "Confirmă" owned: "Deținute" # For items you own locked: "Blocate" available: "Disponibile" skills_granted: "Abilități acordate" # Property documentation details heroes: "Eroi" # Tooltip on hero shop button from /play achievements: "Realizări" # Tooltip on achievement list button from /play settings: "Setări" # Tooltip on settings button from /play poll: "Sondaj" # Tooltip on poll button from /play next: "Următorul" # Go from choose hero to choose inventory before playing a level change_hero: "Schimbă eroul" # Go back from choose inventory to choose hero change_hero_or_language: "Schimbă eroul sau limba" buy_gems: "Cumpără pietre prețioase" subscribers_only: "Doar pentru abonați!" subscribe_unlock: "Pentru deblocare abonează-te!" subscriber_heroes: "Abonează-te azi pentru a debloca imediat <NAME>a, H<NAME>baum și <NAME>ori!" subscriber_gems: "Abonează-te azi pentru a cumpăra acest erou cu pietre prețioase!" anonymous: "<NAME>" level_difficulty: "Dificultate: " awaiting_levels_adventurer_prefix: "Lansăm niveluri noi în fiecare săptămână." awaiting_levels_adventurer: "Înscrie-te ca aventurier " awaiting_levels_adventurer_suffix: "pentru a fi primul care joacă nivele noi." adjust_volume: "Reglează volumul" campaign_multiplayer: "Arene multi-jucător" campaign_multiplayer_description: "... în care lupți cot-la-cot contra altor jucători." brain_pop_done: "Ai înfrânt căpcăunii cu codul tău! Ai învins!" brain_pop_challenge: "Ca și provocare joacă din nou utilizând un limbaj de programare diferit!" replay: "Joacă din nou" back_to_classroom: "Înapoi la clasă" teacher_button: "Pentru profesori" get_more_codecombat: "Mai mult CodeCombat" code: if: "dacă" # Keywords--these translations show up on hover, so please translate them all, even if it's kind of long. (In the code editor, they will still be in English.) else: "altfel" elif: "altfel dacă" while: "atăta timp cât" loop: "buclă" for: "pentru" break: "oprește" continue: "continuă" pass: "pass" return: "întoarce" then: "atunci" do: "execută" end: "sfârșit" function: "funcție" def: "definește" var: "variabilă" self: "se referă la el însuși" hero: "erou" this: "acesta (aceasta)" or: "sau" "||": "sau" and: "și" "&&": "și" not: "not (negație)" "!": "not (negație)" "=": "atribuie" "==": "egal cu" "===": "strict egal cu" "!=": "nu este egal cu" "!==": "nu este strict egal cu" ">": "mai mare decât" ">=": "mai mare sau egal decât" "<": "mai mic decât" "<=": "mai mic sau egal cu" "*": "înmulțit cu" "/": "împărțit la" "+": "plus" "-": "minus" "+=": "adaugă și atribuie" "-=": "scade și atribuie" True: "Adevărat" true: "adevărat" False: "Fals" false: "fals" undefined: "nedefinit" null: "Zero/Fără valoare cand nu este obiect" nil: "Zero/Fără valoare pentru obiecte" None: "Nici unul/una" share_progress_modal: blurb: "Faci progrese mari! Spune-le părinților cât de mult ai învățat cu CodeCombat." email_invalid: "Adresă email invalidă." form_blurb: "Introdu adresa email al unui părinte mai jos și le vom arăta!" form_label: "Adresă email" placeholder: "adresă email" title: "Excelentă treabă, ucenicule" login: sign_up: "Creează cont" email_or_username: "Email sau nume de utilizator" log_in: "Conectare" logging_in: "Se conectează" log_out: "Deconectare" forgot_password: "<PASSWORD>?" finishing: "Terminare" sign_in_with_facebook: "Conectează-te cu Facebook" sign_in_with_gplus: "Conectează-te cu Google" signup_switch: "Dorești să creezi un cont?" accounts_merge_confirmation: "Există un cont asociat cu adresa de email a acestui cont Google. Vrei să unim aceste conturi?" signup: complete_subscription: "Completează abonamentul" create_student_header: "Creează cont elev" create_teacher_header: "Creează cont profesor" create_individual_header: "Creează cont individual" email_announcements: "Primește anunțuri despre niveluri și îmbunătățiri ale CodeCombat!" sign_in_to_continue: "Conectează-te sau creează un cont pentru a continua" create_account_to_submit_multiplayer: "Creează un cont gratuit pentru a-ți clasifica IA multi-jucător și explorează tot jocul!" teacher_email_announcements: "Înformează-mă cu noutățile despre noi resurse pentru profesori, curicule și coursuri!" creating: "Se creează contul..." sign_up: "Înscrie-te" log_in: "conectează-te cu parolă" login: "Conectare" required: "Trebuie să te înregistrezi înaite să mergi mai departe." login_switch: "Ai deja un cont?" optional: "opțional" connected_gplus_header: "Te-ai conectat cu succes cu Google+!" connected_gplus_p: "Termină înregistrarea pentru a te putea autentifica cu contul Google+." connected_facebook_header: "Te-ai conectat cu succes cu Facebook!" connected_facebook_p: "Termină înregistrarea pentru a te putea autentifica cu contul Facebook." hey_students: "Elevi, introduceți codul clasei dat de profesor." birthday: "Ziua de naștere" parent_email_blurb: "Știm că abia aștepți să înveți programare &mdash; și noi suntem nerăbdători! Părinții tăi vor primi un email cu detalii despre cum să îți creeze un cont. Trimite email {{email_link}} dacă ai întrebări." classroom_not_found: "Nu există clase cu acest cod de clasă. Verifică ceea ce ai scris sau întreabă profesorul pentru ajutor." checking: "Verificare..." account_exists: "Acest e-mail este deja utilizat:" sign_in: "Autentificare" email_good: "Email-ul arată bine!" name_taken: "Nume de utilizator deja folosit! Încearcă {{suggestedName}}?" name_available: "Nume utilizator disponibil!" name_is_email: "Nume de utilizator nu poate fi o adresă email" choose_type: "Alege tipul de cont:" teacher_type_1: "Predă programare utilizând CodeCombat!" teacher_type_2: "Creează clasa" teacher_type_3: "Instrucțiuni accesare curs" teacher_type_4: "Vezi progresul elevilor" signup_as_teacher: "Autentificare profesor" student_type_1: "Învață să programezi în timp ce joci un joc captivant!" student_type_2: "Joacă cu clasa ta" student_type_3: "Concurează în arenă" student_type_4: "Alege eroul!" student_type_5: "Pregătește codul de clasă!" signup_as_student: "Autentificare ca elev" individuals_or_parents: "Persoane & Părinți" individual_type: "Pentru jucători care învață să scrie cod în afara unei clase. Părinții trebuie să se înregistreze pentru un cont aici." signup_as_individual: "Înregistrare persoană" enter_class_code: "Introdu codul de clasă" enter_birthdate: "Introdu data nașterii:" parent_use_birthdate: "Părinți, utilizați data dvs de naștere." ask_teacher_1: "Întreabă profesorul despre codul de clasă." ask_teacher_2: "Nu ești parte dintr-o clasă? Creează un" ask_teacher_3: "cont individual" ask_teacher_4: " în loc." about_to_join: "Ești pe cale să te alături:" enter_parent_email: "Introdu adresa de email a părintelui dvs .:" parent_email_error: "Ceva a mers greșit când am încercat să trimitem email. Verifică adresa de email și mai încearcă o dată." parent_email_sent: "Am trimis un email cu instrucțiuni cum să creezi un cont. Roagă părinții să-și verifice căsuța de email." account_created: "Cont creat!" confirm_student_blurb: "Notează pe ceva informațiile pentru a nu le uita. Profesorul tău te poate ajuta să îți resetezi parola în orice moment." confirm_individual_blurb: "Notează pe ceva informațiile de autentificare în caz că vei avea nevoie de ele mai târziu. Verifică căsuța de email ca să îți poți recupera contul dacă îți vei uita parola - verifică căsuța de email!" write_this_down: "Notează asta:" start_playing: "Începe jocul!" sso_connected: "Conectare reușită cu:" select_your_starting_hero: "Alege eroul de început:" you_can_always_change_your_hero_later: "Poți schimba eroul mai târziu." finish: "Termină" teacher_ready_to_create_class: "Ești gata să creezi prima ta clasă!" teacher_students_can_start_now: "Elevii vor putea să înceapă să joace primul curs, Introducere în informatică, immediat." teacher_list_create_class: "În următorul ecran vei putea crea o nouă clasă." teacher_list_add_students: "Adaugă elevi la clasă la link-ul Vezi clasă, apoi trimite elevilor codul de clasă sau URL-ul. Poți de asemenea să îi inviți prin email dacă aceștia au adrese de email." teacher_list_resource_hub_1: "Verifică" teacher_list_resource_hub_2: "Ghidurile de curs" teacher_list_resource_hub_3: "pentru soluțiile fiecărui nivel și " teacher_list_resource_hub_4: "Zona de resurse " teacher_list_resource_hub_5: "pentru ghiduri privind curicula, activitățile și altele!" teacher_additional_questions: "Asta e tot! Dacă ai nevoie de mai mult ajutor sau ai întrebări, contactează-ne la __supportEmail__." dont_use_our_email_silly: "Nu scrie adresa noastră de email aici! Pune adresa de email a unui părinte." want_codecombat_in_school: "Vrei să joci CodeCombat tot timpul?" eu_confirmation: "Sunt de acord să permit CodeCombat să stocheze datele mele pe un server din SUA." eu_confirmation_place_of_processing: "Află mai multe despre riscuri posibile." eu_confirmation_student: "Dacă nu ești sigur, întreabă-ți profesorul." eu_confirmation_individual: "Dacă nu vrei să îți păstrăm datele pe serverele din SUA, poți juca tot timpul în mod anonim fără salvarea codului scris." password_requirements: "de la 8 până la 64 de caractere fără repetare" invalid: "Invalid" invalid_password: "<PASSWORD>" with: "cu" want_to_play_codecombat: "Nu, nu am una dar vreau să joc CodeCombat!" have_a_classcode: "Ai un cod de clasă?" yes_i_have_classcode: "Da, am un cod de clasă!" enter_it_here: "Introdu codul aici:" recover: recover_account_title: "Recuperează cont" send_password: "<PASSWORD>" recovery_sent: "Email de recuperare trimis." items: primary: "Primar" secondary: "Secundar" armor: "Armură" accessories: "Accesorii" misc: "Diverse" books: "Cărți" common: default_title: "CodeCombat - Jocuri de scris cod pentru a învăța Python și Javascript" default_meta_description: "Învață să scrii cod prin programarea unui joc. Învață Python, Javascript și HTML ca și când ai rezolva puzzle-uri și învață să îți faci propriile jocuri și site-uri web." back: "Înapoi" # When used as an action verb, like "Navigate backward" coming_soon: "în curând!" continue: "Continuă" # When used as an action verb, like "Continue forward" next: "Următor" default_code: "Cod implicit" loading: "Se încarcă..." overview: "Prezentare generală" processing: "Procesare..." solution: "Soluţie" table_of_contents: "Cuprins" intro: "Introducere" saving: "Se salvează..." sending: "Se trimite..." send: "Trimite" sent: "Trimis" cancel: "Anulează" save: "Salvează" publish: "Publică" create: "Creează" fork: "Fork" play: "Joacă" # When used as an action verb, like "Play next level" retry: "Reîncearcă" actions: "Acţiuni" info: "Info" help: "Ajutor" watch: "Urmărește" unwatch: "Nu mai urmări" submit_patch: "Trimite patch" submit_changes: "Trimite modificări" save_changes: "Salvează modificări" required_field: "obligatoriu" submit: "Transmite" replay: "Rejoacă" complete: "Complet" pick_image: "Alege imagine" general: and: "și" name: "Nume" date: "Dată" body: "Corp" version: "Versiune" pending: "În așteptare" accepted: "Acceptat" rejected: "Respins" withdrawn: "Retras" accept: "Acceptă" accept_and_save: "Acceptă și salvează" reject: "Respinge" withdraw: "Retrage" submitter: "Expeditor" submitted: "Expediat" commit_msg: "Înregistrează mesajul" version_history: "Istoricul versiunilor" version_history_for: "Istoricul versiunilor pentru: " select_changes: "Selectați două schimbări de mai jos pentru a vedea diferenţa." undo_prefix: "Undo" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Redo" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Joaca previzualizarea nivelului curent" result: "Rezultat" results: "Rezultate" description: "Descriere" or: "sau" subject: "Subiect" email: "Email" password: "<PASSWORD>" confirm_password: "<PASSWORD>" message: "Mesaj" code: "Cod" ladder: "Clasament" when: "când" opponent: "oponent" rank: "Rang" score: "Scor" win: "Victorie" loss: "Înfrângere" tie: "Remiză" easy: "Ușor" medium: "Mediu" hard: "Greu" player: "<NAME>" player_level: "Nivel" # Like player level 5, not like level: Dungeons of Kithgard warrior: "Războinic" ranger: "Arcaș" wizard: "Vrăjitor" first_name: "<NAME>" last_name: "<NAME>" last_initial: "Inițială nume" username: "Nume de utilizator" contact_us: "Contactează-ne" close_window: "Închide fereastra" learn_more: "Află mai mult" more: "Mai mult" fewer: "Mai puțin" with: "cu" chat: "Chat" chat_with_us: "Vorbește cu noi" email_us: "Trimite-ne email" sales: "Vânzări" support: "Suport" here: "aici" units: second: "secundă" seconds: "secunde" sec: "sec" minute: "minut" minutes: "minute" hour: "oră" hours: "ore" day: "zi" days: "zile" week: "săptămână" weeks: "săptămâni" month: "lună" months: "luni" year: "an" years: "ani" play_level: back_to_map: "Înapoi la hartă" directions: "Direcții" edit_level: "Modifică nivel" keep_learning: "Continuă să înveți" explore_codecombat: "Explorează CodeCombat" finished_hoc: "Am terminat Hour of Code" get_certificate: "Obține certificatul!" level_complete: "Nivel terminat" completed_level: "Nivel terminat:" course: "Curs:" done: "Terminat" next_level: "Următorul nivel" combo_challenge: "Provocare combinată" concept_challenge: "Provocare concept" challenge_unlocked: "Provocare deblocată" combo_challenge_unlocked: "Provocare combinată deblocată" concept_challenge_unlocked: "Provocare concept deblocată" concept_challenge_complete: "Provocare concept terminată!" combo_challenge_complete: "Provocare combinată terminată!" combo_challenge_complete_body: "Foarte bine, se pare că stai foarte bine în înțelegerea __concept__!" replay_level: "Joacă din nou nivelul" combo_concepts_used: "__complete__/__total__ concepte utilizate" combo_all_concepts_used: "Ai utilizat toate conceptele posibile pentru a rezolva provocarea. Foarte bine!" combo_not_all_concepts_used: "Ai utilizat __complete__ din __total__ concepte posibile pentru a rezolva provocarea. Încearcă să utilizezi toate cele __total__ concepte următoarea dată!" start_challenge: "Start provocare" next_game: "Următorul joc" languages: "Limbi" programming_language: "Limbaj de programare" show_menu: "Arată meniul jocului" home: "Acasă" # Not used any more, will be removed soon. level: "Nivel" # Like "Level: Dungeons of Kithgard" skip: "Sări peste" game_menu: "Meniul Jocului" restart: "Restart" goals: "Obiective" goal: "Obiectiv" challenge_level_goals: "Obiectivele nivelului tip provocare" challenge_level_goal: "Obiectivul nivelului tip provocare" concept_challenge_goals: "Obiectivele provocării concept" combo_challenge_goals: "Obiectivele provocării combinate" concept_challenge_goal: "Obiectivul provocării concept" combo_challenge_goal: "Obiectivul provocării combinate" running: "Rulează..." success: "Success!" incomplete: "Incomplet" timed_out: "Ai rămas fără timp" failing: "Eşec" reload: "Reîncarcă" reload_title: "Reîncarcă tot codul?" reload_really: "Ești sigur că vrei să reîncarci nivelul de la început?" reload_confirm: "Reîncarca tot" restart_really: "Ești sigur că vrei să joci din nou nivelul? Vei pierde tot codul pe care l-ai scris." restart_confirm: "Da, joc din nou" test_level: "Nivel de test" victory: "Victorie" victory_title_prefix: "" victory_title_suffix: " Terminat" victory_sign_up: "Înscrie-te pentru a salva progresul" victory_sign_up_poke: "Vrei să-ți salvezi codul? Creează un cont gratuit!" victory_rate_the_level: "Cât de amuzant a fost acest nivel?" victory_return_to_ladder: "Înapoi la clasament" victory_saving_progress: "Salvează progresul" victory_go_home: "Mergi acasă" victory_review: "Spune-ne mai multe!" victory_review_placeholder: "Cum a fost nivelul?" victory_hour_of_code_done: "Ai terminat?" victory_hour_of_code_done_yes: "Da, am terminat Hour of Code™!" victory_experience_gained: "Ai câștigat XP" victory_gems_gained: "Ai câștigat pietre prețioase" victory_new_item: "Articol nou" victory_new_hero: "Erou nou" victory_viking_code_school: "Oau, acesta a fost un nivel greu! Daca nu ești deja un dezvoltator de software, ar trebui să fi. Tocmai ai fost selectat pentru acceptare în Viking Code School, unde poți să îți dezvolți abilitățile la nivelul următor și să devi un dezvoltator web profesionist în 14 săptămâni." victory_become_a_viking: "Devin-o Viking" victory_no_progress_for_teachers: "Progresul nu este salvat pentru profesori. Dar, poți adăuga un cont de elev la clasa ta pentru tine." tome_cast_button_run: "Execută" tome_cast_button_running: "În execuție" tome_cast_button_ran: "S-a executat" tome_cast_button_update: "Actualizare" tome_submit_button: "Trimite" tome_reload_method: "Reîncarcă codul original pentru a restarta nivelul" tome_your_skills: "Abilitățile tale" hints: "Indicii" videos: "Filme" hints_title: "Indiciul {{number}}" code_saved: "Cod salvat" skip_tutorial: "Sări peste (esc)" keyboard_shortcuts: "Scurtături tastatură" loading_start: "Începe nivel" loading_start_combo: "Începe provocarea combinată" loading_start_concept: "Începe provocarea concept" problem_alert_title: "Repară codul" time_current: "Acum:" time_total: "Max:" time_goto: "Mergi la:" non_user_code_problem_title: "Imposibil de încărcat nivel" infinite_loop_title: "Buclă infinită detectată" infinite_loop_description: "Codul inițial pentru a construi lumea nu a terminat de rulat niciodată. Este probabil foarte lent sau are o buclă infinită. Sau ar putea fi o eroare de programare. Poți încerca să executați acest cod din nou sau să resetezi codul la starea implicită. Dacă nu se remediază, te rog să ne anunți." check_dev_console: "Puteți deschide, de asemenea, consola de dezvoltator pentru a vedea ce ar putea merge greșit." check_dev_console_link: "(instrucțiuni)" infinite_loop_try_again: "Încearcă din nou" infinite_loop_reset_level: "Resetează nivelul" infinite_loop_comment_out: "Comentează codul meu" tip_toggle_play: "schimbă între joacă/pauză cu Ctrl+P." tip_scrub_shortcut: "Utilizează Ctrl+[ și Ctrl+] pentru a derula înapoi sau a da pe repede înainte." tip_guide_exists: "Apasă pe ghid, din meniul jocului (din partea de sus a paginii), pentru informații utile." tip_open_source: "CodeCombat este parte a comunității open source!" tip_tell_friends: "Îți place CodeCombat? Spune-le prietenilor tăi despre noi!" tip_beta_launch: "CodeCombat a fost lansat în format beta în Octombrie 2013." tip_think_solution: "Gândește-te la soluție, nu la problemă." tip_theory_practice: "Teoretic nu este nici o diferență înte teorie și practică. Dar în practică este. - <NAME>" tip_error_free: "Există doar două metode de a scrie un program fără erori; numai a treia funcționează. - <NAME>" tip_debugging_program: "Dacă a face depanare este procesul de a elimina erorile, atunci a programa este procesul de a introduce erori. - <NAME>" tip_forums: "Mergi la forum și spune-ți părerea!" tip_baby_coders: "În vitor până și bebelușii vor fi Archmage." tip_morale_improves: "Încărcarea va continua până când moralul se va îmbunătăți." tip_all_species: "Noi credem în șanse egale pentru toate speciile pentru a învăța programare." tip_reticulating: "Re-articulăm coloane vertebrale." tip_harry: "Yer a Wizard, " tip_great_responsibility: "Cu o mare abilitate de programare vine și o mare responsabilitate de depanare." tip_munchkin: "Dacă nu iți mănânci legumele, un munchkin va veni după tine când dormi." tip_binary: "Sunt doar 10 tipuri de oameni în lume: cei ce înteleg sistemul binar și ceilalți." tip_commitment_yoda: "Un programator trebuie să aibă cel mai profund angajament, mintea cea mai serioasă. ~Yoda" tip_no_try: "A face. Sau a nu face. Nu există voi încerca. ~Yoda" tip_patience: "Să ai rabdare trebuie, tinere Padawan. ~Yoda" tip_documented_bug: "O eroare (bug) documentată nu e chiar o eroare; este o caracteristică." tip_impossible: "Mereu pare imposibil până când e gata. ~<NAME>" tip_talk_is_cheap: "Vorbele sunt goale. Arată-mi codul. ~<NAME>" tip_first_language: "Cel mai dezastruos lucru pe care poți să îl înveți este primul limbaj de programare. ~<NAME>" tip_hardware_problem: "Întrebare: De câți programatori ai nevoie ca să schimbi un bec? Răspuns: Niciunul, e o problemă de hardware." tip_hofstadters_law: "Legea lui Hofstadter: Mereu durează mai mult decât te aștepți, chiar dacă iei în considerare Legea lui Hofstadter." tip_premature_optimization: "Optimizarea prematură este rădăcina tuturor răutăților. ~<NAME>" tip_brute_force: "Atunci cănd ești în dubii, folosește forța brută. ~<NAME>" tip_extrapolation: "Există doar două feluri de oameni: cei care pot extrapola din date incomplete..." tip_superpower: "Programarea este cel mai apropiat lucru de o superputere." tip_control_destiny: "În open source, ai dreptul de a-ți controla propiul destin. ~<NAME>" tip_no_code: "Niciun cod nu e mai rapid decat niciun cod." tip_code_never_lies: "Codul nu minte niciodată, commenturile mai mint. ~<NAME>" tip_reusable_software: "Înainte ca un software să fie reutilizabil, trebuie să fie mai întâi utilizabil." tip_optimization_operator: "Fiecare limbaj are un operator de optimizare. La majoritatea acela este '//'" tip_lines_of_code: "Măsurarea progresului în lini de cod este ca și măsurarea progresului de construcție a aeronavelor în greutate. ~<NAME>" tip_source_code: "Vreau să schimb lumea dar nu îmi dă nimeni codul sursă." tip_javascript_java: "Java e pentru Javascript exact ce e o mașina pentru o carpetă. ~<NAME>" tip_move_forward: "Orice ai face, mergi înainte. ~<NAME> Jr." tip_google: "Ai o problemă care nu o poți rezolva? Folosește Google!" tip_adding_evil: "Adaugăm un strop de răutate." tip_hate_computers: "Tocmai aia e problema celor care cred că urăsc calulatoarele. Ceea ce urăsc ei de fapt sunt programatorii nepricepuți. ~<NAME>" tip_open_source_contribute: "Poți ajuta la îmbunătățirea jocului CodeCombat!" tip_recurse: "A itera este uman, recursiv este divin. ~<NAME>. <NAME>" tip_free_your_mind: "Trebuie sa lași totul, <NAME>, îndoiala și necredința. Eliberează-ți mintea. ~Morpheus" tip_strong_opponents: "Și cei mai puternici dintre oponenți întodeauna au o slăbiciune. ~<NAME>" tip_paper_and_pen: "Înainte să începi să scrii cod, poți tot mereu să planific mai întâi pe o foaie de hârtie cu un creion." tip_solve_then_write: "Mai întâi, rezolvă problema. Apoi, scrie codul. - <NAME>" tip_compiler_ignores_comments: "Câteodată cred că compilatorul îmi ignoră comentariile." tip_understand_recursion: "Singura modalitate de a înțelege recursivitatea este să înțelegi recursivitatea." tip_life_and_polymorphism: "Open Source este ca o structură total polimorfică și eterogenă: Toate tipurile sun primite." tip_mistakes_proof_of_trying: "Greșelile din codul tău sunt dovezi că încerci." tip_adding_orgres: "Scurtăm niște căpcăuni." tip_sharpening_swords: "Ascuțim săbiile." tip_ratatouille: "Nu trebuie să lași pe nimeni să-ți definească limitele pe baza locului de unde vi. Singura ta limită este sufletul tău. - Gusteau, Ratatouille" tip_nemo: "Când viața te pune la pământ, vrei să ști ce trebuie să faci? Doar continuă să înoți, doar continuă să înoți. - <NAME>" tip_internet_weather: "Mută-te pe Internet, este minunat aici. Ajungem să trăim înauntru unde vremea este tot mereu frumoasă. - <NAME>" tip_nerds: "Tocilarilor le este permis să iubească lucruri, ca de exemplu sări-sus-și-jos-în-scaun-nu-te-poți-controla. - <NAME>" tip_self_taught: "M-am învățat singur 90% din ceea ce am învățat. Și așa e normal! - <NAME>" tip_luna_lovegood: "Nu-ți face griji, ești la fel de sănătos la minte ca și mine. - <NAME>" tip_good_idea: "Modalitatea cea mai bună de a avea o idee bună este să ai multe idei. - <NAME>" tip_programming_not_about_computers: "În informatică nu mai este vorba doar despre calculatoare așa cum în astronomie nu e vorba doar despre telescoape. - <NAME>" tip_mulan: "Crede că poți și atunci vei putea. - <NAME>" project_complete: "Proiect terminat!" share_this_project: "Partajează acest proiect cu prietenii și familia:" ready_to_share: "Gata să îți publici proiectul?" click_publish: "Apasă \"Publică\" pentru a-l face să apară în galeria clasei, apoi verifică ce au făcut colegii! Te poți întoarce să continui să lucrezi la acest proiect. Orice schimbare viitoare va fi automat salvată și partajată cu colegii tăi." already_published_prefix: "Modificările tale au fost publicate în galeria clasei." already_published_suffix: "Continuă să experimentezi și să îmbunătățești acest proiect, sau vezi ceea ce au construit restul colegilor! Modificările tale vor fi automat salvate și partajate cu colegii tăi." view_gallery: "Vezi galeria" project_published_noty: "Nivelul tău a fost publicat!" keep_editing: "Continuă să modifici" learn_new_concepts: "Învață noi concepte" watch_a_video: "Urmărește un video despre __concept_name__" concept_unlocked: "Concept deblocat" use_at_least_one_concept: "Utilizează cel puțin un concept: " command_bank: "Banca de comenzi" learning_goals: "Obiectivele învățării" start: "Start" vega_character: "<NAME>" click_to_continue: "Apasă pentru a continua" fill_in_solution: "Completează cu soluția" play_as_humans: "Joacă ca om" play_as_ogres: "Joacă ca căpcăun" apis: methods: "Metode" events: "Evenimente" handlers: "Handler-e" properties: "Proprietăți" snippets: "Fragmente" spawnable: "Generabil" html: "HTML" math: "Mate" array: "Matrice" object: "Obiect" string: "Șir de caractere" function: "Funcție" vector: "Vector" date: "Dată" jquery: "jQuery" json: "JSON" number: "Număr" webjavascript: "Javascript" amazon_hoc: title: "Continuă să înveți cu Amazon!" congrats: "Felicitări în câștigarea provocărilor din Hour of Code!" educate_1: "Acum, continuă să înveți despre scrieres codului și despre cloud computing cu AWS Educate, un program gratuit și captivant de la Amazon atât pentru cursanți cât și pentru profesori. Cu AWS Educate, poți câștiga insigne virtuale când înveți despre noțiunile de bază din cloud și despre tehnologiile de ultimă generație cum sunt jocurile, realitatea virtuală și Alexa." educate_2: "Învață mai multe și înregistrează-te aici" future_eng_1: "Poți să încerci să construiești abilități noi pentru <NAME>a legate de fapte școlare" future_eng_2: "aici" future_eng_3: "(echipamentul nu este necesar). Această activitate cu <NAME>a este prezentată de" future_eng_4: "Amazon Future Engineer (Viitorii Ingineri Amazon)" future_eng_5: "un program care creează oportunități pentru învățare și munncă pentru toți elevii K-12 din Statele Unite care doresc să urmeze o carieră în informatică." live_class: title: "Mulțumesc!" content: "Uimitor! Tocmai am lansat clase on-line în timp real." link: "Ești pregătit să mergi mai departe cu programarea?" code_quest: great: "Minunat!" join_paragraph: "Alătură-te celui mai mare turneu internațional de programare Python IA pentru toate vârstele și concurează pentru a ajunge în vârful tabelei de scor! Această bătălie globală de o lună, începe pe 1 August și include premii în valoare de $5k și o ceremonie virtuală de decernare a premiilor unde vom anunța câștigătorii și vom recunoaște abilitățile voastre de a scrie cod." link: "Apasă aici pentru înregistrare și mai multe detalii" global_tournament: "Turneu global" register: "Înregistrare" date: "1 Aug - 31 Aug" play_game_dev_level: created_by: "Creat de {{name}}" created_during_hoc: "Creat în timpul Hour of Code" restart: "Reîncepe nivel" play: "Joacă nivel" play_more_codecombat: "Joacă mai mult CodeCombat" default_student_instructions: "Apasă pentru a controla eroul și a câștiga jocul!" goal_survive: "Supraviețuiește." goal_survive_time: "Supraviețuiește pentru __seconds__ secunde." goal_defeat: "Învinge toți inamicii." goal_defeat_amount: "Învinge __amount__ inamici." goal_move: "Mergi la toate marcajele cu X." goal_collect: "Colectează toate obiectele." goal_collect_amount: "Ai colectat __amount__ obiecte." game_menu: inventory_tab: "Inventar" save_load_tab: "Salvează/Încarcă" options_tab: "Opțiuni" guide_tab: "Ghid" guide_video_tutorial: "Tutorial Video" guide_tips: "Sfaturi" multiplayer_tab: "Multiplayer" auth_tab: "Înscriere" inventory_caption: "Echipează eroul" choose_hero_caption: "Alege eroul, limba" options_caption: "Configurare setări" guide_caption: "Documentație și sfaturi" multiplayer_caption: "Joacă cu prietenii!" auth_caption: "Salvează progresul." leaderboard: view_other_solutions: "Vezi tabelul de clasificare" scores: "Scoruri" top_players: "Top jucători după" day: "Azi" week: "Săptămâna aceasta" all: "Tot timpul" latest: "Ultimul" time: "Timp" damage_taken: "Vătămare primită" damage_dealt: "Vătămare oferită" difficulty: "Dificultate" gold_collected: "Aur colectat" survival_time: "Supraviețuit" defeated: "Inamici înfrânți" code_length: "Linii de cod" score_display: "__scoreType__: __score__" inventory: equipped_item: "Echipat" required_purchase_title: "Necesar" available_item: "Disponibil" restricted_title: "Restricționat" should_equip: "(dublu-click pentru echipare)" equipped: "(echipat)" locked: "(blocat)" restricted: "(restricționat în acest nivel)" equip: "Echipează" unequip: "Dezechipează" warrior_only: "Doar războinic" ranger_only: "Doar arcaș" wizard_only: "Doar vrăjitor" buy_gems: few_gems: "Căteva pietre prețioase" pile_gems: "Morman de pietre prețioase" chest_gems: "Cufăr cu pietre prețioase" purchasing: "Cumpărare..." declined: "Cardul tău a fost refuzat." retrying: "Eroare de server, reîncerc." prompt_title: "Nu sunt destule pietre prețioase." prompt_body: "Vrei să cumperi mai multe?" prompt_button: "Intră în magazin." recovered: "Pietre prețioase cumpărate anterior recuperate. Vă rugăm să reîncărcați pagina." price: "x{{gems}} / lună" buy_premium: "Cumpără premium" purchase: "Cumpără" purchased: "Cumpărat" subscribe_for_gems: prompt_title: "Pietre prețioase insuficiente!" prompt_body: "Abonează-te la Premium pentru a obține pietre prețioase și pentru a accesa chiar mai multe niveluri!" earn_gems: prompt_title: "Pietre prețioase insuficiente" prompt_body: "Continuă să joci pentru a câștiga mai multe!" subscribe: best_deal: "Cea mai bună afacere!" confirmation: "Felicitări! Acum ai abonament CodeCombat Premium!" premium_already_subscribed: "Ești deja abonat la Premium!" subscribe_modal_title: "CodeCombat Premium" comparison_blurb: "Devino un Master Coder - abonează-te la varianta <b>Premium</b> azi! " must_be_logged: "Trebuie să te conectezi mai întâi. Te rugăm să creezi un cont sau să te conectezi din meniul de mai sus." subscribe_title: "Abonare" # Actually used in subscribe buttons, too unsubscribe: "Dezabonare" confirm_unsubscribe: "Confirmă dezabonarea" never_mind: "Nu contează, eu tot te iubesc!" thank_you_months_prefix: "Mulțumesc pentru sprijinul acordat în aceste" thank_you_months_suffix: "luni." thank_you: "Mulțumim pentru susținerea CodeCombat!" sorry_to_see_you_go: "Ne pare rău că pleci! Te rugăm să ne spui ce am fi putut face mai bine." unsubscribe_feedback_placeholder: "Of, ce am făcut?" stripe_description: "Abonament lunar" stripe_yearly_description: "Abonament anual" buy_now: "Cumpără acum" subscription_required_to_play: "Ai nevoie de abonament ca să joci acest nivel." unlock_help_videos: "Abonează-te pentru deblocarea tuturor tutorialelor video." personal_sub: "Abonament personal" # Accounts Subscription View below loading_info: "Se încarcă informațile despre abonament..." managed_by: "Gestionat de" will_be_cancelled: "Va fi anulat pe" currently_free: "În prezent ai un abonament gratuit" currently_free_until: "În prezent ai un abonament până pe" free_subscription: "Abonament gratuit" was_free_until: "Ai avut un abonament gratuit până pe" managed_subs: "Abonamente Gestionate" subscribing: "Te abonăm..." current_recipients: "Recipienți curenți" unsubscribing: "Dezabonare..." subscribe_prepaid: "Apasă pe abonare pentru a folosi un cod preplătit" using_prepaid: "Foloseste cod preplătit pentru un abonament lunar" feature_level_access: "Accesează peste 500+ de nivele disponibile" feature_heroes: "Deblochează eroi exclusivi și animăluțe de companie" feature_learn: "Învață să creezi jocuri și site-uri web" feature_gems: "Primește __gems__ pietre prețioase pe lună" month_price: "$__price__" # {change} first_month_price: "Doar $__price__ pentru prima lună!" lifetime: "Acces pe viață" lifetime_price: "$__price__" year_subscription: "Abonament anual" year_price: "$__price__/an" # {change} support_part1: "Ai nevoie de ajutor cu plata sau preferi PayPal? Email" support_part2: "<EMAIL>" announcement: now_available: "Acum disponibil pentru abonați!" subscriber: "abonat" cuddly_companions: "Animăluțe drăguțe!" # Pet Announcement Modal kindling_name: "Kindling Elemental" kindling_description: "Kindling Elemental-ii vor doar să îți țină de cald noaptea. Și în timpul zilei. Toto timpul, pe cuvânt." griffin_name: "<NAME>" griffin_description: "Grifonii sunt jumătate vultur, jumătate leu, foarte adorabili." raven_name: "<NAME>" raven_description: "Corbii sunt excelenți la adunarea sticluțelor pline cu poțiune de sănătate." mimic_name: "<NAME>" mimic_description: "Mimii pot aduna monede pentru tine. Pune-i peste monede pentru a crește provizia de aur." cougar_name: "<NAME>" cougar_description: "Pumelor le place să își ia PhD prin Purring Happily Daily.(joc de cuvinte)" fox_name: "<NAME>" fox_description: "Vulpile albastre sunt foarte istețe și le place să sape în pământ și zăpadă!" pugicorn_name: "<NAME>" pugicorn_description: "Pugicornii sunt cele mai rare creaturi care pot face vrăji!" wolf_name: "<NAME>" wolf_description: "Puii de lup sunt foarte buni la vânătoare, culegere și fac un joc răutăcios de-a fața-ascunselea!" ball_name: "<NAME>inge roșie chițăitoare" ball_description: "ball.squeak()" collect_pets: "Adună animăluțe pentru eroul tău!" each_pet: "Fiecare animăluț are o abilitate unică de a te ajuta!" upgrade_to_premium: "Devino un {{subscriber}} pentru a echipa animăluțele." play_second_kithmaze: "Joacă {{the_second_kithmaze}} pentru a debloca puiul de lup!" the_second_kithmaze: "Al doilea Kithmaze" keep_playing: "Continuă să joci pentru a descoperi primul animăluț!" coming_soon: "În curând" ritic: "Ritic al frigului" # Ritic Announcement Modal ritic_description: "Ritic al frigului. Prins în capcana ghețarului <NAME> de nenumărați ani, este în sfârșit liber și pregătit să aibă grijă de căpcăunii care l-au închis." ice_block: "Un bloc de gheață" ice_description: "Pare să fie ceva prins în interior ..." blink_name: "Blink" blink_description: "Ritic dispare și apare într-o clipire de ochi, lăsând în urmă doar umbră." shadowStep_name: "Shadowstep" shadowStep_description: "Un assasin maestru care știe să umble printre umbre." tornado_name: "Tornado" tornado_description: "Este bine să ai un buton de reset când acoperirea cuiva este spulberată." wallOfDarkness_name: "Zidul Întunericului" wallOfDarkness_description: "Se ascunde în spatele unui zid de umbră pentru a evita privirile." avatar_selection: pick_an_avatar: "Alege un avatar care te reprezintă ca și jucător" premium_features: get_premium: "Cumpără<br>CodeCombat<br>Premium" # Fit into the banner on the /features page master_coder: "Devino un master al codului abonându-te azi!" paypal_redirect: "Vei fi redirecționat către PayPal pentru a finaliza procesul de abonare." subscribe_now: "Abonează-te acum" hero_blurb_1: "Obține acces la __premiumHeroesCount__ de eroi super dotați disponibili doar pentru abonați! Valorifică puterea de neoprit a lui <NAME>, precizia mortală a lu Naria of the Leaf, sau cheamă \"adorable\" scheleți cu Nalfar Cryptor." hero_blurb_2: "Luptătorii premium deblochează arte marțiale uimitoare ca Warcry, Stomp și Hurl Enemy. Sau, joacă ca și Arcaș, utilizând procedee ascunse și arcuri, aruncarea de cuțite, capcane! Încearcă-ți aptitudinile ca Vrăjitor și eliberează o serie de magii puternice ca Primordial, Necromantic sau Elemental!" hero_caption: "Noi eroi impresionanți!" pet_blurb_1: "Animăluțele nu sunt numai companioni adorabili, ei furnizează funcții și metode unice. Piul de grifon poate căra trupe prin aer, puiul de lup joacă prinselea cu săgeține inamicilor, pumei îi place să fugărească căpcăuni iar Mim-ul atrage monedele ca magnetul!" pet_blurb_2: "Adună toate animăluțele pentru a descoperi abilitățile lor unice!" pet_caption: "Adoptă animăluțe care să îl însoțească pe eroul tău!" game_dev_blurb: "Învață game scripting și construiește noi nivele pe care să le partajezi cu prietenii tăi! Pune obiectele pe care le dorești, scrie cod pentru unitatea logică și de comportament și vezi dacă prietenii pot să termine nivelul!" game_dev_caption: "Dezvoltă propriile jocuri pentru a-ți provoca prietenii!" everything_in_premium: "Tot ceea ce vei obține în CodeCombat Premium:" list_gems: "Primești pietre prețioase bonus pentru cumpărarea echipamentului, animaăluțelor și eroilor" list_levels: "Obții acces la __premiumLevelsCount__ alte niveluri" list_heroes: "Deblochează eroi exclusivi, care cuprind clasele Arcaș și Vrăjitor" list_game_dev: "Creează și partajează jocuri cu prietenii" list_web_dev: "Construiește site-uri web și aplicații interactive" list_items: "Echipează-te cu elemente specifice premium cum sunt animăluțele" list_support: "Primește suport de tip premium pentru a te ajuta să rezolvi situațiile încâlcite" list_clans: "Creează clanuri private în care să inviți prieteni și concurează într-un clasament de grup" choose_hero: choose_hero: "Alege eroul" programming_language: "Limbaj de programare" programming_language_description: "Ce limbaj de programare vrei să folosești?" default: "Implicit" experimental: "Experimental" python_blurb: "Simplu dar puternic, minunat atât pentru începători cât și pentru experți" javascript_blurb: "Limbajul web-ului. (Nu este același lucru ca Java.)" coffeescript_blurb: "Javascript cu o syntaxă mai placută!" lua_blurb: "Limbaj de scripting pentru jocuri." java_blurb: "(Numai pentru abonați) Android și pentru afaceri." cpp_blurb: "(Numai pentru abonați) Dezvoltare de jocuri și calcul de înaltă performanță." status: "Stare" weapons: "Armament" weapons_warrior: "Săbii - Distanță scurtă, Fără magie" weapons_ranger: "Arbalete, Pistoale - Distanță mare, Fără magie" weapons_wizard: "Baghete, Toiege - Distanță mare, Magie" attack: "Atac" # Can also translate as "Attack" health: "Viață" speed: "Viteză" regeneration: "Regenerare" range: "Rază" # As in "attack or visual range" blocks: "Blochează" # As in "this shield blocks this much damage" backstab: "Înjunghiere" # As in "this dagger does this much backstab damage" skills: "Abilități" attack_1: "Oferă" attack_2: "din cele listate" attack_3: "Vătămare cu arma." health_1: "Primește" health_2: "din cele listate" health_3: "Stare armură." speed_1: "Se deplasează cu" speed_2: "metri pe secundă." available_for_purchase: "Disponibil pentru cumpărare" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Nivel ce trebuie deblocat:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see) restricted_to_certain_heroes: "Numai anumiți eroi pot juca acest nivel." char_customization_modal: heading: "Personalizează eroul" body: "Cor<NAME>" name_label: "<NAME>" hair_label: "Culoare păr" skin_label: "Culoare piele" skill_docs: function: "funcție" # skill types method: "metodă" snippet: "fragment" number: "număr" array: "matrice" object: "obiect" string: "șir de caractere" writable: "permisiuni de scriere" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "permisiuni doar de citire" action: "Acțiune" spell: "Vrajă" action_name: "nume" action_cooldown: "Durează" action_specific_cooldown: "Răcire" action_damage: "Vătămare" action_range: "Raza de acțiune" action_radius: "Raza" action_duration: "Durata" example: "Exemplu" ex: "ex" # Abbreviation of "example" current_value: "Valoare curentă" default_value: "Valoare implicită" parameters: "Parametrii" required_parameters: "Parametrii necesari" optional_parameters: "Parametrii opționali" returns: "Întoarce" granted_by: "Acordat de" still_undocumented: "Încă nedocumentat, ne pare rău." save_load: granularity_saved_games: "Salvate" granularity_change_history: "Istoric" options: general_options: "Opțiuni Generale" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volum" music_label: "Muzic<NAME>" music_description: "Oprește/pornește muzica din fundal." editor_config_title: "Configurare editor" editor_config_livecompletion_label: "Autocompletare live" editor_config_livecompletion_description: "Afișează sugesti de autocompletare în timp ce scri." editor_config_invisibles_label: "Arată etichetele invizibile" editor_config_invisibles_description: "Arată spațiile și taburile invizibile." editor_config_indentguides_label: "Arată ghidul de indentare" editor_config_indentguides_description: "Arată linii verticale pentru a vedea mai bine indentarea." editor_config_behaviors_label: "Comportamente inteligente" editor_config_behaviors_description: "Completează automat parantezele, ghilimele etc." about: title: "Despre CodeCombat - Elevi pasionați, Profesori implicați, Creații inspirate" meta_description: "Misiunea noastră este să ridicăm nivelul informaticii prin învățarea bazată pe joc și să facem programarea accesibilă fiecărui elev. Noi credem că programarea este magică și vrem că le dăm elevilor puterea de a crea lucruri din imaginație." learn_more: "Află mai multe" main_title: "Dacă vrei să înveți să programezi, trebuie să scrii (foarte mult) cod." main_description: "La CodeCombat, rolul nostru este să ne asigurăm că vei face acest lucru cu zâmbetul pe față." mission_link: "Misiune" team_link: "Echipă" story_link: "Poveste" press_link: "Presă" mission_title: "Misiunea noastră: să facem programarea accesibilă fiecărui elev de pe Pământ." mission_description_1: "<strong>Programarea este magică</strong>. Este abilitatea de a creea lucruri din imaginație. Am pornit CodeCombat pentru a-i face pe cursanți să simtă că au puteri magice la degetul lor mic utilizând <strong>cod scris</strong>." mission_description_2: "Dupăc cum am văzut, acest lucru îi face să învețe să scrie cod mai repede. MULT MAI rapid. Este ca și când am avea o conversație în loc de a citi un manual. Vrem să aducem această conversație în fiecare școală și la <strong>fiecare elev</strong>, deoarece toată lumea ar trebui să aibă o șansă să învețe magia programării." team_title: "Întâlnește echipa CodeCombat" team_values: "Punem preș pe dialoguș deschis și respectuos, în care cea mai bună idee câștigă. Deciziile noastre sun bazate pe cercetarea consumatorilor iar procesul nostru pune accent pe livrarea resultatelor tangibile pentru ei. Toată lumea luCreează la asta, de la CEO la contributorii noștri GitHub, deoarece noi în echipa noastră punem valoare pe creștere și dezvoltare ." nick_title: "<NAME>, C<NAME>" # csr_title: "Customer Success Representative" # csm_title: "Customer Success Manager" # scsm_title: "Senior Customer Success Manager" # ae_title: "Account Executive" # sae_title: "Senior Account Executive" # sism_title: "Senior Inside Sales Manager" # shan_title: "Head of Marketing, CodeCombat Greater China" # run_title: "Head of Operations, CodeCombat Greater China" # lance_title: "Head of Technology, CodeCombat Greater China" # zhiran_title: "Head of Curriculum, CodeCombat Greater China" # yuqiang_title: "Head of Innovation, CodeCombat Greater China" swe_title: "Inginer software" sswe_title: "Infiner senior software" css_title: "Specialist suport clienți" css_qa_title: "Suport clienți / Specialis întrebări/răspunsuri" maya_title: "Dezvoltator senior de curiculă" bill_title: "Manager general, CodeCombat Greater China" pvd_title: "Designer vizual și de produs" spvd_title: "Designer senior vizual și de produs" daniela_title: "Manager de marketing" bobby_title: "Dezvoltator joc" brian_title: "Manager senior de dezvoltare joc" stephanie_title: "Specialist suport clienți" # sdr_title: "Sales Development Representative" retrostyle_title: "Ilustrator" retrostyle_blurb: "Jocuri în stil retro" community_title: "...și comunitatea noastră open-source" bryukh_title: "Dezvoltator Senior de joc" # oa_title: "Operations Associate" ac_title: "Coordonator administrativ" ea_title: "Asistent executiv" om_title: "Manager de operații" mo_title: "Manager, Operații" smo_title: "Manager senior, Operații" do_title: "Director de operații" scd_title: "Dezvoltator senior de curiculă" lcd_title: "Dezvoltator șef de curiculă" de_title: "Director de educație" vpm_title: "VP, Marketing" oi_title: "Instructor online " # bdm_title: "Business Development Manager" community_subtitle: "Peste 500 de colaboratori au ajutat la dezvoltarea CodeCombat, numărul acestora crescând în fiecare săptămână!" community_description_3: "CodeCombat este un" community_description_link_2: "proiect colectiv" community_description_1: "cu sute de jucători care se oferă voluntar să creeze noi niveluri, contribuie la codul nostru pentru a adauga componente, a repara erori, a testa jocuri și a traduce jocul în peste 50 de limbi până în prezent. Angajații, contribuabilii și câștigurile aduse de site prin partajarea ideilor dar și un efort comun, așa cum face comunitatea open-source în general. Site-ul este construit pe numeroase proiecte open-source, și suntem deschiși să dăm înapoi comunității și să furnizăm jucătorilor curioși în privința codului un proiect familiar de examinat și experimentat. Oricine se poate alătura comunității CodeCombat! Verifică" community_description_link: "pagina cu cei care au contribuit" community_description_2: "pentru mai multe informații." number_contributors: "Peste 450 contributori și-au adus suportul și timpul la acest proiect." story_title: "Povestea noastră până în prezent" story_subtitle: "Din 2013, CodeCombat a crescut de la un simplu set de schițe la un joc palpitan care continuă să crească." story_statistic_1a: "20,000,000+" story_statistic_1b: "de jucători" story_statistic_1c: "și-au început călătoria în lumea programării prin CodeCombat" story_statistic_2a: "Am tradus în peste 50 de limbi — asta a venit de la jucătorii noștri" story_statistic_2b: "190+ țări" story_statistic_3a: "Împreună, ei au scris" story_statistic_3b: "1 bilion de linii de cod care încă crește" story_statistic_3c: "în diferite limbaje de programare" story_long_way_1: "Cu toate că am parcurs un drum lung..." story_sketch_caption: "cu schița lui Nick care prezenta un joc de programare în acțiune." story_long_way_2: "încă mai avem multe de făcut până ne terminăm misiunea, de aceea..." jobs_title: "Vin-o să lucrezi cu noi și ajută la scrierea istoriei CodeCombat!" jobs_subtitle: """Nu vezi unde te-ai puta încadra dar ai dori să păstrăm legătura? Vezi lista \"Creează propria\".""" jobs_benefits: "Beneficiile angaților" jobs_benefit_4: "Vacanță nelimitată" jobs_benefit_5: "Suport pentru dezvoltare profesională și educație continuă – cărți gratuite și jocuri!" jobs_benefit_6: "Medical (gold), dental, oftamologic, navetist, 401K" jobs_benefit_7: "Birouri de lucru pentru toți" # jobs_benefit_9: "10-year option exercise window" # jobs_benefit_10: "Maternity leave: 12 weeks paid, next 6 @ 55% salary" # jobs_benefit_11: "Paternity leave: 12 weeks paid" # jobs_custom_title: "Create Your Own" jobs_custom_description: "ești un pasionat de CodeCombat dar nu vezi un job care să corespundă calificărilor tale? scrie-ne și arată-ne cum crezi tu că poți contribui la echipa noastră. Ne-ar face plăcere să auzim toate acestea!" jobs_custom_contact_1: "Trimite-ne o notă la" jobs_custom_contact_2: "cu prezentarea ta și poate vom lua legătura în viitor!" contact_title: "Presă & Contact" contact_subtitle: "Ai nevoie de mai multe informații? Ia legătura cu noi la" screenshots_title: "Capturi de ecran din joc" screenshots_hint: "(apasă să vezi în dimensiune maximă)" downloads_title: "Descarcă Download Assets & Information" about_codecombat: "Despre CodeCombat" logo: "Logo" screenshots: "Capturi de ecran" character_art: "Arta caracterului" download_all: "Descarcă tot" previous: "Anterior" location_title: "Suntem localizați în centrul SF:" teachers: licenses_needed: "Sunt necesare licențe" special_offer: special_offer: "Ofertă specială" project_based_title: "Cursuri bazate pe proiecte" project_based_description: "Cursuri de dezvoltare web și de jocuri cu posibilități de partajare a proiectelor finale." great_for_clubs_title: "Ideale pentru cluburi și grupuri școlare" great_for_clubs_description: "Profesorii pot cumpăra până la __maxQuantityStarterLicenses__ licențe de pornire." low_price_title: "Doar __starterLicensePrice__ de cursant" low_price_description: "Licențele de pornire sunt active pentru __starterLicenseLengthMonths__ de luni de la cumpărare." three_great_courses: "Trei cursuri deosebite sunt incluse în licența de pornire:" license_limit_description: "Profesorii pot cumpăra până la __maxQuantityStarterLicenses__ licențe de pornire. Ai cumpărat deja __quantityAlreadyPurchased__. Dacă dorești mai multe, contactează-ne la __supportEmail__. Licențele de pornire sunt valabile pentru __starterLicenseLengthMonths__ de luni." student_starter_license: "Licențe de pornire pentru cursanți" purchase_starter_licenses: "Cumpără licențe de pornire" purchase_starter_licenses_to_grant: "Cumpără licențe de pornire pentru a avea acces la __starterLicenseCourseList__" starter_licenses_can_be_used: "Licențele de pornire pot fi utilizate pentru asignarea de cursuri adiționale imediat după cumpărare." pay_now: "Plătește acum" we_accept_all_major_credit_cards: "Acceptăm marea majoritate a cardurilor de credit." cs2_description: "construite pe fundamentele obținute la cursul Introducere în informatică, cu accent pe instrucțiuni if, funcții, evenimete și altele." wd1_description: "introduce elemente de bază de HTML și CSS în timp ce pregătește abilitățile cursanților necesare pentru dezvoltarea propriei pagini web." gd1_description: "utilizează sintaxe cu care cursanții sunt deja familiarizați pentru a le arăta cum să construiască și să partajeze propriul nivel de joc." see_an_example_project: "vezi un exemplu de proiect" get_started_today: "Începe astăzi!" want_all_the_courses: "Vrei toate cursurile? Cere informații despre licențele complete." compare_license_types: "Compară licențele după tip:" cs: "Informatică" wd: "Dezvoltare web" wd1: "Dezvolare web 1" gd: "Dezvolatre de joc" gd1: "Dezvoltare de joc 1" maximum_students: "Număr maxim # de cursanți" unlimited: "Nelimitat" priority_support: "Suport prioritar" yes: "Da" price_per_student: "__price__ pe cursant" pricing: "Preț" free: "Gratuit" purchase: "Cumpără" courses_prefix: "Cursuri" courses_suffix: "" course_prefix: "Curs" course_suffix: "" teachers_quote: subtitle: "Învață mai multe despre CodeCombat cu un tur interactiv al produsului, al prețului și al implementării acestuia!" email_exists: "Există utilizator cu această adresă de email." phone_number: "Număr de telefon" phone_number_help: "Care este cel mai bun număr la care să te contactăm?" primary_role_label: "Rolul tău primar" role_default: "Alege rol" primary_role_default: "Selectează rol primar" purchaser_role_default: "Selectează rolul tău ca și cumpărător" tech_coordinator: "Coordonator tehnologic" advisor: "Specialist/Consilier de curiculă" principal: "Director" superintendent: "Administrator" parent: "Părinte" purchaser_role_label: "Rolul tău ca și cumpărător" influence_advocate: "Formator de opinii/Susținător" evaluate_recommend: "Evaluează/Recomandă" approve_funds: "Aprobare fonduri" no_purchaser_role: "Nici un rol în decizia de cumpărare" district_label: "județ" district_name: "Nume județ" district_na: "scrie N/A dacă nu se aplică" organization_label: "Școală" school_name: "Numele școlii" city: "Oraș" state: "Sat / Regiune" country: "Țară / Regiune" num_students_help: "Câți elevi vor utiliza CodeCombat?" num_students_default: "Selectează intervalul" education_level_label: "Nivelul de educație al elevilor" education_level_help: "Alege pe toate care se aplică." elementary_school: "Școala primară" high_school: "Liceu" please_explain: "(te rog explică)" middle_school: "Școala gimnazială" college_plus: "Facultate sau mai sus" referrer: "Cum ai auzit despre noi?" referrer_help: "De exemplu: de la un alt profesor, o conferință, elevi, Code.org etc." referrer_default: "Alege una" referrer_conference: "Conferință (ex. ISTE)" referrer_hoc: "Code.org/Hour of Code" referrer_teacher: "Un profesor" referrer_admin: "Un administrator" referrer_student: "Un student" referrer_pd: "Pregătire profesională/Grup de lucru" referrer_web: "Google" referrer_other: "Altele" anything_else: "Pentru ce clasă anticipezi că vei utiliza CodeCombat?" anything_else_helper: "" thanks_header: "Cerere primită!" thanks_sub_header: "Mulțumim de interesul arătat în utilizarea CodeCombat în școala ta." thanks_p: "Vă vom contacta curând! Dacă dorești să ne contacteză, poți ajunge la noi prin:" back_to_classes: "Înapoi la clase" finish_signup: "Contul tău de utilizator a fost creat:" finish_signup_p: "Creează un cont pentru a creea o clasă, adaugă elevii și monitorizează progresul acestora în timp ce aceștia învață informatică." signup_with: "Autentificare cu:" connect_with: "Connectare cu:" conversion_warning: "AVERIZARE: Contul tău curent este un <em>Cont de elev</em>. După ce transmiți acest formular, contul tău va fi transformat într-un cont de profesor." learn_more_modal: "Conturile de profesor din CodeCombat au posibilitatea de a monitoriza progresul elevilor, a aloca licențe și să administreze clase. Conturile de profesor nu pot fi parte dintr-o clasă - dacă sunteți deja parte dintr-o clasă cu acest cont, nu o veți mai putea accesa după ce îl transformați în cont de profesor." create_account: "Creează un cont de profesor" create_account_subtitle: "Obține acces la unelte specifice profesorilor pntru a utiliza CodeCombat în clasă. <strong>Creează o clasă</strong>, adaugă elevii și <strong>monitorizează progresul lor</strong>!" convert_account_title: "Transformă în cont de profesor" not: "Nu" full_name_required: "Numele și prenumele sunt obligatorii" versions: save_version_title: "Salvează noua versiune" new_major_version: "Versiune nouă majoră" submitting_patch: "Trimitere Patch..." cla_prefix: "Pentru a salva modificările mai intâi trebuie sa fiți de acord cu" cla_url: "CLA" cla_suffix: "." cla_agree: "SUNT DE ACORD" owner_approve: "Un proprietar va trebui să aprobe înainte ca modificările să devină vizibile." contact: contact_us: "Contact CodeCombat" welcome: "Folosiți acest formular pentru a ne trimite email. " forum_prefix: "Pentru orice altceva vă rugăm să încercați " forum_page: "forumul nostru" forum_suffix: " în schimb." faq_prefix: "Există și un" faq: "FAQ" subscribe_prefix: "Daca ai nevoie de ajutor ca să termini un nivel te rugăm să" subscribe: "cumperi un abonament CodeCombat" subscribe_suffix: "și vom fi bucuroși să te ajutăm cu codul." subscriber_support: "Din moment ce ești un abonat CodeCombat, adresa ta de email va primi sprijinul nostru prioritar." screenshot_included: "Screenshot-uri incluse." where_reply: "Unde ar trebui să răspundem?" send: "Trimite Feedback" account_settings: title: "Setări Cont" not_logged_in: "Loghează-te sau Creează un cont nou pentru a schimba setările." me_tab: "Eu" picture_tab: "Poză" delete_account_tab: "Șterge contul" wrong_email: "Email greșit" wrong_password: "<PASSWORD>" delete_this_account: "Ștergere permanetă a acestui cont" reset_progress_tab: "Resetare progres" reset_your_progress: "Șterge tot progresul și începe din nou" god_mode: "Mod Dumnezeu" emails_tab: "Email-uri" admin: "Admin" manage_subscription: "Apasă aici pentru a administra abonamentele." new_password: "<PASSWORD>" new_password_verify: "<PASSWORD>" type_in_email: "scrie adresa de email ca să confirmi ștergerea" type_in_email_progress: "scrie adresa de email pentru a confirma ștergerea progresului." type_in_password: "De asemenea, scrie și parola." email_subscriptions: "Subscripție email" email_subscriptions_none: "Nu ai subscripții email." email_announcements: "Anunțuri" email_announcements_description: "Primește email-uri cu ultimele știri despre CodeCombat." email_notifications: "Notificări" email_notifications_summary: "Control pentru notificări email personalizate, legate de activitatea CodeCombat." email_any_notes: "Orice notificări" email_any_notes_description: "Dezactivați pentru a opri toate email-urile de notificare a activității." email_news: "Noutăți" email_recruit_notes: "Oportunități de angajare" email_recruit_notes_description: "Dacă joci foarte bine, este posibil sa te contactăm pentru obținerea unui loc (mai bun) de muncă." # contributor_emails: "Contributor Class Emails" contribute_prefix: "Căutăm oameni să se alăture distracției! Intră pe " contribute_page: "pagina de contribuție" contribute_suffix: " pentru a afla mai multe." email_toggle: "Alege tot" error_saving: "Salvare erori" saved: "Modificări salvate" password_mismatch: "<PASSWORD>." password_repeat: "Te <PASSWORD>m <PASSWORD> repeți par<PASSWORD>." keyboard_shortcuts: keyboard_shortcuts: "Scurtături tastatură" space: "Space" enter: "Enter" press_enter: "apasă enter" escape: "Escape" shift: "Shift" run_code: "Rulează codul." run_real_time: "Rulează în timp real." # continue_script: "Continue past current script." skip_scripts: "Treci peste toate script-urile ce pot fi sărite." toggle_playback: "Comută play/pause." scrub_playback: "Mergi înainte și înapoi în timp." single_scrub_playback: "Mergi înainte și înapoi în timp cu un singur cadru." scrub_execution: "Mergi prin lista curentă de vrăji executate." toggle_debug: "Comută afișaj depanare." toggle_grid: "Comută afișaj grilă." toggle_pathfinding: "Comută afișaj pathfinding." beautify: "Înfrumusețează codul standardizând formatarea lui." maximize_editor: "Mărește/Minimizează editorul." cinematic: click_anywhere_continue: "apasă oriunde pentru a continua" community: main_title: "Comunitatea CodeCombat" introduction: "Vezi metode prin care poți să te implici și tu mai jos și decide să alegi ce ți se pare cel mai distractiv. De abia așteptăm să lucrăm împreună!" level_editor_prefix: "Folosește CodeCombat" level_editor_suffix: "Pentru a crea și a edita niveluri. Utilizatorii au creat niveluri pentru clasele lor, prieteni, hackathonuri, studenți și rude. Dacă crearea unui nivel nou ți se pare intimidant poți să modifici un nivel creat de noi!" thang_editor_prefix: "Numim unitățile din joc 'thangs'. Folosește" thang_editor_suffix: "pentru a modifica ilustrațile sursă CodeCombat. Permitele unităților să arunce proiectile, schimbă direcția unei animații, schimbă viața unei unități, sau încarcă propiile sprite-uri vectoriale." article_editor_prefix: "Vezi o greșeală în documentația noastă? Vrei să documentezi instrucțiuni pentru propiile creații? Vezi" article_editor_suffix: "și ajută jucătorii CodeCombat să obțină căt mai multe din timpul lor de joc." find_us: "Ne găsești pe aceste site-uri" social_github: "Vezi tot codul nostru pe GitHub" social_blog: "Citește blogul CodeCombat pe Sett" # {change} social_discource: "Alătură-te discuțiilor pe forumul Discourse" social_facebook: "Lasă un Like pentru CodeCombat pe facebook" social_twitter: "Urmărește CodeCombat pe Twitter" social_slack: "Vorbește cu noi pe canalul public de Slack CodeCombat" contribute_to_the_project: "Contribuie la proiect" clans: title: "Alătură-te clanurilor CodeCombat - Învață să scrii cod în Python, Javascript și HTML" clan_title: "__clan__ - Alătură-te clanurilor CodeCombat și învață să scrii cod" meta_description: "Alătură-te unui clan pentru a-ți construi propria comunitate de programatori. Joacă nivele multi-jucător în arenă și urcă nivelul eroului tău și al abilităților tale de programare." clan: "Clan" clans: "Clanuri" new_name: "<NAME> nou de clan" new_description: "Descrierea clanului nou" make_private: "Fă clanul privat" subs_only: "numai abonați" create_clan: "Creează un clan nou" private_preview: "Previzualizare" private_clans: "Clanuri private" public_clans: "Clanuri Publice" my_clans: "Clanurile mele" clan_name: "<NAME>umele Cl<NAME>ului" name: "<NAME>" chieftain: "Căpetenie" edit_clan_name: "Editează numele clanului" edit_clan_description: "Editează descrierea clanului" edit_name: "editează nume" edit_description: "editează descriere" private: "(privat)" summary: "Sumar" average_level: "Nivel mediu" average_achievements: "realizare medie" delete_clan: "Șterge Clan" leave_clan: "Pleacă din Clan" join_clan: "Intră în Clan" invite_1: "Invitație:" invite_2: "*Invită jucători în acest clan trimițând acest link." members: "Mem<NAME>" progress: "Progres" not_started_1: "neînceput" started_1: "început" complete_1: "complet" exp_levels: "Extinde niveluri" rem_hero: "Șterge Eroul" status: "Stare" complete_2: "Complet" started_2: "Început" not_started_2: "Neînceput" view_solution: "Apasă pentru a vedea soluția." view_attempt: "Apasă pentru a vedea încercarea." latest_achievement: "Ultimile realizări" playtime: "Timp de joc" last_played: "Ultima oară când ai jucat" leagues_explanation: "Joacă într-o ligă împotriva altor membri de clan în aceste instanțe de arenă multi-jucător." track_concepts1: "Conceptele traseului" track_concepts2a: "învățat de fiecare elev" track_concepts2b: "învățat de fiecare membru" track_concepts3a: "Urmărește nivelurile completate de fiecare elev" track_concepts3b: "Urmărește nivelurile completate de fiecare membru" track_concepts4a: "Vezi soluțiile elevilor" # The text is too fragmented and it does not have sense in Romanian. I added track_concepts5 to this track_concepts4b: "Vezi soluțiile membrilor" # I added track_concepts5 to this track_concepts5: "" track_concepts6a: "Sortează elevii după nume sau progres" track_concepts6b: "Sortează membrii după nume sau progres" track_concepts7: "Necesită invitație" track_concepts8: "pentru a te alătura" private_require_sub: "Clanurile private necesită un abonament pentru a le creea sau a te alătura unuia." courses: create_new_class: "Creează o nouă clasă" hoc_blurb1: "Încearcă" hoc_blurb2: "scrie cod, Joacă, Partajează" hoc_blurb3: "ca și activități! Construiește patru mini-jocuri diferite pentru a învăța bazele dezvoltării jocurilor, apoi creează unul singur!" solutions_require_licenses: "Soluțiile nivelurilor sunt disponibile profesorilor care au licențe." unnamed_class: "Clasă fără nume" edit_settings1: "Modifică setările clasei" add_students: "Adaugă elevi" stats: "Statistici" student_email_invite_blurb: "Elevii tăi pot utiliza codul de clasă <strong>__classCode__</strong> când creează un cont de elevt, nu este necesară o adresă email." total_students: "Total elevi:" average_time: "Timpul mediu de joc pe nivel:" total_time: "Timpul total de joc:" average_levels: "Media nivelurilor terminate:" total_levels: "Total niveluri terminate:" students: "Elevi" concepts: "Concepte" play_time: "Timp de joc:" completed: "Terminate:" enter_emails: "Separați fiecare adresă de email printr-o linie nouă sau virgulă" send_invites: "Invită elevi" number_programming_students: "Număr de elevi care programează" number_total_students: "Total elevi în școală/Județ" enroll: "Înscriere" enroll_paid: "Înscrie elevi la cursuri plătite" get_enrollments: "Cumpără mai multe licențe" change_language: "Schimbă limba cursului" keep_using: "Continuă să utilizezi" switch_to: "Schimbă" greetings: "Salutări!" back_classrooms: "Înapoi la clasa mea" back_classroom: "Înapoi la clasă" back_courses: "Înapoi la cursurile mele" edit_details: "Modifică detaliile clasei" purchase_enrollments: "Cumpără licențe pentru elevi" remove_student: "șterge elevi" assign: "Alocă" to_assign: "pentru a aloca la cursurile plătite." student: "<NAME>" teacher: "<NAME>" arena: "Arenă" available_levels: "Niveluri disponibile" started: "începute" complete: "terminate" practice: "încearcă" required: "obligatorii" welcome_to_courses: "Aventurier, bine ai venit la CodeCombat!" ready_to_play: "Ești gata să joci?" start_new_game: "Începe un joc nou" play_now_learn_header: "Joacă acum ca să înveți" play_now_learn_1: "sintaxa de bază utilizată la controlarea personajului" play_now_learn_2: "bucle while pentru a rezolva puzzle-uri dificile" play_now_learn_3: "șiruri de caractere & variabile pentru a personaliza acțiunile" play_now_learn_4: "cum să înfrângi un căpcăun (o abilitate importantă pentru viață!)" my_classes: "Clase curente" class_added: "Clasă adăugată cu succes!" view_map: "vezi harta" view_videos: "vezi filme" view_project_gallery: "vezi proiectele colegilor" join_class: "Alătură-te unei clase" join_class_2: "Alătură-te clasei" ask_teacher_for_code: "Întreabă profesorul dacă ai un cod de clasă CodeCombat! Dacă ai, scrie codul aici:" enter_c_code: "<scrie codul clasei>" join: "Alătură-te" joining: "intrare în clasă" course_complete: "Curs terminat" play_arena: "Joacă în arenă" view_project: "Vezi proiect" start: "Start" last_level: "Ultimul nivel jucat" not_you: "Nu ești tu?" continue_playing: "Continuă să joci" option1_header: "Invită elevi prin email" remove_student1: "Șterge elev" are_you_sure: "Ești sigur că vrei să ștergi acest elev din clasă?" remove_description1: "Elevul va pierde accesul la această clasă și la celelalte clase alocate. Progresul și jocurile făcute NU se pierd, iar elevul va putea fi adăugat la loc în clasă oricând." remove_description2: "Licențele plătite și activate nu pot fi returnate." license_will_revoke: "Licența acestui elev va fi revocată și va deveni disponibilă pentru alocarea unui alt elev." keep_student: "păstrează elev" removing_user: "Ștergere elev" subtitle: "Analizează prezentarea cursului și nivelurilor" # Flat style redesign select_language: "Alege limba" select_level: "Alege nivel" play_level: "Joacă nivel" concepts_covered: "Concepte acoperite" view_guide_online: "Prezentare nivel și soluții" lesson_slides: "Fișe lecție" grants_lifetime_access: "Permite accesul la toate cursurile." enrollment_credits_available: "licențe disponibile:" language_select: "Alege o limbă" # ClassroomSettingsModal language_cannot_change: "Limba nu mai poate fi schimbată după ce elevii se alătură unei clase." avg_student_exp_label: "Experiența de programare medie a elevului" avg_student_exp_desc: "Acest lucru ne ajută să înțelegem cum să stabilim mai bine ritmul cursului." avg_student_exp_select: "Alege opțiunea cea mai bună" avg_student_exp_none: "Fără experiență - puțină sau fără experiență" avg_student_exp_beginner: "Începător - oarecare expunere sau programare cu blocuri" avg_student_exp_intermediate: "Intermediar - oarecare experință cu scrierea de cod" avg_student_exp_advanced: "Avansat - experineță amplă cu scrierea de cod" avg_student_exp_varied: "Nivele variate de experiență" student_age_range_label: "Interval de vârstă al alevilor" student_age_range_younger: "Mai mici de 6" student_age_range_older: "Mai mari de 18" student_age_range_to: "la" estimated_class_dates_label: "Datele estimate a claselor" estimated_class_frequency_label: "Frecvența estimată a claselor" classes_per_week: "clase pe săptămână" minutes_per_class: "minute pe clasă" create_class: "Creează o clasă" class_name: "Nume clasă" teacher_account_restricted: "Contul tău este un cont de utilizator și nu poate accesa conținut specific elevilor." account_restricted: "Un cont de elev este necesar pentru a accesa această pagină." update_account_login_title: "Autentifică-te pentru a schimba contul" update_account_title: "Contul tău necesită atenție!" update_account_blurb: "Înainte de a accesa clasele, alege cum vei dori să utilizezi acest cont." update_account_current_type: "Tipul contului curent:" update_account_account_email: "Email cont/Utilizator:" update_account_am_teacher: "Sunt un profesor" update_account_keep_access: "Mențien accesul la clasele pe care le-am creat" update_account_teachers_can: "Conturile de profesor pot să:" update_account_teachers_can1: "Creeze/administreze/adauge clase" update_account_teachers_can2: "Aloce/înscrie elevi la cursuri" update_account_teachers_can3: "Deblocheze toate nivelurile de curs pentru încercări" update_account_teachers_can4: "Aceseze elemente noi specifice profesorulu atunci când le lansăm" update_account_teachers_warning: "Atenție: Vei fi șters din toate clasele la care te-ai alăturat anterior și nu vei mai putea juca ca și elev." update_account_remain_teacher: "Rămâi profesor" update_account_update_teacher: "Transformă în profesor" update_account_am_student: "Sunt elev" update_account_remove_access: "Șterge accesul la clasele pe care le-am creat" update_account_students_can: "Conturile de elev pot să:" update_account_students_can1: "Se alăture claselor" update_account_students_can2: "Joace printre cursuri ca elev și să își urmărească progresul" update_account_students_can3: "Concureze împotriva colegilor în arenă" update_account_students_can4: "Aceseze elemente noi specifice elevilor atunci când le lansăm" update_account_students_warning: "Atenție: Nu vei putea administra nici o clasă pe care ai creat-o anterior sau să creezi noi clase." unsubscribe_warning: "Atenție: Vei fi dezabonat de la abonamentul lunar." update_account_remain_student: "Rămâi elev" update_account_update_student: "Transformă în elev" need_a_class_code: "Vei avea nevoie de un cod de clasă pentru a te alătura unei clase:" update_account_not_sure: "Nu ști sigur ce să alegi? Email" update_account_confirm_update_student: "Ești sigur că vrei să transformi contul în unul de elev?" update_account_confirm_update_student2: "Nu vei putea administra nici o clasă pe care ai creat-o anterior sau să creezi noi clase. Clasele create anterior vor fi șterse din CodeCombat și nu mai pot fi recuperate." instructor: "Instructor: " youve_been_invited_1: "AI fost invitat să te alături " youve_been_invited_2: ", unde vei învăța " youve_been_invited_3: " cu colegii de clasă în CodeCombat." by_joining_1: "Dacă te alături " by_joining_2: "vei putea să îți resetezi parola dacă o vei pierde sau uita. Poți de asemenea să îți verifici adresa de email ca să îți resetei parola singur!" sent_verification: "Ți-am trimis un email de verificare la:" you_can_edit: "Poți să modifici adresa de email în " account_settings: "Setări cont" select_your_hero: "Alege eroul" select_your_hero_description: "Poți oricând să schimbi eroul din pagina de Cursuri apăsând \"Schimbă erou\"" select_this_hero: "Alege acest erou" current_hero: "Erou curent:" current_hero_female: "Erou curent:" web_dev_language_transition: "Toate clasele programează în HTML / Javascript la acest curs. Clasele care au utilizat Python vor începe cu niveluri suplimentare de Javascript pentru o tranziție mai ușoară. Clasele care deja utilizează Javascript vor sări peste nivelurile introductive." course_membership_required_to_play: "Trebuie să te alături unui curs pentru a juca acest nivel." license_required_to_play: "Cere profesorului tău să îți asocieze o licență pentru a putea continua să joci CodeCombat!" update_old_classroom: "Un nou an școlar, noi niveluri!" update_old_classroom_detail: "Pentru a fi sigur că ai acces la cele mai moi niveluri, creează o nouă clasă pentru acest semestru apăsând Creează clasă nouă în" teacher_dashboard: "Panou de lucru profesor" update_old_classroom_detail_2: "și dând elevilor noul cod de clasă care apare." view_assessments: "Vezi evaluări" view_challenges: "vezi niveluri tip provocare" challenge: "Provocare:" challenge_level: "Nivel tip provocare:" status: "Stare:" assessments: "Evaluări" challenges: "Provocări" level_name: "Nume nivel:" keep_trying: "Continuă să încerci" start_challenge: "Start provocare" locked: "Blocat" concepts_used: "Concepte utilizate:" show_change_log: "Arată modificările acestor niveluri de curs" hide_change_log: "Ascunde schimbările acestor nivele de curs" concept_videos: "Filme despre concept" concept: "Concept:" basic_syntax: "Sintaxa de bază" while_loops: "Bucle while" variables: "Variabile" basic_syntax_desc: "Sintaxa este despre cum să scrii cod. Așa cum sunt citirea și gramatica importanre în scrierea poveștilor și a esurilor, sintaxa este importantă când scriem cod. Oamenii sunt foarte buni în a înțelege ce înseamnă ceva, chiar și atunci când ceva nu este foarte corect, însă calculatoarele nu sunt atât de inteligente și au nevoie ca tu să scrii foarte foarte precis." while_loops_desc: "O buclă este o modalitate de a repeta acțiuni într-un program. Le poți utiliza pentru a nu scrie același cod de mai multe ori (repetitiv), iar atunci când nu ști de câte ori o acțiune se repetă pentru a îndeplini o sarcină." variables_desc: "Lucrul cu variabilele este ca și organizarea lucrurilor în cutii. Dăi unei cutii un nume, de exemplu \"Rechizite școlare\" și apoi vei pune în ea diverse lucruri. Conținutul exact al cutiei se poate schimba de-a lungul timpului, însă tot mereu ce este înăuntru se va numi \"Rechizite școlare\". În programare, variabilele sunt simboluri utilizate pentru a păstra date care se vor schimba pe timpul programului. Variabilele pot păstra o varietate de tipuri de date, inclusiv numere și șiruri de caractere." locked_videos_desc: "Continuă să joci pentru a debloca filmul conceptului __concept_name__." unlocked_videos_desc: "Examinează filmul conceptului __concept_name__ ." video_shown_before: "afișat înainte de __level__" link_google_classroom: "Conectare cu Google Classroom" select_your_classroom: "Alege clasa" no_classrooms_found: "Nu s-a găsit nici o clasă" create_classroom_manually: "Creează clasa manual" classes: "Clase" certificate_btn_print: "Tipărire" certificate_btn_toggle: "Schimbare" ask_next_course: "Vrei să joci mai mult? Întreabă profesorul pentru a accesa cursul următor." set_start_locked_level: "Nivelurile blocate încep la " no_level_limit: "-- (nici un nivel blocat)" ask_teacher_to_unlock: "Întreabă profesorul pentru deblocare" ask_teacher_to_unlock_instructions: "Pentru a juca nivelul următor, roagă profesorul să îl deblocheze din ecranul lor Progres curs" play_next_level: "Joacă următorul nivel" play_tournament: "Joacă în turneu" levels_completed: "Niveluri terminate: __count__" ai_league_team_rankings: "Clasamentul echipelor din Liga IA" view_standings: "Vezi clasările" view_winners: "Vezi câștigătorii classroom_announcement: "Anunțurile clasei" project_gallery: no_projects_published: "Fi primul care publică un proiect în acest curs!" view_project: "Vezi proiect" edit_project: "Modifică proiect" teacher: assigning_course: "Alocă curs" back_to_top: "Înapoi sus" click_student_code: "Apasă pe oprice nivel de mai jos, început sau terminat de un elev, pentru a vedea codul scris." code: "Codul lui __name__" complete_solution: "Soluția completă" course_not_started: "Elevul nu a început încă acest curs." hoc_happy_ed_week: "Săptămâna informaticii fericită!" hoc_blurb1: "Află despre activități gratuite de" hoc_blurb2: "scriere a codului, Joc, Partajare," hoc_blurb3: " descarcă un nou plan de lecție și spune-le elevilor să se autentifice pentru a se juca!" hoc_button_text: "Vezi activitate" no_code_yet: "Elevul nu a scis încă nici un cod pentru acest nivel." open_ended_level: "Nivel deschis-terminat" partial_solution: "Soluție parțială" capstone_solution: "Soluția cea mai bună" removing_course: "Șterge curs" solution_arena_blurb: "Elevii sunt încurajați să rezolve nivelurile din arenă în mod creativ. Soluția furnizată mai jos îndeplinește cerințele acestui nivel din arenă." solution_challenge_blurb: "Elevii sunt încurajați să rezolve nivelurile tip provocare deschise-terminate în mod creativ. O soluție posibilă este afișată mai jos." solution_project_blurb: "Elevii sunt încurajați să construiască proiecte creative în acest nivel. Vă rog să urmăriți liniile directoare din curiculă din Zona de resurse pentru informații despre cum să evaluați aceste proiecte." students_code_blurb: "O soluție corectă pentru fiecare nivel este furnizată acolo unde este cazul. În unele cazuri, este posibil ca un elev să rezoove un nivel utilizând alte linii de cod. Soluțiile nu sunt afișate pentru nivelurile pe care elevii nu le-au început." course_solution: "Soluție curs" level_overview_solutions: "Prezentare nivel și soluții" no_student_assigned: "Nici un elev nu este alocat acestui curs." paren_new: "(nou)" student_code: "Cod student pentru __name__" teacher_dashboard: "Panou de lucru profesor" # Navbar my_classes: "Clasele mele" courses: "Ghiduri curs" enrollments: "Licențe elevi" resources: "Resurse" help: "Ajutor" language: "Limba" edit_class_settings: "modifică setările clasei" access_restricted: "Actualizare cont necesară" teacher_account_required: "Un cont de profesor este necesar pentru a accesa acest conținut." create_teacher_account: "Creează cont profesor" what_is_a_teacher_account: "Ce este un cond de profesor?" teacher_account_explanation: "Un cont de profesor CodeCombat îți permite să creezi clase, să monitorizezi progresul elevilor de-a lungul cursurilor, să administrezi licențele și să accesezi resurse din curicula pe care vrei să o construiești." current_classes: "Clase curente" archived_classes: "Clase arhivate" archived_classes_blurb: "Clasele pot fi arhivate pentru referințe viitoare. Dezarhivează o clasă pentru a o putea vedea în lista de clase curente din nou." view_class: "vezi clasă" view_ai_league_team: "Vezi echipa din liga IA" archive_class: "arhivează clasă" unarchive_class: "dezarhivează clasă" unarchive_this_class: "Dezarhivează această clasă" no_students_yet: "Această clasă nu are încă elevi." no_students_yet_view_class: "Vezi clasa pentru a adăuga elevi." try_refreshing: "(Ar putea fi nevoie să reîncarci pagina)" create_new_class: "Creează o nouă clasă" class_overview: "Vezi pagina clasei" # View Class page avg_playtime: "Timpul mediu al nivelului" total_playtime: "Tmpul de joc total" avg_completed: "Numărul mediu de niveluri teminate" total_completed: "Total niveluri terminate" created: "Create" concepts_covered: "Concepte acoperite" earliest_incomplete: "Primul nivel necompletat" latest_complete: "Ultimul nivel completat" enroll_student: "Înscrie elevi" apply_license: "Adaugă licență" revoke_license: "Înlătură licență" revoke_licenses: "Înlătură toate licențele" course_progress: "Progresul cursului" not_applicable: "N/A" edit: "modifică" edit_2: "Modifică" remove: "șterge" latest_completed: "Ultimul terminat:" sort_by: "Sortează după" progress: "Progres" concepts_used: "Concepte utilizate de elev:" concept_checked: "Concepte verificate:" completed: "Terminat" practice: "Practică" started: "Început" no_progress: "Fără progres" not_required: "Nu este obligatoriu" view_student_code: "Apasă să vezi codul de elev" select_course: "Alege cursul dorit" progress_color_key: "Codul de culoare pentru propgres:" level_in_progress: "Nivel în progres" level_not_started: "Nivel neînceput" project_or_arena: "Proiect sau Arenă" students_not_assigned: "Elevi care nu au fost alocați la {{courseName}}" course_overview: "Prezentare curs" copy_class_code: "Copiază codul clasei" class_code_blurb: "Elevii pot să se alăture clasei utilizând acest cod de clasă. Nu este necesară o adresă de email când creezi un cont de elev cu acest cod de clasă." copy_class_url: "Copiază URL-ul clasei" class_join_url_blurb: "Poți să publici această adresă unică URL pe o pagină de web." add_students_manually: "Invită elevii prin email" bulk_assign: "Alege curs" assigned_msg_1: "{{numberAssigned}} studenți au fost alocați cursului {{courseName}}." assigned_msg_2: "{{numberEnrolled}} licențe au fost aplicate." assigned_msg_3: "Mai ai {{remainingSpots}} licențe disponibile." assign_course: "Alocă curs" removed_course_msg: "{{numberRemoved}} elevi au fost șterși de la cursul {{courseName}}." remove_course: "Șterge curs" not_assigned_msg_1: "Nu poți adăuga elevi la o instanță de curs până când ei nu sunt adăugați unui abonament care conține acest curs" not_assigned_modal_title: "Cursurile nu au fost alocate" not_assigned_modal_starter_body_1: "Acest curs necesită o licență de tip Starter. Nu ai suficiente licențe Starter disponibile pentru a le aloca acestui curs pentru __selected__ de elevi selectați." not_assigned_modal_starter_body_2: "Cumpără licențe Starter pentru a permite accesul la acest curs." not_assigned_modal_full_body_1: "Acest curs necesită licență completă. Nu aveți suficiente licențe complete disponibile pentru a le aloca acestui curs pentru __selected__ de elevi selectați." not_assigned_modal_full_body_2: "Mai aveți doar __numFullLicensesAvailable__ de licențe complete disponibile (__numStudentsWithoutFullLicenses__ elevi nu au o licență completă alocată)." not_assigned_modal_full_body_3: "Te rog să alegi mai puțini elevi, sau contactează-ne la adresa __supportEmail__ pentru asistență." assigned: "Alocate" enroll_selected_students: "Înscrie elevii selectați" no_students_selected: "Nici un student nu este selectat." show_students_from: "Arată elevii din" # Enroll students modal apply_licenses_to_the_following_students: "Alocă licențe acestor elevi" select_license_type: "Selectează tipul de licență de aplicat" students_have_licenses: "Acești elevi au deja licențe alocate:" all_students: "Toți elevii" apply_licenses: "Alocă licențele" not_enough_enrollments: "Licențe disponibile insuficiente." enrollments_blurb: "Elevii trebuie să aibă o licență pentru a accesa conținutul după primul curs." how_to_apply_licenses: "Cum să aloci licențe" export_student_progress: "Exportă progresul elevilor (CSV)" send_email_to: "Trimite email de recuperare parolă la:" email_sent: "Email trimis" send_recovery_email: "Trimite email de recuperare" enter_new_password_below: "Introdu parola mai jos:" change_password: "<PASSWORD>" changed: "Schimbată" available_credits: "Licențe disponibile" pending_credits: "Licențe în așteptare" empty_credits: "Licențe epuizate" license_remaining: "licență rămasă" licenses_remaining: "licențe rămase" student_enrollment_history: "Istoricul înscrierilor elevilor" enrollment_explanation_1: "" # the definite article in Ro is placed at the end of the substantive enrollment_explanation_2: "Istoricul înscrierilor elevilor" enrollment_explanation_3: "afișează numărul total de elevi unici care au fost alocați de toți profesorii în toate clasele adăugate în panoul de lucru. Acesta include elevii atât din clasele arhivate cât și nearhivate dintr-o clasă creată între 1 iulie - 30 iunie din respectivul an școlar." enrollment_explanation_4: "Amintește-ți" enrollment_explanation_5: "clasele pot fi arhivate și licențele pot fi reutilizate de-a lungul anului școlar, ceea ce permite administratorilor să înțeleagă câți elevi au participat per ansamblu de fapt în program." one_license_used: "1 din __totalLicenses__ licențe au fost utilizate" num_licenses_used: "__numLicensesUsed__ out of __totalLicenses__ licențe au fost utilizate" starter_licenses: "licențe tip starter" start_date: "data început:" end_date: "data sfărșit:" get_enrollments_blurb: " Te vom ajuta să construiești o soluție care îndeplinește cerințele clasei tale, școlii sau districtului." see_also_our: "Vezi de asemenea" for_more_funding_resources: "pentru informații cu privire la accesarea surselor de finanțare CARES Act cum sunt ESSER și GEER." how_to_apply_licenses_blurb_1: "Când un profesor alocă un curs unui elev pentru prima dată, vom aplica o licență în mod automat. Utilizează lista de alocare în grup din clasa ta pentru a aloca un curs mai multor elevi selectați:" how_to_apply_licenses_blurb_2: "Pot să aplic o licență fără a aloca un curs?" how_to_apply_licenses_blurb_3: "Da — mergi la tabul Stare licențe din clasa ta și apasă \"Aplică licență\" pentru orice elev care nu are încă o licență activă." request_sent: "Cerere transmisă!" assessments: "Evaluări" license_status: "Stare licență" status_expired: "Expiră în {{date}}" status_not_enrolled: "Nu este înrolat" status_enrolled: "Expiră în {{date}}" select_all: "Selectează tot" project: "Proiect" project_gallery: "Galerie proiecte" view_project: "Vezi proiect" unpublished: "(nepublicat)" view_arena_ladder: "Vezi clasament arenă" resource_hub: "Zonă de resurse" pacing_guides: "Ghiduri parcurgere Clasa-în-cutie" pacing_guides_desc: "Învață cum să încorporezi toate resursele CodeCombat în planificarea anului tău școlar!" pacing_guides_elem: "Ghid parcurgere școala primară" pacing_guides_middle: "Ghid parcurgere școala generală" pacing_guides_high: "Ghid parcurgere liceu" getting_started: "Noțiuni de bază" educator_faq: "Întrebări instructori" educator_faq_desc: "Întrebări frecvente despre utilizarea CodeCombat în clasă sau în școală." teacher_getting_started: "Ghid de noțiuni generale pentru profesor" teacher_getting_started_desc: "Nou la CodeCombat? Descarcă acest ghid de noțiuni generale pentru profesori pentru a-ți creea contul, a creea prima ta clasă și a invita elevii la primul curs." student_getting_started: "Ghid rapid de pornire pentru elevi" student_getting_started_desc: "Poți distribui acest ghid elevilor tăi înainte de începerea CodeCombat astfel încât aceștia să se familiarizeze cu editorul de cod. Acest ghid poate fi utilizat atât pentru clasele de Python cât și cele de Javascript." standardized_curricula: "Curicula standardizată" ap_cs_principles: "Principiile AP ale informaticii" ap_cs_principles_desc: "Principiile AP ale informaticii le face elevilor o introducere extinsă asupra puterii, impactului și posibilităților informaticii. Cursul pune accent pe rezolvarea problemelor și gândirea algoritmică și logică în timp ce aceștia învață bazele programării." cs1: "Introducere în informatică" cs2: "Informatică 2" cs3: "Informatică 3" cs4: "Informatică 4" cs5: "Informatică 5" cs1_syntax_python: "Curs 1 - Ghid sinatxă Python" cs1_syntax_python_desc: "Foaie rezumat cu referințe către cele mai uzuale sintaxe Python pe care elevii le vor învăța în lecția Introducere în informatică." cs1_syntax_javascript: "Curs 1 - Ghid sinatxă Javascript" cs1_syntax_javascript_desc: "Foaie rezumat cu referințe către cele mai uzuale sintaxe Javascript syntax pe care elevii le vor învăța în lecția Introducere în informatică." coming_soon: "În curând mai multe ghiduri!" engineering_cycle_worksheet: "Foaie rezumat despre ciclul tehnologic" engineering_cycle_worksheet_desc: "Utilizează această foaie de lucru pentru a-i învăța pe elevi bazele ciclului tehnologic: Evaluare, Proiectare, Implementare și Depanare. Fă referire la fișa cu exemplu complet ca și ghid." engineering_cycle_worksheet_link: "Vezi exemplu" progress_journal: "Jurnal de progres" progress_journal_desc: "Încurajează elevii să-și urmărească progresul cu ajutorul jurnalului de progres." cs1_curriculum: "Introducere în informatică - Ghid de curiculă" cs1_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 1." arenas_curriculum: "Niveluri arenă - Ghid profesor" arenas_curriculum_desc: "Instrucțiuni despre rularea arenelor multi-jucător Wakka Maul, Cross Bones și Power Peak în clasă." assessments_curriculum: "Niveluri de evaluare - Ghid profesor" assessments_curriculum_desc: "Învață cum să utilizezi Nivelurile de provocare și nivelurile de provocare combo pentru a evalua rezultatele învățării." cs2_curriculum: "Informatică 2 - Ghid de curiculă" cs2_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 2." cs3_curriculum: "Informatică 3 - Ghid de curiculă" cs3_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 3." cs4_curriculum: "Informatică 4 - Ghid de curiculă" cs4_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 4." cs5_curriculum_js: "Informatică 5 - Ghid de curiculă (Javascript)" cs5_curriculum_desc_js: "Scop și secvențiere, planuri de lecții, activități și altele pentru clasele Cursului 5 de Javascript." cs5_curriculum_py: "Informatică 5 - Ghid de curiculă (Python)" cs5_curriculum_desc_py: "Scop și secvențiere, planuri de lecții, activități și altele pentru clasele Cursului 5 de Python." cs1_pairprogramming: "Activitate de programare pe echipe" cs1_pairprogramming_desc: "introduce elevii într-un exercițiu de programare pe echipe care îi va ajuta să fie mai buni la ascultat și la comunicat." gd1: "Dezvoltare joc 1" gd1_guide: "Dezvoltare joc 1 - Ghid de proiect" gd1_guide_desc: "Utilizează acest proiect să ghidezi elevii în crearea primului lor proiect de dezvoltare joc partajat pe parcursul a 5 zile." gd1_rubric: "Dezvoltare joc 1 - Fișă proiect" gd1_rubric_desc: "Utilizează această fișă să evaluezi proiectele elevilor la sfârșitul proiectului Dezvoltare joc 1." gd2: "Dezvoltare joc 2" gd2_curriculum: "Dezvoltare joc 2 - Ghid de curiculă" gd2_curriculum_desc: "Planuri de lecție pentru Dezvoltare joc 2." gd3: "Dezvoltare joc 3" gd3_curriculum: "Dezvoltare joc 3 - Ghid de curiculă" gd3_curriculum_desc: "Planuri de lecție pentru Dezvoltare joc 3." wd1: "Dezvoltare web 1" wd1_curriculum: "Dezvoltare web 1 - Ghid de curiculă" wd1_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul Dezvoltare web 1." wd1_headlines: "Activitate despre titluri și antete" wd1_headlines_example: "Vezi soluțiile date ca exemplu" wd1_headlines_desc: "De ce sunt marcajele de paragraf și antetele importante? Utilizează această activitate să arăți cât de ușor sunt de citit paginile cu antete bine alese. Sunt mai multe soluții corecte pentru acesta!" wd1_html_syntax: "Ghid de sintaxă HTML" wd1_html_syntax_desc: "Referință de o pagină pentru stilurile HTML pe care elevii le vor învăța în Dezvoltare web 1." wd1_css_syntax: "Ghid sinatxă CSS" wd1_css_syntax_desc: "Referință de o pagină pentru sintaxa stilurilor CSS pe care elevii le vor învăța în Dezvoltare web 1." wd2: "Dezvolatre web 2" wd2_jquery_syntax: "Ghid de sintaxă pentru funcțiile jQuery" wd2_jquery_syntax_desc: "Referință de o pagină pentru sintaxa funcțiilor jQuery pe care elevii le vor învăța în Dezvoltare web 2." wd2_quizlet_worksheet: "Fișă de lucru chestionar" wd2_quizlet_worksheet_instructions: "Vezi instrucțiuni și exemple" wd2_quizlet_worksheet_desc: "Înainte ca elevii să își construiască proiectul cu chestionarul despre personalitate de la sfârșitul cursului Dezvoltare web 2, ar trebui să își planifice mai întâi întrebările, rezultate și răspunsuri utilizând această fișă de lucru. Profesorii pot să distribuie aceste instrucțiuni și exemple ca elevii să poată face referire la acestea." student_overview: "Prezentare generală" student_details: "Detalii elev" student_name: "<NAME>" no_name: "Nu este furnizat un nume." no_username: "Nu este furnizat un nume de utilizator." no_email: "Elevul nu are adresă de email setată." student_profile: "Profil elev" playtime_detail: "Detalii despre timpul de joc" student_completed: "Terminate de elev" student_in_progress: "Elev în progress" class_average: "Media clasei" not_assigned: "nu au fost alocate următoarele cursuri" playtime_axis: "Timp de joc în secunde" levels_axis: "Niveluri în" student_state: "Cum se" student_state_2: "descurcă?" student_good: "se descurcă bine în" student_good_detail: "Acest elev ține pasul cu timpul mediu de terminare a nivelului de către clasă." student_warn: "poate avea nevoie de ajutor în" student_warn_detail: "Timpul mediu de terminare a acestui nivel pentru acest elev sugerează că ar putea avea nevoie de ajutor cu conceptele noi care au fost introduse în acest curs." student_great: "se descurcă foarte bine în" student_great_detail: "Acest elev ar putea fi un bun candidat să îi ajute pe ceilalți elevi în acest curs, pe baza timpilor medii de terminare a nivelului." full_license: "Licență completă" starter_license: "Licență începător" customized_license: "Licență personalizată" trial: "Încercare" hoc_welcome: "Săptămână a informaticii fericită" hoc_title: "Jocuri pentru Hour of Code - Activități gratuite pentru a învăța să scrii cod în limbaje de programare reale" hoc_meta_description: "Fă-ți propriul joc sau programează-ți ieșirea din temniță! CodeCombat are patru activități diferite pentru Hour of Code și peste 60 de niveluri să înveți să programezi, să te joci și să creezi." hoc_intro: "Există trei modalități ca și clasa ta să participe la Hour of Code cu CodeCombat" hoc_self_led: "Joc individual" hoc_self_led_desc: "Elevii se pot juca cu tutorialele CodeCombat pentru Hour of Code singuri" hoc_game_dev: "Dezvoltare de joc" hoc_and: "și" hoc_programming: "Programare Javascript/Python" hoc_teacher_led: "Lecții cu profesor" hoc_teacher_led_desc1: "Descarcă" hoc_teacher_led_link: "planurile noastre de lecție pentru Hour of Code" hoc_teacher_led_desc2: "pentru a prezenta elevilor concepte de programare utilizând activități offline" hoc_group: "Joc în grup" hoc_group_desc_1: "Profesorii pot utiliza lecțiile în conjuncție cu cursul Introducere în informatică ca să poată monitoriza progresul elevilor. Vezi" hoc_group_link: "Ghidul de noțiuni de bază" hoc_group_desc_2: "pentru mai multe detalii" hoc_additional_desc1: "Pentru resurse și activități educaționale CodeCombat, vezi" hoc_additional_desc2: "Întrebările" hoc_additional_contact: "Ține legătura" revoke_confirm: "Ești sigur că vrei să înlături licența completă de la {{student_name}}? Licența va deveni disponibilă să o aloci altui elev." revoke_all_confirm: "Ești sigur că vrei să înlături licențele complete de la toți elevii din clasa aceasta?" revoking: "Revocare..." unused_licenses: "Ai licențe neutilizate care îți permit să aloci elevilor cursuri plătite atunci când aceștia vor fi gata să învețe mai mult!" remember_new_courses: "Amintește-ți să aloci cursuri noi!" more_info: "Mai multe informații" how_to_assign_courses: "Cum să aloci cursuri" select_students: "Alege elevi" select_instructions: "Selectează căsuța din dreptul fiecărui elev pentru care vrei să adaugi cursuri." choose_course: "Alege curs" choose_instructions: "Alege cursul din lista derulantă care vrei să îl aloci, apoi apasă “Alocă elevilor selectați.”" push_projects: "recomandăm alocarea cursului Dezvoltare web 1 sau Dezvoltare joc 1 după ce elevii au terminat Introducere în informatică! Vezi {{resource_hub}} pentru mai multe detalii despre aceste cursuri." teacher_quest: "Aventura profesorului către succes" quests_complete: "Aventuri terminate" teacher_quest_create_classroom: "Creează clasă" teacher_quest_add_students: "Adaugă elevi" teacher_quest_teach_methods: "Ajută-i pe elevii tăi să învețe cum să `cheme metode`." teacher_quest_teach_methods_step1: "Obține 75% din primul nivel cu cel puțin o clasă la Dungeons of Kithgard" teacher_quest_teach_methods_step2: "Tipărește [Ghidul elevului de introducere rapidă](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) din Zona de resurse." teacher_quest_teach_strings: "Nu îți face elevii să meargă pe ață (string), învață-i despre șiruri de caractere - `strings`." teacher_quest_teach_strings_step1: "Obține 75% cu cel puțin o clasă la Nume adevărate (True Names)" teacher_quest_teach_strings_step2: "Utilizează Selectorul de nivel al profesorului în pagina [Ghiduri de cursuri](/teachers/courses) să vezi prezentare Nume adevărate." teacher_quest_teach_loops: "Ține-ți elevii aproape cu buclele - `loops`." teacher_quest_teach_loops_step1: "Obține 75% cu cel puțin o clasă la Focul dansator (Fire Dancing)." teacher_quest_teach_loops_step2: "Utilizează Activitatea despre bocle din [Ghidul de curiculă CS1](/teachers/resources/cs1) pentru a întări acest concept." teacher_quest_teach_variables: "Variaz-l un pic cu variabilele - `variables`." teacher_quest_teach_variables_step1: "Obține 75% ocu cel puțin o clasă la Inamicul cunoscut (Known Enemy)." teacher_quest_teach_variables_step2: "Încurajează colaborarer utilizând [Activitatea de programare în perechi](/teachers/resources/pair-programming)." teacher_quest_kithgard_gates_100: "Evadează din Porțile Kithgard(Kithgard Gates) cu clasa ta." teacher_quest_kithgard_gates_100_step1: "Obține 75% cu cel puțin o clasă la Porțile Kithgard." teacher_quest_kithgard_gates_100_step2: "Îndrumă elevi cum să gândească problemele complexe utilizând [Foaie rezumat despre ciclul tehnologic](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)." teacher_quest_wakka_maul_100: "Pregătește-te de duel în Wakka Maul." teacher_quest_wakka_maul_100_step1: "Obține 75% cu cel puțin o clasă la Wakka Maul." teacher_quest_wakka_maul_100_step2: "Vezi [Ghidul arenei](/teachers/resources/arenas) din [Zona de resurse](/teachers/resources) pentru sfaturi despre cum să desfășori cu succes o zi de arenă." teacher_quest_reach_gamedev: "Explorează nou lumi!" teacher_quest_reach_gamedev_step1: "[Cumpără licențe](/teachers/licenses) ca elevii tăi să poată explora noi lumi, ca Dezvoltare de joc și Dezvoltare web!" teacher_quest_done: "Vrei ca elevii tăi să învețe să scrie cod și mai mult? Ia legătura cu [specialiștii școlari](mailto:<EMAIL>) astăzi!" teacher_quest_keep_going: "Continuă! Iată ce poți face mai departe:" teacher_quest_more: "Vezi toate misiunile" teacher_quest_less: "Vezi mai puține misiuni" refresh_to_update: "(reîncarcă pagina să vezi noutățile)" view_project_gallery: "Vezi galeria de proiecte" office_hours: "Conferințe pentru profesori" office_hours_detail: "Învață cum să ți pasul cu elevii tăi în timp ce aceștia creează jocuri și se îmbarcă în aventura lor de scriere a codului! Vino și participă la" office_hours_link: "conferințe pentru profesori" office_hours_detail_2: "." #included in the previous line success: "Succes" in_progress: "În progres" not_started: "Nu a început" mid_course: "Curs la jumătate" end_course: "Curs terminat" none: "Nedetectat încă" explain_open_ended: "Notă: Elevii sunt încurajați să rezolve acest nivel în mod creativ — o soluție posibilă este dată mai jos." level_label: "Nivel:" time_played_label: "Timp jucat:" back_to_resource_hub: "Înapoi la Zona de resurse" back_to_course_guides: "Înapoi la Ghidurile de curs" print_guide: "Tipărește acest ghid" combo: "Combo" combo_explanation: "Elevi trec de nivelurile de provocare combo utilizând cel puțin unul din conceptele listate. Analizează codul elevului apăsând pe punctul de progres." concept: "Concept" sync_google_classroom: "Sincronizează Clasa Google" try_ozaria_footer: "Încearcă noul nostru joc de aventură, Ozaria!" try_ozaria_free: "Încearcă gratuit Ozaria" ozaria_intro: "Introducem noul nostru program de informatică" teacher_ozaria_encouragement_modal: title: "Dezvoltă-ți abilitățile de programare pentru a salva Ozaria" sub_title: "Ești invitat să încerci noul joc de aventură de la CodeCombat" cancel: "Înapoi la CodeCombat" accept: "Încearcă prima unitate gratuit" bullet1: "Aprofundați conexiunea elevului cu învățarea printr-o poveste epică și un joc captivant" bullet2: "Predă fundamentele informaticii, Python sau Javascript și alte abilități specifice secolului 21" bullet3: "Deblochează creativitatea prin proiecte personalizate" bullet4: "Instrucțiuni de suport prin resurse curiculare dedicate" you_can_return: "Poți oricând să te întorci la CodeCombat" educator_signup_ozaria_encouragement: recommended_for: "Recomandat pentru:" independent_learners: "Cursanți independenți" homeschoolers: "Elevii școlii de acasă" educators_continue_coco: "Instructorii care doresc să continue să utilizeze CodeCombat în clasa lor" continue_coco: "Continuă cu CodeCombat" ozaria_cta: title1: "Curicula de bază aliniată standardelor" description1: "Captivantă, povestea este bazată pe o curiculă care îndeplinește standardele CSTA pentru clasele 6-8." title2: "Planuri de lecție la cheie" description2: "Prezentare detaliată și foi de lucru pentru profesori pentru ghidarea elevilor printre obiectivele de învățare." title3: "Profesor nou & Panouri de administrare" # description3: "All the actionable insights educators need at a glance, such as student progress and concept understanding." share_licenses: share_licenses: "Partajează licențe" shared_by: "Partajat de:" add_teacher_label: "Introdu adresa de email exactă a profesorului:" add_teacher_button: "Adaugă profesor" subheader: "Poți să îți faci licențele disponibile altor profesori din organizația ta. Fiecare licență poate fi utilizată pentru un singur elev la un moment dat." teacher_not_found: "Profesor negăsit. Te rog verifică dacă acest profesor are deja un Cont de profesor." teacher_not_valid: "Acesta nu este un Cond de profesor valid. Numai conturile de profesor pot partaja licențe." already_shared: "Ai partajat deja aceste licențe cu acel profesor." have_not_shared: "Nu ai partajat aceste licente cu acel profesor." teachers_using_these: "Profesori care pot accesa aceste licențe:" footer: "Când profesorii înlătură licențele de la elevi, licențele vor fi returnate în setul partajat pentru ca alți profesori din acest grup să le poată utiliza." you: "(tu)" one_license_used: "(1 licență utilizată)" licenses_used: "(__licensesUsed__ licențe utilizate)" more_info: "Mai multe informații" sharing: game: "Jov" webpage: "Pagină web" your_students_preview: "Elevii tăi vor apăsa aici ca să își vadă proiectele finalizate! Nedisponibil în zona profesorului." unavailable: "Link-ul de partajare nu este disponibil în zona profesorului." share_game: "Partajează acest joc" share_web: "Partajează această pagină web" victory_share_prefix: "Partajează acest link ca să inviți prietenii și familia" victory_share_prefix_short: "Invită persoane să" victory_share_game: "joace nivelul tău de joc" victory_share_web: "vadă pagina ta web" victory_share_suffix: "." victory_course_share_prefix: "Acest link îi lasă pe prietenii & familia ta să" victory_course_share_game: "joace jocul" victory_course_share_web: "vadă pagina web" victory_course_share_suffix: "pe care l-ai creat/ai creat-o." copy_url: "Copiază URL" share_with_teacher_email: "trimite profesorului tău" share_ladder_link: "Partajează link multi-jucător" ladder_link_title: "Partajează link către meciul tău multi-jucător" ladder_link_blurb: "Partajează link-ul de luptă IA ca prietenii și familia să joace împotriva codului tău:" game_dev: creator: "<NAME>" web_dev: image_gallery_title: "Galeria cu imagini" select_an_image: "Alege o imagine pe care vrei să o utilizezi" scroll_down_for_more_images: "(Derulează în jos pentru mai multe imagini)" copy_the_url: "Copiază URL-ul de mai jos" copy_the_url_description: "Util dacă vrei să schimbi o imagine existentă." copy_the_img_tag: "Copiază marcajul <img>" copy_the_img_tag_description: "Util dacă vrei să schimbi o imagine nouă." copy_url: "Copiază URL" copy_img: "Copiază <img>" how_to_copy_paste: "Cum să Copiezi/Lipești" copy: "Copiază" paste: "Lipește" back_to_editing: "Înapoi la editare" classes: archmage_title: "Archmage" archmage_title_description: "(Programator)" archmage_summary: "Dacă ești un dezvoltator interesat să programezi jocuri educaționale, devino Archmage și ajută-ne să construim CodeCombat!" artisan_title: "Artizan" artisan_title_description: "(Creator de nivele)" artisan_summary: "Construiește și oferă nivele pentru tine și pentru prieteni tăi, ca să se joace. <NAME> și învață arta de a împărtăși cunoștințe despre programare." adventurer_title: "A<NAME>urier" adventurer_title_description: "(Playtester de nivele)" adventurer_summary: "Primește nivelele noastre noi (chiar și cele pentru abonați) gratis cu o săptămână înainte și ajută-ne să reparăm erorile până la lansare." scribe_title: "scrib" scribe_title_description: "(Editor de articole)" scribe_summary: "Un cod bun are nevoie de o documentație bună. scrie, editează și improvizează documentația citită de milioane de jucători din întreaga lume." diplomat_title: "Diplomat" diplomat_title_description: "(Translator)" diplomat_summary: "CodeCombat e tradus în 45+ de limbi de Diplomații noștri. Ajută-ne și contribuie la traducere." ambassador_title: "Ambasador" ambassador_title_description: "(Suport)" ambassador_summary: "Îmblânzește utilizatorii de pe forumul nostru și oferă direcții pentru cei cu întrebări. Ambasadorii noștri reprezintă CodeCombat în fața lumii." teacher_title: "<NAME>es<NAME>" editor: main_title: "Editori CodeCombat" article_title: "Editor de articole" thang_title: "Editor thang" level_title: "Editor niveluri" course_title: "Editor curs" achievement_title: "Editor realizări" poll_title: "Editor sondaje" back: "Înapoi" revert: "Revino la versiunea anterioară" revert_models: "Resetează Modelele" pick_a_terrain: "Alege terenul" dungeon: "Temniță" indoor: "Interior" desert: "Deșert" grassy: "Ierbos" mountain: "Munte" glacier: "Ghețar" small: "Mic" large: "Mare" fork_title: "Fork Versiune Nouă" fork_creating: "Creare Fork..." generate_terrain: "Generează teren" more: "Mai multe" wiki: "Wiki" live_chat: "Chat Live" thang_main: "Principal" thang_spritesheets: "Spritesheets" thang_colors: "Culori" level_some_options: "Opțiuni?" level_tab_thangs: "Thangs" level_tab_scripts: "script-uri" level_tab_components: "Componente" level_tab_systems: "Sisteme" level_tab_docs: "Documentație" level_tab_thangs_title: "Thangs actuali" level_tab_thangs_all: "Toate" level_tab_thangs_conditions: "Condiți inițiale" level_tab_thangs_add: "Adaugă thangs" level_tab_thangs_search: "Caută thangs" add_components: "Adaugă componente" component_configs: "Configurare componente" config_thang: "Dublu click pentru a configura un thang" delete: "Șterge" duplicate: "Duplică" stop_duplicate: "Oprește duplicarea" rotate: "Rotește" level_component_tab_title: "Componente actuale" level_component_btn_new: "Creează componentă nouă" level_systems_tab_title: "Sisteme actuale" level_systems_btn_new: "Creează sistem nou" level_systems_btn_add: "Adaugă sistem" level_components_title: "Înapoi la toți Thangs" level_components_type: "Tip" level_component_edit_title: "Editează componentă" level_component_config_schema: "Schema config" level_system_edit_title: "Editează sistem" create_system_title: "Creează sistem nou" new_component_title: "Creează componentă nouă" new_component_field_system: "Sistem" new_article_title: "Creează un articol nou" new_thang_title: "Creează un nou tip de Thang" new_level_title: "Creează un nivel nou" new_article_title_login: "Loghează-te pentru a crea un Articol Nou" new_thang_title_login: "Loghează-te pentru a crea un Thang de Tip Nou" new_level_title_login: "Loghează-te pentru a crea un Nivel Nou" new_achievement_title: "Creează o realizare nouă" new_achievement_title_login: "Loghează-te pentru a crea o realizare nouă" new_poll_title: "Creează un sondaj nou" new_poll_title_login: "Autentifică-te pentru a crea un sondaj nou" article_search_title: "Caută articole aici" thang_search_title: "Caută tipuri de Thang aici" level_search_title: "Caută niveluri aici" achievement_search_title: "Caută realizări" poll_search_title: "Caută sondaje" read_only_warning2: "Notă: nu poți salva editările aici, pentru că nu ești autentificat." no_achievements: "Nici-un achivement adăugat acestui nivel până acum." achievement_query_misc: "Realizări cheie din diverse" achievement_query_goals: "Realizări cheie din obiectivele nivelurilor" level_completion: "Finalizare nivel" pop_i18n: "Populează I18N" tasks: "Sarcini" clear_storage: "Șterge schimbările locale" add_system_title: "Adaugă sisteme la nivel" done_adding: "Terminat de adăugat" article: edit_btn_preview: "Preview" edit_article_title: "Editează articol" polls: priority: "Prioritate" contribute: page_title: "Contribuțtii" intro_blurb: "CodeCombat este 100% open source! Sute de jucători dedicați ne-au ajutat să transformăm jocul în cea ce este astăzi. Alătură-te și scrie următorul capitol din aventura CodeCombat pentru a ajuta lumea să învețe cod!" # {change} alert_account_message_intro: "Salutare!" alert_account_message: "Pentru a te abona la mesajele email ale clasei trebuie să fi autentificat." archmage_introduction: "Una dintre cele mai bune părți despre construirea unui joc este că sintetizează atât de multe lucruri diferite. Grafică, sunet, conectarea în timp real, rețelele sociale și desigur multe dintre aspectele comune ale programării, de la gestiunea de nivel scăzut a bazelor de date și administrarea serverelor până la construirea de interfețe. Este mult de muncă și dacă ești un programator cu experiență, cu un dor de a te arunca cu capul înainte în CodeCombat, această clasă ți se potrivește. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." class_attributes: "Atribute pe clase" archmage_attribute_1_pref: "Cunoștințe în " archmage_attribute_1_suf: ", sau o dorință de a învăța. Majoritatea codului este în acest limbaj. Dacă ești fan Ruby sau Python, te vei simți ca acasă. Este Javascript, dar cu o sintaxă mai frumoasă." archmage_attribute_2: "Ceva experiență în programare și inițiativă personală. Te vom ajuta să te orientezi, dar nu putem aloca prea mult timp pentru a te pregăti." how_to_join: "Cum să ni te alături" join_desc_1: "Oricine poate să ajute! Doar intrați pe " join_desc_2: "pentru a începe, bifați căsuța de dedesubt pentru a te marca ca un Archmage curajos și pentru a primi ultimele știri pe email. Vrei să discuți despre ce să faci sau cum să te implici mai mult? " join_desc_3: ", sau găsește-ne în " join_desc_4: "și pornim de acolo!" join_url_email: "Trimite-ne Email" join_url_slack: "canal public de Slack" archmage_subscribe_desc: "Primește email-uri despre noi oportunități de progrmare și anunțuri." artisan_introduction_pref: "Trebuie să construim nivele adiționale! Oamenii sunt nerăbdători pentru mai mult conținut, și noi putem face doar atât singuri. Momentan editorul de nivele abia este utilizabil până și de creatorii lui, așa că aveți grijă. Dacă ai viziuni cu campanii care cuprind bucle for pentru" artisan_introduction_suf: ", atunci aceasta ar fi clasa pentru tine." artisan_attribute_1: "Orice experiență în crearea de conținut ca acesta ar fi de preferat, precum folosirea editoarelor de nivele de la Blizzard. Dar nu este obligatoriu!" artisan_attribute_2: "Un chef de a face o mulțime de teste și iterări. Pentru a face nivele bune, trebuie să fie test de mai mulți oameni și să obțineți păreri și să fiți pregăți să reparați o mulțime de lucruri." artisan_attribute_3: "Pentru moment trebuie să ai nervi de oțel. Editorul nostru de nivele este abia la început și încă are multe probleme. Ai fost avertizat!" artisan_join_desc: "Folosiți editorul de nivele urmărind acești pași, mai mult sau mai puțin:" artisan_join_step1: "Citește documentația." artisan_join_step2: "Creează un nivel nou și explorează nivelurile deja existente." artisan_join_step3: "Găsește-ne pe chatul nostru de Hipchat pentru ajutor." artisan_join_step4: "Postează nivelurile tale pe forum pentru feedback." artisan_subscribe_desc: "Primește email-uri despre update-uri legate de Editorul de nivele și anunțuri." adventurer_introduction: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze niveluri noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura, atunci aceasta este clasa pentru tine." adventurer_attribute_1: "O sete de cunoaștere. Tu vrei să înveți cum să programezi și noi vrem să te învățăm. Cel mai probabil tu vei fi cel care va preda mai mult în acest caz." adventurer_attribute_2: "Carismatic. Formulează într-un mod clar ceea ce trebuie îmbunătățit și oferă sugestii." adventurer_join_pref: "Ori fă echipă (sau recrutează!) cu un Artizan și lucreează cu el, sau bifează căsuța de mai jos pentru a primi email când sunt noi niveluri de testat. De asemenea vom posta despre niveluri care trebuie revizuite pe rețelele noastre precum" adventurer_forum_url: "forumul nostru" adventurer_join_suf: "deci dacă preferi să fi înștiințat în acele moduri, înscrie-te acolo!" adventurer_subscribe_desc: "Primește email-uri când sunt noi niveluri de testat." scribe_introduction_pref: "CodeCombat nu o să fie doar o colecție de niveluri. Vor fi incluse resurse de cunoaștere, un wiki despre concepte de programare legate de fiecare nivel. În felul acesta fiecare Artisan nu trebuie să mai descrie în detaliu ce este un operator de comparație, ei pot să pună un link la un articol mai bine documentat. Ceva asemănător cu ce " scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: " a construit. Dacă idea ta de distracție este să articulezi conceptele de programare în formă Markdown, această clasă ți s-ar potrivi." scribe_attribute_1: "Un talent în cuvinte este tot ce îți trebuie. Nu numai gramatică și ortografie, trebuie să poți să explici ideii complicate celorlați." contact_us_url: "Contactați-ne" # {change} scribe_join_description: "spune-ne câte ceva despre tine, experiențele tale despre programare și despre ce fel de lucruri ți-ar place să scrid. Vom începe de acolo!." scribe_subscribe_desc: "Primește email-uri despre scrisul de articole." diplomat_introduction_pref: "Dacă ar fi un lucru care l-am învățat din " diplomat_introduction_url: "comunitatea open source" diplomat_introduction_suf: "acesta ar fi că: există un interes mare pentru CodeCombat și în alte țări! Încercăm să adunăm cât mai mulți traducători care sunt pregătiți să transforme un set de cuvinte intr-un alt set de cuvinte ca să facă CodeCombat cât mai accesibil în toată lumea. Dacă vrei să tragi cu ochiul la conțintul ce va apărea și să aduci niveluri cât mai repede pentru conaționalii tăi, această clasă ți se potrivește." diplomat_attribute_1: "Fluență în Engleză și limba în care vrei să traduci. Când explici idei complicate este important să înțelegi bine ambele limbi!" diplomat_i18n_page_prefix: "Poți începe să traduci nivele accesând" diplomat_i18n_page: "Pagina de traduceri" diplomat_i18n_page_suffix: ", sau interfața și site-ul web pe GitHub." diplomat_join_pref_github: "Găsește fișierul pentru limba ta " diplomat_github_url: "pe GitHub" diplomat_join_suf_github: ", editează-l online și trimite un pull request. Bifează căsuța de mai jos ca să fi up-to-date cu dezvoltările noastre internaționale!" diplomat_subscribe_desc: "Primește mail-uri despre dezvoltările i18n și niveluri de tradus." ambassador_introduction: "Aceasta este o comunitate pe care o construim, iar voi sunteți conexiunile. Avem forumuri, email-uri și rețele sociale cu mulți oameni cu care se poate vorbi despre joc și de la care se poate învăța. Dacă vrei să ajuți oameni să se implice și să se distreze această clasă este potrivită pentru tine." ambassador_attribute_1: "Abilități de comunicare. Abilitatea de a indentifica problemele pe care jucătorii le au si să îi poți ajuta. De asemenea, trebuie să ne informezi cu părerile jucătoriilor, ce le place și ce vor mai mult!" ambassador_join_desc: "spune-ne câte ceva despre tine, ce ai făcut și ce te interesează să faci. Vom porni de acolo!." ambassador_join_step1: "Citește documentația." ambassador_join_step2: "ne găsești pe canalul public de Slack." ambassador_join_step3: "Ajută pe alții din categoria Ambasador." ambassador_subscribe_desc: "Primește email-uri despre actualizările suport și dezvoltări multi-jucător." teacher_subscribe_desc: "Primește mesaje email pentru actualizări și anunțuri destinate profesorilor." changes_auto_save: "Modificările sunt salvate automat când apeși checkbox-uri." diligent_scribes: "scribii noștri:" powerful_archmages: "Bravii noștri Archmage:" creative_artisans: "Artizanii noștri creativi:" brave_adventurers: "Aventurierii noștri neînfricați:" translating_diplomats: "Diplomații noștri abili:" helpful_ambassadors: "Ambasadorii noștri de ajutor:" ladder: title: "Arene multi-jucător" arena_title: "__arena__ | Arenă multi-jucător" my_matches: "Jocurile mele" simulate: "Simulează" simulation_explanation: "Simulând jocuri poți afla poziția în clasament a jocului tău mai repede!" simulation_explanation_leagues: "Vei simula în principal jocuri pentru jucătorii aliați din clanul și cursurile tale." simulate_games: "Simulează Jocuri!" games_simulated_by: "Jocuri simulate de tine:" games_simulated_for: "Jocuri simulate pentru tine:" games_in_queue: "Jocuri aflate în prezent în așteptare:" games_simulated: "Jocuri simulate" games_played: "Jocuri jucate" ratio: "Rație" leaderboard: "Clasament" battle_as: "Luptă ca " summary_your: "Al tău " summary_matches: "Meciuri - " summary_wins: " Victorii, " summary_losses: " Înfrângeri" rank_no_code: "Nici un cod nou pentru Clasament" rank_my_game: "Plasează-mi jocul în Clasament!" rank_submitting: "Se trimite..." rank_submitted: "Se trimite pentru Clasament" rank_failed: "A eșuat plasarea în clasament" rank_being_ranked: "Jocul se plasează în Clasament" rank_last_submitted: "trimis " help_simulate: "Ne ajuți simulând jocuri?" code_being_simulated: "Codul tău este simulat de alți jucători pentru clasament. Se va actualiza cum apar meciuri." no_ranked_matches_pre: "Niciun meci de clasament pentru " no_ranked_matches_post: " echipă! Joacă împotriva unor concurenți și revino apoi aici pentru a-ți plasa meciul în clasament." choose_opponent: "Alege un adversar" select_your_language: "Alege limba!" tutorial_play: "Joacă tutorial-ul" tutorial_recommended: "Recomandat dacă nu ai mai jucat niciodată înainte" tutorial_skip: "Sări peste tutorial" tutorial_not_sure: "Nu ești sigur ce se întâmplă?" tutorial_play_first: "Joacă tutorial-ul mai întâi." simple_ai: "CPU simplu" # {change} warmup: "Încălzire" friends_playing: "Prieteni ce se joacă" log_in_for_friends: "Autentifică-te ca să joci cu prieteni tăi!" social_connect_blurb: "Conectează-te și joacă împotriva prietenilor tăi!" invite_friends_to_battle: "Invită-ți prietenii să se alăture bătăliei" fight: "Luptă!" # {change} watch_victory: "Vizualizează victoria" defeat_the: "Învinge" watch_battle: "Privește lupta" tournament_starts: "Turneul începe" tournament_started: ", a început" tournament_ends: "Turneul se termină" tournament_ended: "Turneul s-a terminat" tournament_results_published: ", rezultate publicate" tournament_rules: "Regulile turneului" tournament_blurb_criss_cross: "Caștigă pariuri, creează căi, păcălește-ți oponenți, strânge pietre prețioase și îmbunătățește-ți cariera în turneul Criss-Cross! Află detalii" tournament_blurb_zero_sum: "Dezlănțuie creativitatea de programare în strângerea de aur sau în tactici de bătălie în meciul în oglindă din munte dintre vrăjitorii roși și cei albaștri.Turneul începe Vineri, 27 Martie și se va desfăsura până Luni, 6 Aprilie la 5PM PDT. Află detalii" # tournament_blurb_ace_of_coders: "Battle it out in the frozen glacier in this domination-style mirror match! The tournament began on Wednesday, September 16 and will run until Wednesday, October 14 at 5PM PDT. Check out the details" tournament_blurb_blog: "pe blogul nostru" rules: "Reguli" winners: "Învingători" league: "Ligă" red_ai: "CPU Roșu" # "Red AI Wins", at end of multiplayer match playback blue_ai: "<NAME>" wins: "<NAME>" # At end of multiplayer match playback losses: "Pierderi" win_num: "Victorii" loss_num: "Pierderi" win_rate: "Victorii %" humans: "<NAME>" # Ladder page display team name ogres: "<NAME>" tournament_end_desc: "Turneul este terminat, mulțumim că ați jucat" age: "Vârsta" age_bracket: "Intervalul de vârstă" bracket_0_11: "0-11" bracket_11_14: "11-14" bracket_14_18: "14-18" bracket_11_18: "11-18" bracket_open: "Deschis" user: user_title: "__name__ - <NAME>ță să scrii cod cu CodeCombat" stats: "Statistici" singleplayer_title: "Niveluri individuale" multiplayer_title: "Niveluri multi-jucător" achievements_title: "Realizări" last_played: "Ultima oară jucat" status: "Stare" status_completed: "Complet" status_unfinished: "Neterminat" no_singleplayer: "Niciun joc individual jucat." no_multiplayer: "Niciun joc multi-jucător jucat." no_achievements: "Nici o realizare obținută." favorite_prefix: "Limbaj preferat" favorite_postfix: "." not_member_of_clans: "Nu ești membrul unui clan." certificate_view: "vezi certificat" certificate_click_to_view: "apasă să vezi certificatul" certificate_course_incomplete: "curs incomplet" certificate_of_completion: "Certificat de participare" certificate_endorsed_by: "Aprobat de" certificate_stats: "Nivelul de curs" certificate_lines_of: "linii de" certificate_levels_completed: "niveluri terminate" certificate_for: "pentru" certificate_number: "Nr." achievements: last_earned: "Ultimul câștigat" amount_achieved: "Sumă" achievement: "Realizare" current_xp_prefix: "" current_xp_postfix: " în total" new_xp_prefix: "" new_xp_postfix: " câștigat" left_xp_prefix: "" left_xp_infix: " până la nivelul" left_xp_postfix: "" account: title: "Cont" settings_title: "Setări cont" unsubscribe_title: "Dezabonare" payments_title: "Plăți" subscription_title: "Abonament" invoices_title: "Facturi" prepaids_title: "Preplătite" payments: "Plăți" prepaid_codes: "Coduri preplătite" purchased: "Cumpărate" subscribe_for_gems: "Abonează-te pentru pietre" subscription: "Abonament" invoices: "Facturi" service_apple: "Apple" service_web: "Web" paid_on: "Plătit pe" service: "Service" price: "Preț" gems: "Pietre prețioase" active: "Activ" subscribed: "Abonat" unsubscribed: "Dezabonat" active_until: "Activ până la" cost: "Cost" next_payment: "Următoarea plată" card: "Card" status_unsubscribed_active: "Nu ești abonat și nu vei fi facturat, contul tău este activ deocamdată." status_unsubscribed: "Primește access la niveluri noi, eroi, articole și pietre prețioase bonus cu un abonament CodeCombat!" not_yet_verified: "Neverificat încă." resend_email: "Te rog să salvezi mai întâi apoi retrimite email" email_sent: "Email transmis! Verifică casuța de email." verifying_email: "Verificarea adresei de email..." successfully_verified: "Ai verificat cu succes căsuța de email!" verify_error: "ceva a mers rău la verificarea adresei tale de email :(" unsubscribe_from_marketing: "Dezabonează __email__ de la toate mesajele de marketing ale CodeCombat?" unsubscribe_button: "Da, dezabonează" unsubscribe_failed: "Eșuat" unsubscribe_success: "Succes" manage_billing: "Administrare facturi" account_invoices: amount: "Sumă in dolari US" declined: "Cardul tău a fost refuzat" invalid_amount: "Introdu o sumă în dolari US." not_logged_in: "Autentifică-te sau Creează un cont pentru a accesa facturile." pay: "Plată factură" purchasing: "Cumpăr..." retrying: "Eroare server, reîncerc." success: "Plătit cu success. Mulțumim!" account_prepaid: purchase_code: "Cumpără un cod de abonament" purchase_code1: "Codurile de abonament revendicate vor adăuga o perioadă de subscripție premium la unul sau mai multe conturi pentru versiunea Home a CodeCombat." purchase_code2: "Fiecare cont CodeCombat poate revendica un anumit cod de abonament o singură dată." purchase_code3: "Codurile lunare de abnament vor fi adăugate în cont la sfârsitul abonamentelor deja existente." purchase_code4: "Codurile de abonament sunt pentru conturile care au acces la versiunea Home a CodeCombat, ele nu pot fi utilizate ca licențe de elevi la versiunea Classroom." purchase_code5: "Pentru mai multe informații asupra licențelor de elevi, contactați-ne la" users: "Utilizatori" months: "luni" purchase_total: "Total" purchase_button: "Transmite cererea de cumpărare" your_codes: "Codurile tale" redeem_codes: "Revendicare cod de abonament" prepaid_code: "Cod pre-plătit" lookup_code: "Vezi coduri pre-plătite" apply_account: "Aplică contului tău" copy_link: "Poți copia link-ul de cod și îl poți transmite către o altă persoană." quantity: "Cantitate" redeemed: "Revendicate" no_codes: "Nici un cod încă!" you_can1: "Poți" you_can2: "cumpăra un cod pre-plătit" you_can3: "care poate fi aplicat contului tău sau poate fi dat altora." impact: hero_heading: "Construim o clasă de informatică la nivel global" hero_subheading: "Ajutăm profesorii implicați și inspirăm elevii din întreaga țară" featured_partner_story: "Experiențele partenerilor noștri" partner_heading: "Predarea cu succes a programării la Title I School" partner_school: "Școala gimanzială <NAME>" featured_teacher: "<NAME>" teacher_title: "Profesor de tehnologie în Coachella, CA" implementation: "Implementare" grades_taught: "Predare la clasele" length_use: "Timp utilizare" length_use_time: "3 ani" students_enrolled: "Elevi înscriși anul acesta" students_enrolled_number: "130" courses_covered: "Cursuri acoperite" course1: "CompSci 1" course2: "CompSci 2" course3: "CompSci 3" course4: "CompSci 4" course5: "GameDev 1" fav_features: "Caracterisitici preferate" responsive_support: "Suport responsiv" immediate_engagement: "Angajare imediată" paragraph1: "Școala gimanzială <NAME> se află situată între munții Coachella Valley din California de sud în vest și est și la 33 mile de Salton Sea în sud, și are o pulație de 697 elevi în cadrul unei populații de 18,861 elevi din districtul Coachella Valley Unified." paragraph2: "Elevii școlii gimanziale <NAME> reflectă provocările socio-economice ale populației și elevilor din Valea Coachella. Cu peste 95% dintre copii din Școala gimnazială calaficându-se pentru programul de masă gratuit sau cu preț redus și peste 40% clasificați ca populație ce învață limba Engleză, importanța predării unor aptitudini ale secolului 21 a fost o prioritate de top a profesorului de tehnologie din Școala gimanziă <NAME>, <NAME>." paragraph3: "<NAME> a știut că învățarea elevilor să scrie cod este o modalitate importantă pentru a creea o oportunitate în condițiile în care piața muncii prioritizează din ce în ce mai mult și necesită abilități în domeniul calculatoarelor. De aceea, s-a hotărât să își asume această provocare captivantă de creare și predare a singurei clase de programare din școală și găsirea unei soluții accesibile financiar, care răspunde rapid la păreri, și antrenantă pentru elevi cu diverse abilități și condiții de studiu." teacher_quote: "Când am pus mâna pe CodeCombat [și] elevii mei au început să îl folosească, am avut o revelație. Era diferit ca ziua de noapte față de alte programe pe care le-am utilizat. Nu se apropie nici măcar un pic." quote_attribution: "<NAME>, Profesor de tehnologe" read_full_story: "Citește povestea întreagă" more_stories: "Mai multe experiențe ale partenerilor" partners_heading_1: "Sprijin pentru mai multe linii de învățare informatică într-o singură clasă" partners_school_1: "Liceul Preston" partners_heading_2: "Excelență în examenele de plasare - AP Exam" partners_school_2: "Liceul River Ridge" partners_heading_3: "Predare informaticăă fără o experiență prealabilă" partners_school_3: "Liceul Riverdale" download_study: "Descarcă studiul de cercetare" teacher_spotlight: "Profesor & Elev în lumina reflectoarelor" teacher_name_1: "<NAME>" teacher_title_1: "Instructor de reabilitare" teacher_location_1: "Morehead, Kentucky" spotlight_1: "Prin compasiunea ei și dorința de a ajuta pe cei ce au nevoie de a adoua șansă, <NAME> a ajutat la schimbarea vieții elevilor care au nevoie de modele pozitive în viață. Fără o experiență în informatică prealabilă, <NAME> și-a condus elevii pe calea succesului într-o competiție regională de programare." teacher_name_2: "<NAME>" teacher_title_2: "Colegiul comunal & tehnologic Maysville" teacher_location_2: "Lexington, Kentucky" spotlight_2: "<NAME> a fost o elevă care niciodată nu s-a gândit că va putea scrie linii de cod, nicidecum că va fi înscrisă la un colegiu care-i oferă o cale către un viitor luminos." teacher_name_3: "<NAME>" teacher_title_3: "Profesor bibliotecar" teacher_school_3: "Școala primară Ruby Bridges" teacher_location_3: "Alameda, CA" spotlight_3: "<NAME>-<NAME> promovează o atmosferă echitabilă în clasa ei unde toată lumea poate obține rezultate în ritmul său. Greșelile și strădania sunt binevenite deoarece toată lumea învață din provocări, chiar și profesorul." continue_reading_blog: "Continuă să citești pe blog..." loading_error: could_not_load: "Eroare la încărcarea de pe server. Încearcă să reîncarci pagina" connection_failure: "Conexiune eșuată." connection_failure_desc: "Nu pare să fi conectat la Internet! Verifică conexiunea de rețea și apoi reîncarcă pagina." login_required: "Autentificare necesară" login_required_desc: "Trebuie să te autentifici pentru a avea acces la această pagină." unauthorized: "Trebuie să te autentifici. Ai cookies dezactivate?" forbidden: "Nepermis." forbidden_desc: "Oh nu, nu este nimic de văzut aici! Fi sigur că te-ai conectat la contul potrivit, sau vizitează unul din link-urile de mai jos ca să te reîntorci la programare!" user_not_found: "Utilizatoul nu este găsit" not_found: "Nu a fost găsit." not_found_desc: "Hm, nu este nimci aici. Vizitează unul din link-urile următoare ca să te reîntorci la programare!" not_allowed: "Metodă nepermisă." timeout: "Serverul nu poate fi contactat." conflict: "Conflict de resurse." bad_input: "Date greșite." server_error: "Eroare Server." unknown: "Eroare necunoscută." error: "EROARE" general_desc: "Ceva nu a mers bine, și probabil este vina noastră. Încearcă să aștepți puțin și apoi reîncarcă pagina, sau vizitează unul din link-urile următoare ca să te reîntorci la programare!" too_many_login_failures: "Au fost prea multe încercări eșuate de autentificare. Te rog să încerci mai târziu." resources: level: "Nivel" patch: "Patch" patches: "Patch-uri" system: "Sistem" systems: "Sisteme" component: "Componentă" components: "Componente" hero: "Erou" campaigns: "Campanii" concepts: advanced_css_rules: "Reguli CSS avansate" advanced_css_selectors: "Selectori CSS avansați" advanced_html_attributes: "Atribute HTML avansate" advanced_html_tags: "Tag-uri HTML avansate" algorithm_average: "Algoritm Medie aritmetică" algorithm_find_minmax: "Algoritm Caută Min/Max" algorithm_search_binary: "Algoritm Căutare binară" algorithm_search_graph: "Algoritm Căutare în graf" algorithm_sort: "Algoritm Sortare" algorithm_sum: "Algoritm Suma" arguments: "Argumente" arithmetic: "Aritmetică" array_2d: "Matrice bi-dimensională" array_index: "Indexare matriceală" array_iterating: "Iterare prin matrici" array_literals: "Literele matricelor" array_searching: "Căutare în matrice" array_sorting: "Sortare în matrice" arrays: "Matrici" basic_css_rules: "Regulii CSS de bază" basic_css_selectors: "Selectori CSS de bază" basic_html_attributes: "Atribute HTML de bază" basic_html_tags: "Tag-uri HTML de bază" basic_syntax: "Sintaxă de bază" binary: "Binar" boolean_and: "Și boolean" boolean_inequality: "Ingalitatea booleană" boolean_equality: "Egalitatea booleană" boolean_greater_less: "Mai mare/mai mic boolean" boolean_logic_shortcircuit: "Scurtături logice booleene" boolean_not: "Nu boolean" boolean_operator_precedence: "Precedența operatorilor booleeni" boolean_or: "Sau boolean" boolean_with_xycoordinates: "Comparații de coordonate" bootstrap: "Bootstrap" # Can't be translate in Romanian, is used in English form break_statements: "Instrucțiuni de oprire" classes: "Clase" continue_statements: "Instrucțiuni de continuare" dom_events: "Evenimente DOM" dynamic_styling: "Stilizare dinamică" events: "Evenimente" event_concurrency: "Evenimente concurente" event_data: "Date pentru evenimente" event_handlers: "Manipulatori de eveniment" # event_spawn: "Spawn Event" for_loops: "Bucle for" for_loops_nested: "Bucle for îmbricate" for_loops_range: "Zona de aplicare a buclelor for" functions: "Funcții" functions_parameters: "Parametrii" functions_multiple_parameters: "Parametrii multiplii" game_ai: "Joc AI" game_goals: "Obiectivele jocului" # game_spawn: "Game Spawn" graphics: "Grafică" graphs: "Grafuri" heaps: "Stive" if_condition: "Instrucțiuni condiționale if" if_else_if: "Instrucțiuni If/Else/IF" if_else_statements: "Instrucțiuni If/Else" if_statements: "Instrucțiuni If" if_statements_nested: "Instrucțiuni if îmbricate" indexing: "Indexuri matriceale" input_handling_flags: "Manipulare intrări - Flag-uri" input_handling_keyboard: "Manipulare intrări - Tastatură" input_handling_mouse: "Manipulare intrări - Mouse" intermediate_css_rules: "Reguli CSS intermediare" intermediate_css_selectors: "Selectrori CSS intermediari" intermediate_html_attributes: "Atribute HTML intermediare" intermediate_html_tags: "Tag-uri HTML intermediare" jquery: "jQuery" jquery_animations: "Animații jQuery" jquery_filtering: "Filtrare elemente jQuery" jquery_selectors: "Selectori jQuery" length: "Lungime matrice" math_coordinates: "Calculare coordonate" math_geometry: "Geometrie" math_operations: "Librăria de operații matematice" math_proportions: "Proporții matematice" math_trigonometry: "Trigonometrie" # object_literals: "Object literals" parameters: "Parametrii" programs: "Programe" properties: "Proprietăți" property_access: "Accesare proprietăți" property_assignment: "Alocarea proprietăți" property_coordinate: "Proprietatea coordonate" queues: "Structuri de date - Cozi" reading_docs: "Citirea documentației" recursion: "Recursivitate" return_statements: "Instrucțiunea return" stacks: "Structuri de date - Stive" strings: "Șiruri de caractere" strings_concatenation: "Concatenare șiruri de caractere" strings_substrings: "Sub-șir de caractere" trees: "Structuri de date - Arbori" variables: "Variabile" vectors: "Vectori" while_condition_loops: "Bucle while cu condiționare" while_loops_simple: "Bucle while" while_loops_nested: "Bucle while îmbricate" xy_coordinates: "Perechi de coordonate" advanced_strings: "Șiruri de caractere avansate" # Rest of concepts are deprecated algorithms: "Algoritmi" boolean_logic: "Logică booleană" basic_html: "HTML de bază" basic_css: "CSS de bază" basic_web_scripting: "Programare web de bază" intermediate_html: "HTML intermediar" intermediate_css: "CSS intermediar" intermediate_web_scripting: "Programare web intermediar" advanced_html: "HTML avansat" advanced_css: "CSS avansat" advanced_web_scripting: "Programare web avansat" input_handling: "Manipulare intrări" while_loops: "Bucle while" place_game_objects: "Plasare obiecte de joc" construct_mazes: "Construcție labirinturi" create_playable_game: "Creează un proiect de joc pe care îl poți juca, partaja" alter_existing_web_pages: "Modifică pagini de web existente" create_sharable_web_page: "Creează o pagină web care poate fi partajată" basic_input_handling: "Manipulare de bază a intrărilor" basic_game_ai: "Joc IA de bază" basic_javascript: "Javascript de bază" basic_event_handling: "Manipulare de bază a evenimentelor" create_sharable_interactive_web_page: "Creează o pagină de web interactivă care poate fi partajată" anonymous_teacher: notify_teacher: "Anunță profesor" create_teacher_account: "Creează un cont de profesor gratuit" enter_student_name: "N<NAME>:" enter_teacher_email: "Adresa de email de profesor:" teacher_email_placeholder: "<EMAIL>" student_name_placeholder: "scri<NAME>" teachers_section: "Profesori:" students_section: "Elevi:" teacher_notified: "Ți-am anunțat profesorul că vrei să joci mai mult CodeCombat în clasă!" delta: added: "Adăugat" modified: "Modificat" not_modified: "Nemodificat" deleted: "Șters" moved_index: "Index mutat" text_diff: "Diff text" merge_conflict_with: "COMBINĂ CONFLICTUL CU" no_changes: "Fară schimbări" legal: page_title: "Aspecte Legale" opensource_introduction: "CodeCombat este parte a comunității open source." opensource_description_prefix: "Vizitează " github_url: "pagina noastră de GitHub" opensource_description_center: "și ajută-ne dacă îți place! CodeCombat este construit dintr-o mulțime de proiecte open source, pe care noi le iubim. Vizitați" archmage_wiki_url: "Archmage wiki" opensource_description_suffix: "pentru o listă cu softul care face acest joc posibil." practices_title: "Convenții" practices_description: "Acestea sunt promisiunile noastre către tine, jucătorul, fără așa mulți termeni legali." privacy_title: "Confidenţialitate şi termeni" privacy_description: "Nu o să iți vindem datele personale." security_title: "Securitate" security_description: "Ne străduim să vă protejăm informațiile personale. Fiind un proiect open-source, site-ul nostru oferă oricui posibilitatea de a ne revizui și îmbunătăți sistemul de securitate." email_title: "Email" email_description_prefix: "Noi nu vă vom inunda cu spam. Prin" email_settings_url: "setările tale de email" email_description_suffix: " sau prin link-urile din email-urile care vi le trimitem, puteți să schimbați preferințele și să vâ dezabonați oricând." cost_title: "Cost" cost_description: "CodeCombat se poate juca gratuit în nivelurile introductive, cu un abonament de ${{price}} USD/lună pentru acces la niveluri suplimentare și {{gems}} pietre prețioase bonus pe lună. Poți să anulezi printr-un simplu clic și oferim banii înapoi garantat în proporție de 100%." copyrights_title: "Drepturi de autor și licențe" contributor_title: "Acord de licență Contributor" contributor_description_prefix: "Toți contribuitorii, atât pe site cât și pe GitHub-ul nostru, sunt supuși la" cla_url: "ALC" contributor_description_suffix: "la care trebuie să fi de accord înainte să poți contribui." code_title: "Code - MIT" # {change} client_code_description_prefix: "Tot codul pe partea de client al codecombat.com din depozitul public GitHub și din baza de date codecombat.com, este licențiat sub" mit_license_url: "licența MIT" code_description_suffix: "Asta include tot codul din Systems și Components care este oferit de către CodeCombat cu scopul de a creea nivelurile." art_title: "Artă/Muzică - Conținut comun " art_description_prefix: "Tot conținutul creativ/artistic este valabil sub" cc_license_url: "Creative Commons Attribution 4.0 International License" art_description_suffix: "Conținut comun este orice făcut general valabil de către CodeCombat cu scopul de a crea niveluri. Asta include:" art_music: "Muzică" art_sound: "Sunet" art_artwork: "Artwork" art_sprites: "Sprites" art_other: "Orice și toate celelalte creații non-cod care sunt disponibile când se creează niveluri." art_access: "Momentan nu există nici un sistem universal, ușor pentru preluarea acestor bunuri. În general, preluați-le din adresele URL așa cum sunt folosite de site-ul web, contactați-ne pentru asistență, sau ajutați-ne să extindem site-ul ca să facem aceste bunuri mai ușor accesibile." art_paragraph_1: "Pentru atribuire, vă rugăm denumiți și să faceți referire la codecombat.com aproape de locația unde este folosită sursa sau unde este adecvat pentru mediu. De exemplu:" use_list_1: "Dacă este folosit într-un film sau alt joc, includeți codecombat.com la credite." use_list_2: "Dacă este folosit pe un site, includeți un link în apropiere, de exemplu sub o imagine, sau în pagina generală de atribuiri unde menționați și alte bunuri creative și softul open source folosit pe site. Ceva care face referință explicit la CodeCombat, precum o postare pe un blog care menționează CodeCombat, nu trebuie să se facă o atribuire separată." art_paragraph_2: "Dacă conținutul folosit nu este creat de către CodeCombat ci de către un utilizator al codecombat.com,atunci faceți referință către el și urmăriți indicațiile de atribuire prevăzute în descrierea resursei, dacă aceasta există." rights_title: "Drepturi rezervate" rights_desc: "Toate drepturile sunt rezervate pentru nivelurile în sine. Asta include" rights_scripts: "script-uri" rights_unit: "Configurații de unități" rights_writings: "scrieri" rights_media: "Media (sunete, muzică) și orice alt conținut creativ dezvoltat special pentru un nivel și care nu sunt valabile în mod normal pentru creearea altor niveluri." rights_clarification: "Pentru a clarifica, orice este valabil în Editorul de Niveluri pentru scopul de a crea niveluri se află sub licențiere CC, pe când conținutul creat cu Editorul de Niveluri sau încărcat pentru a face niveluru nu se află sub aceasta." nutshell_title: "Pe scurt" nutshell_description: "Orice resurse vă punem la dispoziție în Editorul de Niveluri puteți folosi liber cum vreți pentru a crea niveluri. Dar ne rezervăm dreptul de a rezerva distribuția de niveluri în sine (care sunt create pe codecombat.com) astfel încât să se poată percepe o taxă pentru ele pe vitor, dacă se va ajunge la așa ceva." nutshell_see_also: "Vezi și:" canonical: "Versiunea în engleză a acestui document este cea definitivă, versiunea canonică. Dacă există orice discrepanțe între versiunea tradusă și cea originală, documentul în engleză are prioritate." third_party_title: "Servicii Third Party" third_party_description: "CodeCombat utilizează următoarele servicii third party (printre altele):" cookies_message: "CodeCombat utilizează câteva cookies esențiale și neesențaile." cookies_deny: "Refuză cookies neesențiale" cookies_allow: "Permite cookies" calendar: year: "An" day: "Zi" month: "Luna" january: "Ianuarie" february: "Februarie" march: "Martie" april: "Aprilie" may: "Mai" june: "Iunie" july: "Iulie" august: "August" september: "Septembrie" october: "Octombrie" november: "Noiembrie" december: "Decembrie" code_play_create_account_modal: title: "Ai reușit!" # This section is only needed in US, UK, Mexico, India, and Germany body: "Ești pe cale să devii un programator de top. Înregistrează-te ca să primești suplimentar <strong>100 pietre prețioase</strong> & vei intra de asemenea pentru o șansă de a <strong>câștiga $2,500 & alte premii Lenovo</strong>." sign_up: "Întregistrează-te & continuă să programezi ▶" victory_sign_up_poke: "Creează un cont gratuit ca să poți salva codul scris & o șansă să câștigi premii!" victory_sign_up: "Înregistrează-te & să intri să <strong>câștigi $2,500</strong>" server_error: email_taken: "Email deja utilizat" username_taken: "Cont de utilizator existent" easy_password: "<PASSWORD>" reused_password: "<PASSWORD>" esper: line_no: "Linia $1: " uncaught: "Ne detectat $1" # $1 will be an error type, eg "Uncaught SyntaxError" reference_error: "ReferenceError: " argument_error: "ArgumentError: " type_error: "TypeError: " syntax_error: "SyntaxError: " error: "Eroare: " x_not_a_function: "$1 nu este o funcție" x_not_defined: "$1 nu este definit" spelling_issues: "Verifică erori de scriere: ai vrut `$1` în loc de `$2`?" capitalization_issues: "Verifică modul de scriere cu literele mari/mici: `$1` trebuie să fie `$2`." py_empty_block: "$1 este gol. Pune 4 spații în fața instrucțiunilor în interiorul instrucțiunii $2." fx_missing_paren: "Dacă vrei să chemi `$1` ca și funcție, ai nevoie de `()`" unmatched_token: "`$1` fără pereche. Fiecare deschidere `$2` trebuie să aibă o încheiere `$3` ca și pereche." unterminated_string: "Șir de caractere neterminat. Adaugă perechea de `\"` la sfârșitul șirului de caractere." missing_semicolon: "Punct și virgulă (;) lipsește." missing_quotes: "Ghilimelele lipsesc. Încearcă `$1`" argument_type: "Argumentul lui`$1` este `$2` care trebuie să fie de tipul`$3`, dar are `$4`: `$5`." argument_type2: "Argumentul lui `$1` este `$2` care trebuie să fie de tipul `$3`, dar are `$4`." target_a_unit: "Țintește o unitate." attack_capitalization: "Atacă $1, nu $2. (Literele mari sunt importante.)" empty_while: "Instrucțiune while goală. Pune 4 spații în fața instrucțiunilor în interiorul instrucțiunii while." line_of_site: "Argumentul `$1` este `$2` și are o problemă. Este deja un inamic în linia ta vizuală?" need_a_after_while: "Ai nevoie de un `$1` după `$2`." too_much_indentation: "Prea multă indentare la începutul acestei linii." missing_hero: "Cuvântul cheie `$1` lipsește; ar trebui să fie `$2`." takes_no_arguments: "`$1` nu ia nici un argument." no_one_named: "Nu este nimeni cu numele \"$1\" ca și țintă." separated_by_comma: "Parametrii de chemare a funcțiilor ar trebui separați cu `,`" protected_property: "Nu pot citi proprietatea protejată: $1" need_parens_to_call: "Dacă vrei să chemi `$1` ca și funcție ai nevoie de `()`" expected_an_identifier: "Se asteaptă un identificator dar în loc este '$1'." unexpected_identifier: "Identificator neașteptat" unexpected_end_of: "Terminare intrare neașteptată" unnecessary_semicolon: "Punct și virgulă neașteptate." unexpected_token_expected: "Token neașteptat: se aștepta $1 dar s-a găsit $2 când s-a analizat $3" unexpected_token: "$1 este un token neașteptat" unexpected_token2: "Token neașteptat" unexpected_number: "Număr neașteptat" unexpected: "'$1' neașteptat." escape_pressed_code: "Tasta escape apăsată; cod întrerupt." target_an_enemy: "Țintește un inamic după nume, ca `$1`, nu șirul de caractere `$2`." target_an_enemy_2: "Țintește un inamic după nume, ca $1" cannot_read_property: "Proprietatea '$1' nu se poate citi de tip nedefinit" attempted_to_assign: "Încercare de alocare proprietate readonly (doar pentru cititre)." unexpected_early_end: "Sfârșit de program neașteptat." you_need_a_string: "Trebuie să construiești un șir de caractere; unul ca $1" unable_to_get_property: "Proprietatea '$1' de tip nedefinit nu poate fi accesată sau referință către null" # TODO: Do we translate undefined/null? code_never_finished_its: "Programul nu a terminat niciodată. Este fie foarte încet or are o buclă infinită." unclosed_string: "Șir de caractere neînchis." unmatched: "'$1' fără pereche." error_you_said_achoo: "Ai scris: $1, dar parola este: $2. (Literele mari sunt importante.)" indentation_error_unindent_does: "Eroare de indentare: neindentarea nu se potrivește cu nici una din nivelurile de indentare" indentation_error: "Eroare de identare." need_a_on_the: "Ai nevoie de `:` la sfârșitul liniei după `$1`." attempt_to_call_undefined: "încercare de chemare a '$1' (o valoare nil)" unterminated: "`$1` neterminat" target_an_enemy_variable: "Țintește o variabilă $1, nu șirul de caractere $2. (Încearcă $3.)" error_use_the_variable: "Utilizează numele de variabilă `$1` în loc de șirul de caractere `$2`" indentation_unindent_does_not: "Neindentarea nu se potrivește cu nici una din nivelurile de indentare" unclosed_paren_in_function_arguments: "$1 neînchis în argumentele funcției." unexpected_end_of_input: " Sfârșit de intrare neașteptat" there_is_no_enemy: "Nu există`$1`. Utilizează mai întâi `$2`." # Hints start here try_herofindnearestenemy: "Încearcă `$1`" there_is_no_function: "Nu există funcția `$1`, dar `$2` are metoda `$3`." attacks_argument_enemy_has: "Argumentul lui`$1` este `$2` și are o problemă." is_there_an_enemy: "Este deja un inamic în linia ta vizuală?" target_is_null_is: "Ținta este $1. Există tot mereu o țintă pe care să o ataci? (Utilizezi $2?)" hero_has_no_method: "`$1` nu are nici o metodă`$2`." there_is_a_problem: "Este o problemă cu codul tău." did_you_mean: "Ai vrut să scrii $1? Nu ești echipat cu un element care să aibă acea abilitate." missing_a_quotation_mark: "O pereche de ghilimele lipsesc. " missing_var_use_var: "`$1` lipsește. Utilizează `$2` să faci o nouă variabilă." you_do_not_have: "Nu ești echipat cu un element care să aibă abilitatea $1." put_each_command_on: "Pune fiecare comandă pe o linie separată" are_you_missing_a: "Îți lipsește '$1' după '$2'? " your_parentheses_must_match: "Parantezele tale trebuie să fie pereche." apcsp: title: "Principiile informaticii de plasare avansată (AP) | Aprobate de Comisia colegiilor" meta_description: "Curicula completă a CodeCombat și programul de dezvoltare profesională sunt tot ceea ce ai nevoie pentru a oferi elevilor un nou curs de informatică al Comisiei colegiilor." syllabus: "Programa cu principiile informaticii pentru AP" syllabus_description: "Utilizează această resursă pentru a planifica curicula CodeCombat pentru clasa de principiile informaticii pentru AP." computational_thinking_practices: "Practici de gândire computațională" learning_objectives: "Obiective de învățare" curricular_requirements: "Cerințe curiculare" unit_1: "Unitatea 1: Tehnologie creativă" unit_1_activity_1: "Activitate unitatea 1: Prezentare a utilității tehnologiei" unit_2: "Unitatea 2: Gândire computațională" unit_2_activity_1: "Activitate unitatea 2: Secvențe binare" unit_2_activity_2: "Activitate unitatea 2: Proiect de lecție pentru tehnică de calcul" unit_3: "Unitatea 3: Algoritmi" unit_3_activity_1: "Activitate unitatea 3: Algoritmi - Ghidul Hitchhiker" unit_3_activity_2: "Activitate unitatea 3: Simulare - Prădător & Pradă" unit_3_activity_3: "Activitate unitatea 3: Algoritmi - Programare și design în perechi" unit_4: "Unitatea 4: Programare" unit_4_activity_1: "Activitate unitatea 4: Abstractizare" unit_4_activity_2: "Activitate unitatea 4: Căutare & Sortare" unit_4_activity_3: "Activitate unitatea 4: Refactorizare" unit_5: "Unitatea 5: Internetul" unit_5_activity_1: "Activitate unitatea 5: Cum funcționează Internetul" unit_5_activity_2: "Activitate unitatea 5: Simulator Internet" unit_5_activity_3: "Activitate unitatea 5: Simulator de canal de chat" unit_5_activity_4: "Activitate unitatea 5: Cybersecurity" unit_6: "Unitatea 6: Data" unit_6_activity_1: "Activitate unitatea 6: Introducere în date" unit_6_activity_2: "Activitate unitatea 6: Big Data" unit_6_activity_3: "Activitate unitatea 6: Compresie cu pierderi & fără pierderi" unit_7: "Unitatea 7: Impact personal & global" unit_7_activity_1: "Activitate unitatea 7: Impact personal & global" unit_7_activity_2: "Activitate unitatea 7: Crowdsourcing" unit_8: "Unitatea 8: Proba de performanță" unit_8_description: "Pregătește elevii pentru Creează temă în care vor construi propriile lor jocuri și în care vor testa conceptele de bază." unit_8_activity_1: "Practica 1 - Creează temă: Dezvolatre joc 1" unit_8_activity_2: "Practica 2 - Creează temă: Dezvolatre joc 2" unit_8_activity_3: "Practica 3 - Creează temă: Dezvolatre joc 3" unit_9: "Unitatea 9: Prezentare generală AP" unit_10: "Unitatea 10: După AP" unit_10_activity_1: "Activitate unitatea 10: Chestionar web" parents_landing_2: splash_title: "Descoperă magia programării acasă." learn_with_instructor: "Învață cu un instructor" live_classes: "Clase online în timp real" live_classes_offered: "CodeCombat oferă acum clase online de informatică pentru elevii care fac școala acasă. Bun pentru elevii care lucreează bine 1:1 sau grupuri mici în care rezultatele învățării sunt adaptate nevoilor lor." live_class_details_1: "Grupuri mici sau lecții private" live_class_details_2: "Programare în Javascript și Python, plus concepte de bază în informatică" live_class_details_3: "Predat de instructori experți în programare" live_class_details_4: "Păreri individualizate și imediate" live_class_details_5: "Curicula beneficiază de încrederea a 80,000+ de educatori" try_free_class: "Încearcă o clasă gratuită de 60 minute" pricing_plans: "Planuri de preț" choose_plan: "Alege un plan" per_student: "pentru fiecare elev" sibling_discount: "15% reducere pentru frați!" small_group_classes: "Clase de programare în grupuri mici" small_group_classes_detail: "4 grupuri pe sesiune / lună." small_group_classes_price: "$159/lună" small_group_classes_detail_1: "4:1 este rația elevi-profesor" small_group_classes_detail_2: "Clase de 60 de minute" small_group_classes_detail_3: "Construiește proiecte și spune-ți părerea despre proiectele celorlalți" small_group_classes_detail_4: "Partajare ecran pentru a primi păreri în timp real și depanare cod" private_classes: "Clase de programare private" four_sessions_per_month: "4 sesiuni private / lună." eight_sessions_per_month: "8 sesiuni private / lună." four_private_classes_price: "$219/lună" eight_private_classes_price: "$399/lună" private_classes_detail: "4 sau 8 sesiuni private / lună." private_classes_price: "$219/lună sau $399/lună" private_classes_detail_1: "1:1 este rația elev-profesor" private_classes_detail_2: "Clase de 60 de minut" private_classes_detail_3: "Program flexibil adaptat nevoilor tale" private_classes_detail_4: "Planuri de lecție și păreri în timp real adaptate stilului de învățare al elevului, ritmului acestuia și nivelului de abilități" best_seller: "Cel mai bine vândut" best_value: "Cea mai bună valoare" codecombat_premium: "CodeCombat Premium" learn_at_own_pace: "Învață în ritmul tău" monthly_sub: "Abonament lunar" buy_now: "Cumpără acum" per_month: " / lună" lifetime_access: "Acces pe viață" premium_details_title: "Bun pentru cei ce învață singuri și doresc autonomie completă." premium_details_1: "Accesează eroi, animăluțe și aptitudini disponibile doar abonaților" premium_details_2: "Primește pietre prețioase bonus să cumperi echipament, animăluțe și mai mulți eroi" premium_details_3: "Deblochează detalii despre concepte de bază și abilități ca dezvoltarea web și de jocuri" premium_details_4: "Suport premium pentru cei abonați" premium_details_5: "Creează clanuri private să îți inviți prietenii pentru a concura în grup" premium_need_help: "Ai nevoie de ajutor sau preferi Paypal? Email <a href=\"mailto:<EMAIL>\"><EMAIL></a>" not_sure_kid: "Nu ești sigur dacă CodeCombat este pentru copiii tăi? Întreabă-i!" share_trailer: "Arată-i filmul nostru de prezentare copilului tău și determină-l să își facă un cont pentru a începe." why_kids_love: "De ce iubesc copiii CodeCombat" learn_through_play: "Învață prin joacă" learn_through_play_detail: "Elevii își vor dezvolta abilitățile de a scrie cod și își vor utiliza abilitățile de rezolvare a problemelor pentru a progresa prin niveluri și a-și crește eroul." skills_they_can_share: "Abilități pe care le pot partaja" skills_they_can_share_details: "Elevii își dezvoltă abilități din lumea reală și creează proiecte, cum ar fi jocuri sau pagini web, pe care le pot partaja cu prietenii și familia." help_when_needed: "Ajută-i atunci când au nevoie" help_when_needed_detail: "Utilizând date, fiecare nivel a fost construit să îi incite, dar niciodată să îi descurajeze. Elevii sun ajutați cu indicii atunci când se blochează." book_first_class: "Rezervă-ți prima clasă" why_parents_love: "De ce părinții iubesc CodeCombat" most_engaging: "Cel mai antrenant mod să înveți să scrii cod" most_engaging_detail: "Copilul tău va avea tot ce are nevoie la degentul mic pentru a scrie algoritmi în Python sau Javascript, să dezvolte site-uri web sau chiar să-și proiecteze propriul joc, în timp ce învață materie aliniată la standardele de curiculă națională." critical_skills: "Dezvoltă abilități importante pentru secolul 21" critical_skills_detail: "Copilul tău va învăța să navigheze și să devină cetățean în lumea digitală. CodeCombat este o soluție care îi îmbunătățește copilului tău gândirea critică, creativitatea și reziliența, îmbunătățindu-le abilitățile de care au nevoie în orice domeniu." parent_support: "Susținuți de părinți ca tine" parent_support_detail: "La CodeCombat, noi suntem părinții. Noi suntem programatori. Suntem profesori. Dar în primul rând, suntem oameni care credem că îi dăm copilului tău oportunitatea să aibă succes în orice își doreste acesta să facă." everything_they_need: "Tot ceea ce au nevoie pentru a începe să scrie cod singuri" beginner_concepts: "Concepte pentru începători" beginner_concepts_1: "Sintaxa de bază" beginner_concepts_2: "Bucle while" beginner_concepts_3: "Argumente" beginner_concepts_4: "Șiruri de caractere" beginner_concepts_5: "Variabile" beginner_concepts_6: "Algoritmi" intermediate_concepts: "Concepte de nivel intermediar" intermediate_concepts_1: "Instrucțiunea if" intermediate_concepts_2: "Comparația booleană" intermediate_concepts_3: "Condiționale îmbricate" intermediate_concepts_4: "Funcții" intermediate_concepts_5: "Manipularea de bază a intrărilor" intermediate_concepts_6: "Inteligență artificială de bază pentru jocuri" advanced_concepts: "Concepte avansate" advanced_concepts_1: "Manipularea evenimentelor" advanced_concepts_2: "Bucle condiționale while" # advanced_concepts_3: "Object literals" advanced_concepts_4: "Parametri" advanced_concepts_5: "Vectori" advanced_concepts_6: "Librăria de operatori matematici" advanced_concepts_7: "Recursivitate" get_started: "Hai să începem" quotes_title: "Ce zic părinții și copiii despre CodeCombat" quote_1: "\"Acesta este următorul nivel de scriere cod pentru copii și este foarte amuzant. Voi învăța un lucru sau două din acesta.\"" quote_2: "\"Mi-a plăcut să învăț o nouă abilitate pe care înainte nu o aveam. Mi-a plăcut că atunci când am avut probleme, am putu să-mi stabilesc obiectivele. Mi-a mai plăcut să văd că codul scris de mine funcționează corect.\"" quote_3: "\"Python-ul lui <NAME> începe să aibă sens. El utilizează CodeCombat să își facă jocuri video. M-a provocat să îi joc jocurile, apoi râde când pierd.\"" quote_4: "\"Acesta este unul din lucrurile pe care îmi place să le fac. În fiecare dimineață mă trezesc și joc CodeCombat. Dacă ar trebui să îi dau o notă pentru CodeCombat de la 1 la 10, i-aș da un 10!\"" parent: "Părinți" student: "Elev" grade: "Clasa" subscribe_error_user_type: "Se pare că deja te-ai înregistrat pentru un cont. Dacă ești interesat de CodeCombat Premium, te rog să ne contactezi la <EMAIL>." subscribe_error_already_subscribed: "Deja ai un abonament pentru un cont premium." start_free_trial_today: "Începe gratuit de azi varianta de încercare" live_classes_title: "Clase de programare online de la CodeCombat!" live_class_booked_thank_you: "Clasa de online a fost programată, mulțumim!" book_your_class: "Programează-ți clasa" call_to_book: "Sună acum pentru programare" modal_timetap_confirmation: congratulations: "Felicitări!" paragraph_1: "Aventura elevilor tăi în lumea programării așteaptă." paragraph_2: "Copilul tău este înregistrat la o clasă online și abia așteptăm să îl întâlnim!" paragraph_3: "În curând ar trebui să primești un email de invitație cu detalii atât despre clasa programată cât și numele și datele de contact ale instructorului." paragraph_4: "Dacă, pentru orice motiv, dorești modificarea clasei alese, replanificare sau vrei să vorbești cu un specialist în relația cu clienții, trebuie doar să ne folosești datele de contact furnizate în mesajul email de invitație." paragraph_5: "Îți mulțumim că ai ales CodeCombat și îți urăm noroc în călătoria ta în informatică!" back_to_coco: "Înapoi la CodeCombat" hoc_2018: banner: "Bine ai venit la Hour of Code!" page_heading: "Elevii tăi vor învăța cum să își construiască propriul joc!" page_heading_ai_league: "Elevii tăi vor învăța cum să își construiască propriul joc IA multi-jucător!" step_1: "Pas 1: Urmărește video de prezentare" step_2: "Pas 2: Încearcă-l" step_3: "Pas 3: Descarcă planul de lecție" try_activity: "Încearcă activitatea" download_pdf: "Descarcă PDF" teacher_signup_heading: "Transformă Hour of Code în Year of Code" teacher_signup_blurb: "Tot ce ai nevoie să predai informatică, nu este necesară o experiență anterioară." teacher_signup_input_blurb: "Ia primul curs gratuit:" teacher_signup_input_placeholder: "Adresa de email a profesorului" teacher_signup_input_button: "Ia cursul CS1 gratuit" activities_header: "Mai multe activități Hour of Cod" activity_label_1: "Informatică nivel începător: Scapă din temniță!" activity_label_2: " Dezvoltare jocuri nivel începător: Construiește un joc!" activity_label_3: "Dezvoltare de jocuri nivel avansat: Construiește un joc tip arcadă!" activity_label_hoc_2018: "Dezvoltare de jocuri nivel intermediar: scrie cod, joacă, creează" activity_label_ai_league: "Informatică nivel începător: Calea către liga IA" activity_button_1: "Vezi lecția" about: "Despre CodeCombat" about_copy: "Un program de informatică bazat pe joc, aliniat standardelor care predă scriere de cod în Python și Javascript." point1: "✓ Punerea bazelor" point2: "✓ Diferențiere" point3: "✓ Evaluări" point4: "✓ Cursuri bazate pe proiecte" point5: "✓ Monitorizare elevi" point6: "✓ Planuri de lecție complete" title: "HOUR OF CODE" acronym: "HOC" hoc_2018_interstitial: welcome: "Bine ai venit la Hour of Code organizat de CodeCombat!" educator: "Sunt instructor" show_resources: "Arată-mi resursele profesorului!" student: "Sunt elev" ready_to_code: "Sunt gata să programez!" hoc_2018_completion: congratulations: "Felicitări că ai terminat <b>scrie cod, joacă, creează!</b>" send: "Trimite jocul tău Hour of Code prietenilor și familiei!" copy: "Copiază URL" get_certificate: "Descarcă o diplomă de participare pentru a sărbătorii cu clasa ta!" get_cert_btn: "Descarcă certificat" first_name: "<NAME>" last_initial: "Nume de familie și inițiala" teacher_email: "Adresa de email a profesorului" school_administrator: title: "Panou de lucru al administratorului școlii" my_teachers: "Profesorii mei" last_login: "Ultima autentificare" licenses_used: "licențe utilizate" total_students: "total elevi" active_students: "elevi activi" projects_created: "proiecte create" other: "Altele" notice: "Următorii administratori de școală au acces numai de vizualizare la datele tale de clasă:" add_additional_teacher: "Trebuie să adaugi un alt profesor? Contactează-ți managerul de cont CodCombat sau trimite email la <EMAIL>. " license_stat_description: "Conturile licențiate disponibile reprezintă numărul de licențe disponibile pentru profesori, incluzând licențele partajate." students_stat_description: "Numărul total de conturi de elevi reprezintă toți elevii din toate clasele, indiferent dacă aceștia au sau nu licențe aplicate." active_students_stat_description: "Conturi de elevi activi reprezintă numărul de elevi care s-au conectat la CodeCombat în ultimele 60 de zile." project_stat_description: "Proiectele create reprezintă numărul total de proiecte de dezvoltare web sau de jocuri care au fost create." no_teachers: "Nu aveți în administrare nici un profesor." totals_calculated: "Cum sunt aceste totaluri calculate?" totals_explanation_1: "Cum sunt aceste totaluri calculate?" totals_explanation_2: "Licențe utilizate" totals_explanation_3: "Reprezintă totalul licențelor aplicate elevilor din totalul de licențe disponibile." totals_explanation_4: "Total elevi" totals_explanation_5: "Reprezintă elevii din toate clasele active. Pentru a vedea totalul elevilor înrolați în clasele active și cele arhivate, mergi la pagina Licențe elevi." totals_explanation_6: "Elevi activi" totals_explanation_7: "Resprezintă toți elevii care au fost activi în ultimele 60 de zile." totals_explanation_8: "Proiecte create" totals_explanation_9: "Reprezintă toate proiectele de dezvoltare web sau jocuri create." date_thru_date: "de la __startDateRange__ până la __endDateRange__" interactives: phenomenal_job: "Te-ai descurcat fenomenal!" try_again: "Ups, încearcă din nou!" select_statement_left: "Ups, alege o afirmație din stânga înainte de a apăsa \"Transmite.\"" fill_boxes: "Ups, fi sigur că ai completat toate căsuțele înainte de a apăsa \"Transmite.\"" browser_recommendation: title: "CodeCombat funcționează cel mai bine pe Chrome!" pitch_body: "Pentru o experiență CodeCombat cât mai bună recomandăm să se utilizeze ultima versiune de Chrome. Descarcă ultima versiune de Chrome apăsând butonul de mai jos!" download: "Descarcă Chrome" ignore: "Ignoră" admin: license_type_full: "Cursuri complete" license_type_customize: "Personalizează cursuri" outcomes: school_admin: "Administrator de școală" school_network: "Rețea școlară" school_subnetwork: "Subrețea școlară" classroom: "Clasă" league: student_register_1: "Devino următorul campion IA!" student_register_2: "Înregistrează-te, creează-ți echipa ta sau alătură-te altor echipe pentru a începe să concurezi." student_register_3: "Furnizează informațiile de mai jos pentru a fi eligibil pentru premii." teacher_register_1: "Înregistrează-te pentru a accesa pagina de profil a ligii a clasei tale și pornește clasa." general_news: "Primește mesaje email despre utimele noutăți cu privire la Lgile IA și campionate." team: "echipă" how_it_works1: "Alătură-te __team__" seasonal_arena_tooltip: "Luptă împotriva membrilor de echipă sau alți membrii utilizând cele mai bune aptitudini de programare pe care le ai pentru a câștiga puncte și a te clasa cât mai sus în clasamentul ligii IA înainte de a concura în arena campionatului la sfârșitul sezonului." summary: "Liga IA CodeCombat este atât un simulator unic copetitiv de lupte IA dar și un mototr de jocuri pentru a învăța Python și Javascript." join_now: "Alătură-te acum" tagline: "Liga IA CodeCombat combină curicula aliniată la standarde bazată pe proiecte, programarea de jocuri captivante bazate pe aventură și campionatul anual de programare IA organizat într-o competiție academică anuală cum nu există alta." ladder_subheader: "Utilizează abilitățile tale de programare și strategiile de luptă pentru a urca în clasament!" earn_codepoints: "Câștigă CodePoints finalizând niveluri" codepoints: "CodePoints" free_1: "Accesează arene competitive cu concurenți multiplii, clasamente și campionatul global de programare" free_2: "Câștigă puncte pentru finalizarea nivelurilor de pregătire și concurând în meciuri cot-la-cot" free_3: "Alătură-te echipelor de programare competitive împreună cu prietenii, familia sau colegii de clasă" free_4: "Arată-ți abilitățile de programare și ia acasă premiile mari" compete_season: "Testează toate abilitățile învățate! Concurează împotriva elevilor și jucătorilor din întreaga lume în acest apogeu captivant al sezonului." season_subheading1: "pentru amândouă arenele, cea de Sezon și cea de Turneu, fiecare jucător își programează echipa de “Eroi IA” cu cod scris în Python, Javascript, C++, Lua sau Coffeescript." season_subheading2: "Codul va informa despre strategiile pe care Eroii IA îl vor executa în competițiile față-în-față împotriva altor competitori." team_derbezt: "Învață să scrii cod și câștigă premii sponsorizate de superstarul Mexicanv care este actor, comedian și creator de filme <NAME>." invite_link: "Invită jucători în această echipă trimițăndu-le acest link:" public_link: "Partajează acest clasament cu link-ul public:" end_to_end: "Diferite de alte platforme de e-sport utilizate de școli, noi deținem toată structura de sus până jos, ceea ce înseamnă că nu depindem de nici un dezvoltator de jocuri și nu avem probleme de licențiere. Asta înseamnă deasemenea că putem face modificări personalizate la jocuri pentru școala sau organizația ta." path_success: "Platforma jocului se încadrează în curicula de informatică standard, astfel încât în timp ce elevii se joacă nivelurile jocului, ei fac și muncă de completare a cunoștințelor. Elevii învață să scrie cod și informatică în timp ce se joacă, apoi utilizeză aceste abilități în bătăliile din arenă în timp ce fac practică și se joacă pe aceeași platformă." unlimited_potential: "Structura concursului nostru este adaptabilă oricărui mediu sau situație. Elevii pot participa la un anumit moment în timpul orelor normale de clasă, pot să se joace asincron de acasă sau să participe după bunul plac." edit_team: "Modifică echipa" start_team: "Pornește o echipă" leave_team: "Părăsește echipa" join_team: "Alătură-te echipei" view_team: "Vezi echipa" join_team_name: "Alătură-te echipei __name__" features: "Caracteristici" built_in: "Infrastructură competitivă încorporată" built_in_subheader: "Platforma noastră găzduiește fiecare element al procesului competițional, de la tabele de scor la platforma de joc, bunuri și premii de concurs." custom_dev: "Dezvoltare personalizată" custom_dev_subheader: "Elementele personalizate pentru școala sau organizația ta sunt incluse, plus opțiuni ca pagini de prezentare cu marcaj specific și personaje de joc." comprehensive_curr: "Curiculă completă" comprehensive_curr_subheader: "CodeCombat este o soluție CS aliniată standardelor care susțin profesorii în predarea programării în Javascript și Python, indiferent de experiența lor." # roster_management: "Roster Management Tools" roster_management_subheader: "Monitorizează performanța elevilor pe timpul curiculei și al jocului, și adaugă sau șterge elevi facil." share_flyer: "Partajează afișul nostru despre Liga IA cu instructorii, administratorii, părinții, antrenorii de e-sport sau alte persoane care pot fi interesate." download_flyer: "Descarcă afișul" championship_summary: "Arena campionatului __championshipArena__ este deschisă! Luptă acum în ea în cadrul lunii __championshipMonth__ pentru a câștiga premii în __championshipArena__ __championshipType__." play_arena_full: "Joacă în __arenaName__ __arenaType__" play_arena_short: "Joacă în __arenaName__" view_arena_winners: "Vezi câștigătorii din __arenaName__ __arenaType__ " arena_type_championship: "Arena campionatului" arena_type_regular: "Arena multi-jucător" blazing_battle: "Luptă aprinsă" infinite_inferno: "Infern infinit" mages_might: "Puterea magilor" sorcerers: "Vr<NAME>i" giants_gate: "Poarta giganților" colossus: "Colossus" cup: "Cupa" blitz: "Blitz" clash: "Încleștare" season2_announcement_1: "Este timpul să îți testezi abilitățile de a scrie cod în arena finală a sezonului 2. Vrăjitorul Blitz este viu și oferă o nouă provocare și o nouă tabelă de scor de urcat." season2_announcement_2: "Ai nevoie de mai multă practică? Rămâi la Arena mare a magilorpentru a-ți îmbunătății abilitățile. Ai timp până pe 31 August să joci în ambele arene. Notă: modificări de echilibrare a arenei pot apărea până pe 23 August." season2_announcement_3: "Premii deosebite sunt disponibile pentru jucătorii de top în Vrăjitorul Blitz:" season1_prize_1: "burse de $1,000" # season1_prize_2: "RESPAWN Gaming Chair" season1_prize_3: "Avatar CodeCombat personalizat" season1_prize_4: "Și mult mai multe!" season1_prize_hyperx: "Echipamente perfierice premium HyperX" codecombat_ai_league: "Liga IA CodeCombat" register: "Înregistrare" not_registered: "Neînregistrat" register_for_ai_league: "Înregistrare în Liga IA" world: "Lumea" quickstart_video: "Video de prezentare" arena_rankings: "Calificări arenă" arena_rankings_blurb: "Calificări arenă la liga globală IA" arena_rankings_title: "Clasamentul global al tuturor jucătorilor din această echipă la toate arenele Ligii IA din intervalul de vârstă nespecificat." competing: "Concurenți:" # Competing: 3 students count_student: "elev" # 1 elev count_students: "elevi" # 2 elevi top_student: "Top:" # Top: <NAME> top_percent: "top" # - top 3%) top_of: "din" # (#8 of 35). Perhaps just use "/" if this doesn't translate naturally. arena_victories: "Victorii în Arenă" arena_victories_blurb: "Victoriile recente din Liga globală IA" arena_victories_title: "Victoriile sunt numărate în baza la ultimele 1000 de meciuri jucate asincron de fiecare jucător în fiecare arenă a Ligii IA din care fac parte." count_wins: "victorii" # 100+ wins or 974 wins codepoints_blurb: "1 CodePoint = 1 linie de cod scrisă" codepoints_title: "Un CodePoint este obținut pentru fiecare linie de cod care nu este goală utilizată pentru câștigarea nivelului. Fiecare nivel valorează același număr de CodePoints în concordanță cu soluția standard, indiferent dacă elevul a scris mai multe sau mai puține linii de cod." count_total: "Total:" # Total: 300 CodePoints, or Total: 300 wins join_teams_header: "Alătură-te echipelor & Primește chestii tari!" join_team_hyperx_title: "Alătură-te echipei HyperX și primești 10% reducere" join_team_hyperx_blurb: "30 de membri ai echipelor vor fi aleși aleator să câștige un mousepad de joc gratuit!" join_team_derbezt_title: "Alătură-te echipei <NAME>, și primește un erou unic" join_team_derbezt_blurb: "Deblochează eroul <NAME> de la superstarul mexican Eugenio <NAME>bez!" join_team_ned_title: "Alătură-te echipei N<NAME>, și deblochează eroul lui Ned" join_team_ned_blurb: "Primește eroul unic mânuitor-de-spatulă de la starul YouTube, Încearcă <NAME>!" tournament: mini_tournaments: "Mini campionate" usable_ladders: "Toate scările posibile" make_tournament: "Creează un mini campionat" go_tournaments: "Mergi la mini campionat" class_tournaments: "Clasifică mini campionatele" no_tournaments_owner: "Nu există nici un campionat acum, te rog Creează unul" no_tournaments: "Nu există nici un campionat acum" edit_tournament: "Editează campionatul" create_tournament: "Creează campionatul" payments: student_licenses: "Licențe pentru elevi" computer_science: "Informatică" web_development: "Dezvoltare web" game_development: "Dezvoltare de jocuri" per_student: "per elev" just: "Doar" teachers_upto: "Profesorul poate cumpăra până la" great_courses: "Mai multe cursuri sunt incluse pentru" studentLicense_successful: "Felicitări! Licențele tale vor fi gata într-un minut. Apasă pe Ghidul de noțiuni de bază din zona de Resurse pentru a învăța cum să le prezinți elevilor." onlineClasses_successful: "Felicitări! Plata ta s-a efectuat cu succes. Echipa noastră te va contacta în pașii următori." homeSubscriptions_successful: "Felicitări! Plata ta s-a efectuat cu succes. Accesul de tip premium va fi disponibil în câteva minute." failed: "Plata ta a eșuat, te rog să încerci din nou" session_week_1: "1 sesiune/săptămână" session_week_2: "2 sesiuni/săptămână" month_1: "Lunar" month_3: "Trimestrial" month_6: "Bi-anual" year_1: "Anual" most_popular: "Cel mai popular" best_value: "Valoarea cea mai bună" purchase_licenses: "Cumpără licențe ușor pentru a avea acces la CodeCombat și Ozaria" homeschooling: "Licențe pentru școala făcută acasă" recurring: month_1: 'Facturare recurentă lunară' month_3: 'Facturare recurentă la 3 luni' month_6: 'Facturare recurentă la 6 luni' year_1: 'Facturare recurentă anuală' form_validation_errors: required: "Câmpul este obligatoriu" invalidEmail: "Email invalid" invalidPhone: "Număr de telefon invalid" emailExists: "Adresa de email există deja" numberGreaterThanZero: "Ar trebui să fie un număr mai mare decât 0"
true
module.exports = nativeDescription: "Română", englishDescription: "Romanian", translation: new_home: title: "CodeCombat - Învăța Python și Javascript prin jocuri de programare" meta_keywords: "CodeCombat, python, javascript, jocuri de programare" meta_description: "Învață să scrii cod printr-un joc de programare. Învață Python, Javascript, și HTML ca și când ai rezolva puzzle-uri și învață să îți faci propriile jocuri și site-uri web." meta_og_url: "https://codecombat.com" become_investor: "pentru a devi un investitor în CodeCombat" built_for_teachers_title: "Un joc de programare dezvoltat cu gândul la profesori." built_for_teachers_blurb: "Învățarea copiilor să scrie cod poate fi copleșitoare câteodată. CodeCombat îi ajută pe instructori să-i învețe pe elevi cum să scrie cod în Javascript sau în Python, două din cele mai populare limbaje de programare. Cu o curiculă completă incluzând șase unități care consolidează învățarea prin unități de dezvoltare a jocurilor bazată pe proiecte și a celor de dezvoltare web, copiii vor progresa de-a lungul unei călătorii de la sintaxa de bază până la recursivitate!" built_for_teachers_subtitle1: "Informatică" built_for_teachers_subblurb1: "Începând de la cursul nostru gratuit de Introducere în informatică, studenții își însușesc concepte de bază în programare, cum ar fi bucle while/for, funcții și algoritmi." built_for_teachers_subtitle2: "Dezvoltare de jocuri" built_for_teachers_subblurb2: "Cursanții construiesc labirinturi și utilizează elemente de bază despre manipularea intrărilor ca să programeze propriile jocuri care pot fi partajate mai apoi cu prietenii și familia." built_for_teachers_subtitle3: "Dezvoltare web" built_for_teachers_subblurb3: "Utilizând HTML, CSS și jQuery, cursanții își antrenează mușchii creativității prin programarea propriilor pagini web cu un URL propriu ce poate fi partajat cu colegii de clasă." century_skills_title: "Abilități pentru secolul 21" century_skills_blurb1: "Elevii nu își vor dezvolta doar eroul, se vor dezvolta pe ei înșiși" century_skills_quote1: "Ai greșit ... deci te vei gândi la toate posibilitățile să repari greșeala, iar apoi încerci din nou. Nu aș putea să ajung aici dacă nu aș încerca din greu." century_skills_subtitle1: "Gândire critică" century_skills_subblurb1: "Prin scrierea de cod pentru puzzle-urile încorporate în nivelurile din ce în ce mai incitante, jocurile de programare ale CodeCombat se asigură că gândirea critică este mereu exerseată de copii." century_skills_quote2: "Toată lumea făcea labirinturi, atunci m-am gândit, ‘capturează steagul’ și asta am făcut." century_skills_subtitle2: "Creativitate" century_skills_subblurb2: "CodeCombat încurajează elevii să își arate creativitatea construind și partajând propriile jocuri și pagini web." century_skills_quote3: "Dacă m-am blocat la un nivel. Voi lucra cu persoanele de lângă mine până ce toți ne vom da seama cum să mergem mai departe." century_skills_subtitle3: "Colaborare" century_skills_subblurb3: "În timpul jocului, există oportunități pentru elevi să colaboreze atunci când s-au blocat și să lucreze împreună utilizând ghidul nostru de programare în perechi." century_skills_quote4: "Tot mereu am avut aspirații pentru proiectarea de jocuri video și învățarea programării ... acesta îmi oferă un punct important de plecare." century_skills_quote4_author: "PI:NAME:<NAME>END_PI, clasa a 10-a" century_skills_subtitle4: "Comunicare" century_skills_subblurb4: "scrierea de cod le solicită copiilor să exerseze noi forme de comunicare, inclusiv comunicarea cu calculatorul dar și transmiterea ideilor lor printr-un cod eficient." classroom_in_box_title: "Ne străduim să:" classroom_in_box_blurb1: "Antrenăm fiecare elev astfel încât el să creadă că programarea este pentru el." classroom_in_box_blurb2: "Permitem oricărui instructor să fie confident atunci când predă programare." classroom_in_box_blurb3: "Inspirăm toți liderii din școli pentru a crea un program internațional de informatică." classroom_in_box_blurb4: "" click_here: "Apasă aici" creativity_rigor_title: "Unde creativitatea întâlnește rigoarea" creativity_rigor_subtitle1: "Facem programarea distractivă și învățăm abilități necesare lumii actuale" creativity_rigor_blurb1: "Elevii vor scrie cod real de Python și Javascript în timp ce se joacă care încurajează încercările și erorile, gândirea critică și creativitatea. elevii aplică mai apoi abilitățile de programare învățate dezvoltând propriile jocuri și site-uri web în cursuri bazate pe proiecte." creativity_rigor_subtitle2: "Accesibil tuturor elevilor indiferent de nivel" creativity_rigor_blurb2: "Fiecare nivel CodeCombat este construit pe baza a milioane de date și optimizat să se poată adapta fiecărui cursant. Nivelurile de practică și indiciile îi ajută pe elevi atunci când aceștia se blochează, iar nivelurile tip provocare evaluează ceea ce au învățat elevii prin joc." creativity_rigor_subtitle3: "Construit pentru profesori, indiferent de experiența lor" creativity_rigor_blurb3: "CodeCombat poate fi urmat într-un ritm propriu, curicula aliniată la standarde permite învățarea informaticii de către toată lumea. CodeCombat echipează profesorii cu resursele de învățare necesare și cu un suport dedicat care să îi ajute să fie confidenți și să aibă succes în clasă." featured_partners_title1: "Prezentat în" featured_partners_title2: "Premii & Parteneri" featured_partners_blurb1: "Parteneri ingenioși" featured_partners_blurb2: "Cel mai creativ instrument pentru elevi" featured_partners_blurb3: "Alegerea de top pentru învățare" featured_partners_blurb4: "Partener oficial Code.org" featured_partners_blurb5: "Membru oficial CSforAll" featured_partners_blurb6: "Partener activități Hour of Code" for_leaders_title: "Pentru liderii din școli" for_leaders_blurb: "Un program de informatică cuprinzător și aliniat standardelor" for_leaders_subtitle1: "Implementare ușoară" for_leaders_subblurb1: "Un program bazat pe web care nu necesită suport IT. Pentru a începe aveți nevoie de mai puțin de 5 minute, utilizând Google sau Clever Single Sign-On (SSO)." for_leaders_subtitle2: "Curiculă completă de programare" for_leaders_subblurb2: "O curiculă aliniată standardelor cu resurse de pregătire și de dezvoltare profesională care permit oricărui profesor să predea informatică." for_leaders_subtitle3: "Modalități de utilizare flexibilă" for_leaders_subblurb3: "Indiferent dacă vrei să construiești un cerc de programare la școala generală, o curriculă de pregătire a carierei tehnice sau vrei să predai elemente de introducere în informatică la clasă, CodeCombat este pregătit să se adapteze nevoilor tale." for_leaders_subtitle4: "Abilități din lumea reală" for_leaders_subblurb4: "Elevii prind curaj și își dezvoltă modul de gândire prin provocări de programare care îi pregătește pentru cele 500K+ locuri de muncă disponibile în domeniul IT." for_teachers_title: "Pentru profesori" for_teachers_blurb: "Instrumente pentru descoperirea potențialului elevilor" for_teachers_subtitle1: "Învățare bazată pe proiecte" for_teachers_subblurb1: "Promovează creativitatea, rezolvarea problemelor și încrederea în forțele proprii prin cursuri orientate pe proiecte în care elevii își dezvoltă propriile jocuri și pagini web." for_teachers_subtitle2: "Panoul de lucru al profesorului" for_teachers_subblurb2: "Vizualizează date despre progresul elevilor, descoperă resurse care susțin curicula și accesează suportul în timp real pentru a susține procesul de învățare al elevilor." for_teachers_subtitle3: "Evaluări încorporate" for_teachers_subblurb3: "Personalizează instrucțiunile și asigură-te că elevii înțeleg conceptele de bază cu evaluări formative și sumative." for_teachers_subtitle4: "Diferențiere automată" for_teachers_subblurb4: "Implică toți cursanții dintr-o clasă mixtă în niveluri practice care se adaptează nevoilor de învățare specifice." game_based_blurb: "CodeCombat este un program de informatică bazat pe jocuri în care elevii scriu cod real și își pot urmării personajele în timp real." get_started: "Să începem" global_title: "Alătură-te comunității noastre globale de cursanți și instructori" global_subtitle1: "Cursanți" global_subtitle2: "Linii de cod" global_subtitle3: "Profesori" global_subtitle4: "Țări" go_to_my_classes: "Către clasele mele" go_to_my_courses: "Către cursurile mele" quotes_quote1: "Numește orice program online, eu deja l-am încercat. Nici unul dintre ele nu se compară cu CodeCombat & Ozaria. Orice profesor care vrea să își învețe elevii cum să scrie cod ... să înceapă aici!" quotes_quote2: " Am fost surprins să văd cât de simplu și intuitiv face învățarea informaticii CodeCombat. Notele la examenele AP au fost mai mari decât m-am așteptat și cred că CodeCombat este cel responsabilde acest lucru." quotes_quote3: "CodeCombat a fost cel mai util în învpțarea elevilor mei capabilități de scriere a codului real. Soțul meu este inginer software și mi-a testat toate programele mele. A fost prioritatea lui principală." quotes_quote4: "Părerile … au fost atât de pozitive încât construim o clasă de informatică în jurul CodeCombat. Programul îi antrenează cu adevărat pe elevi cu o platformă de tipul celor de jocuri care este este amuzantă și instructivă în același timp. Continuați cu treaba bine făcută, CodeCombat!" quotes_quote5: "Deși clasa începe în fiecare sâmbătă la ora 7am, fiul meu este atât de încântat încât se trezește înaintea mea! CodeCombat creează o cale pentru fiul meu ca acesta să își îmbunătățească abilitățile de scriere a codului." quotes_quote5_author: "PI:NAME:<NAME>END_PI, părinte" see_example: "Vezi exemplul" slogan: "Cel mai antrenat mod de a învăța informatică" slogan_power_of_play: "Învață să programezi prin puterea jocului" teach_cs1_free: "Predă informatică gratuit" teachers_love_codecombat_title: "Profesorii iubesc CodeCombat" teachers_love_codecombat_blurb1: "Raportează că elevii lor îndrăgesc utilizarea CodeCombat pentru învățarea programării" teachers_love_codecombat_blurb2: "Recomandă CodeCombat altor profesori de informatică" teachers_love_codecombat_blurb3: "Spun că CodeCombat îi ajută să sprijine elevii cu abilitățile de rezolvare a problemelor" teachers_love_codecombat_subblurb: "În parteneriat cu McREL International, un lider în îndrumarea și evaluarea bazată pe cercetare a tehnologiilor educaționale." top_banner_blurb: "Părinți, dați-i copilului vostru darul programării și a instruirii personalizate cu profesorii noștri!" top_banner_summer_camp: "Înscrierile sunt acum deschise pentru taberele de vară de programare – întreabă-ne despre sesiunile virtuale de o săptămână începând doar de la $199." top_banner_blurb_funding: "Nou: Ghidul de resurse de finațare CARES Act pentru fondurile ESSER și GEER pentru programele tale de CS." try_the_game: "Încearcă jocul" classroom_edition: "Ediția pentru clasă:" learn_to_code: "Învață să scrii cod:" play_now: "Joacă acum" im_a_parent: "Sunt părinte" im_an_educator: "Sunt instructor" im_a_teacher: "Sunt profesor" im_a_student: "Sunt elev" learn_more: "Aflați mai multe" classroom_in_a_box: "O clasă „la cutie„ pentru a preda informatica." codecombat_is: "CodeCombat este o platformă <strong>pentru elevi</strong> să învețe informatică în timp ce se joacă un joc real." our_courses: "Cursurile noastre au fost testate în mod special <strong>pentru a excela în clasă</strong>, chiar și pentru profesorii cu puțină sau fără experiență prealabilă în informatică." watch_how: "Privește cum CodeCombat transformă modul în care oamenii învață informatică." top_screenshots_hint: "Elevii scriu cod și văd modificările lor actualizate în timp real" designed_with: "Proiectat cu gândul la profesori" real_code: "Cod scris, real" from_the_first_level: "de la primul nivel" getting_students: "Ajungerea elevilor la nivelul de a scrie cod cât mai repede posibil este critică în învățarea sinatxei programării și a structurii corecte." educator_resources: "Resurse pentru instructori" course_guides: "și ghiduri de curs" teaching_computer_science: "Predarea informaticii nu necesită o diplomă costisitoare, deoarece furnizăm unelte care să suțină profesori din toate mediile." accessible_to: "Accesibil pentru" everyone: "toată lumea" democratizing: "Democrația procesului de învățare a programării stă la baza filozofiei noastre. Toată lumea ar trebui să poată să învețe programare." forgot_learning: "Eu cred că ei de fapt au uitat că învață ceva." wanted_to_do: " scrierea de cod este ceva ce întotdeauna mi-am dorit să fac, și niciodată nu m-am gândit că aș putea să învăț în școală." builds_concepts_up: "Îmi place cum CodeCombat construiește conceptele. Este foarte ușor să înțelegi și amuzant să îți dai seama." why_games: "De ce este importantă învățarea prin jocuri?" games_reward: "Jocul răsplătește efortul productiv." encourage: "Jocul este un mediu care încurajează interacțiunea, descoperirea, și încercarea-și-eroarea. Un joc bun provoacă jucătorul să își îmbunătățească abilitățile în timp, care este un proces similar cu al elevilor când învață." excel: "Jocul este mai mult decât plin de satisfacții" struggle: "efort productiv" kind_of_struggle: "tipul de efort care rezultă din procesul de învățare care este antrenant și" motivating: "motivant" not_tedious: "nu plictisitor." gaming_is_good: "Studiile sugerează că jocurile sunt bune pentru creierul copiilor. (E adevarat!)" game_based: "Când sistemele de învățare bazate pe joc sunt" compared: "comparate" conventional: "metodele de evaluare convenționale, diferența este clară: jocurile sunt mai bune să ajute elevii să rețină cunoștințe, să se concentreze și" perform_at_higher_level: "să performeze la un nivel mai înalt" feedback: "Jocurile furnizează de asemenea un feedback în timp real care le permite elevilor să-și ajusteze calea către soluție și să înțeleagă concepte mai holistic, în loc să fie limitați doar la răspunsuri “corect” sau “incorect”." real_game: "Un joc real, jucat cu programare reală." great_game: "Un joc bun este mai mult decât insigne și realizări - este despre călătoria unui jucător, puzzle-uri bine făcute și abilitatea de abordare a provocărilor prin acțiune și încredere." agency: "CodeCombat este un joc care dă jucătorilor acea putere de a acționa și încredere prin intermediul motorului nostru de scriere cod, care îi ajută pe elevii începători și avansați deopotrică să scrie cod corect și valid." request_demo_title: "Pune-i pe elevii tăi să înceapă astăzi!" request_demo_subtitle: "Cere un demo și pune-i pe elevii tăi să înceapă în mai puțin de o oră." get_started_title: "Creează clasa azi" get_started_subtitle: "Creează o clasă, adaugă elevii și monitorizează progresul lor în timp ce ei învață informatică." request_demo: "Cere o demonstrație" request_quote: "Cere o ofertă de preț" setup_a_class: "Creează o clasă" have_an_account: "Aveți un cont?" logged_in_as: "În prezent sunteți conectat(ă) ca" computer_science: "Cursurile în ritm personal acoperă de la sintaxa de bază până la concepte avansate" ffa: "Gratuit pentru toți elevii" coming_soon: "Mai multe vor apărea în curând!" courses_available_in: "Cursurile sunt disponibile în Javascript și Python. Cursurile de Dezvoltare web utilizează HTML, CSS și jQuery." boast: "Se laudă cu ghicitori care sunt suficient de complexe să fascineze jucătorii și programatorii deopotrivă." winning: "O combinație câștigătoare de joc RPG și temă la programare care conduce la o educație prietenoasă și cu adevărat distractivă pentru copii." run_class: "Tot ceea ce ai nevoie pentru a ține clasa de informatică în școala ta astăzi, nu este nevoie de cunoștințe în CS." goto_classes: "Vezi clasa mea" view_profile: "Vezi profilul meu" view_progress: "Vezi progres" go_to_courses: "Vezi cursurile mele" want_coco: "Vrei CodeCombat în școala ta?" educator: "Instructor" student: "PI:NAME:<NAME>END_PI" our_coding_programs: "Programele noastre de programare" codecombat: "CodeCombat" ozaria: "Ozaria" codecombat_blurb: "Jocul nostru de scriere cod original. Recomndat pentru părinți, persoane, instructori și elevi care doresc să experimenteze unul dintre jocurile de programare cel mai iubit din lume." ozaria_blurb: "Un joc de aventură și program de informatică unde elevii stăpânesc magia pierdută a codului pentru a salva lumea. Recomndat pentru instructori și elevi." try_codecombat: "Încearcă CodeCombat" try_ozaria: "Încearcă Ozaria" explore_codecombat: "Explorează CodeCombat" explore_ai_league: "Explorează liga IA" explore_ozaria: "Explorează Ozaria" explore_online_classes: "Explorează clasele online" explore_pd: "Explorează dezvoltarea profesională" new_adventure_game_blurb: "Ozaria este noul nostru joc de aventură nou-nouț și soluția ta la cheie pentru predare informaticii. Notele noastre pentru elevi __slides__ și pentru profesori fac ca planificarea și prezentarea lecțiilor să fie ușoară și rapidă." lesson_slides: "fișe lecții" pd_blurb: "Învață abilitățile necesare pentru predarea efectivă a informaticiicu cursul nostru de dezvoltare profesională auto-direcționat și acreditat CSTA. Obține 40 de ore în credite în orice moment, de pe orice dispozitiv. Face pereche bună cu clasele Ozaria." ai_league_blurb: "scrierea de cod în mediu competitiv nu a fost niciodată mai eroică cu aceste ligi educaționale de e-sport, care sunt în același timp niște simulatoare de lupă IA unice cât și motoare de joc pentru a învățarea scrierii de cod real." codecombat_live_online_classes: "Clase online în timp real CodeCombat" learning_technology_blurb: "Jocul nostru original învață aptitudini din lumea reală prin puterea jocului. Curicula bine construită construiește în mod sistematic experiența și cunoștințele elevului în timp ce ei progresează." learning_technology_blurb_short: "Tehnologia noastră inovativă bazată pe joc a transformat modul în care elevii învață să scrie cod." online_classes_blurb: "Clasele noastre online de sciere cod combină puterea jocului și instrucțiunile personalizate pentru o experiență pe care copilul tău nu o va îndrăgi. Cu cele două opțiuni disponibile, private sau de grup, acestea sunt sistemele de învățare la distanță care merg." for_educators: "Pentru instructori" for_parents: "Pentru părinți" for_everyone: "Pentru toată lumea" what_our_customers_are_saying: "Ce zic clienții noștri" game_based_learning: "Învățare pe bază de joc" unique_approach_blurb: "Cu abordarea noastră unică, elevii adoptă învățarea în timp ce joacă și scriu cod încă de la începutul aventurii lor, promovând învățarea activă și îmbunătățirea modului de a gândi." text_based_coding: "Programare pe bază de text" custom_code_engine_blurb: "Motorul și interpretorul nostru personalizat este proiectat pentru începători, pentru învățarea limbajelor de programare reale Python, Javascript și C++ utilizând termeni umani, prietenoase cu începătorii." student_impact: "Impact asupra elevilor" help_enjoy_learning_blurb: "Produsele noastre au ajutat peste 20 de milioane de elevi care s-au bucurat să învețe informatică, învățându-i să fie elevi critici, confidenți și creativi. Noi îi implicăm pe toți elevii, indiferent de experiență, ajutându-i să-și construiască o cale de succes în informatică." global_community: "Alătură-te comunității globale" million: "__num__ milioane" billion: "__num__ bilioane" nav: educators: "Instructori" follow_us: "Urmăriți-ne" general: "General" map: "Hartă" play: "Niveluri" # The top nav bar entry where players choose which levels to play community: "Communitate" courses: "Cursuri" blog: "Blog" forum: "Forum" account: "Cont" my_account: "Contul meu" profile: "Profil" home: "Acasă" contribute: "Contribuie" legal: "Confidențialitate și termeni" privacy: "Notă de confidențialitate" about: "Despre" impact: "Impact" contact: "Contact" twitter_follow: "Urmărește" my_classrooms: "Clasa mea" my_courses: "Cursurile mele" my_teachers: "Profesorii mei" careers: "Cariere" facebook: "Facebook" twitter: "Twitter" create_a_class: "Creează o clasă" other: "Altele" learn_to_code: "Învață să scrii cod!" toggle_nav: "Schimbare navigație" schools: "Școli" get_involved: "Implică-te" open_source: "Open source (GitHub)" support: "Suport" faqs: "Întrebări" copyright_prefix: "Copyright" copyright_suffix: "Toate drepturile rezervate." help_pref: "Ai nevoie de ajutor? Email" help_suff: "și vom lua legătura cu tine!" resource_hub: "Zona de resurse" apcsp: "Principiile AP CS" parent: "Părinți" esports: "E-sporturi" browser_recommendation: "Pentru cea mai bună experință vă recomandăm să utilizați ultima versiune de Chrome. Descarcă navigatorul web de aici!" ozaria_classroom: "Clasa Ozaria" codecombat_classroom: "Clasa CodeCombat" ozaria_dashboard: "Panou de lucru Ozaria" codecombat_dashboard: "Panou de lucru CodeCombat" professional_development: "Dezvoltare profesională" new: "Nou!" admin: "Admin" api_dashboard: "Panou de lucru API" funding_resources_guide: "Ghid resurse de finanțare" modal: close: "Închide" okay: "Okay" cancel: "Anulează" not_found: page_not_found: "Pagina nu a fost gasită" diplomat_suggestion: title: "Ajută la traducrea CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Avem nevoie de abilitățile tale lingvistice." pitch_body: "CodeCombat este dezvoltat în limba engleza, dar deja avem jucători din toate colțurile lumii. Mulți dintre ei vor să joace în română și nu vorbesc engleză. Dacă poți vorbi ambele limbi te rugăm să te gândești dacă ai dori să devi un Diplomat și să ne ajuți să traducem atât jocul cât și site-ul." missing_translations: "Până când nu putem traduce totul în română, vei vedea limba engleză acolo unde limba română nu este displonibilă." learn_more: "Află mai multe despre cum să fi un Diplomat" subscribe_as_diplomat: "Înscrie-te ca Diplomat" new_home_faq: what_programming_languages: "Ce limbaje de programare sunt disponibile?" python_and_javascript: "În prezent lucrăm cu Python și Javascript." why_python: "De ce să alegi Python?" why_python_blurb: "Python este prietenos pentru începători dar este în prezent utilizat de majoritatea corporațiilor (cum este Google). Dacă aveți cursanți mai tineri sau începători, vă recomandăm cu încredere Python." why_javascript: "De ce să alegi Javascript?" why_javascript_blurb: "Javascript este limbajul web și este utilizat în aproape toate site-urile web. Vei prefera să alegi Javascript dacă ai în plan se studiezi dezvoltarea web. Am făcut deasemenea ca tranziția elevilor de la Python la dezvoltarea web pe bază de Javascript să fie ușoară." javascript_versus_python: "Sintaxa Javascript este un pic mai dificilă pentru începători decât cea Python, de aceea dacă nu te poți decide între cele două, noi îți recomandăm Python." how_do_i_get_started: "Cum pot să încep?" getting_started_1: "Creează un cont de profesor" getting_started_2: "Creează o clasă" getting_started_3: "Addaugă elevi" getting_started_4: "Stai și observă elevii cum se delectează învățând să scrie cod" main_curriculum: "Pot utliza CodeCombat sau Ozaria ca și curiculă de bază?" main_curriculum_blurb: "Absolut! Am alocat timp consultațiilor cu specialiștii în educație pentru a dezvola curicule pentru clasă și materiale special concepute pentru profesorii care utilizează CodeCombat sau Ozaria fără ca aceștia să aibă cunoștințe prealabile de informatică. Multe școli implementează CodeCombat și/sau Ozaria ca și curiculă de bază pentru informatică." clever_instant_login: "CodeCombat și Ozaria au suport pentru Clever Instant Login?" clever_instant_login_blurb: "Da! Verifică __clever__ pentru mai multe detalii cum să începi." clever_integration_faq: "Întrebări despre integrarea Clever" google_classroom: "Dar Google Classroom?" google_classroom_blurb1: "Da! Fi sigur că utilizezi Google Single Sign-On (SSO) Modal pentru a te înregistra în contul tău de profesor. Dacă deja ai un cont pe care îl utilizezi pentru Google email, utilizează Google SSO modal pentru a te autentifica următoarea dată. În Creează Class modal, vei găsi o opțiune să faci legătura cu Google Classroom. În prezent avem suport numai pentru Google Classroom rostering." google_classroom_blurb2: "Notă: trebuie să utilizezi Google SSO să te autentifici sau să te autentifici măcar o dată pentru a vedea opțiunile de integrare Google Classroom." how_much_does_it_cost: "Cât de mult costă să acesez toate cursurile și resursele disponibile?" how_much_does_it_cost_blurb: "Personalizăm soluțiile pentru școli și districte și vom lucra cu tine pentru a înțelege cerința de utilizare, contextul și bugetul. __contact__ pentru mai multe detalii! Vezi de asemenea __funding__ pentru informații cu privire la accesarea surselor de finanțare CARES Act cum sunt ESSER și GEER." recommended_systems: "Există o recomandare cu privire la navigatorul web și la sistemul de operare?" recommended_systems_blurb: "CodeCombat și Ozaria rulează cel mai bine pe calculatoare cu cel puțin 4GB de RAM, pe navigatoare web moderne cum sunt Chrome, Safari, Firefox sau Edge. Chromebooks cu 2GB de RAM pot avea probleme minore de grafică în cursurile mai avansate. Un minim de 200 Kbps lățime de bandă pentru fiecare elev este necesară, deși este recomandat 1+ Mbps." other_questions: "Dacă ai și alte întrebări, te rog __contact__." play: title: "Joacă nivelele CodeCombat - Învață Python, Javascript și HTML" meta_description: "Învață programare cu un joc de scris cod pentru începători. Învață Python și Javascript în timp ce rezolvi labirinturi, Creează propriile jocuri și crește-ți nivelul. Provoacă prietenii în nivelurile din arena multi-utilizator!" level_title: "__level__ - Învață să scrii cod în Python, Javascript, HTML" video_title: "__video__ | Nivel video" game_development_title: "__level__ | Dezvoltare jocuri" web_development_title: "__level__ | Dezvoltare web" anon_signup_title_1: "CodeCombat are o" anon_signup_title_2: "versiune pentru clasă!" anon_signup_enter_code: "Introdu codul de clasă:" anon_signup_ask_teacher: "Nu ai unul? întreabă profesorul!" anon_signup_create_class: "Vrei să creezi o clasă?" anon_signup_setup_class: "Creează o clasă, adaugă elevii și monitorizează progresul!" anon_signup_create_teacher: "Creează un cont de profesor gratuit" play_as: "Joacă ca" # Ladder page get_course_for_class: "Alocă Dezvoltarea de jocuri și altele la clasa ta!" request_licenses: "Contactează specialiștii noștri școlari pentru detalii." compete: "Concurează!" # Course details page spectate: "Spectator" # Ladder page simulate_all: "Simulează totul" players: "jucători" # Hover over a level on /play hours_played: "ore jucate" # Hover over a level on /play items: "Articole" # Tooltip on item shop button from /play unlock: "Deblochează" # For purchasing items and heroes confirm: "Confirmă" owned: "Deținute" # For items you own locked: "Blocate" available: "Disponibile" skills_granted: "Abilități acordate" # Property documentation details heroes: "Eroi" # Tooltip on hero shop button from /play achievements: "Realizări" # Tooltip on achievement list button from /play settings: "Setări" # Tooltip on settings button from /play poll: "Sondaj" # Tooltip on poll button from /play next: "Următorul" # Go from choose hero to choose inventory before playing a level change_hero: "Schimbă eroul" # Go back from choose inventory to choose hero change_hero_or_language: "Schimbă eroul sau limba" buy_gems: "Cumpără pietre prețioase" subscribers_only: "Doar pentru abonați!" subscribe_unlock: "Pentru deblocare abonează-te!" subscriber_heroes: "Abonează-te azi pentru a debloca imediat PI:NAME:<NAME>END_PIa, HPI:NAME:<NAME>END_PIbaum și PI:NAME:<NAME>END_PIori!" subscriber_gems: "Abonează-te azi pentru a cumpăra acest erou cu pietre prețioase!" anonymous: "PI:NAME:<NAME>END_PI" level_difficulty: "Dificultate: " awaiting_levels_adventurer_prefix: "Lansăm niveluri noi în fiecare săptămână." awaiting_levels_adventurer: "Înscrie-te ca aventurier " awaiting_levels_adventurer_suffix: "pentru a fi primul care joacă nivele noi." adjust_volume: "Reglează volumul" campaign_multiplayer: "Arene multi-jucător" campaign_multiplayer_description: "... în care lupți cot-la-cot contra altor jucători." brain_pop_done: "Ai înfrânt căpcăunii cu codul tău! Ai învins!" brain_pop_challenge: "Ca și provocare joacă din nou utilizând un limbaj de programare diferit!" replay: "Joacă din nou" back_to_classroom: "Înapoi la clasă" teacher_button: "Pentru profesori" get_more_codecombat: "Mai mult CodeCombat" code: if: "dacă" # Keywords--these translations show up on hover, so please translate them all, even if it's kind of long. (In the code editor, they will still be in English.) else: "altfel" elif: "altfel dacă" while: "atăta timp cât" loop: "buclă" for: "pentru" break: "oprește" continue: "continuă" pass: "pass" return: "întoarce" then: "atunci" do: "execută" end: "sfârșit" function: "funcție" def: "definește" var: "variabilă" self: "se referă la el însuși" hero: "erou" this: "acesta (aceasta)" or: "sau" "||": "sau" and: "și" "&&": "și" not: "not (negație)" "!": "not (negație)" "=": "atribuie" "==": "egal cu" "===": "strict egal cu" "!=": "nu este egal cu" "!==": "nu este strict egal cu" ">": "mai mare decât" ">=": "mai mare sau egal decât" "<": "mai mic decât" "<=": "mai mic sau egal cu" "*": "înmulțit cu" "/": "împărțit la" "+": "plus" "-": "minus" "+=": "adaugă și atribuie" "-=": "scade și atribuie" True: "Adevărat" true: "adevărat" False: "Fals" false: "fals" undefined: "nedefinit" null: "Zero/Fără valoare cand nu este obiect" nil: "Zero/Fără valoare pentru obiecte" None: "Nici unul/una" share_progress_modal: blurb: "Faci progrese mari! Spune-le părinților cât de mult ai învățat cu CodeCombat." email_invalid: "Adresă email invalidă." form_blurb: "Introdu adresa email al unui părinte mai jos și le vom arăta!" form_label: "Adresă email" placeholder: "adresă email" title: "Excelentă treabă, ucenicule" login: sign_up: "Creează cont" email_or_username: "Email sau nume de utilizator" log_in: "Conectare" logging_in: "Se conectează" log_out: "Deconectare" forgot_password: "PI:PASSWORD:<PASSWORD>END_PI?" finishing: "Terminare" sign_in_with_facebook: "Conectează-te cu Facebook" sign_in_with_gplus: "Conectează-te cu Google" signup_switch: "Dorești să creezi un cont?" accounts_merge_confirmation: "Există un cont asociat cu adresa de email a acestui cont Google. Vrei să unim aceste conturi?" signup: complete_subscription: "Completează abonamentul" create_student_header: "Creează cont elev" create_teacher_header: "Creează cont profesor" create_individual_header: "Creează cont individual" email_announcements: "Primește anunțuri despre niveluri și îmbunătățiri ale CodeCombat!" sign_in_to_continue: "Conectează-te sau creează un cont pentru a continua" create_account_to_submit_multiplayer: "Creează un cont gratuit pentru a-ți clasifica IA multi-jucător și explorează tot jocul!" teacher_email_announcements: "Înformează-mă cu noutățile despre noi resurse pentru profesori, curicule și coursuri!" creating: "Se creează contul..." sign_up: "Înscrie-te" log_in: "conectează-te cu parolă" login: "Conectare" required: "Trebuie să te înregistrezi înaite să mergi mai departe." login_switch: "Ai deja un cont?" optional: "opțional" connected_gplus_header: "Te-ai conectat cu succes cu Google+!" connected_gplus_p: "Termină înregistrarea pentru a te putea autentifica cu contul Google+." connected_facebook_header: "Te-ai conectat cu succes cu Facebook!" connected_facebook_p: "Termină înregistrarea pentru a te putea autentifica cu contul Facebook." hey_students: "Elevi, introduceți codul clasei dat de profesor." birthday: "Ziua de naștere" parent_email_blurb: "Știm că abia aștepți să înveți programare &mdash; și noi suntem nerăbdători! Părinții tăi vor primi un email cu detalii despre cum să îți creeze un cont. Trimite email {{email_link}} dacă ai întrebări." classroom_not_found: "Nu există clase cu acest cod de clasă. Verifică ceea ce ai scris sau întreabă profesorul pentru ajutor." checking: "Verificare..." account_exists: "Acest e-mail este deja utilizat:" sign_in: "Autentificare" email_good: "Email-ul arată bine!" name_taken: "Nume de utilizator deja folosit! Încearcă {{suggestedName}}?" name_available: "Nume utilizator disponibil!" name_is_email: "Nume de utilizator nu poate fi o adresă email" choose_type: "Alege tipul de cont:" teacher_type_1: "Predă programare utilizând CodeCombat!" teacher_type_2: "Creează clasa" teacher_type_3: "Instrucțiuni accesare curs" teacher_type_4: "Vezi progresul elevilor" signup_as_teacher: "Autentificare profesor" student_type_1: "Învață să programezi în timp ce joci un joc captivant!" student_type_2: "Joacă cu clasa ta" student_type_3: "Concurează în arenă" student_type_4: "Alege eroul!" student_type_5: "Pregătește codul de clasă!" signup_as_student: "Autentificare ca elev" individuals_or_parents: "Persoane & Părinți" individual_type: "Pentru jucători care învață să scrie cod în afara unei clase. Părinții trebuie să se înregistreze pentru un cont aici." signup_as_individual: "Înregistrare persoană" enter_class_code: "Introdu codul de clasă" enter_birthdate: "Introdu data nașterii:" parent_use_birthdate: "Părinți, utilizați data dvs de naștere." ask_teacher_1: "Întreabă profesorul despre codul de clasă." ask_teacher_2: "Nu ești parte dintr-o clasă? Creează un" ask_teacher_3: "cont individual" ask_teacher_4: " în loc." about_to_join: "Ești pe cale să te alături:" enter_parent_email: "Introdu adresa de email a părintelui dvs .:" parent_email_error: "Ceva a mers greșit când am încercat să trimitem email. Verifică adresa de email și mai încearcă o dată." parent_email_sent: "Am trimis un email cu instrucțiuni cum să creezi un cont. Roagă părinții să-și verifice căsuța de email." account_created: "Cont creat!" confirm_student_blurb: "Notează pe ceva informațiile pentru a nu le uita. Profesorul tău te poate ajuta să îți resetezi parola în orice moment." confirm_individual_blurb: "Notează pe ceva informațiile de autentificare în caz că vei avea nevoie de ele mai târziu. Verifică căsuța de email ca să îți poți recupera contul dacă îți vei uita parola - verifică căsuța de email!" write_this_down: "Notează asta:" start_playing: "Începe jocul!" sso_connected: "Conectare reușită cu:" select_your_starting_hero: "Alege eroul de început:" you_can_always_change_your_hero_later: "Poți schimba eroul mai târziu." finish: "Termină" teacher_ready_to_create_class: "Ești gata să creezi prima ta clasă!" teacher_students_can_start_now: "Elevii vor putea să înceapă să joace primul curs, Introducere în informatică, immediat." teacher_list_create_class: "În următorul ecran vei putea crea o nouă clasă." teacher_list_add_students: "Adaugă elevi la clasă la link-ul Vezi clasă, apoi trimite elevilor codul de clasă sau URL-ul. Poți de asemenea să îi inviți prin email dacă aceștia au adrese de email." teacher_list_resource_hub_1: "Verifică" teacher_list_resource_hub_2: "Ghidurile de curs" teacher_list_resource_hub_3: "pentru soluțiile fiecărui nivel și " teacher_list_resource_hub_4: "Zona de resurse " teacher_list_resource_hub_5: "pentru ghiduri privind curicula, activitățile și altele!" teacher_additional_questions: "Asta e tot! Dacă ai nevoie de mai mult ajutor sau ai întrebări, contactează-ne la __supportEmail__." dont_use_our_email_silly: "Nu scrie adresa noastră de email aici! Pune adresa de email a unui părinte." want_codecombat_in_school: "Vrei să joci CodeCombat tot timpul?" eu_confirmation: "Sunt de acord să permit CodeCombat să stocheze datele mele pe un server din SUA." eu_confirmation_place_of_processing: "Află mai multe despre riscuri posibile." eu_confirmation_student: "Dacă nu ești sigur, întreabă-ți profesorul." eu_confirmation_individual: "Dacă nu vrei să îți păstrăm datele pe serverele din SUA, poți juca tot timpul în mod anonim fără salvarea codului scris." password_requirements: "de la 8 până la 64 de caractere fără repetare" invalid: "Invalid" invalid_password: "PI:PASSWORD:<PASSWORD>END_PI" with: "cu" want_to_play_codecombat: "Nu, nu am una dar vreau să joc CodeCombat!" have_a_classcode: "Ai un cod de clasă?" yes_i_have_classcode: "Da, am un cod de clasă!" enter_it_here: "Introdu codul aici:" recover: recover_account_title: "Recuperează cont" send_password: "PI:PASSWORD:<PASSWORD>END_PI" recovery_sent: "Email de recuperare trimis." items: primary: "Primar" secondary: "Secundar" armor: "Armură" accessories: "Accesorii" misc: "Diverse" books: "Cărți" common: default_title: "CodeCombat - Jocuri de scris cod pentru a învăța Python și Javascript" default_meta_description: "Învață să scrii cod prin programarea unui joc. Învață Python, Javascript și HTML ca și când ai rezolva puzzle-uri și învață să îți faci propriile jocuri și site-uri web." back: "Înapoi" # When used as an action verb, like "Navigate backward" coming_soon: "în curând!" continue: "Continuă" # When used as an action verb, like "Continue forward" next: "Următor" default_code: "Cod implicit" loading: "Se încarcă..." overview: "Prezentare generală" processing: "Procesare..." solution: "Soluţie" table_of_contents: "Cuprins" intro: "Introducere" saving: "Se salvează..." sending: "Se trimite..." send: "Trimite" sent: "Trimis" cancel: "Anulează" save: "Salvează" publish: "Publică" create: "Creează" fork: "Fork" play: "Joacă" # When used as an action verb, like "Play next level" retry: "Reîncearcă" actions: "Acţiuni" info: "Info" help: "Ajutor" watch: "Urmărește" unwatch: "Nu mai urmări" submit_patch: "Trimite patch" submit_changes: "Trimite modificări" save_changes: "Salvează modificări" required_field: "obligatoriu" submit: "Transmite" replay: "Rejoacă" complete: "Complet" pick_image: "Alege imagine" general: and: "și" name: "Nume" date: "Dată" body: "Corp" version: "Versiune" pending: "În așteptare" accepted: "Acceptat" rejected: "Respins" withdrawn: "Retras" accept: "Acceptă" accept_and_save: "Acceptă și salvează" reject: "Respinge" withdraw: "Retrage" submitter: "Expeditor" submitted: "Expediat" commit_msg: "Înregistrează mesajul" version_history: "Istoricul versiunilor" version_history_for: "Istoricul versiunilor pentru: " select_changes: "Selectați două schimbări de mai jos pentru a vedea diferenţa." undo_prefix: "Undo" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Redo" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Joaca previzualizarea nivelului curent" result: "Rezultat" results: "Rezultate" description: "Descriere" or: "sau" subject: "Subiect" email: "Email" password: "PI:PASSWORD:<PASSWORD>END_PI" confirm_password: "PI:PASSWORD:<PASSWORD>END_PI" message: "Mesaj" code: "Cod" ladder: "Clasament" when: "când" opponent: "oponent" rank: "Rang" score: "Scor" win: "Victorie" loss: "Înfrângere" tie: "Remiză" easy: "Ușor" medium: "Mediu" hard: "Greu" player: "PI:NAME:<NAME>END_PI" player_level: "Nivel" # Like player level 5, not like level: Dungeons of Kithgard warrior: "Războinic" ranger: "Arcaș" wizard: "Vrăjitor" first_name: "PI:NAME:<NAME>END_PI" last_name: "PI:NAME:<NAME>END_PI" last_initial: "Inițială nume" username: "Nume de utilizator" contact_us: "Contactează-ne" close_window: "Închide fereastra" learn_more: "Află mai mult" more: "Mai mult" fewer: "Mai puțin" with: "cu" chat: "Chat" chat_with_us: "Vorbește cu noi" email_us: "Trimite-ne email" sales: "Vânzări" support: "Suport" here: "aici" units: second: "secundă" seconds: "secunde" sec: "sec" minute: "minut" minutes: "minute" hour: "oră" hours: "ore" day: "zi" days: "zile" week: "săptămână" weeks: "săptămâni" month: "lună" months: "luni" year: "an" years: "ani" play_level: back_to_map: "Înapoi la hartă" directions: "Direcții" edit_level: "Modifică nivel" keep_learning: "Continuă să înveți" explore_codecombat: "Explorează CodeCombat" finished_hoc: "Am terminat Hour of Code" get_certificate: "Obține certificatul!" level_complete: "Nivel terminat" completed_level: "Nivel terminat:" course: "Curs:" done: "Terminat" next_level: "Următorul nivel" combo_challenge: "Provocare combinată" concept_challenge: "Provocare concept" challenge_unlocked: "Provocare deblocată" combo_challenge_unlocked: "Provocare combinată deblocată" concept_challenge_unlocked: "Provocare concept deblocată" concept_challenge_complete: "Provocare concept terminată!" combo_challenge_complete: "Provocare combinată terminată!" combo_challenge_complete_body: "Foarte bine, se pare că stai foarte bine în înțelegerea __concept__!" replay_level: "Joacă din nou nivelul" combo_concepts_used: "__complete__/__total__ concepte utilizate" combo_all_concepts_used: "Ai utilizat toate conceptele posibile pentru a rezolva provocarea. Foarte bine!" combo_not_all_concepts_used: "Ai utilizat __complete__ din __total__ concepte posibile pentru a rezolva provocarea. Încearcă să utilizezi toate cele __total__ concepte următoarea dată!" start_challenge: "Start provocare" next_game: "Următorul joc" languages: "Limbi" programming_language: "Limbaj de programare" show_menu: "Arată meniul jocului" home: "Acasă" # Not used any more, will be removed soon. level: "Nivel" # Like "Level: Dungeons of Kithgard" skip: "Sări peste" game_menu: "Meniul Jocului" restart: "Restart" goals: "Obiective" goal: "Obiectiv" challenge_level_goals: "Obiectivele nivelului tip provocare" challenge_level_goal: "Obiectivul nivelului tip provocare" concept_challenge_goals: "Obiectivele provocării concept" combo_challenge_goals: "Obiectivele provocării combinate" concept_challenge_goal: "Obiectivul provocării concept" combo_challenge_goal: "Obiectivul provocării combinate" running: "Rulează..." success: "Success!" incomplete: "Incomplet" timed_out: "Ai rămas fără timp" failing: "Eşec" reload: "Reîncarcă" reload_title: "Reîncarcă tot codul?" reload_really: "Ești sigur că vrei să reîncarci nivelul de la început?" reload_confirm: "Reîncarca tot" restart_really: "Ești sigur că vrei să joci din nou nivelul? Vei pierde tot codul pe care l-ai scris." restart_confirm: "Da, joc din nou" test_level: "Nivel de test" victory: "Victorie" victory_title_prefix: "" victory_title_suffix: " Terminat" victory_sign_up: "Înscrie-te pentru a salva progresul" victory_sign_up_poke: "Vrei să-ți salvezi codul? Creează un cont gratuit!" victory_rate_the_level: "Cât de amuzant a fost acest nivel?" victory_return_to_ladder: "Înapoi la clasament" victory_saving_progress: "Salvează progresul" victory_go_home: "Mergi acasă" victory_review: "Spune-ne mai multe!" victory_review_placeholder: "Cum a fost nivelul?" victory_hour_of_code_done: "Ai terminat?" victory_hour_of_code_done_yes: "Da, am terminat Hour of Code™!" victory_experience_gained: "Ai câștigat XP" victory_gems_gained: "Ai câștigat pietre prețioase" victory_new_item: "Articol nou" victory_new_hero: "Erou nou" victory_viking_code_school: "Oau, acesta a fost un nivel greu! Daca nu ești deja un dezvoltator de software, ar trebui să fi. Tocmai ai fost selectat pentru acceptare în Viking Code School, unde poți să îți dezvolți abilitățile la nivelul următor și să devi un dezvoltator web profesionist în 14 săptămâni." victory_become_a_viking: "Devin-o Viking" victory_no_progress_for_teachers: "Progresul nu este salvat pentru profesori. Dar, poți adăuga un cont de elev la clasa ta pentru tine." tome_cast_button_run: "Execută" tome_cast_button_running: "În execuție" tome_cast_button_ran: "S-a executat" tome_cast_button_update: "Actualizare" tome_submit_button: "Trimite" tome_reload_method: "Reîncarcă codul original pentru a restarta nivelul" tome_your_skills: "Abilitățile tale" hints: "Indicii" videos: "Filme" hints_title: "Indiciul {{number}}" code_saved: "Cod salvat" skip_tutorial: "Sări peste (esc)" keyboard_shortcuts: "Scurtături tastatură" loading_start: "Începe nivel" loading_start_combo: "Începe provocarea combinată" loading_start_concept: "Începe provocarea concept" problem_alert_title: "Repară codul" time_current: "Acum:" time_total: "Max:" time_goto: "Mergi la:" non_user_code_problem_title: "Imposibil de încărcat nivel" infinite_loop_title: "Buclă infinită detectată" infinite_loop_description: "Codul inițial pentru a construi lumea nu a terminat de rulat niciodată. Este probabil foarte lent sau are o buclă infinită. Sau ar putea fi o eroare de programare. Poți încerca să executați acest cod din nou sau să resetezi codul la starea implicită. Dacă nu se remediază, te rog să ne anunți." check_dev_console: "Puteți deschide, de asemenea, consola de dezvoltator pentru a vedea ce ar putea merge greșit." check_dev_console_link: "(instrucțiuni)" infinite_loop_try_again: "Încearcă din nou" infinite_loop_reset_level: "Resetează nivelul" infinite_loop_comment_out: "Comentează codul meu" tip_toggle_play: "schimbă între joacă/pauză cu Ctrl+P." tip_scrub_shortcut: "Utilizează Ctrl+[ și Ctrl+] pentru a derula înapoi sau a da pe repede înainte." tip_guide_exists: "Apasă pe ghid, din meniul jocului (din partea de sus a paginii), pentru informații utile." tip_open_source: "CodeCombat este parte a comunității open source!" tip_tell_friends: "Îți place CodeCombat? Spune-le prietenilor tăi despre noi!" tip_beta_launch: "CodeCombat a fost lansat în format beta în Octombrie 2013." tip_think_solution: "Gândește-te la soluție, nu la problemă." tip_theory_practice: "Teoretic nu este nici o diferență înte teorie și practică. Dar în practică este. - PI:NAME:<NAME>END_PI" tip_error_free: "Există doar două metode de a scrie un program fără erori; numai a treia funcționează. - PI:NAME:<NAME>END_PI" tip_debugging_program: "Dacă a face depanare este procesul de a elimina erorile, atunci a programa este procesul de a introduce erori. - PI:NAME:<NAME>END_PI" tip_forums: "Mergi la forum și spune-ți părerea!" tip_baby_coders: "În vitor până și bebelușii vor fi Archmage." tip_morale_improves: "Încărcarea va continua până când moralul se va îmbunătăți." tip_all_species: "Noi credem în șanse egale pentru toate speciile pentru a învăța programare." tip_reticulating: "Re-articulăm coloane vertebrale." tip_harry: "Yer a Wizard, " tip_great_responsibility: "Cu o mare abilitate de programare vine și o mare responsabilitate de depanare." tip_munchkin: "Dacă nu iți mănânci legumele, un munchkin va veni după tine când dormi." tip_binary: "Sunt doar 10 tipuri de oameni în lume: cei ce înteleg sistemul binar și ceilalți." tip_commitment_yoda: "Un programator trebuie să aibă cel mai profund angajament, mintea cea mai serioasă. ~Yoda" tip_no_try: "A face. Sau a nu face. Nu există voi încerca. ~Yoda" tip_patience: "Să ai rabdare trebuie, tinere Padawan. ~Yoda" tip_documented_bug: "O eroare (bug) documentată nu e chiar o eroare; este o caracteristică." tip_impossible: "Mereu pare imposibil până când e gata. ~PI:NAME:<NAME>END_PI" tip_talk_is_cheap: "Vorbele sunt goale. Arată-mi codul. ~PI:NAME:<NAME>END_PI" tip_first_language: "Cel mai dezastruos lucru pe care poți să îl înveți este primul limbaj de programare. ~PI:NAME:<NAME>END_PI" tip_hardware_problem: "Întrebare: De câți programatori ai nevoie ca să schimbi un bec? Răspuns: Niciunul, e o problemă de hardware." tip_hofstadters_law: "Legea lui Hofstadter: Mereu durează mai mult decât te aștepți, chiar dacă iei în considerare Legea lui Hofstadter." tip_premature_optimization: "Optimizarea prematură este rădăcina tuturor răutăților. ~PI:NAME:<NAME>END_PI" tip_brute_force: "Atunci cănd ești în dubii, folosește forța brută. ~PI:NAME:<NAME>END_PI" tip_extrapolation: "Există doar două feluri de oameni: cei care pot extrapola din date incomplete..." tip_superpower: "Programarea este cel mai apropiat lucru de o superputere." tip_control_destiny: "În open source, ai dreptul de a-ți controla propiul destin. ~PI:NAME:<NAME>END_PI" tip_no_code: "Niciun cod nu e mai rapid decat niciun cod." tip_code_never_lies: "Codul nu minte niciodată, commenturile mai mint. ~PI:NAME:<NAME>END_PI" tip_reusable_software: "Înainte ca un software să fie reutilizabil, trebuie să fie mai întâi utilizabil." tip_optimization_operator: "Fiecare limbaj are un operator de optimizare. La majoritatea acela este '//'" tip_lines_of_code: "Măsurarea progresului în lini de cod este ca și măsurarea progresului de construcție a aeronavelor în greutate. ~PI:NAME:<NAME>END_PI" tip_source_code: "Vreau să schimb lumea dar nu îmi dă nimeni codul sursă." tip_javascript_java: "Java e pentru Javascript exact ce e o mașina pentru o carpetă. ~PI:NAME:<NAME>END_PI" tip_move_forward: "Orice ai face, mergi înainte. ~PI:NAME:<NAME>END_PI Jr." tip_google: "Ai o problemă care nu o poți rezolva? Folosește Google!" tip_adding_evil: "Adaugăm un strop de răutate." tip_hate_computers: "Tocmai aia e problema celor care cred că urăsc calulatoarele. Ceea ce urăsc ei de fapt sunt programatorii nepricepuți. ~PI:NAME:<NAME>END_PI" tip_open_source_contribute: "Poți ajuta la îmbunătățirea jocului CodeCombat!" tip_recurse: "A itera este uman, recursiv este divin. ~PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI" tip_free_your_mind: "Trebuie sa lași totul, PI:NAME:<NAME>END_PI, îndoiala și necredința. Eliberează-ți mintea. ~Morpheus" tip_strong_opponents: "Și cei mai puternici dintre oponenți întodeauna au o slăbiciune. ~PI:NAME:<NAME>END_PI" tip_paper_and_pen: "Înainte să începi să scrii cod, poți tot mereu să planific mai întâi pe o foaie de hârtie cu un creion." tip_solve_then_write: "Mai întâi, rezolvă problema. Apoi, scrie codul. - PI:NAME:<NAME>END_PI" tip_compiler_ignores_comments: "Câteodată cred că compilatorul îmi ignoră comentariile." tip_understand_recursion: "Singura modalitate de a înțelege recursivitatea este să înțelegi recursivitatea." tip_life_and_polymorphism: "Open Source este ca o structură total polimorfică și eterogenă: Toate tipurile sun primite." tip_mistakes_proof_of_trying: "Greșelile din codul tău sunt dovezi că încerci." tip_adding_orgres: "Scurtăm niște căpcăuni." tip_sharpening_swords: "Ascuțim săbiile." tip_ratatouille: "Nu trebuie să lași pe nimeni să-ți definească limitele pe baza locului de unde vi. Singura ta limită este sufletul tău. - Gusteau, Ratatouille" tip_nemo: "Când viața te pune la pământ, vrei să ști ce trebuie să faci? Doar continuă să înoți, doar continuă să înoți. - PI:NAME:<NAME>END_PI" tip_internet_weather: "Mută-te pe Internet, este minunat aici. Ajungem să trăim înauntru unde vremea este tot mereu frumoasă. - PI:NAME:<NAME>END_PI" tip_nerds: "Tocilarilor le este permis să iubească lucruri, ca de exemplu sări-sus-și-jos-în-scaun-nu-te-poți-controla. - PI:NAME:<NAME>END_PI" tip_self_taught: "M-am învățat singur 90% din ceea ce am învățat. Și așa e normal! - PI:NAME:<NAME>END_PI" tip_luna_lovegood: "Nu-ți face griji, ești la fel de sănătos la minte ca și mine. - PI:NAME:<NAME>END_PI" tip_good_idea: "Modalitatea cea mai bună de a avea o idee bună este să ai multe idei. - PI:NAME:<NAME>END_PI" tip_programming_not_about_computers: "În informatică nu mai este vorba doar despre calculatoare așa cum în astronomie nu e vorba doar despre telescoape. - PI:NAME:<NAME>END_PI" tip_mulan: "Crede că poți și atunci vei putea. - PI:NAME:<NAME>END_PI" project_complete: "Proiect terminat!" share_this_project: "Partajează acest proiect cu prietenii și familia:" ready_to_share: "Gata să îți publici proiectul?" click_publish: "Apasă \"Publică\" pentru a-l face să apară în galeria clasei, apoi verifică ce au făcut colegii! Te poți întoarce să continui să lucrezi la acest proiect. Orice schimbare viitoare va fi automat salvată și partajată cu colegii tăi." already_published_prefix: "Modificările tale au fost publicate în galeria clasei." already_published_suffix: "Continuă să experimentezi și să îmbunătățești acest proiect, sau vezi ceea ce au construit restul colegilor! Modificările tale vor fi automat salvate și partajate cu colegii tăi." view_gallery: "Vezi galeria" project_published_noty: "Nivelul tău a fost publicat!" keep_editing: "Continuă să modifici" learn_new_concepts: "Învață noi concepte" watch_a_video: "Urmărește un video despre __concept_name__" concept_unlocked: "Concept deblocat" use_at_least_one_concept: "Utilizează cel puțin un concept: " command_bank: "Banca de comenzi" learning_goals: "Obiectivele învățării" start: "Start" vega_character: "PI:NAME:<NAME>END_PI" click_to_continue: "Apasă pentru a continua" fill_in_solution: "Completează cu soluția" play_as_humans: "Joacă ca om" play_as_ogres: "Joacă ca căpcăun" apis: methods: "Metode" events: "Evenimente" handlers: "Handler-e" properties: "Proprietăți" snippets: "Fragmente" spawnable: "Generabil" html: "HTML" math: "Mate" array: "Matrice" object: "Obiect" string: "Șir de caractere" function: "Funcție" vector: "Vector" date: "Dată" jquery: "jQuery" json: "JSON" number: "Număr" webjavascript: "Javascript" amazon_hoc: title: "Continuă să înveți cu Amazon!" congrats: "Felicitări în câștigarea provocărilor din Hour of Code!" educate_1: "Acum, continuă să înveți despre scrieres codului și despre cloud computing cu AWS Educate, un program gratuit și captivant de la Amazon atât pentru cursanți cât și pentru profesori. Cu AWS Educate, poți câștiga insigne virtuale când înveți despre noțiunile de bază din cloud și despre tehnologiile de ultimă generație cum sunt jocurile, realitatea virtuală și Alexa." educate_2: "Învață mai multe și înregistrează-te aici" future_eng_1: "Poți să încerci să construiești abilități noi pentru PI:NAME:<NAME>END_PIa legate de fapte școlare" future_eng_2: "aici" future_eng_3: "(echipamentul nu este necesar). Această activitate cu PI:NAME:<NAME>END_PIa este prezentată de" future_eng_4: "Amazon Future Engineer (Viitorii Ingineri Amazon)" future_eng_5: "un program care creează oportunități pentru învățare și munncă pentru toți elevii K-12 din Statele Unite care doresc să urmeze o carieră în informatică." live_class: title: "Mulțumesc!" content: "Uimitor! Tocmai am lansat clase on-line în timp real." link: "Ești pregătit să mergi mai departe cu programarea?" code_quest: great: "Minunat!" join_paragraph: "Alătură-te celui mai mare turneu internațional de programare Python IA pentru toate vârstele și concurează pentru a ajunge în vârful tabelei de scor! Această bătălie globală de o lună, începe pe 1 August și include premii în valoare de $5k și o ceremonie virtuală de decernare a premiilor unde vom anunța câștigătorii și vom recunoaște abilitățile voastre de a scrie cod." link: "Apasă aici pentru înregistrare și mai multe detalii" global_tournament: "Turneu global" register: "Înregistrare" date: "1 Aug - 31 Aug" play_game_dev_level: created_by: "Creat de {{name}}" created_during_hoc: "Creat în timpul Hour of Code" restart: "Reîncepe nivel" play: "Joacă nivel" play_more_codecombat: "Joacă mai mult CodeCombat" default_student_instructions: "Apasă pentru a controla eroul și a câștiga jocul!" goal_survive: "Supraviețuiește." goal_survive_time: "Supraviețuiește pentru __seconds__ secunde." goal_defeat: "Învinge toți inamicii." goal_defeat_amount: "Învinge __amount__ inamici." goal_move: "Mergi la toate marcajele cu X." goal_collect: "Colectează toate obiectele." goal_collect_amount: "Ai colectat __amount__ obiecte." game_menu: inventory_tab: "Inventar" save_load_tab: "Salvează/Încarcă" options_tab: "Opțiuni" guide_tab: "Ghid" guide_video_tutorial: "Tutorial Video" guide_tips: "Sfaturi" multiplayer_tab: "Multiplayer" auth_tab: "Înscriere" inventory_caption: "Echipează eroul" choose_hero_caption: "Alege eroul, limba" options_caption: "Configurare setări" guide_caption: "Documentație și sfaturi" multiplayer_caption: "Joacă cu prietenii!" auth_caption: "Salvează progresul." leaderboard: view_other_solutions: "Vezi tabelul de clasificare" scores: "Scoruri" top_players: "Top jucători după" day: "Azi" week: "Săptămâna aceasta" all: "Tot timpul" latest: "Ultimul" time: "Timp" damage_taken: "Vătămare primită" damage_dealt: "Vătămare oferită" difficulty: "Dificultate" gold_collected: "Aur colectat" survival_time: "Supraviețuit" defeated: "Inamici înfrânți" code_length: "Linii de cod" score_display: "__scoreType__: __score__" inventory: equipped_item: "Echipat" required_purchase_title: "Necesar" available_item: "Disponibil" restricted_title: "Restricționat" should_equip: "(dublu-click pentru echipare)" equipped: "(echipat)" locked: "(blocat)" restricted: "(restricționat în acest nivel)" equip: "Echipează" unequip: "Dezechipează" warrior_only: "Doar războinic" ranger_only: "Doar arcaș" wizard_only: "Doar vrăjitor" buy_gems: few_gems: "Căteva pietre prețioase" pile_gems: "Morman de pietre prețioase" chest_gems: "Cufăr cu pietre prețioase" purchasing: "Cumpărare..." declined: "Cardul tău a fost refuzat." retrying: "Eroare de server, reîncerc." prompt_title: "Nu sunt destule pietre prețioase." prompt_body: "Vrei să cumperi mai multe?" prompt_button: "Intră în magazin." recovered: "Pietre prețioase cumpărate anterior recuperate. Vă rugăm să reîncărcați pagina." price: "x{{gems}} / lună" buy_premium: "Cumpără premium" purchase: "Cumpără" purchased: "Cumpărat" subscribe_for_gems: prompt_title: "Pietre prețioase insuficiente!" prompt_body: "Abonează-te la Premium pentru a obține pietre prețioase și pentru a accesa chiar mai multe niveluri!" earn_gems: prompt_title: "Pietre prețioase insuficiente" prompt_body: "Continuă să joci pentru a câștiga mai multe!" subscribe: best_deal: "Cea mai bună afacere!" confirmation: "Felicitări! Acum ai abonament CodeCombat Premium!" premium_already_subscribed: "Ești deja abonat la Premium!" subscribe_modal_title: "CodeCombat Premium" comparison_blurb: "Devino un Master Coder - abonează-te la varianta <b>Premium</b> azi! " must_be_logged: "Trebuie să te conectezi mai întâi. Te rugăm să creezi un cont sau să te conectezi din meniul de mai sus." subscribe_title: "Abonare" # Actually used in subscribe buttons, too unsubscribe: "Dezabonare" confirm_unsubscribe: "Confirmă dezabonarea" never_mind: "Nu contează, eu tot te iubesc!" thank_you_months_prefix: "Mulțumesc pentru sprijinul acordat în aceste" thank_you_months_suffix: "luni." thank_you: "Mulțumim pentru susținerea CodeCombat!" sorry_to_see_you_go: "Ne pare rău că pleci! Te rugăm să ne spui ce am fi putut face mai bine." unsubscribe_feedback_placeholder: "Of, ce am făcut?" stripe_description: "Abonament lunar" stripe_yearly_description: "Abonament anual" buy_now: "Cumpără acum" subscription_required_to_play: "Ai nevoie de abonament ca să joci acest nivel." unlock_help_videos: "Abonează-te pentru deblocarea tuturor tutorialelor video." personal_sub: "Abonament personal" # Accounts Subscription View below loading_info: "Se încarcă informațile despre abonament..." managed_by: "Gestionat de" will_be_cancelled: "Va fi anulat pe" currently_free: "În prezent ai un abonament gratuit" currently_free_until: "În prezent ai un abonament până pe" free_subscription: "Abonament gratuit" was_free_until: "Ai avut un abonament gratuit până pe" managed_subs: "Abonamente Gestionate" subscribing: "Te abonăm..." current_recipients: "Recipienți curenți" unsubscribing: "Dezabonare..." subscribe_prepaid: "Apasă pe abonare pentru a folosi un cod preplătit" using_prepaid: "Foloseste cod preplătit pentru un abonament lunar" feature_level_access: "Accesează peste 500+ de nivele disponibile" feature_heroes: "Deblochează eroi exclusivi și animăluțe de companie" feature_learn: "Învață să creezi jocuri și site-uri web" feature_gems: "Primește __gems__ pietre prețioase pe lună" month_price: "$__price__" # {change} first_month_price: "Doar $__price__ pentru prima lună!" lifetime: "Acces pe viață" lifetime_price: "$__price__" year_subscription: "Abonament anual" year_price: "$__price__/an" # {change} support_part1: "Ai nevoie de ajutor cu plata sau preferi PayPal? Email" support_part2: "PI:EMAIL:<EMAIL>END_PI" announcement: now_available: "Acum disponibil pentru abonați!" subscriber: "abonat" cuddly_companions: "Animăluțe drăguțe!" # Pet Announcement Modal kindling_name: "Kindling Elemental" kindling_description: "Kindling Elemental-ii vor doar să îți țină de cald noaptea. Și în timpul zilei. Toto timpul, pe cuvânt." griffin_name: "PI:NAME:<NAME>END_PI" griffin_description: "Grifonii sunt jumătate vultur, jumătate leu, foarte adorabili." raven_name: "PI:NAME:<NAME>END_PI" raven_description: "Corbii sunt excelenți la adunarea sticluțelor pline cu poțiune de sănătate." mimic_name: "PI:NAME:<NAME>END_PI" mimic_description: "Mimii pot aduna monede pentru tine. Pune-i peste monede pentru a crește provizia de aur." cougar_name: "PI:NAME:<NAME>END_PI" cougar_description: "Pumelor le place să își ia PhD prin Purring Happily Daily.(joc de cuvinte)" fox_name: "PI:NAME:<NAME>END_PI" fox_description: "Vulpile albastre sunt foarte istețe și le place să sape în pământ și zăpadă!" pugicorn_name: "PI:NAME:<NAME>END_PI" pugicorn_description: "Pugicornii sunt cele mai rare creaturi care pot face vrăji!" wolf_name: "PI:NAME:<NAME>END_PI" wolf_description: "Puii de lup sunt foarte buni la vânătoare, culegere și fac un joc răutăcios de-a fața-ascunselea!" ball_name: "PI:NAME:<NAME>END_PIinge roșie chițăitoare" ball_description: "ball.squeak()" collect_pets: "Adună animăluțe pentru eroul tău!" each_pet: "Fiecare animăluț are o abilitate unică de a te ajuta!" upgrade_to_premium: "Devino un {{subscriber}} pentru a echipa animăluțele." play_second_kithmaze: "Joacă {{the_second_kithmaze}} pentru a debloca puiul de lup!" the_second_kithmaze: "Al doilea Kithmaze" keep_playing: "Continuă să joci pentru a descoperi primul animăluț!" coming_soon: "În curând" ritic: "Ritic al frigului" # Ritic Announcement Modal ritic_description: "Ritic al frigului. Prins în capcana ghețarului PI:NAME:<NAME>END_PI de nenumărați ani, este în sfârșit liber și pregătit să aibă grijă de căpcăunii care l-au închis." ice_block: "Un bloc de gheață" ice_description: "Pare să fie ceva prins în interior ..." blink_name: "Blink" blink_description: "Ritic dispare și apare într-o clipire de ochi, lăsând în urmă doar umbră." shadowStep_name: "Shadowstep" shadowStep_description: "Un assasin maestru care știe să umble printre umbre." tornado_name: "Tornado" tornado_description: "Este bine să ai un buton de reset când acoperirea cuiva este spulberată." wallOfDarkness_name: "Zidul Întunericului" wallOfDarkness_description: "Se ascunde în spatele unui zid de umbră pentru a evita privirile." avatar_selection: pick_an_avatar: "Alege un avatar care te reprezintă ca și jucător" premium_features: get_premium: "Cumpără<br>CodeCombat<br>Premium" # Fit into the banner on the /features page master_coder: "Devino un master al codului abonându-te azi!" paypal_redirect: "Vei fi redirecționat către PayPal pentru a finaliza procesul de abonare." subscribe_now: "Abonează-te acum" hero_blurb_1: "Obține acces la __premiumHeroesCount__ de eroi super dotați disponibili doar pentru abonați! Valorifică puterea de neoprit a lui PI:NAME:<NAME>END_PI, precizia mortală a lu Naria of the Leaf, sau cheamă \"adorable\" scheleți cu Nalfar Cryptor." hero_blurb_2: "Luptătorii premium deblochează arte marțiale uimitoare ca Warcry, Stomp și Hurl Enemy. Sau, joacă ca și Arcaș, utilizând procedee ascunse și arcuri, aruncarea de cuțite, capcane! Încearcă-ți aptitudinile ca Vrăjitor și eliberează o serie de magii puternice ca Primordial, Necromantic sau Elemental!" hero_caption: "Noi eroi impresionanți!" pet_blurb_1: "Animăluțele nu sunt numai companioni adorabili, ei furnizează funcții și metode unice. Piul de grifon poate căra trupe prin aer, puiul de lup joacă prinselea cu săgeține inamicilor, pumei îi place să fugărească căpcăuni iar Mim-ul atrage monedele ca magnetul!" pet_blurb_2: "Adună toate animăluțele pentru a descoperi abilitățile lor unice!" pet_caption: "Adoptă animăluțe care să îl însoțească pe eroul tău!" game_dev_blurb: "Învață game scripting și construiește noi nivele pe care să le partajezi cu prietenii tăi! Pune obiectele pe care le dorești, scrie cod pentru unitatea logică și de comportament și vezi dacă prietenii pot să termine nivelul!" game_dev_caption: "Dezvoltă propriile jocuri pentru a-ți provoca prietenii!" everything_in_premium: "Tot ceea ce vei obține în CodeCombat Premium:" list_gems: "Primești pietre prețioase bonus pentru cumpărarea echipamentului, animaăluțelor și eroilor" list_levels: "Obții acces la __premiumLevelsCount__ alte niveluri" list_heroes: "Deblochează eroi exclusivi, care cuprind clasele Arcaș și Vrăjitor" list_game_dev: "Creează și partajează jocuri cu prietenii" list_web_dev: "Construiește site-uri web și aplicații interactive" list_items: "Echipează-te cu elemente specifice premium cum sunt animăluțele" list_support: "Primește suport de tip premium pentru a te ajuta să rezolvi situațiile încâlcite" list_clans: "Creează clanuri private în care să inviți prieteni și concurează într-un clasament de grup" choose_hero: choose_hero: "Alege eroul" programming_language: "Limbaj de programare" programming_language_description: "Ce limbaj de programare vrei să folosești?" default: "Implicit" experimental: "Experimental" python_blurb: "Simplu dar puternic, minunat atât pentru începători cât și pentru experți" javascript_blurb: "Limbajul web-ului. (Nu este același lucru ca Java.)" coffeescript_blurb: "Javascript cu o syntaxă mai placută!" lua_blurb: "Limbaj de scripting pentru jocuri." java_blurb: "(Numai pentru abonați) Android și pentru afaceri." cpp_blurb: "(Numai pentru abonați) Dezvoltare de jocuri și calcul de înaltă performanță." status: "Stare" weapons: "Armament" weapons_warrior: "Săbii - Distanță scurtă, Fără magie" weapons_ranger: "Arbalete, Pistoale - Distanță mare, Fără magie" weapons_wizard: "Baghete, Toiege - Distanță mare, Magie" attack: "Atac" # Can also translate as "Attack" health: "Viață" speed: "Viteză" regeneration: "Regenerare" range: "Rază" # As in "attack or visual range" blocks: "Blochează" # As in "this shield blocks this much damage" backstab: "Înjunghiere" # As in "this dagger does this much backstab damage" skills: "Abilități" attack_1: "Oferă" attack_2: "din cele listate" attack_3: "Vătămare cu arma." health_1: "Primește" health_2: "din cele listate" health_3: "Stare armură." speed_1: "Se deplasează cu" speed_2: "metri pe secundă." available_for_purchase: "Disponibil pentru cumpărare" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Nivel ce trebuie deblocat:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see) restricted_to_certain_heroes: "Numai anumiți eroi pot juca acest nivel." char_customization_modal: heading: "Personalizează eroul" body: "CorPI:NAME:<NAME>END_PI" name_label: "PI:NAME:<NAME>END_PI" hair_label: "Culoare păr" skin_label: "Culoare piele" skill_docs: function: "funcție" # skill types method: "metodă" snippet: "fragment" number: "număr" array: "matrice" object: "obiect" string: "șir de caractere" writable: "permisiuni de scriere" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "permisiuni doar de citire" action: "Acțiune" spell: "Vrajă" action_name: "nume" action_cooldown: "Durează" action_specific_cooldown: "Răcire" action_damage: "Vătămare" action_range: "Raza de acțiune" action_radius: "Raza" action_duration: "Durata" example: "Exemplu" ex: "ex" # Abbreviation of "example" current_value: "Valoare curentă" default_value: "Valoare implicită" parameters: "Parametrii" required_parameters: "Parametrii necesari" optional_parameters: "Parametrii opționali" returns: "Întoarce" granted_by: "Acordat de" still_undocumented: "Încă nedocumentat, ne pare rău." save_load: granularity_saved_games: "Salvate" granularity_change_history: "Istoric" options: general_options: "Opțiuni Generale" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volum" music_label: "MuzicPI:NAME:<NAME>END_PI" music_description: "Oprește/pornește muzica din fundal." editor_config_title: "Configurare editor" editor_config_livecompletion_label: "Autocompletare live" editor_config_livecompletion_description: "Afișează sugesti de autocompletare în timp ce scri." editor_config_invisibles_label: "Arată etichetele invizibile" editor_config_invisibles_description: "Arată spațiile și taburile invizibile." editor_config_indentguides_label: "Arată ghidul de indentare" editor_config_indentguides_description: "Arată linii verticale pentru a vedea mai bine indentarea." editor_config_behaviors_label: "Comportamente inteligente" editor_config_behaviors_description: "Completează automat parantezele, ghilimele etc." about: title: "Despre CodeCombat - Elevi pasionați, Profesori implicați, Creații inspirate" meta_description: "Misiunea noastră este să ridicăm nivelul informaticii prin învățarea bazată pe joc și să facem programarea accesibilă fiecărui elev. Noi credem că programarea este magică și vrem că le dăm elevilor puterea de a crea lucruri din imaginație." learn_more: "Află mai multe" main_title: "Dacă vrei să înveți să programezi, trebuie să scrii (foarte mult) cod." main_description: "La CodeCombat, rolul nostru este să ne asigurăm că vei face acest lucru cu zâmbetul pe față." mission_link: "Misiune" team_link: "Echipă" story_link: "Poveste" press_link: "Presă" mission_title: "Misiunea noastră: să facem programarea accesibilă fiecărui elev de pe Pământ." mission_description_1: "<strong>Programarea este magică</strong>. Este abilitatea de a creea lucruri din imaginație. Am pornit CodeCombat pentru a-i face pe cursanți să simtă că au puteri magice la degetul lor mic utilizând <strong>cod scris</strong>." mission_description_2: "Dupăc cum am văzut, acest lucru îi face să învețe să scrie cod mai repede. MULT MAI rapid. Este ca și când am avea o conversație în loc de a citi un manual. Vrem să aducem această conversație în fiecare școală și la <strong>fiecare elev</strong>, deoarece toată lumea ar trebui să aibă o șansă să învețe magia programării." team_title: "Întâlnește echipa CodeCombat" team_values: "Punem preș pe dialoguș deschis și respectuos, în care cea mai bună idee câștigă. Deciziile noastre sun bazate pe cercetarea consumatorilor iar procesul nostru pune accent pe livrarea resultatelor tangibile pentru ei. Toată lumea luCreează la asta, de la CEO la contributorii noștri GitHub, deoarece noi în echipa noastră punem valoare pe creștere și dezvoltare ." nick_title: "PI:NAME:<NAME>END_PI, CPI:NAME:<NAME>END_PI" # csr_title: "Customer Success Representative" # csm_title: "Customer Success Manager" # scsm_title: "Senior Customer Success Manager" # ae_title: "Account Executive" # sae_title: "Senior Account Executive" # sism_title: "Senior Inside Sales Manager" # shan_title: "Head of Marketing, CodeCombat Greater China" # run_title: "Head of Operations, CodeCombat Greater China" # lance_title: "Head of Technology, CodeCombat Greater China" # zhiran_title: "Head of Curriculum, CodeCombat Greater China" # yuqiang_title: "Head of Innovation, CodeCombat Greater China" swe_title: "Inginer software" sswe_title: "Infiner senior software" css_title: "Specialist suport clienți" css_qa_title: "Suport clienți / Specialis întrebări/răspunsuri" maya_title: "Dezvoltator senior de curiculă" bill_title: "Manager general, CodeCombat Greater China" pvd_title: "Designer vizual și de produs" spvd_title: "Designer senior vizual și de produs" daniela_title: "Manager de marketing" bobby_title: "Dezvoltator joc" brian_title: "Manager senior de dezvoltare joc" stephanie_title: "Specialist suport clienți" # sdr_title: "Sales Development Representative" retrostyle_title: "Ilustrator" retrostyle_blurb: "Jocuri în stil retro" community_title: "...și comunitatea noastră open-source" bryukh_title: "Dezvoltator Senior de joc" # oa_title: "Operations Associate" ac_title: "Coordonator administrativ" ea_title: "Asistent executiv" om_title: "Manager de operații" mo_title: "Manager, Operații" smo_title: "Manager senior, Operații" do_title: "Director de operații" scd_title: "Dezvoltator senior de curiculă" lcd_title: "Dezvoltator șef de curiculă" de_title: "Director de educație" vpm_title: "VP, Marketing" oi_title: "Instructor online " # bdm_title: "Business Development Manager" community_subtitle: "Peste 500 de colaboratori au ajutat la dezvoltarea CodeCombat, numărul acestora crescând în fiecare săptămână!" community_description_3: "CodeCombat este un" community_description_link_2: "proiect colectiv" community_description_1: "cu sute de jucători care se oferă voluntar să creeze noi niveluri, contribuie la codul nostru pentru a adauga componente, a repara erori, a testa jocuri și a traduce jocul în peste 50 de limbi până în prezent. Angajații, contribuabilii și câștigurile aduse de site prin partajarea ideilor dar și un efort comun, așa cum face comunitatea open-source în general. Site-ul este construit pe numeroase proiecte open-source, și suntem deschiși să dăm înapoi comunității și să furnizăm jucătorilor curioși în privința codului un proiect familiar de examinat și experimentat. Oricine se poate alătura comunității CodeCombat! Verifică" community_description_link: "pagina cu cei care au contribuit" community_description_2: "pentru mai multe informații." number_contributors: "Peste 450 contributori și-au adus suportul și timpul la acest proiect." story_title: "Povestea noastră până în prezent" story_subtitle: "Din 2013, CodeCombat a crescut de la un simplu set de schițe la un joc palpitan care continuă să crească." story_statistic_1a: "20,000,000+" story_statistic_1b: "de jucători" story_statistic_1c: "și-au început călătoria în lumea programării prin CodeCombat" story_statistic_2a: "Am tradus în peste 50 de limbi — asta a venit de la jucătorii noștri" story_statistic_2b: "190+ țări" story_statistic_3a: "Împreună, ei au scris" story_statistic_3b: "1 bilion de linii de cod care încă crește" story_statistic_3c: "în diferite limbaje de programare" story_long_way_1: "Cu toate că am parcurs un drum lung..." story_sketch_caption: "cu schița lui Nick care prezenta un joc de programare în acțiune." story_long_way_2: "încă mai avem multe de făcut până ne terminăm misiunea, de aceea..." jobs_title: "Vin-o să lucrezi cu noi și ajută la scrierea istoriei CodeCombat!" jobs_subtitle: """Nu vezi unde te-ai puta încadra dar ai dori să păstrăm legătura? Vezi lista \"Creează propria\".""" jobs_benefits: "Beneficiile angaților" jobs_benefit_4: "Vacanță nelimitată" jobs_benefit_5: "Suport pentru dezvoltare profesională și educație continuă – cărți gratuite și jocuri!" jobs_benefit_6: "Medical (gold), dental, oftamologic, navetist, 401K" jobs_benefit_7: "Birouri de lucru pentru toți" # jobs_benefit_9: "10-year option exercise window" # jobs_benefit_10: "Maternity leave: 12 weeks paid, next 6 @ 55% salary" # jobs_benefit_11: "Paternity leave: 12 weeks paid" # jobs_custom_title: "Create Your Own" jobs_custom_description: "ești un pasionat de CodeCombat dar nu vezi un job care să corespundă calificărilor tale? scrie-ne și arată-ne cum crezi tu că poți contribui la echipa noastră. Ne-ar face plăcere să auzim toate acestea!" jobs_custom_contact_1: "Trimite-ne o notă la" jobs_custom_contact_2: "cu prezentarea ta și poate vom lua legătura în viitor!" contact_title: "Presă & Contact" contact_subtitle: "Ai nevoie de mai multe informații? Ia legătura cu noi la" screenshots_title: "Capturi de ecran din joc" screenshots_hint: "(apasă să vezi în dimensiune maximă)" downloads_title: "Descarcă Download Assets & Information" about_codecombat: "Despre CodeCombat" logo: "Logo" screenshots: "Capturi de ecran" character_art: "Arta caracterului" download_all: "Descarcă tot" previous: "Anterior" location_title: "Suntem localizați în centrul SF:" teachers: licenses_needed: "Sunt necesare licențe" special_offer: special_offer: "Ofertă specială" project_based_title: "Cursuri bazate pe proiecte" project_based_description: "Cursuri de dezvoltare web și de jocuri cu posibilități de partajare a proiectelor finale." great_for_clubs_title: "Ideale pentru cluburi și grupuri școlare" great_for_clubs_description: "Profesorii pot cumpăra până la __maxQuantityStarterLicenses__ licențe de pornire." low_price_title: "Doar __starterLicensePrice__ de cursant" low_price_description: "Licențele de pornire sunt active pentru __starterLicenseLengthMonths__ de luni de la cumpărare." three_great_courses: "Trei cursuri deosebite sunt incluse în licența de pornire:" license_limit_description: "Profesorii pot cumpăra până la __maxQuantityStarterLicenses__ licențe de pornire. Ai cumpărat deja __quantityAlreadyPurchased__. Dacă dorești mai multe, contactează-ne la __supportEmail__. Licențele de pornire sunt valabile pentru __starterLicenseLengthMonths__ de luni." student_starter_license: "Licențe de pornire pentru cursanți" purchase_starter_licenses: "Cumpără licențe de pornire" purchase_starter_licenses_to_grant: "Cumpără licențe de pornire pentru a avea acces la __starterLicenseCourseList__" starter_licenses_can_be_used: "Licențele de pornire pot fi utilizate pentru asignarea de cursuri adiționale imediat după cumpărare." pay_now: "Plătește acum" we_accept_all_major_credit_cards: "Acceptăm marea majoritate a cardurilor de credit." cs2_description: "construite pe fundamentele obținute la cursul Introducere în informatică, cu accent pe instrucțiuni if, funcții, evenimete și altele." wd1_description: "introduce elemente de bază de HTML și CSS în timp ce pregătește abilitățile cursanților necesare pentru dezvoltarea propriei pagini web." gd1_description: "utilizează sintaxe cu care cursanții sunt deja familiarizați pentru a le arăta cum să construiască și să partajeze propriul nivel de joc." see_an_example_project: "vezi un exemplu de proiect" get_started_today: "Începe astăzi!" want_all_the_courses: "Vrei toate cursurile? Cere informații despre licențele complete." compare_license_types: "Compară licențele după tip:" cs: "Informatică" wd: "Dezvoltare web" wd1: "Dezvolare web 1" gd: "Dezvolatre de joc" gd1: "Dezvoltare de joc 1" maximum_students: "Număr maxim # de cursanți" unlimited: "Nelimitat" priority_support: "Suport prioritar" yes: "Da" price_per_student: "__price__ pe cursant" pricing: "Preț" free: "Gratuit" purchase: "Cumpără" courses_prefix: "Cursuri" courses_suffix: "" course_prefix: "Curs" course_suffix: "" teachers_quote: subtitle: "Învață mai multe despre CodeCombat cu un tur interactiv al produsului, al prețului și al implementării acestuia!" email_exists: "Există utilizator cu această adresă de email." phone_number: "Număr de telefon" phone_number_help: "Care este cel mai bun număr la care să te contactăm?" primary_role_label: "Rolul tău primar" role_default: "Alege rol" primary_role_default: "Selectează rol primar" purchaser_role_default: "Selectează rolul tău ca și cumpărător" tech_coordinator: "Coordonator tehnologic" advisor: "Specialist/Consilier de curiculă" principal: "Director" superintendent: "Administrator" parent: "Părinte" purchaser_role_label: "Rolul tău ca și cumpărător" influence_advocate: "Formator de opinii/Susținător" evaluate_recommend: "Evaluează/Recomandă" approve_funds: "Aprobare fonduri" no_purchaser_role: "Nici un rol în decizia de cumpărare" district_label: "județ" district_name: "Nume județ" district_na: "scrie N/A dacă nu se aplică" organization_label: "Școală" school_name: "Numele școlii" city: "Oraș" state: "Sat / Regiune" country: "Țară / Regiune" num_students_help: "Câți elevi vor utiliza CodeCombat?" num_students_default: "Selectează intervalul" education_level_label: "Nivelul de educație al elevilor" education_level_help: "Alege pe toate care se aplică." elementary_school: "Școala primară" high_school: "Liceu" please_explain: "(te rog explică)" middle_school: "Școala gimnazială" college_plus: "Facultate sau mai sus" referrer: "Cum ai auzit despre noi?" referrer_help: "De exemplu: de la un alt profesor, o conferință, elevi, Code.org etc." referrer_default: "Alege una" referrer_conference: "Conferință (ex. ISTE)" referrer_hoc: "Code.org/Hour of Code" referrer_teacher: "Un profesor" referrer_admin: "Un administrator" referrer_student: "Un student" referrer_pd: "Pregătire profesională/Grup de lucru" referrer_web: "Google" referrer_other: "Altele" anything_else: "Pentru ce clasă anticipezi că vei utiliza CodeCombat?" anything_else_helper: "" thanks_header: "Cerere primită!" thanks_sub_header: "Mulțumim de interesul arătat în utilizarea CodeCombat în școala ta." thanks_p: "Vă vom contacta curând! Dacă dorești să ne contacteză, poți ajunge la noi prin:" back_to_classes: "Înapoi la clase" finish_signup: "Contul tău de utilizator a fost creat:" finish_signup_p: "Creează un cont pentru a creea o clasă, adaugă elevii și monitorizează progresul acestora în timp ce aceștia învață informatică." signup_with: "Autentificare cu:" connect_with: "Connectare cu:" conversion_warning: "AVERIZARE: Contul tău curent este un <em>Cont de elev</em>. După ce transmiți acest formular, contul tău va fi transformat într-un cont de profesor." learn_more_modal: "Conturile de profesor din CodeCombat au posibilitatea de a monitoriza progresul elevilor, a aloca licențe și să administreze clase. Conturile de profesor nu pot fi parte dintr-o clasă - dacă sunteți deja parte dintr-o clasă cu acest cont, nu o veți mai putea accesa după ce îl transformați în cont de profesor." create_account: "Creează un cont de profesor" create_account_subtitle: "Obține acces la unelte specifice profesorilor pntru a utiliza CodeCombat în clasă. <strong>Creează o clasă</strong>, adaugă elevii și <strong>monitorizează progresul lor</strong>!" convert_account_title: "Transformă în cont de profesor" not: "Nu" full_name_required: "Numele și prenumele sunt obligatorii" versions: save_version_title: "Salvează noua versiune" new_major_version: "Versiune nouă majoră" submitting_patch: "Trimitere Patch..." cla_prefix: "Pentru a salva modificările mai intâi trebuie sa fiți de acord cu" cla_url: "CLA" cla_suffix: "." cla_agree: "SUNT DE ACORD" owner_approve: "Un proprietar va trebui să aprobe înainte ca modificările să devină vizibile." contact: contact_us: "Contact CodeCombat" welcome: "Folosiți acest formular pentru a ne trimite email. " forum_prefix: "Pentru orice altceva vă rugăm să încercați " forum_page: "forumul nostru" forum_suffix: " în schimb." faq_prefix: "Există și un" faq: "FAQ" subscribe_prefix: "Daca ai nevoie de ajutor ca să termini un nivel te rugăm să" subscribe: "cumperi un abonament CodeCombat" subscribe_suffix: "și vom fi bucuroși să te ajutăm cu codul." subscriber_support: "Din moment ce ești un abonat CodeCombat, adresa ta de email va primi sprijinul nostru prioritar." screenshot_included: "Screenshot-uri incluse." where_reply: "Unde ar trebui să răspundem?" send: "Trimite Feedback" account_settings: title: "Setări Cont" not_logged_in: "Loghează-te sau Creează un cont nou pentru a schimba setările." me_tab: "Eu" picture_tab: "Poză" delete_account_tab: "Șterge contul" wrong_email: "Email greșit" wrong_password: "PI:PASSWORD:<PASSWORD>END_PI" delete_this_account: "Ștergere permanetă a acestui cont" reset_progress_tab: "Resetare progres" reset_your_progress: "Șterge tot progresul și începe din nou" god_mode: "Mod Dumnezeu" emails_tab: "Email-uri" admin: "Admin" manage_subscription: "Apasă aici pentru a administra abonamentele." new_password: "PI:PASSWORD:<PASSWORD>END_PI" new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI" type_in_email: "scrie adresa de email ca să confirmi ștergerea" type_in_email_progress: "scrie adresa de email pentru a confirma ștergerea progresului." type_in_password: "De asemenea, scrie și parola." email_subscriptions: "Subscripție email" email_subscriptions_none: "Nu ai subscripții email." email_announcements: "Anunțuri" email_announcements_description: "Primește email-uri cu ultimele știri despre CodeCombat." email_notifications: "Notificări" email_notifications_summary: "Control pentru notificări email personalizate, legate de activitatea CodeCombat." email_any_notes: "Orice notificări" email_any_notes_description: "Dezactivați pentru a opri toate email-urile de notificare a activității." email_news: "Noutăți" email_recruit_notes: "Oportunități de angajare" email_recruit_notes_description: "Dacă joci foarte bine, este posibil sa te contactăm pentru obținerea unui loc (mai bun) de muncă." # contributor_emails: "Contributor Class Emails" contribute_prefix: "Căutăm oameni să se alăture distracției! Intră pe " contribute_page: "pagina de contribuție" contribute_suffix: " pentru a afla mai multe." email_toggle: "Alege tot" error_saving: "Salvare erori" saved: "Modificări salvate" password_mismatch: "PI:PASSWORD:<PASSWORD>END_PI." password_repeat: "Te PI:PASSWORD:<PASSWORD>END_PIm PI:PASSWORD:<PASSWORD>END_PI repeți parPI:PASSWORD:<PASSWORD>END_PI." keyboard_shortcuts: keyboard_shortcuts: "Scurtături tastatură" space: "Space" enter: "Enter" press_enter: "apasă enter" escape: "Escape" shift: "Shift" run_code: "Rulează codul." run_real_time: "Rulează în timp real." # continue_script: "Continue past current script." skip_scripts: "Treci peste toate script-urile ce pot fi sărite." toggle_playback: "Comută play/pause." scrub_playback: "Mergi înainte și înapoi în timp." single_scrub_playback: "Mergi înainte și înapoi în timp cu un singur cadru." scrub_execution: "Mergi prin lista curentă de vrăji executate." toggle_debug: "Comută afișaj depanare." toggle_grid: "Comută afișaj grilă." toggle_pathfinding: "Comută afișaj pathfinding." beautify: "Înfrumusețează codul standardizând formatarea lui." maximize_editor: "Mărește/Minimizează editorul." cinematic: click_anywhere_continue: "apasă oriunde pentru a continua" community: main_title: "Comunitatea CodeCombat" introduction: "Vezi metode prin care poți să te implici și tu mai jos și decide să alegi ce ți se pare cel mai distractiv. De abia așteptăm să lucrăm împreună!" level_editor_prefix: "Folosește CodeCombat" level_editor_suffix: "Pentru a crea și a edita niveluri. Utilizatorii au creat niveluri pentru clasele lor, prieteni, hackathonuri, studenți și rude. Dacă crearea unui nivel nou ți se pare intimidant poți să modifici un nivel creat de noi!" thang_editor_prefix: "Numim unitățile din joc 'thangs'. Folosește" thang_editor_suffix: "pentru a modifica ilustrațile sursă CodeCombat. Permitele unităților să arunce proiectile, schimbă direcția unei animații, schimbă viața unei unități, sau încarcă propiile sprite-uri vectoriale." article_editor_prefix: "Vezi o greșeală în documentația noastă? Vrei să documentezi instrucțiuni pentru propiile creații? Vezi" article_editor_suffix: "și ajută jucătorii CodeCombat să obțină căt mai multe din timpul lor de joc." find_us: "Ne găsești pe aceste site-uri" social_github: "Vezi tot codul nostru pe GitHub" social_blog: "Citește blogul CodeCombat pe Sett" # {change} social_discource: "Alătură-te discuțiilor pe forumul Discourse" social_facebook: "Lasă un Like pentru CodeCombat pe facebook" social_twitter: "Urmărește CodeCombat pe Twitter" social_slack: "Vorbește cu noi pe canalul public de Slack CodeCombat" contribute_to_the_project: "Contribuie la proiect" clans: title: "Alătură-te clanurilor CodeCombat - Învață să scrii cod în Python, Javascript și HTML" clan_title: "__clan__ - Alătură-te clanurilor CodeCombat și învață să scrii cod" meta_description: "Alătură-te unui clan pentru a-ți construi propria comunitate de programatori. Joacă nivele multi-jucător în arenă și urcă nivelul eroului tău și al abilităților tale de programare." clan: "Clan" clans: "Clanuri" new_name: "PI:NAME:<NAME>END_PI nou de clan" new_description: "Descrierea clanului nou" make_private: "Fă clanul privat" subs_only: "numai abonați" create_clan: "Creează un clan nou" private_preview: "Previzualizare" private_clans: "Clanuri private" public_clans: "Clanuri Publice" my_clans: "Clanurile mele" clan_name: "PI:NAME:<NAME>END_PIumele ClPI:NAME:<NAME>END_PIului" name: "PI:NAME:<NAME>END_PI" chieftain: "Căpetenie" edit_clan_name: "Editează numele clanului" edit_clan_description: "Editează descrierea clanului" edit_name: "editează nume" edit_description: "editează descriere" private: "(privat)" summary: "Sumar" average_level: "Nivel mediu" average_achievements: "realizare medie" delete_clan: "Șterge Clan" leave_clan: "Pleacă din Clan" join_clan: "Intră în Clan" invite_1: "Invitație:" invite_2: "*Invită jucători în acest clan trimițând acest link." members: "MemPI:NAME:<NAME>END_PI" progress: "Progres" not_started_1: "neînceput" started_1: "început" complete_1: "complet" exp_levels: "Extinde niveluri" rem_hero: "Șterge Eroul" status: "Stare" complete_2: "Complet" started_2: "Început" not_started_2: "Neînceput" view_solution: "Apasă pentru a vedea soluția." view_attempt: "Apasă pentru a vedea încercarea." latest_achievement: "Ultimile realizări" playtime: "Timp de joc" last_played: "Ultima oară când ai jucat" leagues_explanation: "Joacă într-o ligă împotriva altor membri de clan în aceste instanțe de arenă multi-jucător." track_concepts1: "Conceptele traseului" track_concepts2a: "învățat de fiecare elev" track_concepts2b: "învățat de fiecare membru" track_concepts3a: "Urmărește nivelurile completate de fiecare elev" track_concepts3b: "Urmărește nivelurile completate de fiecare membru" track_concepts4a: "Vezi soluțiile elevilor" # The text is too fragmented and it does not have sense in Romanian. I added track_concepts5 to this track_concepts4b: "Vezi soluțiile membrilor" # I added track_concepts5 to this track_concepts5: "" track_concepts6a: "Sortează elevii după nume sau progres" track_concepts6b: "Sortează membrii după nume sau progres" track_concepts7: "Necesită invitație" track_concepts8: "pentru a te alătura" private_require_sub: "Clanurile private necesită un abonament pentru a le creea sau a te alătura unuia." courses: create_new_class: "Creează o nouă clasă" hoc_blurb1: "Încearcă" hoc_blurb2: "scrie cod, Joacă, Partajează" hoc_blurb3: "ca și activități! Construiește patru mini-jocuri diferite pentru a învăța bazele dezvoltării jocurilor, apoi creează unul singur!" solutions_require_licenses: "Soluțiile nivelurilor sunt disponibile profesorilor care au licențe." unnamed_class: "Clasă fără nume" edit_settings1: "Modifică setările clasei" add_students: "Adaugă elevi" stats: "Statistici" student_email_invite_blurb: "Elevii tăi pot utiliza codul de clasă <strong>__classCode__</strong> când creează un cont de elevt, nu este necesară o adresă email." total_students: "Total elevi:" average_time: "Timpul mediu de joc pe nivel:" total_time: "Timpul total de joc:" average_levels: "Media nivelurilor terminate:" total_levels: "Total niveluri terminate:" students: "Elevi" concepts: "Concepte" play_time: "Timp de joc:" completed: "Terminate:" enter_emails: "Separați fiecare adresă de email printr-o linie nouă sau virgulă" send_invites: "Invită elevi" number_programming_students: "Număr de elevi care programează" number_total_students: "Total elevi în școală/Județ" enroll: "Înscriere" enroll_paid: "Înscrie elevi la cursuri plătite" get_enrollments: "Cumpără mai multe licențe" change_language: "Schimbă limba cursului" keep_using: "Continuă să utilizezi" switch_to: "Schimbă" greetings: "Salutări!" back_classrooms: "Înapoi la clasa mea" back_classroom: "Înapoi la clasă" back_courses: "Înapoi la cursurile mele" edit_details: "Modifică detaliile clasei" purchase_enrollments: "Cumpără licențe pentru elevi" remove_student: "șterge elevi" assign: "Alocă" to_assign: "pentru a aloca la cursurile plătite." student: "PI:NAME:<NAME>END_PI" teacher: "PI:NAME:<NAME>END_PI" arena: "Arenă" available_levels: "Niveluri disponibile" started: "începute" complete: "terminate" practice: "încearcă" required: "obligatorii" welcome_to_courses: "Aventurier, bine ai venit la CodeCombat!" ready_to_play: "Ești gata să joci?" start_new_game: "Începe un joc nou" play_now_learn_header: "Joacă acum ca să înveți" play_now_learn_1: "sintaxa de bază utilizată la controlarea personajului" play_now_learn_2: "bucle while pentru a rezolva puzzle-uri dificile" play_now_learn_3: "șiruri de caractere & variabile pentru a personaliza acțiunile" play_now_learn_4: "cum să înfrângi un căpcăun (o abilitate importantă pentru viață!)" my_classes: "Clase curente" class_added: "Clasă adăugată cu succes!" view_map: "vezi harta" view_videos: "vezi filme" view_project_gallery: "vezi proiectele colegilor" join_class: "Alătură-te unei clase" join_class_2: "Alătură-te clasei" ask_teacher_for_code: "Întreabă profesorul dacă ai un cod de clasă CodeCombat! Dacă ai, scrie codul aici:" enter_c_code: "<scrie codul clasei>" join: "Alătură-te" joining: "intrare în clasă" course_complete: "Curs terminat" play_arena: "Joacă în arenă" view_project: "Vezi proiect" start: "Start" last_level: "Ultimul nivel jucat" not_you: "Nu ești tu?" continue_playing: "Continuă să joci" option1_header: "Invită elevi prin email" remove_student1: "Șterge elev" are_you_sure: "Ești sigur că vrei să ștergi acest elev din clasă?" remove_description1: "Elevul va pierde accesul la această clasă și la celelalte clase alocate. Progresul și jocurile făcute NU se pierd, iar elevul va putea fi adăugat la loc în clasă oricând." remove_description2: "Licențele plătite și activate nu pot fi returnate." license_will_revoke: "Licența acestui elev va fi revocată și va deveni disponibilă pentru alocarea unui alt elev." keep_student: "păstrează elev" removing_user: "Ștergere elev" subtitle: "Analizează prezentarea cursului și nivelurilor" # Flat style redesign select_language: "Alege limba" select_level: "Alege nivel" play_level: "Joacă nivel" concepts_covered: "Concepte acoperite" view_guide_online: "Prezentare nivel și soluții" lesson_slides: "Fișe lecție" grants_lifetime_access: "Permite accesul la toate cursurile." enrollment_credits_available: "licențe disponibile:" language_select: "Alege o limbă" # ClassroomSettingsModal language_cannot_change: "Limba nu mai poate fi schimbată după ce elevii se alătură unei clase." avg_student_exp_label: "Experiența de programare medie a elevului" avg_student_exp_desc: "Acest lucru ne ajută să înțelegem cum să stabilim mai bine ritmul cursului." avg_student_exp_select: "Alege opțiunea cea mai bună" avg_student_exp_none: "Fără experiență - puțină sau fără experiență" avg_student_exp_beginner: "Începător - oarecare expunere sau programare cu blocuri" avg_student_exp_intermediate: "Intermediar - oarecare experință cu scrierea de cod" avg_student_exp_advanced: "Avansat - experineță amplă cu scrierea de cod" avg_student_exp_varied: "Nivele variate de experiență" student_age_range_label: "Interval de vârstă al alevilor" student_age_range_younger: "Mai mici de 6" student_age_range_older: "Mai mari de 18" student_age_range_to: "la" estimated_class_dates_label: "Datele estimate a claselor" estimated_class_frequency_label: "Frecvența estimată a claselor" classes_per_week: "clase pe săptămână" minutes_per_class: "minute pe clasă" create_class: "Creează o clasă" class_name: "Nume clasă" teacher_account_restricted: "Contul tău este un cont de utilizator și nu poate accesa conținut specific elevilor." account_restricted: "Un cont de elev este necesar pentru a accesa această pagină." update_account_login_title: "Autentifică-te pentru a schimba contul" update_account_title: "Contul tău necesită atenție!" update_account_blurb: "Înainte de a accesa clasele, alege cum vei dori să utilizezi acest cont." update_account_current_type: "Tipul contului curent:" update_account_account_email: "Email cont/Utilizator:" update_account_am_teacher: "Sunt un profesor" update_account_keep_access: "Mențien accesul la clasele pe care le-am creat" update_account_teachers_can: "Conturile de profesor pot să:" update_account_teachers_can1: "Creeze/administreze/adauge clase" update_account_teachers_can2: "Aloce/înscrie elevi la cursuri" update_account_teachers_can3: "Deblocheze toate nivelurile de curs pentru încercări" update_account_teachers_can4: "Aceseze elemente noi specifice profesorulu atunci când le lansăm" update_account_teachers_warning: "Atenție: Vei fi șters din toate clasele la care te-ai alăturat anterior și nu vei mai putea juca ca și elev." update_account_remain_teacher: "Rămâi profesor" update_account_update_teacher: "Transformă în profesor" update_account_am_student: "Sunt elev" update_account_remove_access: "Șterge accesul la clasele pe care le-am creat" update_account_students_can: "Conturile de elev pot să:" update_account_students_can1: "Se alăture claselor" update_account_students_can2: "Joace printre cursuri ca elev și să își urmărească progresul" update_account_students_can3: "Concureze împotriva colegilor în arenă" update_account_students_can4: "Aceseze elemente noi specifice elevilor atunci când le lansăm" update_account_students_warning: "Atenție: Nu vei putea administra nici o clasă pe care ai creat-o anterior sau să creezi noi clase." unsubscribe_warning: "Atenție: Vei fi dezabonat de la abonamentul lunar." update_account_remain_student: "Rămâi elev" update_account_update_student: "Transformă în elev" need_a_class_code: "Vei avea nevoie de un cod de clasă pentru a te alătura unei clase:" update_account_not_sure: "Nu ști sigur ce să alegi? Email" update_account_confirm_update_student: "Ești sigur că vrei să transformi contul în unul de elev?" update_account_confirm_update_student2: "Nu vei putea administra nici o clasă pe care ai creat-o anterior sau să creezi noi clase. Clasele create anterior vor fi șterse din CodeCombat și nu mai pot fi recuperate." instructor: "Instructor: " youve_been_invited_1: "AI fost invitat să te alături " youve_been_invited_2: ", unde vei învăța " youve_been_invited_3: " cu colegii de clasă în CodeCombat." by_joining_1: "Dacă te alături " by_joining_2: "vei putea să îți resetezi parola dacă o vei pierde sau uita. Poți de asemenea să îți verifici adresa de email ca să îți resetei parola singur!" sent_verification: "Ți-am trimis un email de verificare la:" you_can_edit: "Poți să modifici adresa de email în " account_settings: "Setări cont" select_your_hero: "Alege eroul" select_your_hero_description: "Poți oricând să schimbi eroul din pagina de Cursuri apăsând \"Schimbă erou\"" select_this_hero: "Alege acest erou" current_hero: "Erou curent:" current_hero_female: "Erou curent:" web_dev_language_transition: "Toate clasele programează în HTML / Javascript la acest curs. Clasele care au utilizat Python vor începe cu niveluri suplimentare de Javascript pentru o tranziție mai ușoară. Clasele care deja utilizează Javascript vor sări peste nivelurile introductive." course_membership_required_to_play: "Trebuie să te alături unui curs pentru a juca acest nivel." license_required_to_play: "Cere profesorului tău să îți asocieze o licență pentru a putea continua să joci CodeCombat!" update_old_classroom: "Un nou an școlar, noi niveluri!" update_old_classroom_detail: "Pentru a fi sigur că ai acces la cele mai moi niveluri, creează o nouă clasă pentru acest semestru apăsând Creează clasă nouă în" teacher_dashboard: "Panou de lucru profesor" update_old_classroom_detail_2: "și dând elevilor noul cod de clasă care apare." view_assessments: "Vezi evaluări" view_challenges: "vezi niveluri tip provocare" challenge: "Provocare:" challenge_level: "Nivel tip provocare:" status: "Stare:" assessments: "Evaluări" challenges: "Provocări" level_name: "Nume nivel:" keep_trying: "Continuă să încerci" start_challenge: "Start provocare" locked: "Blocat" concepts_used: "Concepte utilizate:" show_change_log: "Arată modificările acestor niveluri de curs" hide_change_log: "Ascunde schimbările acestor nivele de curs" concept_videos: "Filme despre concept" concept: "Concept:" basic_syntax: "Sintaxa de bază" while_loops: "Bucle while" variables: "Variabile" basic_syntax_desc: "Sintaxa este despre cum să scrii cod. Așa cum sunt citirea și gramatica importanre în scrierea poveștilor și a esurilor, sintaxa este importantă când scriem cod. Oamenii sunt foarte buni în a înțelege ce înseamnă ceva, chiar și atunci când ceva nu este foarte corect, însă calculatoarele nu sunt atât de inteligente și au nevoie ca tu să scrii foarte foarte precis." while_loops_desc: "O buclă este o modalitate de a repeta acțiuni într-un program. Le poți utiliza pentru a nu scrie același cod de mai multe ori (repetitiv), iar atunci când nu ști de câte ori o acțiune se repetă pentru a îndeplini o sarcină." variables_desc: "Lucrul cu variabilele este ca și organizarea lucrurilor în cutii. Dăi unei cutii un nume, de exemplu \"Rechizite școlare\" și apoi vei pune în ea diverse lucruri. Conținutul exact al cutiei se poate schimba de-a lungul timpului, însă tot mereu ce este înăuntru se va numi \"Rechizite școlare\". În programare, variabilele sunt simboluri utilizate pentru a păstra date care se vor schimba pe timpul programului. Variabilele pot păstra o varietate de tipuri de date, inclusiv numere și șiruri de caractere." locked_videos_desc: "Continuă să joci pentru a debloca filmul conceptului __concept_name__." unlocked_videos_desc: "Examinează filmul conceptului __concept_name__ ." video_shown_before: "afișat înainte de __level__" link_google_classroom: "Conectare cu Google Classroom" select_your_classroom: "Alege clasa" no_classrooms_found: "Nu s-a găsit nici o clasă" create_classroom_manually: "Creează clasa manual" classes: "Clase" certificate_btn_print: "Tipărire" certificate_btn_toggle: "Schimbare" ask_next_course: "Vrei să joci mai mult? Întreabă profesorul pentru a accesa cursul următor." set_start_locked_level: "Nivelurile blocate încep la " no_level_limit: "-- (nici un nivel blocat)" ask_teacher_to_unlock: "Întreabă profesorul pentru deblocare" ask_teacher_to_unlock_instructions: "Pentru a juca nivelul următor, roagă profesorul să îl deblocheze din ecranul lor Progres curs" play_next_level: "Joacă următorul nivel" play_tournament: "Joacă în turneu" levels_completed: "Niveluri terminate: __count__" ai_league_team_rankings: "Clasamentul echipelor din Liga IA" view_standings: "Vezi clasările" view_winners: "Vezi câștigătorii classroom_announcement: "Anunțurile clasei" project_gallery: no_projects_published: "Fi primul care publică un proiect în acest curs!" view_project: "Vezi proiect" edit_project: "Modifică proiect" teacher: assigning_course: "Alocă curs" back_to_top: "Înapoi sus" click_student_code: "Apasă pe oprice nivel de mai jos, început sau terminat de un elev, pentru a vedea codul scris." code: "Codul lui __name__" complete_solution: "Soluția completă" course_not_started: "Elevul nu a început încă acest curs." hoc_happy_ed_week: "Săptămâna informaticii fericită!" hoc_blurb1: "Află despre activități gratuite de" hoc_blurb2: "scriere a codului, Joc, Partajare," hoc_blurb3: " descarcă un nou plan de lecție și spune-le elevilor să se autentifice pentru a se juca!" hoc_button_text: "Vezi activitate" no_code_yet: "Elevul nu a scis încă nici un cod pentru acest nivel." open_ended_level: "Nivel deschis-terminat" partial_solution: "Soluție parțială" capstone_solution: "Soluția cea mai bună" removing_course: "Șterge curs" solution_arena_blurb: "Elevii sunt încurajați să rezolve nivelurile din arenă în mod creativ. Soluția furnizată mai jos îndeplinește cerințele acestui nivel din arenă." solution_challenge_blurb: "Elevii sunt încurajați să rezolve nivelurile tip provocare deschise-terminate în mod creativ. O soluție posibilă este afișată mai jos." solution_project_blurb: "Elevii sunt încurajați să construiască proiecte creative în acest nivel. Vă rog să urmăriți liniile directoare din curiculă din Zona de resurse pentru informații despre cum să evaluați aceste proiecte." students_code_blurb: "O soluție corectă pentru fiecare nivel este furnizată acolo unde este cazul. În unele cazuri, este posibil ca un elev să rezoove un nivel utilizând alte linii de cod. Soluțiile nu sunt afișate pentru nivelurile pe care elevii nu le-au început." course_solution: "Soluție curs" level_overview_solutions: "Prezentare nivel și soluții" no_student_assigned: "Nici un elev nu este alocat acestui curs." paren_new: "(nou)" student_code: "Cod student pentru __name__" teacher_dashboard: "Panou de lucru profesor" # Navbar my_classes: "Clasele mele" courses: "Ghiduri curs" enrollments: "Licențe elevi" resources: "Resurse" help: "Ajutor" language: "Limba" edit_class_settings: "modifică setările clasei" access_restricted: "Actualizare cont necesară" teacher_account_required: "Un cont de profesor este necesar pentru a accesa acest conținut." create_teacher_account: "Creează cont profesor" what_is_a_teacher_account: "Ce este un cond de profesor?" teacher_account_explanation: "Un cont de profesor CodeCombat îți permite să creezi clase, să monitorizezi progresul elevilor de-a lungul cursurilor, să administrezi licențele și să accesezi resurse din curicula pe care vrei să o construiești." current_classes: "Clase curente" archived_classes: "Clase arhivate" archived_classes_blurb: "Clasele pot fi arhivate pentru referințe viitoare. Dezarhivează o clasă pentru a o putea vedea în lista de clase curente din nou." view_class: "vezi clasă" view_ai_league_team: "Vezi echipa din liga IA" archive_class: "arhivează clasă" unarchive_class: "dezarhivează clasă" unarchive_this_class: "Dezarhivează această clasă" no_students_yet: "Această clasă nu are încă elevi." no_students_yet_view_class: "Vezi clasa pentru a adăuga elevi." try_refreshing: "(Ar putea fi nevoie să reîncarci pagina)" create_new_class: "Creează o nouă clasă" class_overview: "Vezi pagina clasei" # View Class page avg_playtime: "Timpul mediu al nivelului" total_playtime: "Tmpul de joc total" avg_completed: "Numărul mediu de niveluri teminate" total_completed: "Total niveluri terminate" created: "Create" concepts_covered: "Concepte acoperite" earliest_incomplete: "Primul nivel necompletat" latest_complete: "Ultimul nivel completat" enroll_student: "Înscrie elevi" apply_license: "Adaugă licență" revoke_license: "Înlătură licență" revoke_licenses: "Înlătură toate licențele" course_progress: "Progresul cursului" not_applicable: "N/A" edit: "modifică" edit_2: "Modifică" remove: "șterge" latest_completed: "Ultimul terminat:" sort_by: "Sortează după" progress: "Progres" concepts_used: "Concepte utilizate de elev:" concept_checked: "Concepte verificate:" completed: "Terminat" practice: "Practică" started: "Început" no_progress: "Fără progres" not_required: "Nu este obligatoriu" view_student_code: "Apasă să vezi codul de elev" select_course: "Alege cursul dorit" progress_color_key: "Codul de culoare pentru propgres:" level_in_progress: "Nivel în progres" level_not_started: "Nivel neînceput" project_or_arena: "Proiect sau Arenă" students_not_assigned: "Elevi care nu au fost alocați la {{courseName}}" course_overview: "Prezentare curs" copy_class_code: "Copiază codul clasei" class_code_blurb: "Elevii pot să se alăture clasei utilizând acest cod de clasă. Nu este necesară o adresă de email când creezi un cont de elev cu acest cod de clasă." copy_class_url: "Copiază URL-ul clasei" class_join_url_blurb: "Poți să publici această adresă unică URL pe o pagină de web." add_students_manually: "Invită elevii prin email" bulk_assign: "Alege curs" assigned_msg_1: "{{numberAssigned}} studenți au fost alocați cursului {{courseName}}." assigned_msg_2: "{{numberEnrolled}} licențe au fost aplicate." assigned_msg_3: "Mai ai {{remainingSpots}} licențe disponibile." assign_course: "Alocă curs" removed_course_msg: "{{numberRemoved}} elevi au fost șterși de la cursul {{courseName}}." remove_course: "Șterge curs" not_assigned_msg_1: "Nu poți adăuga elevi la o instanță de curs până când ei nu sunt adăugați unui abonament care conține acest curs" not_assigned_modal_title: "Cursurile nu au fost alocate" not_assigned_modal_starter_body_1: "Acest curs necesită o licență de tip Starter. Nu ai suficiente licențe Starter disponibile pentru a le aloca acestui curs pentru __selected__ de elevi selectați." not_assigned_modal_starter_body_2: "Cumpără licențe Starter pentru a permite accesul la acest curs." not_assigned_modal_full_body_1: "Acest curs necesită licență completă. Nu aveți suficiente licențe complete disponibile pentru a le aloca acestui curs pentru __selected__ de elevi selectați." not_assigned_modal_full_body_2: "Mai aveți doar __numFullLicensesAvailable__ de licențe complete disponibile (__numStudentsWithoutFullLicenses__ elevi nu au o licență completă alocată)." not_assigned_modal_full_body_3: "Te rog să alegi mai puțini elevi, sau contactează-ne la adresa __supportEmail__ pentru asistență." assigned: "Alocate" enroll_selected_students: "Înscrie elevii selectați" no_students_selected: "Nici un student nu este selectat." show_students_from: "Arată elevii din" # Enroll students modal apply_licenses_to_the_following_students: "Alocă licențe acestor elevi" select_license_type: "Selectează tipul de licență de aplicat" students_have_licenses: "Acești elevi au deja licențe alocate:" all_students: "Toți elevii" apply_licenses: "Alocă licențele" not_enough_enrollments: "Licențe disponibile insuficiente." enrollments_blurb: "Elevii trebuie să aibă o licență pentru a accesa conținutul după primul curs." how_to_apply_licenses: "Cum să aloci licențe" export_student_progress: "Exportă progresul elevilor (CSV)" send_email_to: "Trimite email de recuperare parolă la:" email_sent: "Email trimis" send_recovery_email: "Trimite email de recuperare" enter_new_password_below: "Introdu parola mai jos:" change_password: "PI:PASSWORD:<PASSWORD>END_PI" changed: "Schimbată" available_credits: "Licențe disponibile" pending_credits: "Licențe în așteptare" empty_credits: "Licențe epuizate" license_remaining: "licență rămasă" licenses_remaining: "licențe rămase" student_enrollment_history: "Istoricul înscrierilor elevilor" enrollment_explanation_1: "" # the definite article in Ro is placed at the end of the substantive enrollment_explanation_2: "Istoricul înscrierilor elevilor" enrollment_explanation_3: "afișează numărul total de elevi unici care au fost alocați de toți profesorii în toate clasele adăugate în panoul de lucru. Acesta include elevii atât din clasele arhivate cât și nearhivate dintr-o clasă creată între 1 iulie - 30 iunie din respectivul an școlar." enrollment_explanation_4: "Amintește-ți" enrollment_explanation_5: "clasele pot fi arhivate și licențele pot fi reutilizate de-a lungul anului școlar, ceea ce permite administratorilor să înțeleagă câți elevi au participat per ansamblu de fapt în program." one_license_used: "1 din __totalLicenses__ licențe au fost utilizate" num_licenses_used: "__numLicensesUsed__ out of __totalLicenses__ licențe au fost utilizate" starter_licenses: "licențe tip starter" start_date: "data început:" end_date: "data sfărșit:" get_enrollments_blurb: " Te vom ajuta să construiești o soluție care îndeplinește cerințele clasei tale, școlii sau districtului." see_also_our: "Vezi de asemenea" for_more_funding_resources: "pentru informații cu privire la accesarea surselor de finanțare CARES Act cum sunt ESSER și GEER." how_to_apply_licenses_blurb_1: "Când un profesor alocă un curs unui elev pentru prima dată, vom aplica o licență în mod automat. Utilizează lista de alocare în grup din clasa ta pentru a aloca un curs mai multor elevi selectați:" how_to_apply_licenses_blurb_2: "Pot să aplic o licență fără a aloca un curs?" how_to_apply_licenses_blurb_3: "Da — mergi la tabul Stare licențe din clasa ta și apasă \"Aplică licență\" pentru orice elev care nu are încă o licență activă." request_sent: "Cerere transmisă!" assessments: "Evaluări" license_status: "Stare licență" status_expired: "Expiră în {{date}}" status_not_enrolled: "Nu este înrolat" status_enrolled: "Expiră în {{date}}" select_all: "Selectează tot" project: "Proiect" project_gallery: "Galerie proiecte" view_project: "Vezi proiect" unpublished: "(nepublicat)" view_arena_ladder: "Vezi clasament arenă" resource_hub: "Zonă de resurse" pacing_guides: "Ghiduri parcurgere Clasa-în-cutie" pacing_guides_desc: "Învață cum să încorporezi toate resursele CodeCombat în planificarea anului tău școlar!" pacing_guides_elem: "Ghid parcurgere școala primară" pacing_guides_middle: "Ghid parcurgere școala generală" pacing_guides_high: "Ghid parcurgere liceu" getting_started: "Noțiuni de bază" educator_faq: "Întrebări instructori" educator_faq_desc: "Întrebări frecvente despre utilizarea CodeCombat în clasă sau în școală." teacher_getting_started: "Ghid de noțiuni generale pentru profesor" teacher_getting_started_desc: "Nou la CodeCombat? Descarcă acest ghid de noțiuni generale pentru profesori pentru a-ți creea contul, a creea prima ta clasă și a invita elevii la primul curs." student_getting_started: "Ghid rapid de pornire pentru elevi" student_getting_started_desc: "Poți distribui acest ghid elevilor tăi înainte de începerea CodeCombat astfel încât aceștia să se familiarizeze cu editorul de cod. Acest ghid poate fi utilizat atât pentru clasele de Python cât și cele de Javascript." standardized_curricula: "Curicula standardizată" ap_cs_principles: "Principiile AP ale informaticii" ap_cs_principles_desc: "Principiile AP ale informaticii le face elevilor o introducere extinsă asupra puterii, impactului și posibilităților informaticii. Cursul pune accent pe rezolvarea problemelor și gândirea algoritmică și logică în timp ce aceștia învață bazele programării." cs1: "Introducere în informatică" cs2: "Informatică 2" cs3: "Informatică 3" cs4: "Informatică 4" cs5: "Informatică 5" cs1_syntax_python: "Curs 1 - Ghid sinatxă Python" cs1_syntax_python_desc: "Foaie rezumat cu referințe către cele mai uzuale sintaxe Python pe care elevii le vor învăța în lecția Introducere în informatică." cs1_syntax_javascript: "Curs 1 - Ghid sinatxă Javascript" cs1_syntax_javascript_desc: "Foaie rezumat cu referințe către cele mai uzuale sintaxe Javascript syntax pe care elevii le vor învăța în lecția Introducere în informatică." coming_soon: "În curând mai multe ghiduri!" engineering_cycle_worksheet: "Foaie rezumat despre ciclul tehnologic" engineering_cycle_worksheet_desc: "Utilizează această foaie de lucru pentru a-i învăța pe elevi bazele ciclului tehnologic: Evaluare, Proiectare, Implementare și Depanare. Fă referire la fișa cu exemplu complet ca și ghid." engineering_cycle_worksheet_link: "Vezi exemplu" progress_journal: "Jurnal de progres" progress_journal_desc: "Încurajează elevii să-și urmărească progresul cu ajutorul jurnalului de progres." cs1_curriculum: "Introducere în informatică - Ghid de curiculă" cs1_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 1." arenas_curriculum: "Niveluri arenă - Ghid profesor" arenas_curriculum_desc: "Instrucțiuni despre rularea arenelor multi-jucător Wakka Maul, Cross Bones și Power Peak în clasă." assessments_curriculum: "Niveluri de evaluare - Ghid profesor" assessments_curriculum_desc: "Învață cum să utilizezi Nivelurile de provocare și nivelurile de provocare combo pentru a evalua rezultatele învățării." cs2_curriculum: "Informatică 2 - Ghid de curiculă" cs2_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 2." cs3_curriculum: "Informatică 3 - Ghid de curiculă" cs3_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 3." cs4_curriculum: "Informatică 4 - Ghid de curiculă" cs4_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul 4." cs5_curriculum_js: "Informatică 5 - Ghid de curiculă (Javascript)" cs5_curriculum_desc_js: "Scop și secvențiere, planuri de lecții, activități și altele pentru clasele Cursului 5 de Javascript." cs5_curriculum_py: "Informatică 5 - Ghid de curiculă (Python)" cs5_curriculum_desc_py: "Scop și secvențiere, planuri de lecții, activități și altele pentru clasele Cursului 5 de Python." cs1_pairprogramming: "Activitate de programare pe echipe" cs1_pairprogramming_desc: "introduce elevii într-un exercițiu de programare pe echipe care îi va ajuta să fie mai buni la ascultat și la comunicat." gd1: "Dezvoltare joc 1" gd1_guide: "Dezvoltare joc 1 - Ghid de proiect" gd1_guide_desc: "Utilizează acest proiect să ghidezi elevii în crearea primului lor proiect de dezvoltare joc partajat pe parcursul a 5 zile." gd1_rubric: "Dezvoltare joc 1 - Fișă proiect" gd1_rubric_desc: "Utilizează această fișă să evaluezi proiectele elevilor la sfârșitul proiectului Dezvoltare joc 1." gd2: "Dezvoltare joc 2" gd2_curriculum: "Dezvoltare joc 2 - Ghid de curiculă" gd2_curriculum_desc: "Planuri de lecție pentru Dezvoltare joc 2." gd3: "Dezvoltare joc 3" gd3_curriculum: "Dezvoltare joc 3 - Ghid de curiculă" gd3_curriculum_desc: "Planuri de lecție pentru Dezvoltare joc 3." wd1: "Dezvoltare web 1" wd1_curriculum: "Dezvoltare web 1 - Ghid de curiculă" wd1_curriculum_desc: "Scop și secvențiere, planuri de lecții, activități și altele pentru Cursul Dezvoltare web 1." wd1_headlines: "Activitate despre titluri și antete" wd1_headlines_example: "Vezi soluțiile date ca exemplu" wd1_headlines_desc: "De ce sunt marcajele de paragraf și antetele importante? Utilizează această activitate să arăți cât de ușor sunt de citit paginile cu antete bine alese. Sunt mai multe soluții corecte pentru acesta!" wd1_html_syntax: "Ghid de sintaxă HTML" wd1_html_syntax_desc: "Referință de o pagină pentru stilurile HTML pe care elevii le vor învăța în Dezvoltare web 1." wd1_css_syntax: "Ghid sinatxă CSS" wd1_css_syntax_desc: "Referință de o pagină pentru sintaxa stilurilor CSS pe care elevii le vor învăța în Dezvoltare web 1." wd2: "Dezvolatre web 2" wd2_jquery_syntax: "Ghid de sintaxă pentru funcțiile jQuery" wd2_jquery_syntax_desc: "Referință de o pagină pentru sintaxa funcțiilor jQuery pe care elevii le vor învăța în Dezvoltare web 2." wd2_quizlet_worksheet: "Fișă de lucru chestionar" wd2_quizlet_worksheet_instructions: "Vezi instrucțiuni și exemple" wd2_quizlet_worksheet_desc: "Înainte ca elevii să își construiască proiectul cu chestionarul despre personalitate de la sfârșitul cursului Dezvoltare web 2, ar trebui să își planifice mai întâi întrebările, rezultate și răspunsuri utilizând această fișă de lucru. Profesorii pot să distribuie aceste instrucțiuni și exemple ca elevii să poată face referire la acestea." student_overview: "Prezentare generală" student_details: "Detalii elev" student_name: "PI:NAME:<NAME>END_PI" no_name: "Nu este furnizat un nume." no_username: "Nu este furnizat un nume de utilizator." no_email: "Elevul nu are adresă de email setată." student_profile: "Profil elev" playtime_detail: "Detalii despre timpul de joc" student_completed: "Terminate de elev" student_in_progress: "Elev în progress" class_average: "Media clasei" not_assigned: "nu au fost alocate următoarele cursuri" playtime_axis: "Timp de joc în secunde" levels_axis: "Niveluri în" student_state: "Cum se" student_state_2: "descurcă?" student_good: "se descurcă bine în" student_good_detail: "Acest elev ține pasul cu timpul mediu de terminare a nivelului de către clasă." student_warn: "poate avea nevoie de ajutor în" student_warn_detail: "Timpul mediu de terminare a acestui nivel pentru acest elev sugerează că ar putea avea nevoie de ajutor cu conceptele noi care au fost introduse în acest curs." student_great: "se descurcă foarte bine în" student_great_detail: "Acest elev ar putea fi un bun candidat să îi ajute pe ceilalți elevi în acest curs, pe baza timpilor medii de terminare a nivelului." full_license: "Licență completă" starter_license: "Licență începător" customized_license: "Licență personalizată" trial: "Încercare" hoc_welcome: "Săptămână a informaticii fericită" hoc_title: "Jocuri pentru Hour of Code - Activități gratuite pentru a învăța să scrii cod în limbaje de programare reale" hoc_meta_description: "Fă-ți propriul joc sau programează-ți ieșirea din temniță! CodeCombat are patru activități diferite pentru Hour of Code și peste 60 de niveluri să înveți să programezi, să te joci și să creezi." hoc_intro: "Există trei modalități ca și clasa ta să participe la Hour of Code cu CodeCombat" hoc_self_led: "Joc individual" hoc_self_led_desc: "Elevii se pot juca cu tutorialele CodeCombat pentru Hour of Code singuri" hoc_game_dev: "Dezvoltare de joc" hoc_and: "și" hoc_programming: "Programare Javascript/Python" hoc_teacher_led: "Lecții cu profesor" hoc_teacher_led_desc1: "Descarcă" hoc_teacher_led_link: "planurile noastre de lecție pentru Hour of Code" hoc_teacher_led_desc2: "pentru a prezenta elevilor concepte de programare utilizând activități offline" hoc_group: "Joc în grup" hoc_group_desc_1: "Profesorii pot utiliza lecțiile în conjuncție cu cursul Introducere în informatică ca să poată monitoriza progresul elevilor. Vezi" hoc_group_link: "Ghidul de noțiuni de bază" hoc_group_desc_2: "pentru mai multe detalii" hoc_additional_desc1: "Pentru resurse și activități educaționale CodeCombat, vezi" hoc_additional_desc2: "Întrebările" hoc_additional_contact: "Ține legătura" revoke_confirm: "Ești sigur că vrei să înlături licența completă de la {{student_name}}? Licența va deveni disponibilă să o aloci altui elev." revoke_all_confirm: "Ești sigur că vrei să înlături licențele complete de la toți elevii din clasa aceasta?" revoking: "Revocare..." unused_licenses: "Ai licențe neutilizate care îți permit să aloci elevilor cursuri plătite atunci când aceștia vor fi gata să învețe mai mult!" remember_new_courses: "Amintește-ți să aloci cursuri noi!" more_info: "Mai multe informații" how_to_assign_courses: "Cum să aloci cursuri" select_students: "Alege elevi" select_instructions: "Selectează căsuța din dreptul fiecărui elev pentru care vrei să adaugi cursuri." choose_course: "Alege curs" choose_instructions: "Alege cursul din lista derulantă care vrei să îl aloci, apoi apasă “Alocă elevilor selectați.”" push_projects: "recomandăm alocarea cursului Dezvoltare web 1 sau Dezvoltare joc 1 după ce elevii au terminat Introducere în informatică! Vezi {{resource_hub}} pentru mai multe detalii despre aceste cursuri." teacher_quest: "Aventura profesorului către succes" quests_complete: "Aventuri terminate" teacher_quest_create_classroom: "Creează clasă" teacher_quest_add_students: "Adaugă elevi" teacher_quest_teach_methods: "Ajută-i pe elevii tăi să învețe cum să `cheme metode`." teacher_quest_teach_methods_step1: "Obține 75% din primul nivel cu cel puțin o clasă la Dungeons of Kithgard" teacher_quest_teach_methods_step2: "Tipărește [Ghidul elevului de introducere rapidă](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) din Zona de resurse." teacher_quest_teach_strings: "Nu îți face elevii să meargă pe ață (string), învață-i despre șiruri de caractere - `strings`." teacher_quest_teach_strings_step1: "Obține 75% cu cel puțin o clasă la Nume adevărate (True Names)" teacher_quest_teach_strings_step2: "Utilizează Selectorul de nivel al profesorului în pagina [Ghiduri de cursuri](/teachers/courses) să vezi prezentare Nume adevărate." teacher_quest_teach_loops: "Ține-ți elevii aproape cu buclele - `loops`." teacher_quest_teach_loops_step1: "Obține 75% cu cel puțin o clasă la Focul dansator (Fire Dancing)." teacher_quest_teach_loops_step2: "Utilizează Activitatea despre bocle din [Ghidul de curiculă CS1](/teachers/resources/cs1) pentru a întări acest concept." teacher_quest_teach_variables: "Variaz-l un pic cu variabilele - `variables`." teacher_quest_teach_variables_step1: "Obține 75% ocu cel puțin o clasă la Inamicul cunoscut (Known Enemy)." teacher_quest_teach_variables_step2: "Încurajează colaborarer utilizând [Activitatea de programare în perechi](/teachers/resources/pair-programming)." teacher_quest_kithgard_gates_100: "Evadează din Porțile Kithgard(Kithgard Gates) cu clasa ta." teacher_quest_kithgard_gates_100_step1: "Obține 75% cu cel puțin o clasă la Porțile Kithgard." teacher_quest_kithgard_gates_100_step2: "Îndrumă elevi cum să gândească problemele complexe utilizând [Foaie rezumat despre ciclul tehnologic](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)." teacher_quest_wakka_maul_100: "Pregătește-te de duel în Wakka Maul." teacher_quest_wakka_maul_100_step1: "Obține 75% cu cel puțin o clasă la Wakka Maul." teacher_quest_wakka_maul_100_step2: "Vezi [Ghidul arenei](/teachers/resources/arenas) din [Zona de resurse](/teachers/resources) pentru sfaturi despre cum să desfășori cu succes o zi de arenă." teacher_quest_reach_gamedev: "Explorează nou lumi!" teacher_quest_reach_gamedev_step1: "[Cumpără licențe](/teachers/licenses) ca elevii tăi să poată explora noi lumi, ca Dezvoltare de joc și Dezvoltare web!" teacher_quest_done: "Vrei ca elevii tăi să învețe să scrie cod și mai mult? Ia legătura cu [specialiștii școlari](mailto:PI:EMAIL:<EMAIL>END_PI) astăzi!" teacher_quest_keep_going: "Continuă! Iată ce poți face mai departe:" teacher_quest_more: "Vezi toate misiunile" teacher_quest_less: "Vezi mai puține misiuni" refresh_to_update: "(reîncarcă pagina să vezi noutățile)" view_project_gallery: "Vezi galeria de proiecte" office_hours: "Conferințe pentru profesori" office_hours_detail: "Învață cum să ți pasul cu elevii tăi în timp ce aceștia creează jocuri și se îmbarcă în aventura lor de scriere a codului! Vino și participă la" office_hours_link: "conferințe pentru profesori" office_hours_detail_2: "." #included in the previous line success: "Succes" in_progress: "În progres" not_started: "Nu a început" mid_course: "Curs la jumătate" end_course: "Curs terminat" none: "Nedetectat încă" explain_open_ended: "Notă: Elevii sunt încurajați să rezolve acest nivel în mod creativ — o soluție posibilă este dată mai jos." level_label: "Nivel:" time_played_label: "Timp jucat:" back_to_resource_hub: "Înapoi la Zona de resurse" back_to_course_guides: "Înapoi la Ghidurile de curs" print_guide: "Tipărește acest ghid" combo: "Combo" combo_explanation: "Elevi trec de nivelurile de provocare combo utilizând cel puțin unul din conceptele listate. Analizează codul elevului apăsând pe punctul de progres." concept: "Concept" sync_google_classroom: "Sincronizează Clasa Google" try_ozaria_footer: "Încearcă noul nostru joc de aventură, Ozaria!" try_ozaria_free: "Încearcă gratuit Ozaria" ozaria_intro: "Introducem noul nostru program de informatică" teacher_ozaria_encouragement_modal: title: "Dezvoltă-ți abilitățile de programare pentru a salva Ozaria" sub_title: "Ești invitat să încerci noul joc de aventură de la CodeCombat" cancel: "Înapoi la CodeCombat" accept: "Încearcă prima unitate gratuit" bullet1: "Aprofundați conexiunea elevului cu învățarea printr-o poveste epică și un joc captivant" bullet2: "Predă fundamentele informaticii, Python sau Javascript și alte abilități specifice secolului 21" bullet3: "Deblochează creativitatea prin proiecte personalizate" bullet4: "Instrucțiuni de suport prin resurse curiculare dedicate" you_can_return: "Poți oricând să te întorci la CodeCombat" educator_signup_ozaria_encouragement: recommended_for: "Recomandat pentru:" independent_learners: "Cursanți independenți" homeschoolers: "Elevii școlii de acasă" educators_continue_coco: "Instructorii care doresc să continue să utilizeze CodeCombat în clasa lor" continue_coco: "Continuă cu CodeCombat" ozaria_cta: title1: "Curicula de bază aliniată standardelor" description1: "Captivantă, povestea este bazată pe o curiculă care îndeplinește standardele CSTA pentru clasele 6-8." title2: "Planuri de lecție la cheie" description2: "Prezentare detaliată și foi de lucru pentru profesori pentru ghidarea elevilor printre obiectivele de învățare." title3: "Profesor nou & Panouri de administrare" # description3: "All the actionable insights educators need at a glance, such as student progress and concept understanding." share_licenses: share_licenses: "Partajează licențe" shared_by: "Partajat de:" add_teacher_label: "Introdu adresa de email exactă a profesorului:" add_teacher_button: "Adaugă profesor" subheader: "Poți să îți faci licențele disponibile altor profesori din organizația ta. Fiecare licență poate fi utilizată pentru un singur elev la un moment dat." teacher_not_found: "Profesor negăsit. Te rog verifică dacă acest profesor are deja un Cont de profesor." teacher_not_valid: "Acesta nu este un Cond de profesor valid. Numai conturile de profesor pot partaja licențe." already_shared: "Ai partajat deja aceste licențe cu acel profesor." have_not_shared: "Nu ai partajat aceste licente cu acel profesor." teachers_using_these: "Profesori care pot accesa aceste licențe:" footer: "Când profesorii înlătură licențele de la elevi, licențele vor fi returnate în setul partajat pentru ca alți profesori din acest grup să le poată utiliza." you: "(tu)" one_license_used: "(1 licență utilizată)" licenses_used: "(__licensesUsed__ licențe utilizate)" more_info: "Mai multe informații" sharing: game: "Jov" webpage: "Pagină web" your_students_preview: "Elevii tăi vor apăsa aici ca să își vadă proiectele finalizate! Nedisponibil în zona profesorului." unavailable: "Link-ul de partajare nu este disponibil în zona profesorului." share_game: "Partajează acest joc" share_web: "Partajează această pagină web" victory_share_prefix: "Partajează acest link ca să inviți prietenii și familia" victory_share_prefix_short: "Invită persoane să" victory_share_game: "joace nivelul tău de joc" victory_share_web: "vadă pagina ta web" victory_share_suffix: "." victory_course_share_prefix: "Acest link îi lasă pe prietenii & familia ta să" victory_course_share_game: "joace jocul" victory_course_share_web: "vadă pagina web" victory_course_share_suffix: "pe care l-ai creat/ai creat-o." copy_url: "Copiază URL" share_with_teacher_email: "trimite profesorului tău" share_ladder_link: "Partajează link multi-jucător" ladder_link_title: "Partajează link către meciul tău multi-jucător" ladder_link_blurb: "Partajează link-ul de luptă IA ca prietenii și familia să joace împotriva codului tău:" game_dev: creator: "PI:NAME:<NAME>END_PI" web_dev: image_gallery_title: "Galeria cu imagini" select_an_image: "Alege o imagine pe care vrei să o utilizezi" scroll_down_for_more_images: "(Derulează în jos pentru mai multe imagini)" copy_the_url: "Copiază URL-ul de mai jos" copy_the_url_description: "Util dacă vrei să schimbi o imagine existentă." copy_the_img_tag: "Copiază marcajul <img>" copy_the_img_tag_description: "Util dacă vrei să schimbi o imagine nouă." copy_url: "Copiază URL" copy_img: "Copiază <img>" how_to_copy_paste: "Cum să Copiezi/Lipești" copy: "Copiază" paste: "Lipește" back_to_editing: "Înapoi la editare" classes: archmage_title: "Archmage" archmage_title_description: "(Programator)" archmage_summary: "Dacă ești un dezvoltator interesat să programezi jocuri educaționale, devino Archmage și ajută-ne să construim CodeCombat!" artisan_title: "Artizan" artisan_title_description: "(Creator de nivele)" artisan_summary: "Construiește și oferă nivele pentru tine și pentru prieteni tăi, ca să se joace. PI:NAME:<NAME>END_PI și învață arta de a împărtăși cunoștințe despre programare." adventurer_title: "API:NAME:<NAME>END_PIurier" adventurer_title_description: "(Playtester de nivele)" adventurer_summary: "Primește nivelele noastre noi (chiar și cele pentru abonați) gratis cu o săptămână înainte și ajută-ne să reparăm erorile până la lansare." scribe_title: "scrib" scribe_title_description: "(Editor de articole)" scribe_summary: "Un cod bun are nevoie de o documentație bună. scrie, editează și improvizează documentația citită de milioane de jucători din întreaga lume." diplomat_title: "Diplomat" diplomat_title_description: "(Translator)" diplomat_summary: "CodeCombat e tradus în 45+ de limbi de Diplomații noștri. Ajută-ne și contribuie la traducere." ambassador_title: "Ambasador" ambassador_title_description: "(Suport)" ambassador_summary: "Îmblânzește utilizatorii de pe forumul nostru și oferă direcții pentru cei cu întrebări. Ambasadorii noștri reprezintă CodeCombat în fața lumii." teacher_title: "PI:NAME:<NAME>END_PIesPI:NAME:<NAME>END_PI" editor: main_title: "Editori CodeCombat" article_title: "Editor de articole" thang_title: "Editor thang" level_title: "Editor niveluri" course_title: "Editor curs" achievement_title: "Editor realizări" poll_title: "Editor sondaje" back: "Înapoi" revert: "Revino la versiunea anterioară" revert_models: "Resetează Modelele" pick_a_terrain: "Alege terenul" dungeon: "Temniță" indoor: "Interior" desert: "Deșert" grassy: "Ierbos" mountain: "Munte" glacier: "Ghețar" small: "Mic" large: "Mare" fork_title: "Fork Versiune Nouă" fork_creating: "Creare Fork..." generate_terrain: "Generează teren" more: "Mai multe" wiki: "Wiki" live_chat: "Chat Live" thang_main: "Principal" thang_spritesheets: "Spritesheets" thang_colors: "Culori" level_some_options: "Opțiuni?" level_tab_thangs: "Thangs" level_tab_scripts: "script-uri" level_tab_components: "Componente" level_tab_systems: "Sisteme" level_tab_docs: "Documentație" level_tab_thangs_title: "Thangs actuali" level_tab_thangs_all: "Toate" level_tab_thangs_conditions: "Condiți inițiale" level_tab_thangs_add: "Adaugă thangs" level_tab_thangs_search: "Caută thangs" add_components: "Adaugă componente" component_configs: "Configurare componente" config_thang: "Dublu click pentru a configura un thang" delete: "Șterge" duplicate: "Duplică" stop_duplicate: "Oprește duplicarea" rotate: "Rotește" level_component_tab_title: "Componente actuale" level_component_btn_new: "Creează componentă nouă" level_systems_tab_title: "Sisteme actuale" level_systems_btn_new: "Creează sistem nou" level_systems_btn_add: "Adaugă sistem" level_components_title: "Înapoi la toți Thangs" level_components_type: "Tip" level_component_edit_title: "Editează componentă" level_component_config_schema: "Schema config" level_system_edit_title: "Editează sistem" create_system_title: "Creează sistem nou" new_component_title: "Creează componentă nouă" new_component_field_system: "Sistem" new_article_title: "Creează un articol nou" new_thang_title: "Creează un nou tip de Thang" new_level_title: "Creează un nivel nou" new_article_title_login: "Loghează-te pentru a crea un Articol Nou" new_thang_title_login: "Loghează-te pentru a crea un Thang de Tip Nou" new_level_title_login: "Loghează-te pentru a crea un Nivel Nou" new_achievement_title: "Creează o realizare nouă" new_achievement_title_login: "Loghează-te pentru a crea o realizare nouă" new_poll_title: "Creează un sondaj nou" new_poll_title_login: "Autentifică-te pentru a crea un sondaj nou" article_search_title: "Caută articole aici" thang_search_title: "Caută tipuri de Thang aici" level_search_title: "Caută niveluri aici" achievement_search_title: "Caută realizări" poll_search_title: "Caută sondaje" read_only_warning2: "Notă: nu poți salva editările aici, pentru că nu ești autentificat." no_achievements: "Nici-un achivement adăugat acestui nivel până acum." achievement_query_misc: "Realizări cheie din diverse" achievement_query_goals: "Realizări cheie din obiectivele nivelurilor" level_completion: "Finalizare nivel" pop_i18n: "Populează I18N" tasks: "Sarcini" clear_storage: "Șterge schimbările locale" add_system_title: "Adaugă sisteme la nivel" done_adding: "Terminat de adăugat" article: edit_btn_preview: "Preview" edit_article_title: "Editează articol" polls: priority: "Prioritate" contribute: page_title: "Contribuțtii" intro_blurb: "CodeCombat este 100% open source! Sute de jucători dedicați ne-au ajutat să transformăm jocul în cea ce este astăzi. Alătură-te și scrie următorul capitol din aventura CodeCombat pentru a ajuta lumea să învețe cod!" # {change} alert_account_message_intro: "Salutare!" alert_account_message: "Pentru a te abona la mesajele email ale clasei trebuie să fi autentificat." archmage_introduction: "Una dintre cele mai bune părți despre construirea unui joc este că sintetizează atât de multe lucruri diferite. Grafică, sunet, conectarea în timp real, rețelele sociale și desigur multe dintre aspectele comune ale programării, de la gestiunea de nivel scăzut a bazelor de date și administrarea serverelor până la construirea de interfețe. Este mult de muncă și dacă ești un programator cu experiență, cu un dor de a te arunca cu capul înainte în CodeCombat, această clasă ți se potrivește. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." class_attributes: "Atribute pe clase" archmage_attribute_1_pref: "Cunoștințe în " archmage_attribute_1_suf: ", sau o dorință de a învăța. Majoritatea codului este în acest limbaj. Dacă ești fan Ruby sau Python, te vei simți ca acasă. Este Javascript, dar cu o sintaxă mai frumoasă." archmage_attribute_2: "Ceva experiență în programare și inițiativă personală. Te vom ajuta să te orientezi, dar nu putem aloca prea mult timp pentru a te pregăti." how_to_join: "Cum să ni te alături" join_desc_1: "Oricine poate să ajute! Doar intrați pe " join_desc_2: "pentru a începe, bifați căsuța de dedesubt pentru a te marca ca un Archmage curajos și pentru a primi ultimele știri pe email. Vrei să discuți despre ce să faci sau cum să te implici mai mult? " join_desc_3: ", sau găsește-ne în " join_desc_4: "și pornim de acolo!" join_url_email: "Trimite-ne Email" join_url_slack: "canal public de Slack" archmage_subscribe_desc: "Primește email-uri despre noi oportunități de progrmare și anunțuri." artisan_introduction_pref: "Trebuie să construim nivele adiționale! Oamenii sunt nerăbdători pentru mai mult conținut, și noi putem face doar atât singuri. Momentan editorul de nivele abia este utilizabil până și de creatorii lui, așa că aveți grijă. Dacă ai viziuni cu campanii care cuprind bucle for pentru" artisan_introduction_suf: ", atunci aceasta ar fi clasa pentru tine." artisan_attribute_1: "Orice experiență în crearea de conținut ca acesta ar fi de preferat, precum folosirea editoarelor de nivele de la Blizzard. Dar nu este obligatoriu!" artisan_attribute_2: "Un chef de a face o mulțime de teste și iterări. Pentru a face nivele bune, trebuie să fie test de mai mulți oameni și să obțineți păreri și să fiți pregăți să reparați o mulțime de lucruri." artisan_attribute_3: "Pentru moment trebuie să ai nervi de oțel. Editorul nostru de nivele este abia la început și încă are multe probleme. Ai fost avertizat!" artisan_join_desc: "Folosiți editorul de nivele urmărind acești pași, mai mult sau mai puțin:" artisan_join_step1: "Citește documentația." artisan_join_step2: "Creează un nivel nou și explorează nivelurile deja existente." artisan_join_step3: "Găsește-ne pe chatul nostru de Hipchat pentru ajutor." artisan_join_step4: "Postează nivelurile tale pe forum pentru feedback." artisan_subscribe_desc: "Primește email-uri despre update-uri legate de Editorul de nivele și anunțuri." adventurer_introduction: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze niveluri noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura, atunci aceasta este clasa pentru tine." adventurer_attribute_1: "O sete de cunoaștere. Tu vrei să înveți cum să programezi și noi vrem să te învățăm. Cel mai probabil tu vei fi cel care va preda mai mult în acest caz." adventurer_attribute_2: "Carismatic. Formulează într-un mod clar ceea ce trebuie îmbunătățit și oferă sugestii." adventurer_join_pref: "Ori fă echipă (sau recrutează!) cu un Artizan și lucreează cu el, sau bifează căsuța de mai jos pentru a primi email când sunt noi niveluri de testat. De asemenea vom posta despre niveluri care trebuie revizuite pe rețelele noastre precum" adventurer_forum_url: "forumul nostru" adventurer_join_suf: "deci dacă preferi să fi înștiințat în acele moduri, înscrie-te acolo!" adventurer_subscribe_desc: "Primește email-uri când sunt noi niveluri de testat." scribe_introduction_pref: "CodeCombat nu o să fie doar o colecție de niveluri. Vor fi incluse resurse de cunoaștere, un wiki despre concepte de programare legate de fiecare nivel. În felul acesta fiecare Artisan nu trebuie să mai descrie în detaliu ce este un operator de comparație, ei pot să pună un link la un articol mai bine documentat. Ceva asemănător cu ce " scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: " a construit. Dacă idea ta de distracție este să articulezi conceptele de programare în formă Markdown, această clasă ți s-ar potrivi." scribe_attribute_1: "Un talent în cuvinte este tot ce îți trebuie. Nu numai gramatică și ortografie, trebuie să poți să explici ideii complicate celorlați." contact_us_url: "Contactați-ne" # {change} scribe_join_description: "spune-ne câte ceva despre tine, experiențele tale despre programare și despre ce fel de lucruri ți-ar place să scrid. Vom începe de acolo!." scribe_subscribe_desc: "Primește email-uri despre scrisul de articole." diplomat_introduction_pref: "Dacă ar fi un lucru care l-am învățat din " diplomat_introduction_url: "comunitatea open source" diplomat_introduction_suf: "acesta ar fi că: există un interes mare pentru CodeCombat și în alte țări! Încercăm să adunăm cât mai mulți traducători care sunt pregătiți să transforme un set de cuvinte intr-un alt set de cuvinte ca să facă CodeCombat cât mai accesibil în toată lumea. Dacă vrei să tragi cu ochiul la conțintul ce va apărea și să aduci niveluri cât mai repede pentru conaționalii tăi, această clasă ți se potrivește." diplomat_attribute_1: "Fluență în Engleză și limba în care vrei să traduci. Când explici idei complicate este important să înțelegi bine ambele limbi!" diplomat_i18n_page_prefix: "Poți începe să traduci nivele accesând" diplomat_i18n_page: "Pagina de traduceri" diplomat_i18n_page_suffix: ", sau interfața și site-ul web pe GitHub." diplomat_join_pref_github: "Găsește fișierul pentru limba ta " diplomat_github_url: "pe GitHub" diplomat_join_suf_github: ", editează-l online și trimite un pull request. Bifează căsuța de mai jos ca să fi up-to-date cu dezvoltările noastre internaționale!" diplomat_subscribe_desc: "Primește mail-uri despre dezvoltările i18n și niveluri de tradus." ambassador_introduction: "Aceasta este o comunitate pe care o construim, iar voi sunteți conexiunile. Avem forumuri, email-uri și rețele sociale cu mulți oameni cu care se poate vorbi despre joc și de la care se poate învăța. Dacă vrei să ajuți oameni să se implice și să se distreze această clasă este potrivită pentru tine." ambassador_attribute_1: "Abilități de comunicare. Abilitatea de a indentifica problemele pe care jucătorii le au si să îi poți ajuta. De asemenea, trebuie să ne informezi cu părerile jucătoriilor, ce le place și ce vor mai mult!" ambassador_join_desc: "spune-ne câte ceva despre tine, ce ai făcut și ce te interesează să faci. Vom porni de acolo!." ambassador_join_step1: "Citește documentația." ambassador_join_step2: "ne găsești pe canalul public de Slack." ambassador_join_step3: "Ajută pe alții din categoria Ambasador." ambassador_subscribe_desc: "Primește email-uri despre actualizările suport și dezvoltări multi-jucător." teacher_subscribe_desc: "Primește mesaje email pentru actualizări și anunțuri destinate profesorilor." changes_auto_save: "Modificările sunt salvate automat când apeși checkbox-uri." diligent_scribes: "scribii noștri:" powerful_archmages: "Bravii noștri Archmage:" creative_artisans: "Artizanii noștri creativi:" brave_adventurers: "Aventurierii noștri neînfricați:" translating_diplomats: "Diplomații noștri abili:" helpful_ambassadors: "Ambasadorii noștri de ajutor:" ladder: title: "Arene multi-jucător" arena_title: "__arena__ | Arenă multi-jucător" my_matches: "Jocurile mele" simulate: "Simulează" simulation_explanation: "Simulând jocuri poți afla poziția în clasament a jocului tău mai repede!" simulation_explanation_leagues: "Vei simula în principal jocuri pentru jucătorii aliați din clanul și cursurile tale." simulate_games: "Simulează Jocuri!" games_simulated_by: "Jocuri simulate de tine:" games_simulated_for: "Jocuri simulate pentru tine:" games_in_queue: "Jocuri aflate în prezent în așteptare:" games_simulated: "Jocuri simulate" games_played: "Jocuri jucate" ratio: "Rație" leaderboard: "Clasament" battle_as: "Luptă ca " summary_your: "Al tău " summary_matches: "Meciuri - " summary_wins: " Victorii, " summary_losses: " Înfrângeri" rank_no_code: "Nici un cod nou pentru Clasament" rank_my_game: "Plasează-mi jocul în Clasament!" rank_submitting: "Se trimite..." rank_submitted: "Se trimite pentru Clasament" rank_failed: "A eșuat plasarea în clasament" rank_being_ranked: "Jocul se plasează în Clasament" rank_last_submitted: "trimis " help_simulate: "Ne ajuți simulând jocuri?" code_being_simulated: "Codul tău este simulat de alți jucători pentru clasament. Se va actualiza cum apar meciuri." no_ranked_matches_pre: "Niciun meci de clasament pentru " no_ranked_matches_post: " echipă! Joacă împotriva unor concurenți și revino apoi aici pentru a-ți plasa meciul în clasament." choose_opponent: "Alege un adversar" select_your_language: "Alege limba!" tutorial_play: "Joacă tutorial-ul" tutorial_recommended: "Recomandat dacă nu ai mai jucat niciodată înainte" tutorial_skip: "Sări peste tutorial" tutorial_not_sure: "Nu ești sigur ce se întâmplă?" tutorial_play_first: "Joacă tutorial-ul mai întâi." simple_ai: "CPU simplu" # {change} warmup: "Încălzire" friends_playing: "Prieteni ce se joacă" log_in_for_friends: "Autentifică-te ca să joci cu prieteni tăi!" social_connect_blurb: "Conectează-te și joacă împotriva prietenilor tăi!" invite_friends_to_battle: "Invită-ți prietenii să se alăture bătăliei" fight: "Luptă!" # {change} watch_victory: "Vizualizează victoria" defeat_the: "Învinge" watch_battle: "Privește lupta" tournament_starts: "Turneul începe" tournament_started: ", a început" tournament_ends: "Turneul se termină" tournament_ended: "Turneul s-a terminat" tournament_results_published: ", rezultate publicate" tournament_rules: "Regulile turneului" tournament_blurb_criss_cross: "Caștigă pariuri, creează căi, păcălește-ți oponenți, strânge pietre prețioase și îmbunătățește-ți cariera în turneul Criss-Cross! Află detalii" tournament_blurb_zero_sum: "Dezlănțuie creativitatea de programare în strângerea de aur sau în tactici de bătălie în meciul în oglindă din munte dintre vrăjitorii roși și cei albaștri.Turneul începe Vineri, 27 Martie și se va desfăsura până Luni, 6 Aprilie la 5PM PDT. Află detalii" # tournament_blurb_ace_of_coders: "Battle it out in the frozen glacier in this domination-style mirror match! The tournament began on Wednesday, September 16 and will run until Wednesday, October 14 at 5PM PDT. Check out the details" tournament_blurb_blog: "pe blogul nostru" rules: "Reguli" winners: "Învingători" league: "Ligă" red_ai: "CPU Roșu" # "Red AI Wins", at end of multiplayer match playback blue_ai: "PI:NAME:<NAME>END_PI" wins: "PI:NAME:<NAME>END_PI" # At end of multiplayer match playback losses: "Pierderi" win_num: "Victorii" loss_num: "Pierderi" win_rate: "Victorii %" humans: "PI:NAME:<NAME>END_PI" # Ladder page display team name ogres: "PI:NAME:<NAME>END_PI" tournament_end_desc: "Turneul este terminat, mulțumim că ați jucat" age: "Vârsta" age_bracket: "Intervalul de vârstă" bracket_0_11: "0-11" bracket_11_14: "11-14" bracket_14_18: "14-18" bracket_11_18: "11-18" bracket_open: "Deschis" user: user_title: "__name__ - PI:NAME:<NAME>END_PIță să scrii cod cu CodeCombat" stats: "Statistici" singleplayer_title: "Niveluri individuale" multiplayer_title: "Niveluri multi-jucător" achievements_title: "Realizări" last_played: "Ultima oară jucat" status: "Stare" status_completed: "Complet" status_unfinished: "Neterminat" no_singleplayer: "Niciun joc individual jucat." no_multiplayer: "Niciun joc multi-jucător jucat." no_achievements: "Nici o realizare obținută." favorite_prefix: "Limbaj preferat" favorite_postfix: "." not_member_of_clans: "Nu ești membrul unui clan." certificate_view: "vezi certificat" certificate_click_to_view: "apasă să vezi certificatul" certificate_course_incomplete: "curs incomplet" certificate_of_completion: "Certificat de participare" certificate_endorsed_by: "Aprobat de" certificate_stats: "Nivelul de curs" certificate_lines_of: "linii de" certificate_levels_completed: "niveluri terminate" certificate_for: "pentru" certificate_number: "Nr." achievements: last_earned: "Ultimul câștigat" amount_achieved: "Sumă" achievement: "Realizare" current_xp_prefix: "" current_xp_postfix: " în total" new_xp_prefix: "" new_xp_postfix: " câștigat" left_xp_prefix: "" left_xp_infix: " până la nivelul" left_xp_postfix: "" account: title: "Cont" settings_title: "Setări cont" unsubscribe_title: "Dezabonare" payments_title: "Plăți" subscription_title: "Abonament" invoices_title: "Facturi" prepaids_title: "Preplătite" payments: "Plăți" prepaid_codes: "Coduri preplătite" purchased: "Cumpărate" subscribe_for_gems: "Abonează-te pentru pietre" subscription: "Abonament" invoices: "Facturi" service_apple: "Apple" service_web: "Web" paid_on: "Plătit pe" service: "Service" price: "Preț" gems: "Pietre prețioase" active: "Activ" subscribed: "Abonat" unsubscribed: "Dezabonat" active_until: "Activ până la" cost: "Cost" next_payment: "Următoarea plată" card: "Card" status_unsubscribed_active: "Nu ești abonat și nu vei fi facturat, contul tău este activ deocamdată." status_unsubscribed: "Primește access la niveluri noi, eroi, articole și pietre prețioase bonus cu un abonament CodeCombat!" not_yet_verified: "Neverificat încă." resend_email: "Te rog să salvezi mai întâi apoi retrimite email" email_sent: "Email transmis! Verifică casuța de email." verifying_email: "Verificarea adresei de email..." successfully_verified: "Ai verificat cu succes căsuța de email!" verify_error: "ceva a mers rău la verificarea adresei tale de email :(" unsubscribe_from_marketing: "Dezabonează __email__ de la toate mesajele de marketing ale CodeCombat?" unsubscribe_button: "Da, dezabonează" unsubscribe_failed: "Eșuat" unsubscribe_success: "Succes" manage_billing: "Administrare facturi" account_invoices: amount: "Sumă in dolari US" declined: "Cardul tău a fost refuzat" invalid_amount: "Introdu o sumă în dolari US." not_logged_in: "Autentifică-te sau Creează un cont pentru a accesa facturile." pay: "Plată factură" purchasing: "Cumpăr..." retrying: "Eroare server, reîncerc." success: "Plătit cu success. Mulțumim!" account_prepaid: purchase_code: "Cumpără un cod de abonament" purchase_code1: "Codurile de abonament revendicate vor adăuga o perioadă de subscripție premium la unul sau mai multe conturi pentru versiunea Home a CodeCombat." purchase_code2: "Fiecare cont CodeCombat poate revendica un anumit cod de abonament o singură dată." purchase_code3: "Codurile lunare de abnament vor fi adăugate în cont la sfârsitul abonamentelor deja existente." purchase_code4: "Codurile de abonament sunt pentru conturile care au acces la versiunea Home a CodeCombat, ele nu pot fi utilizate ca licențe de elevi la versiunea Classroom." purchase_code5: "Pentru mai multe informații asupra licențelor de elevi, contactați-ne la" users: "Utilizatori" months: "luni" purchase_total: "Total" purchase_button: "Transmite cererea de cumpărare" your_codes: "Codurile tale" redeem_codes: "Revendicare cod de abonament" prepaid_code: "Cod pre-plătit" lookup_code: "Vezi coduri pre-plătite" apply_account: "Aplică contului tău" copy_link: "Poți copia link-ul de cod și îl poți transmite către o altă persoană." quantity: "Cantitate" redeemed: "Revendicate" no_codes: "Nici un cod încă!" you_can1: "Poți" you_can2: "cumpăra un cod pre-plătit" you_can3: "care poate fi aplicat contului tău sau poate fi dat altora." impact: hero_heading: "Construim o clasă de informatică la nivel global" hero_subheading: "Ajutăm profesorii implicați și inspirăm elevii din întreaga țară" featured_partner_story: "Experiențele partenerilor noștri" partner_heading: "Predarea cu succes a programării la Title I School" partner_school: "Școala gimanzială PI:NAME:<NAME>END_PI" featured_teacher: "PI:NAME:<NAME>END_PI" teacher_title: "Profesor de tehnologie în Coachella, CA" implementation: "Implementare" grades_taught: "Predare la clasele" length_use: "Timp utilizare" length_use_time: "3 ani" students_enrolled: "Elevi înscriși anul acesta" students_enrolled_number: "130" courses_covered: "Cursuri acoperite" course1: "CompSci 1" course2: "CompSci 2" course3: "CompSci 3" course4: "CompSci 4" course5: "GameDev 1" fav_features: "Caracterisitici preferate" responsive_support: "Suport responsiv" immediate_engagement: "Angajare imediată" paragraph1: "Școala gimanzială PI:NAME:<NAME>END_PI se află situată între munții Coachella Valley din California de sud în vest și est și la 33 mile de Salton Sea în sud, și are o pulație de 697 elevi în cadrul unei populații de 18,861 elevi din districtul Coachella Valley Unified." paragraph2: "Elevii școlii gimanziale PI:NAME:<NAME>END_PI reflectă provocările socio-economice ale populației și elevilor din Valea Coachella. Cu peste 95% dintre copii din Școala gimnazială calaficându-se pentru programul de masă gratuit sau cu preț redus și peste 40% clasificați ca populație ce învață limba Engleză, importanța predării unor aptitudini ale secolului 21 a fost o prioritate de top a profesorului de tehnologie din Școala gimanziă PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI." paragraph3: "PI:NAME:<NAME>END_PI a știut că învățarea elevilor să scrie cod este o modalitate importantă pentru a creea o oportunitate în condițiile în care piața muncii prioritizează din ce în ce mai mult și necesită abilități în domeniul calculatoarelor. De aceea, s-a hotărât să își asume această provocare captivantă de creare și predare a singurei clase de programare din școală și găsirea unei soluții accesibile financiar, care răspunde rapid la păreri, și antrenantă pentru elevi cu diverse abilități și condiții de studiu." teacher_quote: "Când am pus mâna pe CodeCombat [și] elevii mei au început să îl folosească, am avut o revelație. Era diferit ca ziua de noapte față de alte programe pe care le-am utilizat. Nu se apropie nici măcar un pic." quote_attribution: "PI:NAME:<NAME>END_PI, Profesor de tehnologe" read_full_story: "Citește povestea întreagă" more_stories: "Mai multe experiențe ale partenerilor" partners_heading_1: "Sprijin pentru mai multe linii de învățare informatică într-o singură clasă" partners_school_1: "Liceul Preston" partners_heading_2: "Excelență în examenele de plasare - AP Exam" partners_school_2: "Liceul River Ridge" partners_heading_3: "Predare informaticăă fără o experiență prealabilă" partners_school_3: "Liceul Riverdale" download_study: "Descarcă studiul de cercetare" teacher_spotlight: "Profesor & Elev în lumina reflectoarelor" teacher_name_1: "PI:NAME:<NAME>END_PI" teacher_title_1: "Instructor de reabilitare" teacher_location_1: "Morehead, Kentucky" spotlight_1: "Prin compasiunea ei și dorința de a ajuta pe cei ce au nevoie de a adoua șansă, PI:NAME:<NAME>END_PI a ajutat la schimbarea vieții elevilor care au nevoie de modele pozitive în viață. Fără o experiență în informatică prealabilă, PI:NAME:<NAME>END_PI și-a condus elevii pe calea succesului într-o competiție regională de programare." teacher_name_2: "PI:NAME:<NAME>END_PI" teacher_title_2: "Colegiul comunal & tehnologic Maysville" teacher_location_2: "Lexington, Kentucky" spotlight_2: "PI:NAME:<NAME>END_PI a fost o elevă care niciodată nu s-a gândit că va putea scrie linii de cod, nicidecum că va fi înscrisă la un colegiu care-i oferă o cale către un viitor luminos." teacher_name_3: "PI:NAME:<NAME>END_PI" teacher_title_3: "Profesor bibliotecar" teacher_school_3: "Școala primară Ruby Bridges" teacher_location_3: "Alameda, CA" spotlight_3: "PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI promovează o atmosferă echitabilă în clasa ei unde toată lumea poate obține rezultate în ritmul său. Greșelile și strădania sunt binevenite deoarece toată lumea învață din provocări, chiar și profesorul." continue_reading_blog: "Continuă să citești pe blog..." loading_error: could_not_load: "Eroare la încărcarea de pe server. Încearcă să reîncarci pagina" connection_failure: "Conexiune eșuată." connection_failure_desc: "Nu pare să fi conectat la Internet! Verifică conexiunea de rețea și apoi reîncarcă pagina." login_required: "Autentificare necesară" login_required_desc: "Trebuie să te autentifici pentru a avea acces la această pagină." unauthorized: "Trebuie să te autentifici. Ai cookies dezactivate?" forbidden: "Nepermis." forbidden_desc: "Oh nu, nu este nimic de văzut aici! Fi sigur că te-ai conectat la contul potrivit, sau vizitează unul din link-urile de mai jos ca să te reîntorci la programare!" user_not_found: "Utilizatoul nu este găsit" not_found: "Nu a fost găsit." not_found_desc: "Hm, nu este nimci aici. Vizitează unul din link-urile următoare ca să te reîntorci la programare!" not_allowed: "Metodă nepermisă." timeout: "Serverul nu poate fi contactat." conflict: "Conflict de resurse." bad_input: "Date greșite." server_error: "Eroare Server." unknown: "Eroare necunoscută." error: "EROARE" general_desc: "Ceva nu a mers bine, și probabil este vina noastră. Încearcă să aștepți puțin și apoi reîncarcă pagina, sau vizitează unul din link-urile următoare ca să te reîntorci la programare!" too_many_login_failures: "Au fost prea multe încercări eșuate de autentificare. Te rog să încerci mai târziu." resources: level: "Nivel" patch: "Patch" patches: "Patch-uri" system: "Sistem" systems: "Sisteme" component: "Componentă" components: "Componente" hero: "Erou" campaigns: "Campanii" concepts: advanced_css_rules: "Reguli CSS avansate" advanced_css_selectors: "Selectori CSS avansați" advanced_html_attributes: "Atribute HTML avansate" advanced_html_tags: "Tag-uri HTML avansate" algorithm_average: "Algoritm Medie aritmetică" algorithm_find_minmax: "Algoritm Caută Min/Max" algorithm_search_binary: "Algoritm Căutare binară" algorithm_search_graph: "Algoritm Căutare în graf" algorithm_sort: "Algoritm Sortare" algorithm_sum: "Algoritm Suma" arguments: "Argumente" arithmetic: "Aritmetică" array_2d: "Matrice bi-dimensională" array_index: "Indexare matriceală" array_iterating: "Iterare prin matrici" array_literals: "Literele matricelor" array_searching: "Căutare în matrice" array_sorting: "Sortare în matrice" arrays: "Matrici" basic_css_rules: "Regulii CSS de bază" basic_css_selectors: "Selectori CSS de bază" basic_html_attributes: "Atribute HTML de bază" basic_html_tags: "Tag-uri HTML de bază" basic_syntax: "Sintaxă de bază" binary: "Binar" boolean_and: "Și boolean" boolean_inequality: "Ingalitatea booleană" boolean_equality: "Egalitatea booleană" boolean_greater_less: "Mai mare/mai mic boolean" boolean_logic_shortcircuit: "Scurtături logice booleene" boolean_not: "Nu boolean" boolean_operator_precedence: "Precedența operatorilor booleeni" boolean_or: "Sau boolean" boolean_with_xycoordinates: "Comparații de coordonate" bootstrap: "Bootstrap" # Can't be translate in Romanian, is used in English form break_statements: "Instrucțiuni de oprire" classes: "Clase" continue_statements: "Instrucțiuni de continuare" dom_events: "Evenimente DOM" dynamic_styling: "Stilizare dinamică" events: "Evenimente" event_concurrency: "Evenimente concurente" event_data: "Date pentru evenimente" event_handlers: "Manipulatori de eveniment" # event_spawn: "Spawn Event" for_loops: "Bucle for" for_loops_nested: "Bucle for îmbricate" for_loops_range: "Zona de aplicare a buclelor for" functions: "Funcții" functions_parameters: "Parametrii" functions_multiple_parameters: "Parametrii multiplii" game_ai: "Joc AI" game_goals: "Obiectivele jocului" # game_spawn: "Game Spawn" graphics: "Grafică" graphs: "Grafuri" heaps: "Stive" if_condition: "Instrucțiuni condiționale if" if_else_if: "Instrucțiuni If/Else/IF" if_else_statements: "Instrucțiuni If/Else" if_statements: "Instrucțiuni If" if_statements_nested: "Instrucțiuni if îmbricate" indexing: "Indexuri matriceale" input_handling_flags: "Manipulare intrări - Flag-uri" input_handling_keyboard: "Manipulare intrări - Tastatură" input_handling_mouse: "Manipulare intrări - Mouse" intermediate_css_rules: "Reguli CSS intermediare" intermediate_css_selectors: "Selectrori CSS intermediari" intermediate_html_attributes: "Atribute HTML intermediare" intermediate_html_tags: "Tag-uri HTML intermediare" jquery: "jQuery" jquery_animations: "Animații jQuery" jquery_filtering: "Filtrare elemente jQuery" jquery_selectors: "Selectori jQuery" length: "Lungime matrice" math_coordinates: "Calculare coordonate" math_geometry: "Geometrie" math_operations: "Librăria de operații matematice" math_proportions: "Proporții matematice" math_trigonometry: "Trigonometrie" # object_literals: "Object literals" parameters: "Parametrii" programs: "Programe" properties: "Proprietăți" property_access: "Accesare proprietăți" property_assignment: "Alocarea proprietăți" property_coordinate: "Proprietatea coordonate" queues: "Structuri de date - Cozi" reading_docs: "Citirea documentației" recursion: "Recursivitate" return_statements: "Instrucțiunea return" stacks: "Structuri de date - Stive" strings: "Șiruri de caractere" strings_concatenation: "Concatenare șiruri de caractere" strings_substrings: "Sub-șir de caractere" trees: "Structuri de date - Arbori" variables: "Variabile" vectors: "Vectori" while_condition_loops: "Bucle while cu condiționare" while_loops_simple: "Bucle while" while_loops_nested: "Bucle while îmbricate" xy_coordinates: "Perechi de coordonate" advanced_strings: "Șiruri de caractere avansate" # Rest of concepts are deprecated algorithms: "Algoritmi" boolean_logic: "Logică booleană" basic_html: "HTML de bază" basic_css: "CSS de bază" basic_web_scripting: "Programare web de bază" intermediate_html: "HTML intermediar" intermediate_css: "CSS intermediar" intermediate_web_scripting: "Programare web intermediar" advanced_html: "HTML avansat" advanced_css: "CSS avansat" advanced_web_scripting: "Programare web avansat" input_handling: "Manipulare intrări" while_loops: "Bucle while" place_game_objects: "Plasare obiecte de joc" construct_mazes: "Construcție labirinturi" create_playable_game: "Creează un proiect de joc pe care îl poți juca, partaja" alter_existing_web_pages: "Modifică pagini de web existente" create_sharable_web_page: "Creează o pagină web care poate fi partajată" basic_input_handling: "Manipulare de bază a intrărilor" basic_game_ai: "Joc IA de bază" basic_javascript: "Javascript de bază" basic_event_handling: "Manipulare de bază a evenimentelor" create_sharable_interactive_web_page: "Creează o pagină de web interactivă care poate fi partajată" anonymous_teacher: notify_teacher: "Anunță profesor" create_teacher_account: "Creează un cont de profesor gratuit" enter_student_name: "NPI:NAME:<NAME>END_PI:" enter_teacher_email: "Adresa de email de profesor:" teacher_email_placeholder: "PI:EMAIL:<EMAIL>END_PI" student_name_placeholder: "scriPI:NAME:<NAME>END_PI" teachers_section: "Profesori:" students_section: "Elevi:" teacher_notified: "Ți-am anunțat profesorul că vrei să joci mai mult CodeCombat în clasă!" delta: added: "Adăugat" modified: "Modificat" not_modified: "Nemodificat" deleted: "Șters" moved_index: "Index mutat" text_diff: "Diff text" merge_conflict_with: "COMBINĂ CONFLICTUL CU" no_changes: "Fară schimbări" legal: page_title: "Aspecte Legale" opensource_introduction: "CodeCombat este parte a comunității open source." opensource_description_prefix: "Vizitează " github_url: "pagina noastră de GitHub" opensource_description_center: "și ajută-ne dacă îți place! CodeCombat este construit dintr-o mulțime de proiecte open source, pe care noi le iubim. Vizitați" archmage_wiki_url: "Archmage wiki" opensource_description_suffix: "pentru o listă cu softul care face acest joc posibil." practices_title: "Convenții" practices_description: "Acestea sunt promisiunile noastre către tine, jucătorul, fără așa mulți termeni legali." privacy_title: "Confidenţialitate şi termeni" privacy_description: "Nu o să iți vindem datele personale." security_title: "Securitate" security_description: "Ne străduim să vă protejăm informațiile personale. Fiind un proiect open-source, site-ul nostru oferă oricui posibilitatea de a ne revizui și îmbunătăți sistemul de securitate." email_title: "Email" email_description_prefix: "Noi nu vă vom inunda cu spam. Prin" email_settings_url: "setările tale de email" email_description_suffix: " sau prin link-urile din email-urile care vi le trimitem, puteți să schimbați preferințele și să vâ dezabonați oricând." cost_title: "Cost" cost_description: "CodeCombat se poate juca gratuit în nivelurile introductive, cu un abonament de ${{price}} USD/lună pentru acces la niveluri suplimentare și {{gems}} pietre prețioase bonus pe lună. Poți să anulezi printr-un simplu clic și oferim banii înapoi garantat în proporție de 100%." copyrights_title: "Drepturi de autor și licențe" contributor_title: "Acord de licență Contributor" contributor_description_prefix: "Toți contribuitorii, atât pe site cât și pe GitHub-ul nostru, sunt supuși la" cla_url: "ALC" contributor_description_suffix: "la care trebuie să fi de accord înainte să poți contribui." code_title: "Code - MIT" # {change} client_code_description_prefix: "Tot codul pe partea de client al codecombat.com din depozitul public GitHub și din baza de date codecombat.com, este licențiat sub" mit_license_url: "licența MIT" code_description_suffix: "Asta include tot codul din Systems și Components care este oferit de către CodeCombat cu scopul de a creea nivelurile." art_title: "Artă/Muzică - Conținut comun " art_description_prefix: "Tot conținutul creativ/artistic este valabil sub" cc_license_url: "Creative Commons Attribution 4.0 International License" art_description_suffix: "Conținut comun este orice făcut general valabil de către CodeCombat cu scopul de a crea niveluri. Asta include:" art_music: "Muzică" art_sound: "Sunet" art_artwork: "Artwork" art_sprites: "Sprites" art_other: "Orice și toate celelalte creații non-cod care sunt disponibile când se creează niveluri." art_access: "Momentan nu există nici un sistem universal, ușor pentru preluarea acestor bunuri. În general, preluați-le din adresele URL așa cum sunt folosite de site-ul web, contactați-ne pentru asistență, sau ajutați-ne să extindem site-ul ca să facem aceste bunuri mai ușor accesibile." art_paragraph_1: "Pentru atribuire, vă rugăm denumiți și să faceți referire la codecombat.com aproape de locația unde este folosită sursa sau unde este adecvat pentru mediu. De exemplu:" use_list_1: "Dacă este folosit într-un film sau alt joc, includeți codecombat.com la credite." use_list_2: "Dacă este folosit pe un site, includeți un link în apropiere, de exemplu sub o imagine, sau în pagina generală de atribuiri unde menționați și alte bunuri creative și softul open source folosit pe site. Ceva care face referință explicit la CodeCombat, precum o postare pe un blog care menționează CodeCombat, nu trebuie să se facă o atribuire separată." art_paragraph_2: "Dacă conținutul folosit nu este creat de către CodeCombat ci de către un utilizator al codecombat.com,atunci faceți referință către el și urmăriți indicațiile de atribuire prevăzute în descrierea resursei, dacă aceasta există." rights_title: "Drepturi rezervate" rights_desc: "Toate drepturile sunt rezervate pentru nivelurile în sine. Asta include" rights_scripts: "script-uri" rights_unit: "Configurații de unități" rights_writings: "scrieri" rights_media: "Media (sunete, muzică) și orice alt conținut creativ dezvoltat special pentru un nivel și care nu sunt valabile în mod normal pentru creearea altor niveluri." rights_clarification: "Pentru a clarifica, orice este valabil în Editorul de Niveluri pentru scopul de a crea niveluri se află sub licențiere CC, pe când conținutul creat cu Editorul de Niveluri sau încărcat pentru a face niveluru nu se află sub aceasta." nutshell_title: "Pe scurt" nutshell_description: "Orice resurse vă punem la dispoziție în Editorul de Niveluri puteți folosi liber cum vreți pentru a crea niveluri. Dar ne rezervăm dreptul de a rezerva distribuția de niveluri în sine (care sunt create pe codecombat.com) astfel încât să se poată percepe o taxă pentru ele pe vitor, dacă se va ajunge la așa ceva." nutshell_see_also: "Vezi și:" canonical: "Versiunea în engleză a acestui document este cea definitivă, versiunea canonică. Dacă există orice discrepanțe între versiunea tradusă și cea originală, documentul în engleză are prioritate." third_party_title: "Servicii Third Party" third_party_description: "CodeCombat utilizează următoarele servicii third party (printre altele):" cookies_message: "CodeCombat utilizează câteva cookies esențiale și neesențaile." cookies_deny: "Refuză cookies neesențiale" cookies_allow: "Permite cookies" calendar: year: "An" day: "Zi" month: "Luna" january: "Ianuarie" february: "Februarie" march: "Martie" april: "Aprilie" may: "Mai" june: "Iunie" july: "Iulie" august: "August" september: "Septembrie" october: "Octombrie" november: "Noiembrie" december: "Decembrie" code_play_create_account_modal: title: "Ai reușit!" # This section is only needed in US, UK, Mexico, India, and Germany body: "Ești pe cale să devii un programator de top. Înregistrează-te ca să primești suplimentar <strong>100 pietre prețioase</strong> & vei intra de asemenea pentru o șansă de a <strong>câștiga $2,500 & alte premii Lenovo</strong>." sign_up: "Întregistrează-te & continuă să programezi ▶" victory_sign_up_poke: "Creează un cont gratuit ca să poți salva codul scris & o șansă să câștigi premii!" victory_sign_up: "Înregistrează-te & să intri să <strong>câștigi $2,500</strong>" server_error: email_taken: "Email deja utilizat" username_taken: "Cont de utilizator existent" easy_password: "PI:PASSWORD:<PASSWORD>END_PI" reused_password: "PI:PASSWORD:<PASSWORD>END_PI" esper: line_no: "Linia $1: " uncaught: "Ne detectat $1" # $1 will be an error type, eg "Uncaught SyntaxError" reference_error: "ReferenceError: " argument_error: "ArgumentError: " type_error: "TypeError: " syntax_error: "SyntaxError: " error: "Eroare: " x_not_a_function: "$1 nu este o funcție" x_not_defined: "$1 nu este definit" spelling_issues: "Verifică erori de scriere: ai vrut `$1` în loc de `$2`?" capitalization_issues: "Verifică modul de scriere cu literele mari/mici: `$1` trebuie să fie `$2`." py_empty_block: "$1 este gol. Pune 4 spații în fața instrucțiunilor în interiorul instrucțiunii $2." fx_missing_paren: "Dacă vrei să chemi `$1` ca și funcție, ai nevoie de `()`" unmatched_token: "`$1` fără pereche. Fiecare deschidere `$2` trebuie să aibă o încheiere `$3` ca și pereche." unterminated_string: "Șir de caractere neterminat. Adaugă perechea de `\"` la sfârșitul șirului de caractere." missing_semicolon: "Punct și virgulă (;) lipsește." missing_quotes: "Ghilimelele lipsesc. Încearcă `$1`" argument_type: "Argumentul lui`$1` este `$2` care trebuie să fie de tipul`$3`, dar are `$4`: `$5`." argument_type2: "Argumentul lui `$1` este `$2` care trebuie să fie de tipul `$3`, dar are `$4`." target_a_unit: "Țintește o unitate." attack_capitalization: "Atacă $1, nu $2. (Literele mari sunt importante.)" empty_while: "Instrucțiune while goală. Pune 4 spații în fața instrucțiunilor în interiorul instrucțiunii while." line_of_site: "Argumentul `$1` este `$2` și are o problemă. Este deja un inamic în linia ta vizuală?" need_a_after_while: "Ai nevoie de un `$1` după `$2`." too_much_indentation: "Prea multă indentare la începutul acestei linii." missing_hero: "Cuvântul cheie `$1` lipsește; ar trebui să fie `$2`." takes_no_arguments: "`$1` nu ia nici un argument." no_one_named: "Nu este nimeni cu numele \"$1\" ca și țintă." separated_by_comma: "Parametrii de chemare a funcțiilor ar trebui separați cu `,`" protected_property: "Nu pot citi proprietatea protejată: $1" need_parens_to_call: "Dacă vrei să chemi `$1` ca și funcție ai nevoie de `()`" expected_an_identifier: "Se asteaptă un identificator dar în loc este '$1'." unexpected_identifier: "Identificator neașteptat" unexpected_end_of: "Terminare intrare neașteptată" unnecessary_semicolon: "Punct și virgulă neașteptate." unexpected_token_expected: "Token neașteptat: se aștepta $1 dar s-a găsit $2 când s-a analizat $3" unexpected_token: "$1 este un token neașteptat" unexpected_token2: "Token neașteptat" unexpected_number: "Număr neașteptat" unexpected: "'$1' neașteptat." escape_pressed_code: "Tasta escape apăsată; cod întrerupt." target_an_enemy: "Țintește un inamic după nume, ca `$1`, nu șirul de caractere `$2`." target_an_enemy_2: "Țintește un inamic după nume, ca $1" cannot_read_property: "Proprietatea '$1' nu se poate citi de tip nedefinit" attempted_to_assign: "Încercare de alocare proprietate readonly (doar pentru cititre)." unexpected_early_end: "Sfârșit de program neașteptat." you_need_a_string: "Trebuie să construiești un șir de caractere; unul ca $1" unable_to_get_property: "Proprietatea '$1' de tip nedefinit nu poate fi accesată sau referință către null" # TODO: Do we translate undefined/null? code_never_finished_its: "Programul nu a terminat niciodată. Este fie foarte încet or are o buclă infinită." unclosed_string: "Șir de caractere neînchis." unmatched: "'$1' fără pereche." error_you_said_achoo: "Ai scris: $1, dar parola este: $2. (Literele mari sunt importante.)" indentation_error_unindent_does: "Eroare de indentare: neindentarea nu se potrivește cu nici una din nivelurile de indentare" indentation_error: "Eroare de identare." need_a_on_the: "Ai nevoie de `:` la sfârșitul liniei după `$1`." attempt_to_call_undefined: "încercare de chemare a '$1' (o valoare nil)" unterminated: "`$1` neterminat" target_an_enemy_variable: "Țintește o variabilă $1, nu șirul de caractere $2. (Încearcă $3.)" error_use_the_variable: "Utilizează numele de variabilă `$1` în loc de șirul de caractere `$2`" indentation_unindent_does_not: "Neindentarea nu se potrivește cu nici una din nivelurile de indentare" unclosed_paren_in_function_arguments: "$1 neînchis în argumentele funcției." unexpected_end_of_input: " Sfârșit de intrare neașteptat" there_is_no_enemy: "Nu există`$1`. Utilizează mai întâi `$2`." # Hints start here try_herofindnearestenemy: "Încearcă `$1`" there_is_no_function: "Nu există funcția `$1`, dar `$2` are metoda `$3`." attacks_argument_enemy_has: "Argumentul lui`$1` este `$2` și are o problemă." is_there_an_enemy: "Este deja un inamic în linia ta vizuală?" target_is_null_is: "Ținta este $1. Există tot mereu o țintă pe care să o ataci? (Utilizezi $2?)" hero_has_no_method: "`$1` nu are nici o metodă`$2`." there_is_a_problem: "Este o problemă cu codul tău." did_you_mean: "Ai vrut să scrii $1? Nu ești echipat cu un element care să aibă acea abilitate." missing_a_quotation_mark: "O pereche de ghilimele lipsesc. " missing_var_use_var: "`$1` lipsește. Utilizează `$2` să faci o nouă variabilă." you_do_not_have: "Nu ești echipat cu un element care să aibă abilitatea $1." put_each_command_on: "Pune fiecare comandă pe o linie separată" are_you_missing_a: "Îți lipsește '$1' după '$2'? " your_parentheses_must_match: "Parantezele tale trebuie să fie pereche." apcsp: title: "Principiile informaticii de plasare avansată (AP) | Aprobate de Comisia colegiilor" meta_description: "Curicula completă a CodeCombat și programul de dezvoltare profesională sunt tot ceea ce ai nevoie pentru a oferi elevilor un nou curs de informatică al Comisiei colegiilor." syllabus: "Programa cu principiile informaticii pentru AP" syllabus_description: "Utilizează această resursă pentru a planifica curicula CodeCombat pentru clasa de principiile informaticii pentru AP." computational_thinking_practices: "Practici de gândire computațională" learning_objectives: "Obiective de învățare" curricular_requirements: "Cerințe curiculare" unit_1: "Unitatea 1: Tehnologie creativă" unit_1_activity_1: "Activitate unitatea 1: Prezentare a utilității tehnologiei" unit_2: "Unitatea 2: Gândire computațională" unit_2_activity_1: "Activitate unitatea 2: Secvențe binare" unit_2_activity_2: "Activitate unitatea 2: Proiect de lecție pentru tehnică de calcul" unit_3: "Unitatea 3: Algoritmi" unit_3_activity_1: "Activitate unitatea 3: Algoritmi - Ghidul Hitchhiker" unit_3_activity_2: "Activitate unitatea 3: Simulare - Prădător & Pradă" unit_3_activity_3: "Activitate unitatea 3: Algoritmi - Programare și design în perechi" unit_4: "Unitatea 4: Programare" unit_4_activity_1: "Activitate unitatea 4: Abstractizare" unit_4_activity_2: "Activitate unitatea 4: Căutare & Sortare" unit_4_activity_3: "Activitate unitatea 4: Refactorizare" unit_5: "Unitatea 5: Internetul" unit_5_activity_1: "Activitate unitatea 5: Cum funcționează Internetul" unit_5_activity_2: "Activitate unitatea 5: Simulator Internet" unit_5_activity_3: "Activitate unitatea 5: Simulator de canal de chat" unit_5_activity_4: "Activitate unitatea 5: Cybersecurity" unit_6: "Unitatea 6: Data" unit_6_activity_1: "Activitate unitatea 6: Introducere în date" unit_6_activity_2: "Activitate unitatea 6: Big Data" unit_6_activity_3: "Activitate unitatea 6: Compresie cu pierderi & fără pierderi" unit_7: "Unitatea 7: Impact personal & global" unit_7_activity_1: "Activitate unitatea 7: Impact personal & global" unit_7_activity_2: "Activitate unitatea 7: Crowdsourcing" unit_8: "Unitatea 8: Proba de performanță" unit_8_description: "Pregătește elevii pentru Creează temă în care vor construi propriile lor jocuri și în care vor testa conceptele de bază." unit_8_activity_1: "Practica 1 - Creează temă: Dezvolatre joc 1" unit_8_activity_2: "Practica 2 - Creează temă: Dezvolatre joc 2" unit_8_activity_3: "Practica 3 - Creează temă: Dezvolatre joc 3" unit_9: "Unitatea 9: Prezentare generală AP" unit_10: "Unitatea 10: După AP" unit_10_activity_1: "Activitate unitatea 10: Chestionar web" parents_landing_2: splash_title: "Descoperă magia programării acasă." learn_with_instructor: "Învață cu un instructor" live_classes: "Clase online în timp real" live_classes_offered: "CodeCombat oferă acum clase online de informatică pentru elevii care fac școala acasă. Bun pentru elevii care lucreează bine 1:1 sau grupuri mici în care rezultatele învățării sunt adaptate nevoilor lor." live_class_details_1: "Grupuri mici sau lecții private" live_class_details_2: "Programare în Javascript și Python, plus concepte de bază în informatică" live_class_details_3: "Predat de instructori experți în programare" live_class_details_4: "Păreri individualizate și imediate" live_class_details_5: "Curicula beneficiază de încrederea a 80,000+ de educatori" try_free_class: "Încearcă o clasă gratuită de 60 minute" pricing_plans: "Planuri de preț" choose_plan: "Alege un plan" per_student: "pentru fiecare elev" sibling_discount: "15% reducere pentru frați!" small_group_classes: "Clase de programare în grupuri mici" small_group_classes_detail: "4 grupuri pe sesiune / lună." small_group_classes_price: "$159/lună" small_group_classes_detail_1: "4:1 este rația elevi-profesor" small_group_classes_detail_2: "Clase de 60 de minute" small_group_classes_detail_3: "Construiește proiecte și spune-ți părerea despre proiectele celorlalți" small_group_classes_detail_4: "Partajare ecran pentru a primi păreri în timp real și depanare cod" private_classes: "Clase de programare private" four_sessions_per_month: "4 sesiuni private / lună." eight_sessions_per_month: "8 sesiuni private / lună." four_private_classes_price: "$219/lună" eight_private_classes_price: "$399/lună" private_classes_detail: "4 sau 8 sesiuni private / lună." private_classes_price: "$219/lună sau $399/lună" private_classes_detail_1: "1:1 este rația elev-profesor" private_classes_detail_2: "Clase de 60 de minut" private_classes_detail_3: "Program flexibil adaptat nevoilor tale" private_classes_detail_4: "Planuri de lecție și păreri în timp real adaptate stilului de învățare al elevului, ritmului acestuia și nivelului de abilități" best_seller: "Cel mai bine vândut" best_value: "Cea mai bună valoare" codecombat_premium: "CodeCombat Premium" learn_at_own_pace: "Învață în ritmul tău" monthly_sub: "Abonament lunar" buy_now: "Cumpără acum" per_month: " / lună" lifetime_access: "Acces pe viață" premium_details_title: "Bun pentru cei ce învață singuri și doresc autonomie completă." premium_details_1: "Accesează eroi, animăluțe și aptitudini disponibile doar abonaților" premium_details_2: "Primește pietre prețioase bonus să cumperi echipament, animăluțe și mai mulți eroi" premium_details_3: "Deblochează detalii despre concepte de bază și abilități ca dezvoltarea web și de jocuri" premium_details_4: "Suport premium pentru cei abonați" premium_details_5: "Creează clanuri private să îți inviți prietenii pentru a concura în grup" premium_need_help: "Ai nevoie de ajutor sau preferi Paypal? Email <a href=\"mailto:PI:EMAIL:<EMAIL>END_PI\">PI:EMAIL:<EMAIL>END_PI</a>" not_sure_kid: "Nu ești sigur dacă CodeCombat este pentru copiii tăi? Întreabă-i!" share_trailer: "Arată-i filmul nostru de prezentare copilului tău și determină-l să își facă un cont pentru a începe." why_kids_love: "De ce iubesc copiii CodeCombat" learn_through_play: "Învață prin joacă" learn_through_play_detail: "Elevii își vor dezvolta abilitățile de a scrie cod și își vor utiliza abilitățile de rezolvare a problemelor pentru a progresa prin niveluri și a-și crește eroul." skills_they_can_share: "Abilități pe care le pot partaja" skills_they_can_share_details: "Elevii își dezvoltă abilități din lumea reală și creează proiecte, cum ar fi jocuri sau pagini web, pe care le pot partaja cu prietenii și familia." help_when_needed: "Ajută-i atunci când au nevoie" help_when_needed_detail: "Utilizând date, fiecare nivel a fost construit să îi incite, dar niciodată să îi descurajeze. Elevii sun ajutați cu indicii atunci când se blochează." book_first_class: "Rezervă-ți prima clasă" why_parents_love: "De ce părinții iubesc CodeCombat" most_engaging: "Cel mai antrenant mod să înveți să scrii cod" most_engaging_detail: "Copilul tău va avea tot ce are nevoie la degentul mic pentru a scrie algoritmi în Python sau Javascript, să dezvolte site-uri web sau chiar să-și proiecteze propriul joc, în timp ce învață materie aliniată la standardele de curiculă națională." critical_skills: "Dezvoltă abilități importante pentru secolul 21" critical_skills_detail: "Copilul tău va învăța să navigheze și să devină cetățean în lumea digitală. CodeCombat este o soluție care îi îmbunătățește copilului tău gândirea critică, creativitatea și reziliența, îmbunătățindu-le abilitățile de care au nevoie în orice domeniu." parent_support: "Susținuți de părinți ca tine" parent_support_detail: "La CodeCombat, noi suntem părinții. Noi suntem programatori. Suntem profesori. Dar în primul rând, suntem oameni care credem că îi dăm copilului tău oportunitatea să aibă succes în orice își doreste acesta să facă." everything_they_need: "Tot ceea ce au nevoie pentru a începe să scrie cod singuri" beginner_concepts: "Concepte pentru începători" beginner_concepts_1: "Sintaxa de bază" beginner_concepts_2: "Bucle while" beginner_concepts_3: "Argumente" beginner_concepts_4: "Șiruri de caractere" beginner_concepts_5: "Variabile" beginner_concepts_6: "Algoritmi" intermediate_concepts: "Concepte de nivel intermediar" intermediate_concepts_1: "Instrucțiunea if" intermediate_concepts_2: "Comparația booleană" intermediate_concepts_3: "Condiționale îmbricate" intermediate_concepts_4: "Funcții" intermediate_concepts_5: "Manipularea de bază a intrărilor" intermediate_concepts_6: "Inteligență artificială de bază pentru jocuri" advanced_concepts: "Concepte avansate" advanced_concepts_1: "Manipularea evenimentelor" advanced_concepts_2: "Bucle condiționale while" # advanced_concepts_3: "Object literals" advanced_concepts_4: "Parametri" advanced_concepts_5: "Vectori" advanced_concepts_6: "Librăria de operatori matematici" advanced_concepts_7: "Recursivitate" get_started: "Hai să începem" quotes_title: "Ce zic părinții și copiii despre CodeCombat" quote_1: "\"Acesta este următorul nivel de scriere cod pentru copii și este foarte amuzant. Voi învăța un lucru sau două din acesta.\"" quote_2: "\"Mi-a plăcut să învăț o nouă abilitate pe care înainte nu o aveam. Mi-a plăcut că atunci când am avut probleme, am putu să-mi stabilesc obiectivele. Mi-a mai plăcut să văd că codul scris de mine funcționează corect.\"" quote_3: "\"Python-ul lui PI:NAME:<NAME>END_PI începe să aibă sens. El utilizează CodeCombat să își facă jocuri video. M-a provocat să îi joc jocurile, apoi râde când pierd.\"" quote_4: "\"Acesta este unul din lucrurile pe care îmi place să le fac. În fiecare dimineață mă trezesc și joc CodeCombat. Dacă ar trebui să îi dau o notă pentru CodeCombat de la 1 la 10, i-aș da un 10!\"" parent: "Părinți" student: "Elev" grade: "Clasa" subscribe_error_user_type: "Se pare că deja te-ai înregistrat pentru un cont. Dacă ești interesat de CodeCombat Premium, te rog să ne contactezi la PI:EMAIL:<EMAIL>END_PI." subscribe_error_already_subscribed: "Deja ai un abonament pentru un cont premium." start_free_trial_today: "Începe gratuit de azi varianta de încercare" live_classes_title: "Clase de programare online de la CodeCombat!" live_class_booked_thank_you: "Clasa de online a fost programată, mulțumim!" book_your_class: "Programează-ți clasa" call_to_book: "Sună acum pentru programare" modal_timetap_confirmation: congratulations: "Felicitări!" paragraph_1: "Aventura elevilor tăi în lumea programării așteaptă." paragraph_2: "Copilul tău este înregistrat la o clasă online și abia așteptăm să îl întâlnim!" paragraph_3: "În curând ar trebui să primești un email de invitație cu detalii atât despre clasa programată cât și numele și datele de contact ale instructorului." paragraph_4: "Dacă, pentru orice motiv, dorești modificarea clasei alese, replanificare sau vrei să vorbești cu un specialist în relația cu clienții, trebuie doar să ne folosești datele de contact furnizate în mesajul email de invitație." paragraph_5: "Îți mulțumim că ai ales CodeCombat și îți urăm noroc în călătoria ta în informatică!" back_to_coco: "Înapoi la CodeCombat" hoc_2018: banner: "Bine ai venit la Hour of Code!" page_heading: "Elevii tăi vor învăța cum să își construiască propriul joc!" page_heading_ai_league: "Elevii tăi vor învăța cum să își construiască propriul joc IA multi-jucător!" step_1: "Pas 1: Urmărește video de prezentare" step_2: "Pas 2: Încearcă-l" step_3: "Pas 3: Descarcă planul de lecție" try_activity: "Încearcă activitatea" download_pdf: "Descarcă PDF" teacher_signup_heading: "Transformă Hour of Code în Year of Code" teacher_signup_blurb: "Tot ce ai nevoie să predai informatică, nu este necesară o experiență anterioară." teacher_signup_input_blurb: "Ia primul curs gratuit:" teacher_signup_input_placeholder: "Adresa de email a profesorului" teacher_signup_input_button: "Ia cursul CS1 gratuit" activities_header: "Mai multe activități Hour of Cod" activity_label_1: "Informatică nivel începător: Scapă din temniță!" activity_label_2: " Dezvoltare jocuri nivel începător: Construiește un joc!" activity_label_3: "Dezvoltare de jocuri nivel avansat: Construiește un joc tip arcadă!" activity_label_hoc_2018: "Dezvoltare de jocuri nivel intermediar: scrie cod, joacă, creează" activity_label_ai_league: "Informatică nivel începător: Calea către liga IA" activity_button_1: "Vezi lecția" about: "Despre CodeCombat" about_copy: "Un program de informatică bazat pe joc, aliniat standardelor care predă scriere de cod în Python și Javascript." point1: "✓ Punerea bazelor" point2: "✓ Diferențiere" point3: "✓ Evaluări" point4: "✓ Cursuri bazate pe proiecte" point5: "✓ Monitorizare elevi" point6: "✓ Planuri de lecție complete" title: "HOUR OF CODE" acronym: "HOC" hoc_2018_interstitial: welcome: "Bine ai venit la Hour of Code organizat de CodeCombat!" educator: "Sunt instructor" show_resources: "Arată-mi resursele profesorului!" student: "Sunt elev" ready_to_code: "Sunt gata să programez!" hoc_2018_completion: congratulations: "Felicitări că ai terminat <b>scrie cod, joacă, creează!</b>" send: "Trimite jocul tău Hour of Code prietenilor și familiei!" copy: "Copiază URL" get_certificate: "Descarcă o diplomă de participare pentru a sărbătorii cu clasa ta!" get_cert_btn: "Descarcă certificat" first_name: "PI:NAME:<NAME>END_PI" last_initial: "Nume de familie și inițiala" teacher_email: "Adresa de email a profesorului" school_administrator: title: "Panou de lucru al administratorului școlii" my_teachers: "Profesorii mei" last_login: "Ultima autentificare" licenses_used: "licențe utilizate" total_students: "total elevi" active_students: "elevi activi" projects_created: "proiecte create" other: "Altele" notice: "Următorii administratori de școală au acces numai de vizualizare la datele tale de clasă:" add_additional_teacher: "Trebuie să adaugi un alt profesor? Contactează-ți managerul de cont CodCombat sau trimite email la PI:EMAIL:<EMAIL>END_PI. " license_stat_description: "Conturile licențiate disponibile reprezintă numărul de licențe disponibile pentru profesori, incluzând licențele partajate." students_stat_description: "Numărul total de conturi de elevi reprezintă toți elevii din toate clasele, indiferent dacă aceștia au sau nu licențe aplicate." active_students_stat_description: "Conturi de elevi activi reprezintă numărul de elevi care s-au conectat la CodeCombat în ultimele 60 de zile." project_stat_description: "Proiectele create reprezintă numărul total de proiecte de dezvoltare web sau de jocuri care au fost create." no_teachers: "Nu aveți în administrare nici un profesor." totals_calculated: "Cum sunt aceste totaluri calculate?" totals_explanation_1: "Cum sunt aceste totaluri calculate?" totals_explanation_2: "Licențe utilizate" totals_explanation_3: "Reprezintă totalul licențelor aplicate elevilor din totalul de licențe disponibile." totals_explanation_4: "Total elevi" totals_explanation_5: "Reprezintă elevii din toate clasele active. Pentru a vedea totalul elevilor înrolați în clasele active și cele arhivate, mergi la pagina Licențe elevi." totals_explanation_6: "Elevi activi" totals_explanation_7: "Resprezintă toți elevii care au fost activi în ultimele 60 de zile." totals_explanation_8: "Proiecte create" totals_explanation_9: "Reprezintă toate proiectele de dezvoltare web sau jocuri create." date_thru_date: "de la __startDateRange__ până la __endDateRange__" interactives: phenomenal_job: "Te-ai descurcat fenomenal!" try_again: "Ups, încearcă din nou!" select_statement_left: "Ups, alege o afirmație din stânga înainte de a apăsa \"Transmite.\"" fill_boxes: "Ups, fi sigur că ai completat toate căsuțele înainte de a apăsa \"Transmite.\"" browser_recommendation: title: "CodeCombat funcționează cel mai bine pe Chrome!" pitch_body: "Pentru o experiență CodeCombat cât mai bună recomandăm să se utilizeze ultima versiune de Chrome. Descarcă ultima versiune de Chrome apăsând butonul de mai jos!" download: "Descarcă Chrome" ignore: "Ignoră" admin: license_type_full: "Cursuri complete" license_type_customize: "Personalizează cursuri" outcomes: school_admin: "Administrator de școală" school_network: "Rețea școlară" school_subnetwork: "Subrețea școlară" classroom: "Clasă" league: student_register_1: "Devino următorul campion IA!" student_register_2: "Înregistrează-te, creează-ți echipa ta sau alătură-te altor echipe pentru a începe să concurezi." student_register_3: "Furnizează informațiile de mai jos pentru a fi eligibil pentru premii." teacher_register_1: "Înregistrează-te pentru a accesa pagina de profil a ligii a clasei tale și pornește clasa." general_news: "Primește mesaje email despre utimele noutăți cu privire la Lgile IA și campionate." team: "echipă" how_it_works1: "Alătură-te __team__" seasonal_arena_tooltip: "Luptă împotriva membrilor de echipă sau alți membrii utilizând cele mai bune aptitudini de programare pe care le ai pentru a câștiga puncte și a te clasa cât mai sus în clasamentul ligii IA înainte de a concura în arena campionatului la sfârșitul sezonului." summary: "Liga IA CodeCombat este atât un simulator unic copetitiv de lupte IA dar și un mototr de jocuri pentru a învăța Python și Javascript." join_now: "Alătură-te acum" tagline: "Liga IA CodeCombat combină curicula aliniată la standarde bazată pe proiecte, programarea de jocuri captivante bazate pe aventură și campionatul anual de programare IA organizat într-o competiție academică anuală cum nu există alta." ladder_subheader: "Utilizează abilitățile tale de programare și strategiile de luptă pentru a urca în clasament!" earn_codepoints: "Câștigă CodePoints finalizând niveluri" codepoints: "CodePoints" free_1: "Accesează arene competitive cu concurenți multiplii, clasamente și campionatul global de programare" free_2: "Câștigă puncte pentru finalizarea nivelurilor de pregătire și concurând în meciuri cot-la-cot" free_3: "Alătură-te echipelor de programare competitive împreună cu prietenii, familia sau colegii de clasă" free_4: "Arată-ți abilitățile de programare și ia acasă premiile mari" compete_season: "Testează toate abilitățile învățate! Concurează împotriva elevilor și jucătorilor din întreaga lume în acest apogeu captivant al sezonului." season_subheading1: "pentru amândouă arenele, cea de Sezon și cea de Turneu, fiecare jucător își programează echipa de “Eroi IA” cu cod scris în Python, Javascript, C++, Lua sau Coffeescript." season_subheading2: "Codul va informa despre strategiile pe care Eroii IA îl vor executa în competițiile față-în-față împotriva altor competitori." team_derbezt: "Învață să scrii cod și câștigă premii sponsorizate de superstarul Mexicanv care este actor, comedian și creator de filme PI:NAME:<NAME>END_PI." invite_link: "Invită jucători în această echipă trimițăndu-le acest link:" public_link: "Partajează acest clasament cu link-ul public:" end_to_end: "Diferite de alte platforme de e-sport utilizate de școli, noi deținem toată structura de sus până jos, ceea ce înseamnă că nu depindem de nici un dezvoltator de jocuri și nu avem probleme de licențiere. Asta înseamnă deasemenea că putem face modificări personalizate la jocuri pentru școala sau organizația ta." path_success: "Platforma jocului se încadrează în curicula de informatică standard, astfel încât în timp ce elevii se joacă nivelurile jocului, ei fac și muncă de completare a cunoștințelor. Elevii învață să scrie cod și informatică în timp ce se joacă, apoi utilizeză aceste abilități în bătăliile din arenă în timp ce fac practică și se joacă pe aceeași platformă." unlimited_potential: "Structura concursului nostru este adaptabilă oricărui mediu sau situație. Elevii pot participa la un anumit moment în timpul orelor normale de clasă, pot să se joace asincron de acasă sau să participe după bunul plac." edit_team: "Modifică echipa" start_team: "Pornește o echipă" leave_team: "Părăsește echipa" join_team: "Alătură-te echipei" view_team: "Vezi echipa" join_team_name: "Alătură-te echipei __name__" features: "Caracteristici" built_in: "Infrastructură competitivă încorporată" built_in_subheader: "Platforma noastră găzduiește fiecare element al procesului competițional, de la tabele de scor la platforma de joc, bunuri și premii de concurs." custom_dev: "Dezvoltare personalizată" custom_dev_subheader: "Elementele personalizate pentru școala sau organizația ta sunt incluse, plus opțiuni ca pagini de prezentare cu marcaj specific și personaje de joc." comprehensive_curr: "Curiculă completă" comprehensive_curr_subheader: "CodeCombat este o soluție CS aliniată standardelor care susțin profesorii în predarea programării în Javascript și Python, indiferent de experiența lor." # roster_management: "Roster Management Tools" roster_management_subheader: "Monitorizează performanța elevilor pe timpul curiculei și al jocului, și adaugă sau șterge elevi facil." share_flyer: "Partajează afișul nostru despre Liga IA cu instructorii, administratorii, părinții, antrenorii de e-sport sau alte persoane care pot fi interesate." download_flyer: "Descarcă afișul" championship_summary: "Arena campionatului __championshipArena__ este deschisă! Luptă acum în ea în cadrul lunii __championshipMonth__ pentru a câștiga premii în __championshipArena__ __championshipType__." play_arena_full: "Joacă în __arenaName__ __arenaType__" play_arena_short: "Joacă în __arenaName__" view_arena_winners: "Vezi câștigătorii din __arenaName__ __arenaType__ " arena_type_championship: "Arena campionatului" arena_type_regular: "Arena multi-jucător" blazing_battle: "Luptă aprinsă" infinite_inferno: "Infern infinit" mages_might: "Puterea magilor" sorcerers: "VrPI:NAME:<NAME>END_PIi" giants_gate: "Poarta giganților" colossus: "Colossus" cup: "Cupa" blitz: "Blitz" clash: "Încleștare" season2_announcement_1: "Este timpul să îți testezi abilitățile de a scrie cod în arena finală a sezonului 2. Vrăjitorul Blitz este viu și oferă o nouă provocare și o nouă tabelă de scor de urcat." season2_announcement_2: "Ai nevoie de mai multă practică? Rămâi la Arena mare a magilorpentru a-ți îmbunătății abilitățile. Ai timp până pe 31 August să joci în ambele arene. Notă: modificări de echilibrare a arenei pot apărea până pe 23 August." season2_announcement_3: "Premii deosebite sunt disponibile pentru jucătorii de top în Vrăjitorul Blitz:" season1_prize_1: "burse de $1,000" # season1_prize_2: "RESPAWN Gaming Chair" season1_prize_3: "Avatar CodeCombat personalizat" season1_prize_4: "Și mult mai multe!" season1_prize_hyperx: "Echipamente perfierice premium HyperX" codecombat_ai_league: "Liga IA CodeCombat" register: "Înregistrare" not_registered: "Neînregistrat" register_for_ai_league: "Înregistrare în Liga IA" world: "Lumea" quickstart_video: "Video de prezentare" arena_rankings: "Calificări arenă" arena_rankings_blurb: "Calificări arenă la liga globală IA" arena_rankings_title: "Clasamentul global al tuturor jucătorilor din această echipă la toate arenele Ligii IA din intervalul de vârstă nespecificat." competing: "Concurenți:" # Competing: 3 students count_student: "elev" # 1 elev count_students: "elevi" # 2 elevi top_student: "Top:" # Top: PI:NAME:<NAME>END_PI top_percent: "top" # - top 3%) top_of: "din" # (#8 of 35). Perhaps just use "/" if this doesn't translate naturally. arena_victories: "Victorii în Arenă" arena_victories_blurb: "Victoriile recente din Liga globală IA" arena_victories_title: "Victoriile sunt numărate în baza la ultimele 1000 de meciuri jucate asincron de fiecare jucător în fiecare arenă a Ligii IA din care fac parte." count_wins: "victorii" # 100+ wins or 974 wins codepoints_blurb: "1 CodePoint = 1 linie de cod scrisă" codepoints_title: "Un CodePoint este obținut pentru fiecare linie de cod care nu este goală utilizată pentru câștigarea nivelului. Fiecare nivel valorează același număr de CodePoints în concordanță cu soluția standard, indiferent dacă elevul a scris mai multe sau mai puține linii de cod." count_total: "Total:" # Total: 300 CodePoints, or Total: 300 wins join_teams_header: "Alătură-te echipelor & Primește chestii tari!" join_team_hyperx_title: "Alătură-te echipei HyperX și primești 10% reducere" join_team_hyperx_blurb: "30 de membri ai echipelor vor fi aleși aleator să câștige un mousepad de joc gratuit!" join_team_derbezt_title: "Alătură-te echipei PI:NAME:<NAME>END_PI, și primește un erou unic" join_team_derbezt_blurb: "Deblochează eroul PI:NAME:<NAME>END_PI de la superstarul mexican Eugenio PI:NAME:<NAME>END_PIbez!" join_team_ned_title: "Alătură-te echipei NPI:NAME:<NAME>END_PI, și deblochează eroul lui Ned" join_team_ned_blurb: "Primește eroul unic mânuitor-de-spatulă de la starul YouTube, Încearcă PI:NAME:<NAME>END_PI!" tournament: mini_tournaments: "Mini campionate" usable_ladders: "Toate scările posibile" make_tournament: "Creează un mini campionat" go_tournaments: "Mergi la mini campionat" class_tournaments: "Clasifică mini campionatele" no_tournaments_owner: "Nu există nici un campionat acum, te rog Creează unul" no_tournaments: "Nu există nici un campionat acum" edit_tournament: "Editează campionatul" create_tournament: "Creează campionatul" payments: student_licenses: "Licențe pentru elevi" computer_science: "Informatică" web_development: "Dezvoltare web" game_development: "Dezvoltare de jocuri" per_student: "per elev" just: "Doar" teachers_upto: "Profesorul poate cumpăra până la" great_courses: "Mai multe cursuri sunt incluse pentru" studentLicense_successful: "Felicitări! Licențele tale vor fi gata într-un minut. Apasă pe Ghidul de noțiuni de bază din zona de Resurse pentru a învăța cum să le prezinți elevilor." onlineClasses_successful: "Felicitări! Plata ta s-a efectuat cu succes. Echipa noastră te va contacta în pașii următori." homeSubscriptions_successful: "Felicitări! Plata ta s-a efectuat cu succes. Accesul de tip premium va fi disponibil în câteva minute." failed: "Plata ta a eșuat, te rog să încerci din nou" session_week_1: "1 sesiune/săptămână" session_week_2: "2 sesiuni/săptămână" month_1: "Lunar" month_3: "Trimestrial" month_6: "Bi-anual" year_1: "Anual" most_popular: "Cel mai popular" best_value: "Valoarea cea mai bună" purchase_licenses: "Cumpără licențe ușor pentru a avea acces la CodeCombat și Ozaria" homeschooling: "Licențe pentru școala făcută acasă" recurring: month_1: 'Facturare recurentă lunară' month_3: 'Facturare recurentă la 3 luni' month_6: 'Facturare recurentă la 6 luni' year_1: 'Facturare recurentă anuală' form_validation_errors: required: "Câmpul este obligatoriu" invalidEmail: "Email invalid" invalidPhone: "Număr de telefon invalid" emailExists: "Adresa de email există deja" numberGreaterThanZero: "Ar trebui să fie un număr mai mare decât 0"
[ { "context": "= undefined\n $timeout = undefined\n validName = 'Paul'\n invalidName = 'Pa'\n\n beforeEach module('ui.bo", "end": 112, "score": 0.9996579885482788, "start": 108, "tag": "NAME", "value": "Paul" }, { "context": "= undefined\n validName = 'Paul'\n invalidName = 'Pa'...
test/showErrors.spec.coffee
malibagci/angular-bootstrap-show-errors
1
describe 'showErrors', -> $compile = undefined $scope = undefined $timeout = undefined validName = 'Paul' invalidName = 'Pa' beforeEach module('ui.bootstrap.showErrors') beforeEach inject((_$compile_, _$rootScope_, _$timeout_) -> $compile = _$compile_ $scope = _$rootScope_ $timeout = _$timeout_ ) compileEl = -> el = $compile( '<form name="userForm"> <div id="first-name-group" class="form-group" show-errors> <input type="text" name="firstName" ng-model="firstName" ng-minlength="3" class="form-control" /> </div> <div id="last-name-group" class="form-group" show-errors="{ showSuccess: true }"> <input type="text" name="lastName" ng-model="lastName" ng-minlength="3" class="form-control" /> </div> </form>' )($scope) angular.element(document.body).append el $scope.$digest() el describe 'directive does not contain an input element with a form-control class and name attribute', -> it 'throws an exception', -> expect( -> $compile('<form name="userForm"><div class="form-group" show-errors><input type="text" name="firstName"></input></div></form>')($scope) ).toThrow "show-errors element has no child input elements with a 'name' attribute and a 'form-control' class" it "throws an exception if the element doesn't have the form-group class", -> expect( -> $compile('<div show-errors></div>')($scope) ).toThrow "show-errors element does not have the 'form-group' class" it "throws an exception if the element isn't in a form tag", -> expect( -> $compile('<div class="form-group" show-errors><input type="text" name="firstName"></input></div>')($scope) ).toThrow() describe '$pristine && $invalid', -> it 'has-error is absent', -> el = compileEl() expectFormGroupHasErrorClass(el).toBe false describe '$dirty && $invalid && blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe true describe '$dirty && $invalid && not blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'keydown' expectFormGroupHasErrorClass(el).toBe false describe '$valid && blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe false describe '$valid && blurred then becomes $invalid before blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$apply -> $scope.userForm.firstName.$setViewValue invalidName expectFormGroupHasErrorClass(el).toBe true describe '$valid && blurred then becomes $valid before blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$apply -> $scope.userForm.firstName.$setViewValue invalidName $scope.$apply -> $scope.userForm.firstName.$setViewValue validName expectFormGroupHasErrorClass(el).toBe false describe '$valid && blurred then becomes $invalid after blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe true describe '$valid && blurred then $invalid after blurred then $valid after blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe false describe '$valid && other input is $invalid && blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName $scope.userForm.lastName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe false describe '$invalid && showErrorsCheckValidity is set before blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName $scope.$broadcast 'show-errors-check-validity' expectFormGroupHasErrorClass(el).toBe true describe 'showErrorsCheckValidity is called twice', -> it 'correctly applies the has-error class', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName $scope.$broadcast 'show-errors-check-validity' $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue invalidName $scope.$apply -> $scope.showErrorsCheckValidity = true expectFormGroupHasErrorClass(el).toBe true describe 'showErrorsReset', -> it 'removes has-error', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() expectFormGroupHasErrorClass(el).toBe false describe 'showErrorsReset then invalid without blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() $scope.$apply -> $scope.userForm.firstName.$setViewValue invalidName expectFormGroupHasErrorClass(el).toBe false describe 'call showErrorsReset multiple times', -> it 'removes has-error', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() expectFormGroupHasErrorClass(el).toBe false describe '{showSuccess: true} option', -> describe '$pristine && $valid', -> it 'has-success is absent', -> el = compileEl() expectLastNameFormGroupHasSuccessClass(el).toBe false describe '$dirty && $valid && blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$digest() expectLastNameFormGroupHasSuccessClass(el).toBe true describe '$dirty && $invalid && blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue invalidName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$digest() expectLastNameFormGroupHasSuccessClass(el).toBe false describe '$invalid && blurred then becomes $valid before blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue invalidName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$apply -> $scope.userForm.lastName.$setViewValue invalidName $scope.$apply -> $scope.userForm.lastName.$setViewValue validName expectLastNameFormGroupHasSuccessClass(el).toBe true describe '$valid && showErrorsCheckValidity is set before blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName $scope.$broadcast 'show-errors-check-validity' expectLastNameFormGroupHasSuccessClass(el).toBe true describe 'showErrorsReset', -> it 'removes has-success', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() expectLastNameFormGroupHasSuccessClass(el).toBe false describe 'showErrorsConfig', -> $compile = undefined $scope = undefined $timeout = undefined validName = 'Paul' invalidName = 'Pa' beforeEach -> testModule = angular.module 'testModule', [] testModule.config (showErrorsConfigProvider) -> showErrorsConfigProvider.showSuccess true showErrorsConfigProvider.trigger 'keypress' module 'ui.bootstrap.showErrors', 'testModule' inject((_$compile_, _$rootScope_, _$timeout_) -> $compile = _$compile_ $scope = _$rootScope_ $timeout = _$timeout_ ) compileEl = -> el = $compile( '<form name="userForm"> <div id="first-name-group" class="form-group" show-errors="{showSuccess: false, trigger: \'blur\'}"> <input type="text" name="firstName" ng-model="firstName" ng-minlength="3" class="form-control" /> </div> <div id="last-name-group" class="form-group" show-errors> <input type="text" name="lastName" ng-model="lastName" ng-minlength="3" class="form-control" /> </div> </form>' )($scope) angular.element(document.body).append el $scope.$digest() el describe 'when showErrorsConfig.showSuccess is true', -> describe 'and no options given', -> it 'show-success class is applied', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName angular.element(lastNameEl(el)).triggerHandler 'keypress' $scope.$digest() expectLastNameFormGroupHasSuccessClass(el).toBe true describe 'when showErrorsConfig.showSuccess is true', -> describe 'but options.showSuccess is false', -> it 'show-success class is not applied', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$digest() expectFirstNameFormGroupHasSuccessClass(el).toBe false describe 'when showErrorsConfig.trigger is "keypress"', -> describe 'and no options given', -> it 'validates the value on the first keypress', -> el = compileEl() $scope.userForm.lastName.$setViewValue invalidName angular.element(lastNameEl(el)).triggerHandler 'keypress' $scope.$digest() expectLastNameFormGroupHasErrorClass(el).toBe true describe 'but options.trigger is "blur"', -> it 'does not validate the value on keypress', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'keypress' $scope.$digest() expectFirstNameFormGroupHasErrorClass(el).toBe false find = (el, selector) -> el[0].querySelector selector firstNameEl = (el) -> find el, '[name=firstName]' lastNameEl = (el) -> find el, '[name=lastName]' expectFormGroupHasErrorClass = (el) -> formGroup = el[0].querySelector '[id=first-name-group]' expect angular.element(formGroup).hasClass('has-error') expectFirstNameFormGroupHasSuccessClass = (el) -> formGroup = el[0].querySelector '[id=first-name-group]' expect angular.element(formGroup).hasClass('has-success') expectLastNameFormGroupHasSuccessClass = (el) -> formGroup = el[0].querySelector '[id=last-name-group]' expect angular.element(formGroup).hasClass('has-success') expectFirstNameFormGroupHasErrorClass = (el) -> formGroup = el[0].querySelector '[id=first-name-group]' expect angular.element(formGroup).hasClass('has-error') expectLastNameFormGroupHasErrorClass = (el) -> formGroup = el[0].querySelector '[id=last-name-group]' expect angular.element(formGroup).hasClass('has-error')
153745
describe 'showErrors', -> $compile = undefined $scope = undefined $timeout = undefined validName = '<NAME>' invalidName = '<NAME>' beforeEach module('ui.bootstrap.showErrors') beforeEach inject((_$compile_, _$rootScope_, _$timeout_) -> $compile = _$compile_ $scope = _$rootScope_ $timeout = _$timeout_ ) compileEl = -> el = $compile( '<form name="userForm"> <div id="first-name-group" class="form-group" show-errors> <input type="text" name="<NAME>" ng-model="<NAME>" ng-minlength="3" class="form-control" /> </div> <div id="last-name-group" class="form-group" show-errors="{ showSuccess: true }"> <input type="text" name="<NAME>" ng-model="<NAME>" ng-minlength="3" class="form-control" /> </div> </form>' )($scope) angular.element(document.body).append el $scope.$digest() el describe 'directive does not contain an input element with a form-control class and name attribute', -> it 'throws an exception', -> expect( -> $compile('<form name="userForm"><div class="form-group" show-errors><input type="text" name="<NAME>"></input></div></form>')($scope) ).toThrow "show-errors element has no child input elements with a 'name' attribute and a 'form-control' class" it "throws an exception if the element doesn't have the form-group class", -> expect( -> $compile('<div show-errors></div>')($scope) ).toThrow "show-errors element does not have the 'form-group' class" it "throws an exception if the element isn't in a form tag", -> expect( -> $compile('<div class="form-group" show-errors><input type="text" name="firstName"></input></div>')($scope) ).toThrow() describe '$pristine && $invalid', -> it 'has-error is absent', -> el = compileEl() expectFormGroupHasErrorClass(el).toBe false describe '$dirty && $invalid && blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe true describe '$dirty && $invalid && not blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'keydown' expectFormGroupHasErrorClass(el).toBe false describe '$valid && blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe false describe '$valid && blurred then becomes $invalid before blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$apply -> $scope.userForm.firstName.$setViewValue invalidName expectFormGroupHasErrorClass(el).toBe true describe '$valid && blurred then becomes $valid before blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$apply -> $scope.userForm.firstName.$setViewValue invalidName $scope.$apply -> $scope.userForm.firstName.$setViewValue validName expectFormGroupHasErrorClass(el).toBe false describe '$valid && blurred then becomes $invalid after blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe true describe '$valid && blurred then $invalid after blurred then $valid after blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe false describe '$valid && other input is $invalid && blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName $scope.userForm.lastName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe false describe '$invalid && showErrorsCheckValidity is set before blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName $scope.$broadcast 'show-errors-check-validity' expectFormGroupHasErrorClass(el).toBe true describe 'showErrorsCheckValidity is called twice', -> it 'correctly applies the has-error class', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName $scope.$broadcast 'show-errors-check-validity' $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue invalidName $scope.$apply -> $scope.showErrorsCheckValidity = true expectFormGroupHasErrorClass(el).toBe true describe 'showErrorsReset', -> it 'removes has-error', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() expectFormGroupHasErrorClass(el).toBe false describe 'showErrorsReset then invalid without blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() $scope.$apply -> $scope.userForm.firstName.$setViewValue invalidName expectFormGroupHasErrorClass(el).toBe false describe 'call showErrorsReset multiple times', -> it 'removes has-error', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() expectFormGroupHasErrorClass(el).toBe false describe '{showSuccess: true} option', -> describe '$pristine && $valid', -> it 'has-success is absent', -> el = compileEl() expectLastNameFormGroupHasSuccessClass(el).toBe false describe '$dirty && $valid && blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$digest() expectLastNameFormGroupHasSuccessClass(el).toBe true describe '$dirty && $invalid && blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue invalidName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$digest() expectLastNameFormGroupHasSuccessClass(el).toBe false describe '$invalid && blurred then becomes $valid before blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue invalidName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$apply -> $scope.userForm.lastName.$setViewValue invalidName $scope.$apply -> $scope.userForm.lastName.$setViewValue validName expectLastNameFormGroupHasSuccessClass(el).toBe true describe '$valid && showErrorsCheckValidity is set before blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName $scope.$broadcast 'show-errors-check-validity' expectLastNameFormGroupHasSuccessClass(el).toBe true describe 'showErrorsReset', -> it 'removes has-success', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() expectLastNameFormGroupHasSuccessClass(el).toBe false describe 'showErrorsConfig', -> $compile = undefined $scope = undefined $timeout = undefined validName = '<NAME>' invalidName = '<NAME>' beforeEach -> testModule = angular.module 'testModule', [] testModule.config (showErrorsConfigProvider) -> showErrorsConfigProvider.showSuccess true showErrorsConfigProvider.trigger 'keypress' module 'ui.bootstrap.showErrors', 'testModule' inject((_$compile_, _$rootScope_, _$timeout_) -> $compile = _$compile_ $scope = _$rootScope_ $timeout = _$timeout_ ) compileEl = -> el = $compile( '<form name="userForm"> <div id="first-name-group" class="form-group" show-errors="{showSuccess: false, trigger: \'blur\'}"> <input type="text" name="firstName" ng-model="firstName" ng-minlength="3" class="form-control" /> </div> <div id="last-name-group" class="form-group" show-errors> <input type="text" name="lastName" ng-model="lastName" ng-minlength="3" class="form-control" /> </div> </form>' )($scope) angular.element(document.body).append el $scope.$digest() el describe 'when showErrorsConfig.showSuccess is true', -> describe 'and no options given', -> it 'show-success class is applied', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName angular.element(lastNameEl(el)).triggerHandler 'keypress' $scope.$digest() expectLastNameFormGroupHasSuccessClass(el).toBe true describe 'when showErrorsConfig.showSuccess is true', -> describe 'but options.showSuccess is false', -> it 'show-success class is not applied', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$digest() expectFirstNameFormGroupHasSuccessClass(el).toBe false describe 'when showErrorsConfig.trigger is "keypress"', -> describe 'and no options given', -> it 'validates the value on the first keypress', -> el = compileEl() $scope.userForm.lastName.$setViewValue invalidName angular.element(lastNameEl(el)).triggerHandler 'keypress' $scope.$digest() expectLastNameFormGroupHasErrorClass(el).toBe true describe 'but options.trigger is "blur"', -> it 'does not validate the value on keypress', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'keypress' $scope.$digest() expectFirstNameFormGroupHasErrorClass(el).toBe false find = (el, selector) -> el[0].querySelector selector firstNameEl = (el) -> find el, '[name=firstName]' lastNameEl = (el) -> find el, '[name=lastName]' expectFormGroupHasErrorClass = (el) -> formGroup = el[0].querySelector '[id=first-name-group]' expect angular.element(formGroup).hasClass('has-error') expectFirstNameFormGroupHasSuccessClass = (el) -> formGroup = el[0].querySelector '[id=first-name-group]' expect angular.element(formGroup).hasClass('has-success') expectLastNameFormGroupHasSuccessClass = (el) -> formGroup = el[0].querySelector '[id=last-name-group]' expect angular.element(formGroup).hasClass('has-success') expectFirstNameFormGroupHasErrorClass = (el) -> formGroup = el[0].querySelector '[id=first-name-group]' expect angular.element(formGroup).hasClass('has-error') expectLastNameFormGroupHasErrorClass = (el) -> formGroup = el[0].querySelector '[id=last-name-group]' expect angular.element(formGroup).hasClass('has-error')
true
describe 'showErrors', -> $compile = undefined $scope = undefined $timeout = undefined validName = 'PI:NAME:<NAME>END_PI' invalidName = 'PI:NAME:<NAME>END_PI' beforeEach module('ui.bootstrap.showErrors') beforeEach inject((_$compile_, _$rootScope_, _$timeout_) -> $compile = _$compile_ $scope = _$rootScope_ $timeout = _$timeout_ ) compileEl = -> el = $compile( '<form name="userForm"> <div id="first-name-group" class="form-group" show-errors> <input type="text" name="PI:NAME:<NAME>END_PI" ng-model="PI:NAME:<NAME>END_PI" ng-minlength="3" class="form-control" /> </div> <div id="last-name-group" class="form-group" show-errors="{ showSuccess: true }"> <input type="text" name="PI:NAME:<NAME>END_PI" ng-model="PI:NAME:<NAME>END_PI" ng-minlength="3" class="form-control" /> </div> </form>' )($scope) angular.element(document.body).append el $scope.$digest() el describe 'directive does not contain an input element with a form-control class and name attribute', -> it 'throws an exception', -> expect( -> $compile('<form name="userForm"><div class="form-group" show-errors><input type="text" name="PI:NAME:<NAME>END_PI"></input></div></form>')($scope) ).toThrow "show-errors element has no child input elements with a 'name' attribute and a 'form-control' class" it "throws an exception if the element doesn't have the form-group class", -> expect( -> $compile('<div show-errors></div>')($scope) ).toThrow "show-errors element does not have the 'form-group' class" it "throws an exception if the element isn't in a form tag", -> expect( -> $compile('<div class="form-group" show-errors><input type="text" name="firstName"></input></div>')($scope) ).toThrow() describe '$pristine && $invalid', -> it 'has-error is absent', -> el = compileEl() expectFormGroupHasErrorClass(el).toBe false describe '$dirty && $invalid && blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe true describe '$dirty && $invalid && not blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'keydown' expectFormGroupHasErrorClass(el).toBe false describe '$valid && blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe false describe '$valid && blurred then becomes $invalid before blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$apply -> $scope.userForm.firstName.$setViewValue invalidName expectFormGroupHasErrorClass(el).toBe true describe '$valid && blurred then becomes $valid before blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$apply -> $scope.userForm.firstName.$setViewValue invalidName $scope.$apply -> $scope.userForm.firstName.$setViewValue validName expectFormGroupHasErrorClass(el).toBe false describe '$valid && blurred then becomes $invalid after blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe true describe '$valid && blurred then $invalid after blurred then $valid after blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe false describe '$valid && other input is $invalid && blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName $scope.userForm.lastName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' expectFormGroupHasErrorClass(el).toBe false describe '$invalid && showErrorsCheckValidity is set before blurred', -> it 'has-error is present', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName $scope.$broadcast 'show-errors-check-validity' expectFormGroupHasErrorClass(el).toBe true describe 'showErrorsCheckValidity is called twice', -> it 'correctly applies the has-error class', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName $scope.$broadcast 'show-errors-check-validity' $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.userForm.firstName.$setViewValue invalidName $scope.$apply -> $scope.showErrorsCheckValidity = true expectFormGroupHasErrorClass(el).toBe true describe 'showErrorsReset', -> it 'removes has-error', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() expectFormGroupHasErrorClass(el).toBe false describe 'showErrorsReset then invalid without blurred', -> it 'has-error is absent', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() $scope.$apply -> $scope.userForm.firstName.$setViewValue invalidName expectFormGroupHasErrorClass(el).toBe false describe 'call showErrorsReset multiple times', -> it 'removes has-error', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() expectFormGroupHasErrorClass(el).toBe false describe '{showSuccess: true} option', -> describe '$pristine && $valid', -> it 'has-success is absent', -> el = compileEl() expectLastNameFormGroupHasSuccessClass(el).toBe false describe '$dirty && $valid && blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$digest() expectLastNameFormGroupHasSuccessClass(el).toBe true describe '$dirty && $invalid && blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue invalidName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$digest() expectLastNameFormGroupHasSuccessClass(el).toBe false describe '$invalid && blurred then becomes $valid before blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue invalidName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$apply -> $scope.userForm.lastName.$setViewValue invalidName $scope.$apply -> $scope.userForm.lastName.$setViewValue validName expectLastNameFormGroupHasSuccessClass(el).toBe true describe '$valid && showErrorsCheckValidity is set before blurred', -> it 'has-success is present', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName $scope.$broadcast 'show-errors-check-validity' expectLastNameFormGroupHasSuccessClass(el).toBe true describe 'showErrorsReset', -> it 'removes has-success', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName angular.element(lastNameEl(el)).triggerHandler 'blur' $scope.$broadcast 'show-errors-reset' $timeout.flush() expectLastNameFormGroupHasSuccessClass(el).toBe false describe 'showErrorsConfig', -> $compile = undefined $scope = undefined $timeout = undefined validName = 'PI:NAME:<NAME>END_PI' invalidName = 'PI:NAME:<NAME>END_PI' beforeEach -> testModule = angular.module 'testModule', [] testModule.config (showErrorsConfigProvider) -> showErrorsConfigProvider.showSuccess true showErrorsConfigProvider.trigger 'keypress' module 'ui.bootstrap.showErrors', 'testModule' inject((_$compile_, _$rootScope_, _$timeout_) -> $compile = _$compile_ $scope = _$rootScope_ $timeout = _$timeout_ ) compileEl = -> el = $compile( '<form name="userForm"> <div id="first-name-group" class="form-group" show-errors="{showSuccess: false, trigger: \'blur\'}"> <input type="text" name="firstName" ng-model="firstName" ng-minlength="3" class="form-control" /> </div> <div id="last-name-group" class="form-group" show-errors> <input type="text" name="lastName" ng-model="lastName" ng-minlength="3" class="form-control" /> </div> </form>' )($scope) angular.element(document.body).append el $scope.$digest() el describe 'when showErrorsConfig.showSuccess is true', -> describe 'and no options given', -> it 'show-success class is applied', -> el = compileEl() $scope.userForm.lastName.$setViewValue validName angular.element(lastNameEl(el)).triggerHandler 'keypress' $scope.$digest() expectLastNameFormGroupHasSuccessClass(el).toBe true describe 'when showErrorsConfig.showSuccess is true', -> describe 'but options.showSuccess is false', -> it 'show-success class is not applied', -> el = compileEl() $scope.userForm.firstName.$setViewValue validName angular.element(firstNameEl(el)).triggerHandler 'blur' $scope.$digest() expectFirstNameFormGroupHasSuccessClass(el).toBe false describe 'when showErrorsConfig.trigger is "keypress"', -> describe 'and no options given', -> it 'validates the value on the first keypress', -> el = compileEl() $scope.userForm.lastName.$setViewValue invalidName angular.element(lastNameEl(el)).triggerHandler 'keypress' $scope.$digest() expectLastNameFormGroupHasErrorClass(el).toBe true describe 'but options.trigger is "blur"', -> it 'does not validate the value on keypress', -> el = compileEl() $scope.userForm.firstName.$setViewValue invalidName angular.element(firstNameEl(el)).triggerHandler 'keypress' $scope.$digest() expectFirstNameFormGroupHasErrorClass(el).toBe false find = (el, selector) -> el[0].querySelector selector firstNameEl = (el) -> find el, '[name=firstName]' lastNameEl = (el) -> find el, '[name=lastName]' expectFormGroupHasErrorClass = (el) -> formGroup = el[0].querySelector '[id=first-name-group]' expect angular.element(formGroup).hasClass('has-error') expectFirstNameFormGroupHasSuccessClass = (el) -> formGroup = el[0].querySelector '[id=first-name-group]' expect angular.element(formGroup).hasClass('has-success') expectLastNameFormGroupHasSuccessClass = (el) -> formGroup = el[0].querySelector '[id=last-name-group]' expect angular.element(formGroup).hasClass('has-success') expectFirstNameFormGroupHasErrorClass = (el) -> formGroup = el[0].querySelector '[id=first-name-group]' expect angular.element(formGroup).hasClass('has-error') expectLastNameFormGroupHasErrorClass = (el) -> formGroup = el[0].querySelector '[id=last-name-group]' expect angular.element(formGroup).hasClass('has-error')
[ { "context": "ns, groups, out, callback) ->\n keys = [\n 'flowhub-avatar'\n 'flowhub-plan'\n 'flowhub-theme'\n ", "end": 324, "score": 0.8955202102661133, "start": 310, "tag": "KEY", "value": "flowhub-avatar" }, { "context": "ck) ->\n keys = [\n 'flowhub...
components/ClearUserData.coffee
rishi229225111/noflo-ui
0
noflo = require 'noflo' exports.getComponent = -> c = new noflo.Component c.inPorts.add 'clear', datatype: 'bang' c.outPorts.add 'user', -> datatype: 'object' noflo.helpers.WirePattern c, in: 'clear' out: 'user' async: true , (ins, groups, out, callback) -> keys = [ 'flowhub-avatar' 'flowhub-plan' 'flowhub-theme' 'flowhub-token' 'flowhub-user' 'github-token' 'github-username' ] for key in keys localStorage.removeItem key newUserInfo = {} for key in keys newUserInfo[key] = null out.send newUserInfo do callback
90517
noflo = require 'noflo' exports.getComponent = -> c = new noflo.Component c.inPorts.add 'clear', datatype: 'bang' c.outPorts.add 'user', -> datatype: 'object' noflo.helpers.WirePattern c, in: 'clear' out: 'user' async: true , (ins, groups, out, callback) -> keys = [ '<KEY>' '<KEY>' 'flow<KEY>-theme' 'flowhub-token' 'flowhub-user' 'github<KEY>-token' 'github-username' ] for key in keys localStorage.removeItem key newUserInfo = {} for key in keys newUserInfo[key] = null out.send newUserInfo do callback
true
noflo = require 'noflo' exports.getComponent = -> c = new noflo.Component c.inPorts.add 'clear', datatype: 'bang' c.outPorts.add 'user', -> datatype: 'object' noflo.helpers.WirePattern c, in: 'clear' out: 'user' async: true , (ins, groups, out, callback) -> keys = [ 'PI:KEY:<KEY>END_PI' 'PI:KEY:<KEY>END_PI' 'flowPI:KEY:<KEY>END_PI-theme' 'flowhub-token' 'flowhub-user' 'githubPI:KEY:<KEY>END_PI-token' 'github-username' ] for key in keys localStorage.removeItem key newUserInfo = {} for key in keys newUserInfo[key] = null out.send newUserInfo do callback
[ { "context": " 37\n ,\n token: \"test token two\"\n misc: \"test miscellaneous da", "end": 2080, "score": 0.6951109766960144, "start": 2066, "tag": "KEY", "value": "test token two" }, { "context": " 73\n ,\n ...
src/coffee/parseList.spec.coffee
jameswilddev/influx7
1
describe "parseList", -> parseList = require "./parseList" run = (config) -> describe config.description, -> inputCopy = undefined beforeEach -> inputCopy = JSON.parse JSON.stringify config.input if config.throws it "throws the expected exception", -> (expect -> parseList inputCopy, "test deliminator").toThrow config.throws else it "returns the expected output", -> (expect parseList inputCopy, "test deliminator").toEqual config.output beforeEach -> try parseList inputCopy, "test deliminator" catch it "does not modify the input", -> (expect inputCopy).toEqual config.input run description: "no tokens" input: [] output: [] run description: "a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 ] ] run description: "multiple tokens without deliminators" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 , token: "test token two" misc: "test miscellaneous data two" starts: 52 ends: 73 , token: "test token three" misc: "test miscellaneous data three" starts: 123 ends: 160 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 , token: "test token two" misc: "test miscellaneous data two" starts: 52 ends: 73 , token: "test token three" misc: "test miscellaneous data three" starts: 123 ends: 160 ] ] run description: "a single deliminator" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 17 ends: 25 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "two deliminators" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 17 ends: 25 , token: "test deliminator" misc: "test miscellaneous data two" starts: 31 ends: 56 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "one token then a single deliminator" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 8 , token: "test deliminator" misc: "test miscellaneous data two" starts: 17 ends: 25 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "multiple tokens then a single deliminator" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 60 ends: 84 , token: "test deliminator" misc: "test miscellaneous data two" starts: 112 ends: 148 ] throws: reason: "emptyGroup" starts: 112 ends: 148 run description: "single deliminator then a single token" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 17 ends: 25 , token: "test token two" misc: "test miscellaneous data two" starts: 36 ends: 41 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "single deliminator then multiple tokens" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token one" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token two" misc: "test miscellaneous data three" starts: 60 ends: 84 , token: "test token three" misc: "test miscellaneous data two" starts: 112 ends: 148 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "single token then a single deliminator then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test deliminator" misc: "test miscellaneous data two" starts: 17 ends: 25 , token: "test token three" misc: "test miscellaneous data three" starts: 36 ends: 41 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 ] [ token: "test token three" misc: "test miscellaneous data three" starts: 36 ends: 41 ] ] run description: "multiple tokens then a single deliminator then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "test token three" misc: "test miscellaneous data three" starts: 34 ends: 39 , token: "test deliminator" misc: "test miscellaneous data four" starts: 58 ends: 72 , token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "test token three" misc: "test miscellaneous data three" starts: 34 ends: 39 ] [ token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] ] run description: "a single token then a single deliminator then multiple tokens" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test deliminator" misc: "test miscellaneous data two" starts: 24 ends: 37 , token: "test token three" misc: "test miscellaneous data three" starts: 49 ends: 57 , token: "test token four" misc: "test miscellaneous data four" starts: 78 ends: 88 , token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 ] [ token: "test token three" misc: "test miscellaneous data three" starts: 49 ends: 57 , token: "test token four" misc: "test miscellaneous data four" starts: 78 ends: 88 , token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] ] run description: "multiple tokens then a single deliminator then multiple tokens" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "test token three" misc: "test miscellaneous data three" starts: 34 ends: 39 , token: "test deliminator" misc: "test miscellaneous data four" starts: 58 ends: 72 , token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 , token: "test token six" misc: "test miscellaneous data six" starts: 163 ends: 174 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "test token three" misc: "test miscellaneous data three" starts: 34 ends: 39 ] [ token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 , token: "test token six" misc: "test miscellaneous data six" starts: 163 ends: 174 ] ] run description: "two deliminators" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "a single token then two deliminators" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 ] throws: reason: "emptyGroup" starts: 35 ends: 89 run description: "a deliminator then a single token then a deliminator" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "two deliminators then a single toke" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "a single token then a deliminator then a single token then a deliminator" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test deliminator" misc: "test miscellaneous data four" starts: 124 ends: 148 ] throws: reason: "emptyGroup" starts: 124 ends: 148 run description: "a single token then two deliminators then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 ] throws: reason: "emptyGroup" starts: 35 ends: 89 run description: "a deliminator then a single token then a deliminator then a single token" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "a single token then a deliminator then a single token then a deliminator then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test deliminator" misc: "test miscellaneous data four" starts: 124 ends: 148 , token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 ] [ token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 ] [ token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 ] ] run description: "multiple tokens then a deliminator then multiple tokens then a deliminator then multiple tokens" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 , token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 , token: "test token six" misc: "test miscellaneous data six" starts: 204 ends: 248 , token: "test deliminator" misc: "test miscellaneous data seven" starts: 265 ends: 283 , token: "test token eight" misc: "test miscellaneous data eight" starts: 292 ends: 301 , token: "test token nine" misc: "test miscellaneous data nine" starts: 314 ends: 348 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 ] [ token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 , token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 , token: "test token six" misc: "test miscellaneous data six" starts: 204 ends: 248 ] [ token: "test token eight" misc: "test miscellaneous data eight" starts: 292 ends: 301 , token: "test token nine" misc: "test miscellaneous data nine" starts: 314 ends: 348 ] ]
134149
describe "parseList", -> parseList = require "./parseList" run = (config) -> describe config.description, -> inputCopy = undefined beforeEach -> inputCopy = JSON.parse JSON.stringify config.input if config.throws it "throws the expected exception", -> (expect -> parseList inputCopy, "test deliminator").toThrow config.throws else it "returns the expected output", -> (expect parseList inputCopy, "test deliminator").toEqual config.output beforeEach -> try parseList inputCopy, "test deliminator" catch it "does not modify the input", -> (expect inputCopy).toEqual config.input run description: "no tokens" input: [] output: [] run description: "a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 ] ] run description: "multiple tokens without deliminators" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 , token: "test token two" misc: "test miscellaneous data two" starts: 52 ends: 73 , token: "test token three" misc: "test miscellaneous data three" starts: 123 ends: 160 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 , token: "<KEY>" misc: "test miscellaneous data two" starts: 52 ends: 73 , token: "<KEY> three" misc: "test miscellaneous data three" starts: 123 ends: 160 ] ] run description: "a single deliminator" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 17 ends: 25 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "two deliminators" input: [ token: "<KEY> deliminator" misc: "test miscellaneous data one" starts: 17 ends: 25 , token: "<KEY>minator" misc: "test miscellaneous data two" starts: 31 ends: 56 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "one token then a single deliminator" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 8 , token: "test deliminator" misc: "test miscellaneous data two" starts: 17 ends: 25 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "multiple tokens then a single deliminator" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 60 ends: 84 , token: "<KEY> deliminator" misc: "test miscellaneous data two" starts: 112 ends: 148 ] throws: reason: "emptyGroup" starts: 112 ends: 148 run description: "single deliminator then a single token" input: [ token: "<KEY>" misc: "test miscellaneous data one" starts: 17 ends: 25 , token: "test token two" misc: "test miscellaneous data two" starts: 36 ends: 41 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "single deliminator then multiple tokens" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token one" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token two" misc: "test miscellaneous data three" starts: 60 ends: 84 , token: "test token three" misc: "test miscellaneous data two" starts: 112 ends: 148 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "single token then a single deliminator then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test deliminator" misc: "test miscellaneous data two" starts: 17 ends: 25 , token: "test token three" misc: "test miscellaneous data three" starts: 36 ends: 41 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 ] [ token: "test token three" misc: "test miscellaneous data three" starts: 36 ends: 41 ] ] run description: "multiple tokens then a single deliminator then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "test token three" misc: "test miscellaneous data three" starts: 34 ends: 39 , token: "test deliminator" misc: "test miscellaneous data four" starts: 58 ends: 72 , token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "<KEY> token three" misc: "test miscellaneous data three" starts: 34 ends: 39 ] [ token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] ] run description: "a single token then a single deliminator then multiple tokens" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test deliminator" misc: "test miscellaneous data two" starts: 24 ends: 37 , token: "test token three" misc: "test miscellaneous data three" starts: 49 ends: 57 , token: "test token four" misc: "test miscellaneous data four" starts: 78 ends: 88 , token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 ] [ token: "<KEY> three" misc: "test miscellaneous data three" starts: 49 ends: 57 , token: "<KEY>" misc: "test miscellaneous data four" starts: 78 ends: 88 , token: "<KEY> five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] ] run description: "multiple tokens then a single deliminator then multiple tokens" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "test token three" misc: "test miscellaneous data three" starts: 34 ends: 39 , token: "<KEY> deliminator" misc: "test miscellaneous data four" starts: 58 ends: 72 , token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 , token: "test token six" misc: "test miscellaneous data six" starts: 163 ends: 174 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "test token three" misc: "test miscellaneous data three" starts: 34 ends: 39 ] [ token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 , token: "test token six" misc: "test miscellaneous data six" starts: 163 ends: 174 ] ] run description: "two deliminators" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "<KEY> deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "a single token then two deliminators" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 ] throws: reason: "emptyGroup" starts: 35 ends: 89 run description: "a deliminator then a single token then a deliminator" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "<KEY> token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "two deliminators then a single toke" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "a single token then a deliminator then a single token then a deliminator" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "<KEY> deliminator" misc: "test miscellaneous data four" starts: 124 ends: 148 ] throws: reason: "emptyGroup" starts: 124 ends: 148 run description: "a single token then two deliminators then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "<KEY> deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "<KEY> deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 ] throws: reason: "emptyGroup" starts: 35 ends: 89 run description: "a deliminator then a single token then a deliminator then a single token" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "a single token then a deliminator then a single token then a deliminator then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test deliminator" misc: "test miscellaneous data four" starts: 124 ends: 148 , token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 ] [ token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 ] [ token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 ] ] run description: "multiple tokens then a deliminator then multiple tokens then a deliminator then multiple tokens" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 , token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 , token: "test token six" misc: "test miscellaneous data six" starts: 204 ends: 248 , token: "test deliminator" misc: "test miscellaneous data seven" starts: 265 ends: 283 , token: "test token eight" misc: "test miscellaneous data eight" starts: 292 ends: 301 , token: "test token nine" misc: "test miscellaneous data nine" starts: 314 ends: 348 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 ] [ token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 , token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 , token: "test token six" misc: "test miscellaneous data six" starts: 204 ends: 248 ] [ token: "test token eight" misc: "test miscellaneous data eight" starts: 292 ends: 301 , token: "test token nine" misc: "test miscellaneous data nine" starts: 314 ends: 348 ] ]
true
describe "parseList", -> parseList = require "./parseList" run = (config) -> describe config.description, -> inputCopy = undefined beforeEach -> inputCopy = JSON.parse JSON.stringify config.input if config.throws it "throws the expected exception", -> (expect -> parseList inputCopy, "test deliminator").toThrow config.throws else it "returns the expected output", -> (expect parseList inputCopy, "test deliminator").toEqual config.output beforeEach -> try parseList inputCopy, "test deliminator" catch it "does not modify the input", -> (expect inputCopy).toEqual config.input run description: "no tokens" input: [] output: [] run description: "a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 ] ] run description: "multiple tokens without deliminators" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 , token: "test token two" misc: "test miscellaneous data two" starts: 52 ends: 73 , token: "test token three" misc: "test miscellaneous data three" starts: 123 ends: 160 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 15 ends: 37 , token: "PI:KEY:<KEY>END_PI" misc: "test miscellaneous data two" starts: 52 ends: 73 , token: "PI:KEY:<KEY>END_PI three" misc: "test miscellaneous data three" starts: 123 ends: 160 ] ] run description: "a single deliminator" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 17 ends: 25 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "two deliminators" input: [ token: "PI:KEY:<KEY>END_PI deliminator" misc: "test miscellaneous data one" starts: 17 ends: 25 , token: "PI:KEY:<KEY>END_PIminator" misc: "test miscellaneous data two" starts: 31 ends: 56 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "one token then a single deliminator" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 8 , token: "test deliminator" misc: "test miscellaneous data two" starts: 17 ends: 25 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "multiple tokens then a single deliminator" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 60 ends: 84 , token: "PI:KEY:<KEY>END_PI deliminator" misc: "test miscellaneous data two" starts: 112 ends: 148 ] throws: reason: "emptyGroup" starts: 112 ends: 148 run description: "single deliminator then a single token" input: [ token: "PI:KEY:<KEY>END_PI" misc: "test miscellaneous data one" starts: 17 ends: 25 , token: "test token two" misc: "test miscellaneous data two" starts: 36 ends: 41 ] throws: reason: "emptyGroup" starts: 17 ends: 25 run description: "single deliminator then multiple tokens" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token one" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token two" misc: "test miscellaneous data three" starts: 60 ends: 84 , token: "test token three" misc: "test miscellaneous data two" starts: 112 ends: 148 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "single token then a single deliminator then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test deliminator" misc: "test miscellaneous data two" starts: 17 ends: 25 , token: "test token three" misc: "test miscellaneous data three" starts: 36 ends: 41 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 ] [ token: "test token three" misc: "test miscellaneous data three" starts: 36 ends: 41 ] ] run description: "multiple tokens then a single deliminator then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "test token three" misc: "test miscellaneous data three" starts: 34 ends: 39 , token: "test deliminator" misc: "test miscellaneous data four" starts: 58 ends: 72 , token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "PI:KEY:<KEY>END_PI token three" misc: "test miscellaneous data three" starts: 34 ends: 39 ] [ token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] ] run description: "a single token then a single deliminator then multiple tokens" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test deliminator" misc: "test miscellaneous data two" starts: 24 ends: 37 , token: "test token three" misc: "test miscellaneous data three" starts: 49 ends: 57 , token: "test token four" misc: "test miscellaneous data four" starts: 78 ends: 88 , token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 ] [ token: "PI:KEY:<KEY>END_PI three" misc: "test miscellaneous data three" starts: 49 ends: 57 , token: "PI:KEY:<KEY>END_PI" misc: "test miscellaneous data four" starts: 78 ends: 88 , token: "PI:KEY:<KEY>END_PI five" misc: "test miscellaneous data five" starts: 101 ends: 140 ] ] run description: "multiple tokens then a single deliminator then multiple tokens" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "test token three" misc: "test miscellaneous data three" starts: 34 ends: 39 , token: "PI:KEY:<KEY>END_PI deliminator" misc: "test miscellaneous data four" starts: 58 ends: 72 , token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 , token: "test token six" misc: "test miscellaneous data six" starts: 163 ends: 174 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 3 ends: 5 , token: "test token two" misc: "test miscellaneous data two" starts: 24 ends: 27 , token: "test token three" misc: "test miscellaneous data three" starts: 34 ends: 39 ] [ token: "test token five" misc: "test miscellaneous data five" starts: 101 ends: 140 , token: "test token six" misc: "test miscellaneous data six" starts: 163 ends: 174 ] ] run description: "two deliminators" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "PI:KEY:<KEY>END_PI deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "a single token then two deliminators" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 ] throws: reason: "emptyGroup" starts: 35 ends: 89 run description: "a deliminator then a single token then a deliminator" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "PI:KEY:<KEY>END_PI token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "two deliminators then a single toke" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "a single token then a deliminator then a single token then a deliminator" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "PI:KEY:<KEY>END_PI deliminator" misc: "test miscellaneous data four" starts: 124 ends: 148 ] throws: reason: "emptyGroup" starts: 124 ends: 148 run description: "a single token then two deliminators then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "PI:KEY:<KEY>END_PI deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "PI:KEY:<KEY>END_PI deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 ] throws: reason: "emptyGroup" starts: 35 ends: 89 run description: "a deliminator then a single token then a deliminator then a single token" input: [ token: "test deliminator" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 ] throws: reason: "emptyGroup" starts: 13 ends: 27 run description: "a single token then a deliminator then a single token then a deliminator then a single token" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test deliminator" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test deliminator" misc: "test miscellaneous data four" starts: 124 ends: 148 , token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 ] [ token: "test token three" misc: "test miscellaneous data three" starts: 65 ends: 89 ] [ token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 ] ] run description: "multiple tokens then a deliminator then multiple tokens then a deliminator then multiple tokens" input: [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 , token: "test deliminator" misc: "test miscellaneous data three" starts: 65 ends: 89 , token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 , token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 , token: "test token six" misc: "test miscellaneous data six" starts: 204 ends: 248 , token: "test deliminator" misc: "test miscellaneous data seven" starts: 265 ends: 283 , token: "test token eight" misc: "test miscellaneous data eight" starts: 292 ends: 301 , token: "test token nine" misc: "test miscellaneous data nine" starts: 314 ends: 348 ] output: [ [ token: "test token one" misc: "test miscellaneous data one" starts: 13 ends: 27 , token: "test token two" misc: "test miscellaneous data two" starts: 35 ends: 47 ] [ token: "test token four" misc: "test miscellaneous data four" starts: 124 ends: 148 , token: "test token five" misc: "test miscellaneous data five" starts: 167 ends: 184 , token: "test token six" misc: "test miscellaneous data six" starts: 204 ends: 248 ] [ token: "test token eight" misc: "test miscellaneous data eight" starts: 292 ends: 301 , token: "test token nine" misc: "test miscellaneous data nine" starts: 314 ends: 348 ] ]
[ { "context": "flege'\n 'en': 'Kneipp Care'\n 'es': 'Cuidado Kneipp'\n 'cn': '克奈普护理'\n 'legcare4desc':\n ", "end": 11605, "score": 0.9998322129249573, "start": 11591, "tag": "NAME", "value": "Cuidado Kneipp" } ]
source/datahandermodule/programsLangfile.coffee
JhonnyJason/program-editor-frontend-sources
0
programLangStrings = 'relax1': 'de': 'Beruhigung' 'en': 'Chillout' 'es': 'Chilling' 'cn': '自我放空' 'relax1desc': 'de': 'Hast du gerne Zeit für dich? Manchmal ist es notwendig, sich von allem zu trennen, um sich zu entspannen und die Ruhe zu Manchmal ist es notwendig, zur Ruhe zu kommen und sich zu entspannen. Verwenden Sie das AUROX® Headband um noch effektiver zu relaxen.' 'en': 'Do you like having time for yourself? Sometimes it is necessary to disconnect from everything to just relax and enjoy tranquillity. Then AUROX® Headband is your solution!' 'es': '¿Te gusta tener tiempo para ti? A veces es necesario esconectar del mundo para relajarse y disfrutar de la tranquilidad. ¡AUROX® Headband es tu solución!' 'cn': '你喜欢给予自己一些独处的时间吗?有时候置身自己于世界之外的舒适感是必不可少的,那么,AUROX® Headband(头戴仪)就是你的归属。' 'relax2': 'de': 'Freiheit' 'en': 'Freedom' 'es': 'Libertad' 'cn': '自由' 'relax2desc': 'de': 'Das AUROX® Headband bietet eine angenehme Massage und stimuliert mit anregender Kühlung. Durch abwechselnde Kühlung Ihres Kopfes wird ein positives und frisches Gefühl in Ihren Sinn gebracht. Gerade nach körperlicher oder geistiger Anstrengung ist eine Erholungsphase zwingend erforderlich.' 'en': 'The AUROX® Headband provides a refreshing massage effect by stimulating cooling processes. By alternating cooling applied to your head, a positive and fresh feeling is brought to your sense. After physical or mental effort a period of recovery is absolutely necessary.' 'es': 'AUROX® Headband proporciona un efecto de masaje refrescante al estimular tu cabeza mediante el enfriamiento alternado, lo cual transmite una sensación agradable y fresca. Después de un esfuerzo físico o mental es absolutamente necesario un período de recuperación.' 'cn': 'AUROX® Headband(头戴仪)冷却功能给予你焕然一新般的按摩享受。通过头部特定部位导片温度的改变,你会感到触动神经般的放松。体力或脑力活动之后,你需要我们的产品来助你快速恢复。' 'relax3': 'de': 'Power Nap' 'en': 'Powernap' 'es': 'Mini-siesta' 'cn': '能量盹' 'relax3desc': 'de': 'Benötigen Sie eine kurze Pause während des Tages? Sehen Sie, wie wirksam ein Powernap sein kann, wenn Sie Ihr AUROX® Headband starten. Spüren Sie ein Gefühl der Entspannung und des Wohlbefindens und seien Sie nach wenigen Minuten wieder bereit, den Tag aktiv fortzusetzen!' 'en': 'Need a short break in your day? See how well you are able to sleep once you start your device and push the button. A sense of relaxation and well-being will come to you and after some minutes you will be completely prepared to actively continue with your day!' 'es': '¿Necesitas un descanso? Comprueba lo bien que se duerme después de encender tu dispositivo y pulsar el botón. Sumérgete en una sensación de bienestar y relajación y tras varios minutos serás capaz de continuar con tu día.' 'cn': '冗长的一天需要惬意的小憩吗?只需要一键开启你的设备,你会发现原来可以睡的如此香甜。仅需几分钟,疲劳感将一扫而光,满足感一涌而上,重新变得活力满满!' 'relax4': 'de': 'Abkühlen' 'en': 'Cool down' 'es': 'Refréscate' 'cn': '极致冰点' 'relax4desc': 'de': 'Da sich die Blutgefäße zusammenziehen, wenn sie erkalten und sich bei Wärme ausdehnen, verbessert abwechselnd Kälte und Wärme die Zirkulation. Manchmal fühlt sich der Körper zu heiß an und daher ist eine Kühlung erforderlich, um die beste Temperatur zu erreichen und sich vollkommen entspannt und wohl zu fühlen.' 'en': 'As blood vessels contract when they are cold and expand when heat is applied, alternating cold and heat improves circulation. Sometimes the body feels too hot and therefore, it is necessary to apply some cooling to have the best temperature and feel completely relaxed.' 'es': 'Los vasos sanguíneos se contraen cuando están fríos y se expanden cuando se les aplica calor. Por lo tanto, alternar el frío y el calor mejora la circulación. A veces la temperatura corporal aumenta demasiado y es necesario aplicar frío para la mejorarla y sentirse completamente relajado.' 'cn': '血管在低温下收缩与高温中扩张,因此在皮肤表面进行冷热交替变换可促进血液循环。同时,你同样需要体温的适感调节,当你觉得身体“发烧”时,那你将不会想要错过我们的“极致冰点”时刻。' 'relax5': 'de': 'Kater' 'en': 'Hangover' 'es': 'Resaca' 'cn': '宿醉救星' 'relax5desc': 'de': 'Ist Ihr Leben voller Feste, Partys oder Abendessen auswärts, die später möglicherweise in den Clubs enden? Alkohol trinken schadet und entwässert Ihren Körper. Sie fühlen sich vielleicht schrecklich, aber das AUROX® Headband kann Ihnen dabei helfen, Ihr Wohlbefinden zu steigern. Wasser trinken, frische Luft schnappen und AUROX® Headband einschalten.' 'en': 'Is your life full of celebrations, farewells or dinners that end up in clubs later than the expected? Drinking alcohol harms and dehydrates your body. You may feel horrible but the AUROX® Headband can help you to increase your wellbeing. Drink water, get some fresh air and switch on your device.' 'es': '¿Está tu vida repleta de celebraciones, despedidas o cenas que terminan más tarde de lo esperado? Beber alcohol daña y deshidrata tu cuerpo. Sentirás malestar pero AUROX® Headband te ayuda a aumentar el bienestar. Bebe agua, toma aire fresco y enciende tu dispositivo. ¡Tu bienestar incrementará en abundancia!' 'cn': '您的生活中是否充满了庆祝活动,告别或晚餐,最终会在俱乐部中落后于预期? 饮酒有害并使身体脱水。 您可能感觉很糟糕,但AUROX®头带可以帮助您增加健康。 喝水,呼吸新鲜空气并打开设备。' 'perform1': 'de': 'Bleib wach' 'en': 'Stay up' 'es': 'Aguanta' 'cn': '来劲了' 'perform1desc': 'de': 'Fühlst du dich müde, hast aber noch etwas zu erledigen? Die sanften und sich wiederholenden Kühlintervalle des AUROX® Headband helfen Ihnen, sich erfrischt zu fühlen und länger wach zu bleiben.' 'en': 'Are you feeling tired but still have some work to finish? The gentle and repeating cooling intervals of the AUROX® Headband will help you stay awake. Work completely refreshed!' 'es': '¿Sientes que el cansancio puede contigo pero necesitas terminar con tu trabajo? Los agradables y repetidos intervalos de enfriamiento de AUROX® Headband te ayudarán a mantenerte despierto/a. ¡Trabaja completamente despejado/a!' 'cn': '感觉到无精打采却还要维持工作?Aurox轻柔振频冷却功能使你振作精神,赶走困意!' 'perform2': 'de': 'Stress' 'en': 'Busy' 'es': 'Atareado' 'cn': '压力山大' 'perform2desc': 'de': 'Viele Aufgaben in kurzer Zeit zu erledigen? Machen Sie sich kein Stress mehr! Holen Sie sich den nötigen Schub, vergessen Sie, dass Sie sich müde fühlen. und schließen Sie Ihre Arbeit erfolgreich ab.' 'en': 'So many tasks, so little time... Don’t stress anymore! Get the push you need to complete all your work and forget about feeling fatigued.' 'es': 'Demasiadas obligaciones y muy poco tiempo… ¡No te estreses más! Consigue el empujón que necesitas para completar todos tus quehaceres y olvídate del cansancio.' 'cn': '有限的时间,无限的工作…别担心!按下启动键,疲劳统统不见,工作加速完成!' 'perform3': 'de': 'Sei bereit' 'en': 'Get ready' 'es': 'Prepárate' 'cn': '状态准备' 'perform3desc': 'de': 'Müssen Sie sich motiviert fühlen und besser sein als je zuvor? Warten Sie nicht länger und drücken Sie die Taste. Holen Sie mit Ihrem AUROX® Headband das Beste aus Ihrer Aktivität heraus.' 'en': 'Do you need to feel motivated and perform better than ever? Don’t wait longer and press the button, this is your need! Get the best out of your activity with your AUROX® Headband.' 'es': '¿Necesitas motivarte y rendir mejor que nunca? No esperes más y presiona el botón, ¡es lo que necesitas! Consigue el mejor resultado con tu AUROX® Headband.' 'cn': '需要一些外界的动力来提升表现吗?别再犹豫,按下启动键,与AUROX® Headband(头戴仪)踏上旅程!' 'perform4': 'de': 'Fokus' 'en': 'Focus' 'es': 'Céntrate' 'cn': '聚精会神' 'perform4desc': 'de': 'Fällt es Ihnen schwer fokussiert und konzentriert zu bleiben? Diese Programm kann durch verschiedene Kühlverläufe eine erfrischende Wirkung erzielen, was sich positiv auf ihre Vigilanz auswirken kann.' 'en': 'Is it difficult for you to stay focused and focused? This program can provide a refreshing effect through different cooling patterns, which can have a positive effect on your vigilance.' 'es': '¿Es difícil para ti mantenerte enfocado y enfocado? Este programa puede proporcionar un efecto refrescante a través de diferentes patrones de enfriamiento, lo que puede tener un efecto positivo en su vigilancia.' 'cn': '你难以保持专注和专注吗? 该程序可以通过不同的冷却模式提供清新效果,这可以对您的警惕产生积极影响。' 'perform5': 'de': 'Morgen!' 'en': 'Wake up!' 'es': '¡Despierta!' 'cn': '唤醒时间;' 'perform5desc': 'de': 'Fällt es Ihnen schwer, morgens das warme Bett zu verlassen? Kommen Sie mit dem AUROX® Headband leichter in die Schwünge und haben Sie einen tollen Start in den Tag.' 'en': 'Is it difficult to wake up? Want to stay in bed longer? This is the best choice to start your day in a completely good way and with the best of your moods!' 'es': '¿Se te hace difícil levantarte por las mañanas? ¿Quieres quedarte más tiempo en tu cama? ¡Esta es la mejor elección para empezar el día de la mejor manera y con el mejor humor posible!' 'cn': '起床困难户?赖床户?一触即发,告别沉睡!' 'legcare1': 'de': 'Gesundes Sitzen' 'en': 'Healthy Sitting' 'es': 'Siéntate' 'cn': '健康坐' 'legcare1desc': 'de': 'Verbringen Sie längere Zeit im Sitzen? Es ist hiflreich, die Beine mit Kühlverläufen zu behandeln. Es fördert den Blutfluß der Beine bei der Arbeit, im Büro oder auf langen Reisestrecken.' 'en': 'Do you spend long periods of time sitting? It is necessary to apply some cooling and warming effects to increase the blood flow when working in an office or travelling long distances.' 'es': '¿Pasas largos períodos de tiempo sentado? Es necesario aplicar algunos efectos de enfriamiento y calentamiento para aumentar el flujo sanguíneo al trabajar en una oficina o viajar largas distancias.' 'cn': '您是否花费很长时间坐着?在办公室工作或长途旅行时,有必要施加一些降温和加温效果以增加血液流量。' 'legcare2': 'de': 'Gesund Stehen' 'en': 'Healthy Standing' 'es': 'Levántate' 'cn': '健康的地位' 'legcare2desc': 'de': 'Stehen sie täglich mehrere Stunden? Drücken Sie die Taste und aktivieren Sie Ihre Beine mit einer kühlenden Behandlung.' 'en': 'Does your day to day activity involve long periods of time standing? Press the button and activate your legs applying some cooling and warming effects.' 'es': '¿Su actividad diaria implica largos períodos de tiempo de pie? Presione el botón y active sus piernas aplicando algunos efectos de enfriamiento y calentamiento.' 'cn': '您的日常练习是否需要长时间站立?按下按钮并激活双腿,从而起到一些降温和保暖的作用。' 'legcare3': 'de': 'Aufwärmen' 'en': 'Warm Up' 'es': 'Calentamiento' 'cn': '暖身' 'legcare3desc': 'de': 'Müssen Sie Ihre Muskeln aktivieren, um eine bessere Leistung zu erzielen als je? Warten Sie nicht länger und drücken Sie die Taste! Mach das Beste aus deiner Aktivität!' 'en': 'Do you need to activate your muscles to perform better than ever? Don‘t wait longer and press the button! Make the best out of your activity!' 'es': '¿Necesita activar sus músculos para rendir mejor que nunca? ¡No espere más y presione el botón! ¡Aproveche al máximo su actividad!' 'cn': '您是否需要激活肌肉以使其表现得比曾经吗?不要等待更长的时间并按下按钮!尽力而为失去您的活动!' 'legcare4': 'de': 'Kneipp-Pflege' 'en': 'Kneipp Care' 'es': 'Cuidado Kneipp' 'cn': '克奈普护理' 'legcare4desc': 'de': 'Sehen Sie, wie gut Ihre Zirkulation sein wird, nachdem Sie den AUROX probiert haben Actileg simuliert Erwärmungs- und Abkühlungskontraste.' 'en': 'See how well your circulation will be after you try the AUROX Actileg simulating warming and cooling contrasts.' 'es': 'Vea qué tan bien estará su circulación después de probar el AUROX Actileg simulando contrastes de calentamiento y enfriamiento.' 'cn': '尝试AUROX后,看看您的血液循环情况如何Actileg模拟升温和降温对比' export default programLangStrings
175917
programLangStrings = 'relax1': 'de': 'Beruhigung' 'en': 'Chillout' 'es': 'Chilling' 'cn': '自我放空' 'relax1desc': 'de': 'Hast du gerne Zeit für dich? Manchmal ist es notwendig, sich von allem zu trennen, um sich zu entspannen und die Ruhe zu Manchmal ist es notwendig, zur Ruhe zu kommen und sich zu entspannen. Verwenden Sie das AUROX® Headband um noch effektiver zu relaxen.' 'en': 'Do you like having time for yourself? Sometimes it is necessary to disconnect from everything to just relax and enjoy tranquillity. Then AUROX® Headband is your solution!' 'es': '¿Te gusta tener tiempo para ti? A veces es necesario esconectar del mundo para relajarse y disfrutar de la tranquilidad. ¡AUROX® Headband es tu solución!' 'cn': '你喜欢给予自己一些独处的时间吗?有时候置身自己于世界之外的舒适感是必不可少的,那么,AUROX® Headband(头戴仪)就是你的归属。' 'relax2': 'de': 'Freiheit' 'en': 'Freedom' 'es': 'Libertad' 'cn': '自由' 'relax2desc': 'de': 'Das AUROX® Headband bietet eine angenehme Massage und stimuliert mit anregender Kühlung. Durch abwechselnde Kühlung Ihres Kopfes wird ein positives und frisches Gefühl in Ihren Sinn gebracht. Gerade nach körperlicher oder geistiger Anstrengung ist eine Erholungsphase zwingend erforderlich.' 'en': 'The AUROX® Headband provides a refreshing massage effect by stimulating cooling processes. By alternating cooling applied to your head, a positive and fresh feeling is brought to your sense. After physical or mental effort a period of recovery is absolutely necessary.' 'es': 'AUROX® Headband proporciona un efecto de masaje refrescante al estimular tu cabeza mediante el enfriamiento alternado, lo cual transmite una sensación agradable y fresca. Después de un esfuerzo físico o mental es absolutamente necesario un período de recuperación.' 'cn': 'AUROX® Headband(头戴仪)冷却功能给予你焕然一新般的按摩享受。通过头部特定部位导片温度的改变,你会感到触动神经般的放松。体力或脑力活动之后,你需要我们的产品来助你快速恢复。' 'relax3': 'de': 'Power Nap' 'en': 'Powernap' 'es': 'Mini-siesta' 'cn': '能量盹' 'relax3desc': 'de': 'Benötigen Sie eine kurze Pause während des Tages? Sehen Sie, wie wirksam ein Powernap sein kann, wenn Sie Ihr AUROX® Headband starten. Spüren Sie ein Gefühl der Entspannung und des Wohlbefindens und seien Sie nach wenigen Minuten wieder bereit, den Tag aktiv fortzusetzen!' 'en': 'Need a short break in your day? See how well you are able to sleep once you start your device and push the button. A sense of relaxation and well-being will come to you and after some minutes you will be completely prepared to actively continue with your day!' 'es': '¿Necesitas un descanso? Comprueba lo bien que se duerme después de encender tu dispositivo y pulsar el botón. Sumérgete en una sensación de bienestar y relajación y tras varios minutos serás capaz de continuar con tu día.' 'cn': '冗长的一天需要惬意的小憩吗?只需要一键开启你的设备,你会发现原来可以睡的如此香甜。仅需几分钟,疲劳感将一扫而光,满足感一涌而上,重新变得活力满满!' 'relax4': 'de': 'Abkühlen' 'en': 'Cool down' 'es': 'Refréscate' 'cn': '极致冰点' 'relax4desc': 'de': 'Da sich die Blutgefäße zusammenziehen, wenn sie erkalten und sich bei Wärme ausdehnen, verbessert abwechselnd Kälte und Wärme die Zirkulation. Manchmal fühlt sich der Körper zu heiß an und daher ist eine Kühlung erforderlich, um die beste Temperatur zu erreichen und sich vollkommen entspannt und wohl zu fühlen.' 'en': 'As blood vessels contract when they are cold and expand when heat is applied, alternating cold and heat improves circulation. Sometimes the body feels too hot and therefore, it is necessary to apply some cooling to have the best temperature and feel completely relaxed.' 'es': 'Los vasos sanguíneos se contraen cuando están fríos y se expanden cuando se les aplica calor. Por lo tanto, alternar el frío y el calor mejora la circulación. A veces la temperatura corporal aumenta demasiado y es necesario aplicar frío para la mejorarla y sentirse completamente relajado.' 'cn': '血管在低温下收缩与高温中扩张,因此在皮肤表面进行冷热交替变换可促进血液循环。同时,你同样需要体温的适感调节,当你觉得身体“发烧”时,那你将不会想要错过我们的“极致冰点”时刻。' 'relax5': 'de': 'Kater' 'en': 'Hangover' 'es': 'Resaca' 'cn': '宿醉救星' 'relax5desc': 'de': 'Ist Ihr Leben voller Feste, Partys oder Abendessen auswärts, die später möglicherweise in den Clubs enden? Alkohol trinken schadet und entwässert Ihren Körper. Sie fühlen sich vielleicht schrecklich, aber das AUROX® Headband kann Ihnen dabei helfen, Ihr Wohlbefinden zu steigern. Wasser trinken, frische Luft schnappen und AUROX® Headband einschalten.' 'en': 'Is your life full of celebrations, farewells or dinners that end up in clubs later than the expected? Drinking alcohol harms and dehydrates your body. You may feel horrible but the AUROX® Headband can help you to increase your wellbeing. Drink water, get some fresh air and switch on your device.' 'es': '¿Está tu vida repleta de celebraciones, despedidas o cenas que terminan más tarde de lo esperado? Beber alcohol daña y deshidrata tu cuerpo. Sentirás malestar pero AUROX® Headband te ayuda a aumentar el bienestar. Bebe agua, toma aire fresco y enciende tu dispositivo. ¡Tu bienestar incrementará en abundancia!' 'cn': '您的生活中是否充满了庆祝活动,告别或晚餐,最终会在俱乐部中落后于预期? 饮酒有害并使身体脱水。 您可能感觉很糟糕,但AUROX®头带可以帮助您增加健康。 喝水,呼吸新鲜空气并打开设备。' 'perform1': 'de': 'Bleib wach' 'en': 'Stay up' 'es': 'Aguanta' 'cn': '来劲了' 'perform1desc': 'de': 'Fühlst du dich müde, hast aber noch etwas zu erledigen? Die sanften und sich wiederholenden Kühlintervalle des AUROX® Headband helfen Ihnen, sich erfrischt zu fühlen und länger wach zu bleiben.' 'en': 'Are you feeling tired but still have some work to finish? The gentle and repeating cooling intervals of the AUROX® Headband will help you stay awake. Work completely refreshed!' 'es': '¿Sientes que el cansancio puede contigo pero necesitas terminar con tu trabajo? Los agradables y repetidos intervalos de enfriamiento de AUROX® Headband te ayudarán a mantenerte despierto/a. ¡Trabaja completamente despejado/a!' 'cn': '感觉到无精打采却还要维持工作?Aurox轻柔振频冷却功能使你振作精神,赶走困意!' 'perform2': 'de': 'Stress' 'en': 'Busy' 'es': 'Atareado' 'cn': '压力山大' 'perform2desc': 'de': 'Viele Aufgaben in kurzer Zeit zu erledigen? Machen Sie sich kein Stress mehr! Holen Sie sich den nötigen Schub, vergessen Sie, dass Sie sich müde fühlen. und schließen Sie Ihre Arbeit erfolgreich ab.' 'en': 'So many tasks, so little time... Don’t stress anymore! Get the push you need to complete all your work and forget about feeling fatigued.' 'es': 'Demasiadas obligaciones y muy poco tiempo… ¡No te estreses más! Consigue el empujón que necesitas para completar todos tus quehaceres y olvídate del cansancio.' 'cn': '有限的时间,无限的工作…别担心!按下启动键,疲劳统统不见,工作加速完成!' 'perform3': 'de': 'Sei bereit' 'en': 'Get ready' 'es': 'Prepárate' 'cn': '状态准备' 'perform3desc': 'de': 'Müssen Sie sich motiviert fühlen und besser sein als je zuvor? Warten Sie nicht länger und drücken Sie die Taste. Holen Sie mit Ihrem AUROX® Headband das Beste aus Ihrer Aktivität heraus.' 'en': 'Do you need to feel motivated and perform better than ever? Don’t wait longer and press the button, this is your need! Get the best out of your activity with your AUROX® Headband.' 'es': '¿Necesitas motivarte y rendir mejor que nunca? No esperes más y presiona el botón, ¡es lo que necesitas! Consigue el mejor resultado con tu AUROX® Headband.' 'cn': '需要一些外界的动力来提升表现吗?别再犹豫,按下启动键,与AUROX® Headband(头戴仪)踏上旅程!' 'perform4': 'de': 'Fokus' 'en': 'Focus' 'es': 'Céntrate' 'cn': '聚精会神' 'perform4desc': 'de': 'Fällt es Ihnen schwer fokussiert und konzentriert zu bleiben? Diese Programm kann durch verschiedene Kühlverläufe eine erfrischende Wirkung erzielen, was sich positiv auf ihre Vigilanz auswirken kann.' 'en': 'Is it difficult for you to stay focused and focused? This program can provide a refreshing effect through different cooling patterns, which can have a positive effect on your vigilance.' 'es': '¿Es difícil para ti mantenerte enfocado y enfocado? Este programa puede proporcionar un efecto refrescante a través de diferentes patrones de enfriamiento, lo que puede tener un efecto positivo en su vigilancia.' 'cn': '你难以保持专注和专注吗? 该程序可以通过不同的冷却模式提供清新效果,这可以对您的警惕产生积极影响。' 'perform5': 'de': 'Morgen!' 'en': 'Wake up!' 'es': '¡Despierta!' 'cn': '唤醒时间;' 'perform5desc': 'de': 'Fällt es Ihnen schwer, morgens das warme Bett zu verlassen? Kommen Sie mit dem AUROX® Headband leichter in die Schwünge und haben Sie einen tollen Start in den Tag.' 'en': 'Is it difficult to wake up? Want to stay in bed longer? This is the best choice to start your day in a completely good way and with the best of your moods!' 'es': '¿Se te hace difícil levantarte por las mañanas? ¿Quieres quedarte más tiempo en tu cama? ¡Esta es la mejor elección para empezar el día de la mejor manera y con el mejor humor posible!' 'cn': '起床困难户?赖床户?一触即发,告别沉睡!' 'legcare1': 'de': 'Gesundes Sitzen' 'en': 'Healthy Sitting' 'es': 'Siéntate' 'cn': '健康坐' 'legcare1desc': 'de': 'Verbringen Sie längere Zeit im Sitzen? Es ist hiflreich, die Beine mit Kühlverläufen zu behandeln. Es fördert den Blutfluß der Beine bei der Arbeit, im Büro oder auf langen Reisestrecken.' 'en': 'Do you spend long periods of time sitting? It is necessary to apply some cooling and warming effects to increase the blood flow when working in an office or travelling long distances.' 'es': '¿Pasas largos períodos de tiempo sentado? Es necesario aplicar algunos efectos de enfriamiento y calentamiento para aumentar el flujo sanguíneo al trabajar en una oficina o viajar largas distancias.' 'cn': '您是否花费很长时间坐着?在办公室工作或长途旅行时,有必要施加一些降温和加温效果以增加血液流量。' 'legcare2': 'de': 'Gesund Stehen' 'en': 'Healthy Standing' 'es': 'Levántate' 'cn': '健康的地位' 'legcare2desc': 'de': 'Stehen sie täglich mehrere Stunden? Drücken Sie die Taste und aktivieren Sie Ihre Beine mit einer kühlenden Behandlung.' 'en': 'Does your day to day activity involve long periods of time standing? Press the button and activate your legs applying some cooling and warming effects.' 'es': '¿Su actividad diaria implica largos períodos de tiempo de pie? Presione el botón y active sus piernas aplicando algunos efectos de enfriamiento y calentamiento.' 'cn': '您的日常练习是否需要长时间站立?按下按钮并激活双腿,从而起到一些降温和保暖的作用。' 'legcare3': 'de': 'Aufwärmen' 'en': 'Warm Up' 'es': 'Calentamiento' 'cn': '暖身' 'legcare3desc': 'de': 'Müssen Sie Ihre Muskeln aktivieren, um eine bessere Leistung zu erzielen als je? Warten Sie nicht länger und drücken Sie die Taste! Mach das Beste aus deiner Aktivität!' 'en': 'Do you need to activate your muscles to perform better than ever? Don‘t wait longer and press the button! Make the best out of your activity!' 'es': '¿Necesita activar sus músculos para rendir mejor que nunca? ¡No espere más y presione el botón! ¡Aproveche al máximo su actividad!' 'cn': '您是否需要激活肌肉以使其表现得比曾经吗?不要等待更长的时间并按下按钮!尽力而为失去您的活动!' 'legcare4': 'de': 'Kneipp-Pflege' 'en': 'Kneipp Care' 'es': '<NAME>' 'cn': '克奈普护理' 'legcare4desc': 'de': 'Sehen Sie, wie gut Ihre Zirkulation sein wird, nachdem Sie den AUROX probiert haben Actileg simuliert Erwärmungs- und Abkühlungskontraste.' 'en': 'See how well your circulation will be after you try the AUROX Actileg simulating warming and cooling contrasts.' 'es': 'Vea qué tan bien estará su circulación después de probar el AUROX Actileg simulando contrastes de calentamiento y enfriamiento.' 'cn': '尝试AUROX后,看看您的血液循环情况如何Actileg模拟升温和降温对比' export default programLangStrings
true
programLangStrings = 'relax1': 'de': 'Beruhigung' 'en': 'Chillout' 'es': 'Chilling' 'cn': '自我放空' 'relax1desc': 'de': 'Hast du gerne Zeit für dich? Manchmal ist es notwendig, sich von allem zu trennen, um sich zu entspannen und die Ruhe zu Manchmal ist es notwendig, zur Ruhe zu kommen und sich zu entspannen. Verwenden Sie das AUROX® Headband um noch effektiver zu relaxen.' 'en': 'Do you like having time for yourself? Sometimes it is necessary to disconnect from everything to just relax and enjoy tranquillity. Then AUROX® Headband is your solution!' 'es': '¿Te gusta tener tiempo para ti? A veces es necesario esconectar del mundo para relajarse y disfrutar de la tranquilidad. ¡AUROX® Headband es tu solución!' 'cn': '你喜欢给予自己一些独处的时间吗?有时候置身自己于世界之外的舒适感是必不可少的,那么,AUROX® Headband(头戴仪)就是你的归属。' 'relax2': 'de': 'Freiheit' 'en': 'Freedom' 'es': 'Libertad' 'cn': '自由' 'relax2desc': 'de': 'Das AUROX® Headband bietet eine angenehme Massage und stimuliert mit anregender Kühlung. Durch abwechselnde Kühlung Ihres Kopfes wird ein positives und frisches Gefühl in Ihren Sinn gebracht. Gerade nach körperlicher oder geistiger Anstrengung ist eine Erholungsphase zwingend erforderlich.' 'en': 'The AUROX® Headband provides a refreshing massage effect by stimulating cooling processes. By alternating cooling applied to your head, a positive and fresh feeling is brought to your sense. After physical or mental effort a period of recovery is absolutely necessary.' 'es': 'AUROX® Headband proporciona un efecto de masaje refrescante al estimular tu cabeza mediante el enfriamiento alternado, lo cual transmite una sensación agradable y fresca. Después de un esfuerzo físico o mental es absolutamente necesario un período de recuperación.' 'cn': 'AUROX® Headband(头戴仪)冷却功能给予你焕然一新般的按摩享受。通过头部特定部位导片温度的改变,你会感到触动神经般的放松。体力或脑力活动之后,你需要我们的产品来助你快速恢复。' 'relax3': 'de': 'Power Nap' 'en': 'Powernap' 'es': 'Mini-siesta' 'cn': '能量盹' 'relax3desc': 'de': 'Benötigen Sie eine kurze Pause während des Tages? Sehen Sie, wie wirksam ein Powernap sein kann, wenn Sie Ihr AUROX® Headband starten. Spüren Sie ein Gefühl der Entspannung und des Wohlbefindens und seien Sie nach wenigen Minuten wieder bereit, den Tag aktiv fortzusetzen!' 'en': 'Need a short break in your day? See how well you are able to sleep once you start your device and push the button. A sense of relaxation and well-being will come to you and after some minutes you will be completely prepared to actively continue with your day!' 'es': '¿Necesitas un descanso? Comprueba lo bien que se duerme después de encender tu dispositivo y pulsar el botón. Sumérgete en una sensación de bienestar y relajación y tras varios minutos serás capaz de continuar con tu día.' 'cn': '冗长的一天需要惬意的小憩吗?只需要一键开启你的设备,你会发现原来可以睡的如此香甜。仅需几分钟,疲劳感将一扫而光,满足感一涌而上,重新变得活力满满!' 'relax4': 'de': 'Abkühlen' 'en': 'Cool down' 'es': 'Refréscate' 'cn': '极致冰点' 'relax4desc': 'de': 'Da sich die Blutgefäße zusammenziehen, wenn sie erkalten und sich bei Wärme ausdehnen, verbessert abwechselnd Kälte und Wärme die Zirkulation. Manchmal fühlt sich der Körper zu heiß an und daher ist eine Kühlung erforderlich, um die beste Temperatur zu erreichen und sich vollkommen entspannt und wohl zu fühlen.' 'en': 'As blood vessels contract when they are cold and expand when heat is applied, alternating cold and heat improves circulation. Sometimes the body feels too hot and therefore, it is necessary to apply some cooling to have the best temperature and feel completely relaxed.' 'es': 'Los vasos sanguíneos se contraen cuando están fríos y se expanden cuando se les aplica calor. Por lo tanto, alternar el frío y el calor mejora la circulación. A veces la temperatura corporal aumenta demasiado y es necesario aplicar frío para la mejorarla y sentirse completamente relajado.' 'cn': '血管在低温下收缩与高温中扩张,因此在皮肤表面进行冷热交替变换可促进血液循环。同时,你同样需要体温的适感调节,当你觉得身体“发烧”时,那你将不会想要错过我们的“极致冰点”时刻。' 'relax5': 'de': 'Kater' 'en': 'Hangover' 'es': 'Resaca' 'cn': '宿醉救星' 'relax5desc': 'de': 'Ist Ihr Leben voller Feste, Partys oder Abendessen auswärts, die später möglicherweise in den Clubs enden? Alkohol trinken schadet und entwässert Ihren Körper. Sie fühlen sich vielleicht schrecklich, aber das AUROX® Headband kann Ihnen dabei helfen, Ihr Wohlbefinden zu steigern. Wasser trinken, frische Luft schnappen und AUROX® Headband einschalten.' 'en': 'Is your life full of celebrations, farewells or dinners that end up in clubs later than the expected? Drinking alcohol harms and dehydrates your body. You may feel horrible but the AUROX® Headband can help you to increase your wellbeing. Drink water, get some fresh air and switch on your device.' 'es': '¿Está tu vida repleta de celebraciones, despedidas o cenas que terminan más tarde de lo esperado? Beber alcohol daña y deshidrata tu cuerpo. Sentirás malestar pero AUROX® Headband te ayuda a aumentar el bienestar. Bebe agua, toma aire fresco y enciende tu dispositivo. ¡Tu bienestar incrementará en abundancia!' 'cn': '您的生活中是否充满了庆祝活动,告别或晚餐,最终会在俱乐部中落后于预期? 饮酒有害并使身体脱水。 您可能感觉很糟糕,但AUROX®头带可以帮助您增加健康。 喝水,呼吸新鲜空气并打开设备。' 'perform1': 'de': 'Bleib wach' 'en': 'Stay up' 'es': 'Aguanta' 'cn': '来劲了' 'perform1desc': 'de': 'Fühlst du dich müde, hast aber noch etwas zu erledigen? Die sanften und sich wiederholenden Kühlintervalle des AUROX® Headband helfen Ihnen, sich erfrischt zu fühlen und länger wach zu bleiben.' 'en': 'Are you feeling tired but still have some work to finish? The gentle and repeating cooling intervals of the AUROX® Headband will help you stay awake. Work completely refreshed!' 'es': '¿Sientes que el cansancio puede contigo pero necesitas terminar con tu trabajo? Los agradables y repetidos intervalos de enfriamiento de AUROX® Headband te ayudarán a mantenerte despierto/a. ¡Trabaja completamente despejado/a!' 'cn': '感觉到无精打采却还要维持工作?Aurox轻柔振频冷却功能使你振作精神,赶走困意!' 'perform2': 'de': 'Stress' 'en': 'Busy' 'es': 'Atareado' 'cn': '压力山大' 'perform2desc': 'de': 'Viele Aufgaben in kurzer Zeit zu erledigen? Machen Sie sich kein Stress mehr! Holen Sie sich den nötigen Schub, vergessen Sie, dass Sie sich müde fühlen. und schließen Sie Ihre Arbeit erfolgreich ab.' 'en': 'So many tasks, so little time... Don’t stress anymore! Get the push you need to complete all your work and forget about feeling fatigued.' 'es': 'Demasiadas obligaciones y muy poco tiempo… ¡No te estreses más! Consigue el empujón que necesitas para completar todos tus quehaceres y olvídate del cansancio.' 'cn': '有限的时间,无限的工作…别担心!按下启动键,疲劳统统不见,工作加速完成!' 'perform3': 'de': 'Sei bereit' 'en': 'Get ready' 'es': 'Prepárate' 'cn': '状态准备' 'perform3desc': 'de': 'Müssen Sie sich motiviert fühlen und besser sein als je zuvor? Warten Sie nicht länger und drücken Sie die Taste. Holen Sie mit Ihrem AUROX® Headband das Beste aus Ihrer Aktivität heraus.' 'en': 'Do you need to feel motivated and perform better than ever? Don’t wait longer and press the button, this is your need! Get the best out of your activity with your AUROX® Headband.' 'es': '¿Necesitas motivarte y rendir mejor que nunca? No esperes más y presiona el botón, ¡es lo que necesitas! Consigue el mejor resultado con tu AUROX® Headband.' 'cn': '需要一些外界的动力来提升表现吗?别再犹豫,按下启动键,与AUROX® Headband(头戴仪)踏上旅程!' 'perform4': 'de': 'Fokus' 'en': 'Focus' 'es': 'Céntrate' 'cn': '聚精会神' 'perform4desc': 'de': 'Fällt es Ihnen schwer fokussiert und konzentriert zu bleiben? Diese Programm kann durch verschiedene Kühlverläufe eine erfrischende Wirkung erzielen, was sich positiv auf ihre Vigilanz auswirken kann.' 'en': 'Is it difficult for you to stay focused and focused? This program can provide a refreshing effect through different cooling patterns, which can have a positive effect on your vigilance.' 'es': '¿Es difícil para ti mantenerte enfocado y enfocado? Este programa puede proporcionar un efecto refrescante a través de diferentes patrones de enfriamiento, lo que puede tener un efecto positivo en su vigilancia.' 'cn': '你难以保持专注和专注吗? 该程序可以通过不同的冷却模式提供清新效果,这可以对您的警惕产生积极影响。' 'perform5': 'de': 'Morgen!' 'en': 'Wake up!' 'es': '¡Despierta!' 'cn': '唤醒时间;' 'perform5desc': 'de': 'Fällt es Ihnen schwer, morgens das warme Bett zu verlassen? Kommen Sie mit dem AUROX® Headband leichter in die Schwünge und haben Sie einen tollen Start in den Tag.' 'en': 'Is it difficult to wake up? Want to stay in bed longer? This is the best choice to start your day in a completely good way and with the best of your moods!' 'es': '¿Se te hace difícil levantarte por las mañanas? ¿Quieres quedarte más tiempo en tu cama? ¡Esta es la mejor elección para empezar el día de la mejor manera y con el mejor humor posible!' 'cn': '起床困难户?赖床户?一触即发,告别沉睡!' 'legcare1': 'de': 'Gesundes Sitzen' 'en': 'Healthy Sitting' 'es': 'Siéntate' 'cn': '健康坐' 'legcare1desc': 'de': 'Verbringen Sie längere Zeit im Sitzen? Es ist hiflreich, die Beine mit Kühlverläufen zu behandeln. Es fördert den Blutfluß der Beine bei der Arbeit, im Büro oder auf langen Reisestrecken.' 'en': 'Do you spend long periods of time sitting? It is necessary to apply some cooling and warming effects to increase the blood flow when working in an office or travelling long distances.' 'es': '¿Pasas largos períodos de tiempo sentado? Es necesario aplicar algunos efectos de enfriamiento y calentamiento para aumentar el flujo sanguíneo al trabajar en una oficina o viajar largas distancias.' 'cn': '您是否花费很长时间坐着?在办公室工作或长途旅行时,有必要施加一些降温和加温效果以增加血液流量。' 'legcare2': 'de': 'Gesund Stehen' 'en': 'Healthy Standing' 'es': 'Levántate' 'cn': '健康的地位' 'legcare2desc': 'de': 'Stehen sie täglich mehrere Stunden? Drücken Sie die Taste und aktivieren Sie Ihre Beine mit einer kühlenden Behandlung.' 'en': 'Does your day to day activity involve long periods of time standing? Press the button and activate your legs applying some cooling and warming effects.' 'es': '¿Su actividad diaria implica largos períodos de tiempo de pie? Presione el botón y active sus piernas aplicando algunos efectos de enfriamiento y calentamiento.' 'cn': '您的日常练习是否需要长时间站立?按下按钮并激活双腿,从而起到一些降温和保暖的作用。' 'legcare3': 'de': 'Aufwärmen' 'en': 'Warm Up' 'es': 'Calentamiento' 'cn': '暖身' 'legcare3desc': 'de': 'Müssen Sie Ihre Muskeln aktivieren, um eine bessere Leistung zu erzielen als je? Warten Sie nicht länger und drücken Sie die Taste! Mach das Beste aus deiner Aktivität!' 'en': 'Do you need to activate your muscles to perform better than ever? Don‘t wait longer and press the button! Make the best out of your activity!' 'es': '¿Necesita activar sus músculos para rendir mejor que nunca? ¡No espere más y presione el botón! ¡Aproveche al máximo su actividad!' 'cn': '您是否需要激活肌肉以使其表现得比曾经吗?不要等待更长的时间并按下按钮!尽力而为失去您的活动!' 'legcare4': 'de': 'Kneipp-Pflege' 'en': 'Kneipp Care' 'es': 'PI:NAME:<NAME>END_PI' 'cn': '克奈普护理' 'legcare4desc': 'de': 'Sehen Sie, wie gut Ihre Zirkulation sein wird, nachdem Sie den AUROX probiert haben Actileg simuliert Erwärmungs- und Abkühlungskontraste.' 'en': 'See how well your circulation will be after you try the AUROX Actileg simulating warming and cooling contrasts.' 'es': 'Vea qué tan bien estará su circulación después de probar el AUROX Actileg simulando contrastes de calentamiento y enfriamiento.' 'cn': '尝试AUROX后,看看您的血液循环情况如何Actileg模拟升温和降温对比' export default programLangStrings
[ { "context": "ame: 1, modelYear: 1 }, { unique: true })\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n@abstract\r\n###\r\nclass Airc", "end": 353, "score": 0.9998853206634521, "start": 341, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/schema/AircraftProductAuthorizationAttemptSchema.coffee
qrefdev/qref
0
mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.ObjectId Mixed = Schema.Types.Mixed ### Schema representing a specific aircraft make and model. @example MongoDB Collection db.aircraft.models @example MongoDB Indexes db.aircraft.models.ensureIndex({ name: 1, modelYear: 1 }, { unique: true }) @author Nathan Klick @copyright QRef 2012 @abstract ### class AircraftProductAuthorizationAttemptSchemaInternal user: type: ObjectId required: true ref: 'users' product: type: ObjectId required: true ref: 'products' attemptType: type: String required: true enum: ['apple', 'android'] isReceiptValid: type: Boolean required: true default: false isComplete: type: Boolean required: true default: false appleReceiptHash: type: String required: false default: null appleReceipt: type: Mixed required: false default: null androidReceiptHash: type: String required: false default: null androidReceipt: type: Mixed required: false default: null checklist: type: ObjectId required: false default: null ref: 'aircraft.checklists' timestamp: type: Date required: false default: new Date() AircraftProductAuthorizationAttemptSchema = new Schema(new AircraftProductAuthorizationAttemptSchemaInternal()) AircraftProductAuthorizationAttemptSchema.index({ user: 1, product: 1 }) module.exports = AircraftProductAuthorizationAttemptSchema
210194
mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.ObjectId Mixed = Schema.Types.Mixed ### Schema representing a specific aircraft make and model. @example MongoDB Collection db.aircraft.models @example MongoDB Indexes db.aircraft.models.ensureIndex({ name: 1, modelYear: 1 }, { unique: true }) @author <NAME> @copyright QRef 2012 @abstract ### class AircraftProductAuthorizationAttemptSchemaInternal user: type: ObjectId required: true ref: 'users' product: type: ObjectId required: true ref: 'products' attemptType: type: String required: true enum: ['apple', 'android'] isReceiptValid: type: Boolean required: true default: false isComplete: type: Boolean required: true default: false appleReceiptHash: type: String required: false default: null appleReceipt: type: Mixed required: false default: null androidReceiptHash: type: String required: false default: null androidReceipt: type: Mixed required: false default: null checklist: type: ObjectId required: false default: null ref: 'aircraft.checklists' timestamp: type: Date required: false default: new Date() AircraftProductAuthorizationAttemptSchema = new Schema(new AircraftProductAuthorizationAttemptSchemaInternal()) AircraftProductAuthorizationAttemptSchema.index({ user: 1, product: 1 }) module.exports = AircraftProductAuthorizationAttemptSchema
true
mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.ObjectId Mixed = Schema.Types.Mixed ### Schema representing a specific aircraft make and model. @example MongoDB Collection db.aircraft.models @example MongoDB Indexes db.aircraft.models.ensureIndex({ name: 1, modelYear: 1 }, { unique: true }) @author PI:NAME:<NAME>END_PI @copyright QRef 2012 @abstract ### class AircraftProductAuthorizationAttemptSchemaInternal user: type: ObjectId required: true ref: 'users' product: type: ObjectId required: true ref: 'products' attemptType: type: String required: true enum: ['apple', 'android'] isReceiptValid: type: Boolean required: true default: false isComplete: type: Boolean required: true default: false appleReceiptHash: type: String required: false default: null appleReceipt: type: Mixed required: false default: null androidReceiptHash: type: String required: false default: null androidReceipt: type: Mixed required: false default: null checklist: type: ObjectId required: false default: null ref: 'aircraft.checklists' timestamp: type: Date required: false default: new Date() AircraftProductAuthorizationAttemptSchema = new Schema(new AircraftProductAuthorizationAttemptSchemaInternal()) AircraftProductAuthorizationAttemptSchema.index({ user: 1, product: 1 }) module.exports = AircraftProductAuthorizationAttemptSchema
[ { "context": "#\n# Configuration:\n# HUBOT_TEAMCITY_USERNAME = <user name>\n# HUBOT_TEAMCITY_PASSWORD = <password>\n# HUB", "end": 152, "score": 0.9595211744308472, "start": 143, "tag": "USERNAME", "value": "user name" }, { "context": "NAME = <user name>\n# HUBOT_TEAMCITY_PAS...
src/scripts/teamcity.coffee
TaxiOS/hubot-scripts
1
# Description: # wrapper for TeamCity REST API # # Dependencies: # "underscore": "1.3.3" # # Configuration: # HUBOT_TEAMCITY_USERNAME = <user name> # HUBOT_TEAMCITY_PASSWORD = <password> # HUBOT_TEAMCITY_HOSTNAME = <host : port> # HUBOT_TEAMCITY_SCHEME = <http || https> defaults to http if not set. # # Commands: # hubot show me builds - Show status of currently running builds # hubot tc list projects - Show all available projects # hubot tc list buildTypes - Show all available build types # hubot tc list buildTypes of <project> - Show all available build types for the specified project # hubot tc list builds <buildType> <number> - Show the status of the last <number> builds. Number defaults to five. # hubot tc list builds of <buildType> of <project> <number>- Show the status of the last <number> builds of the specified build type of the specified project. Number can only follow the last variable, so if project is not passed, number must follow buildType directly. <number> Defaults to 5 # hubot tc build start <buildType> - Adds a build to the queue for the specified build type # hubot tc build start <buildType> of <project> - Adds a build to the queue for the specified build type of the specified project # hubot tc build stop all <buildType> id <buildId> of <project> - Stops all currently running builds of a given buildType. Project parameter is optional. Please note that the special 'all' keyword will kill all currently running builds ignoring all further parameters. hubot tc build stop all all # # Author: # Micah Martin and Jens Jahnke #Contributor: # Abraham Polishchuk util = require 'util' _ = require 'underscore' module.exports = (robot) -> username = process.env.HUBOT_TEAMCITY_USERNAME password = process.env.HUBOT_TEAMCITY_PASSWORD hostname = process.env.HUBOT_TEAMCITY_HOSTNAME scheme = process.env.HUBOT_TEAMCITY_SCHEME || "http" base_url = "#{scheme}://#{hostname}" buildTypes = [] getAuthHeader = -> return Authorization: "Basic #{new Buffer("#{username}:#{password}").toString("base64")}", Accept: "application/json" getBuildType = (msg, type, callback) -> url = "#{base_url}/httpAuth/app/rest/buildTypes/#{type}" console.log "sending request to #{url}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getCurrentBuilds = (msg, type, callback) -> if (arguments.length == 2) if (Object.prototype.toString.call(type) == "[object Function]") callback = type url = "http://#{hostname}/httpAuth/app/rest/builds/?locator=running:true" else url = "http://#{hostname}/httpAuth/app/rest/builds/?locator=buildType:#{type},running:true" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getProjects = (msg, callback) -> url = "#{base_url}/httpAuth/app/rest/projects" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 projects = JSON.parse(body).project unless err callback err, msg, projects getBuildTypes = (msg, project, callback) -> projectSegment = '' if project? projectSegment = '/projects/name:' + encodeURIComponent project url = "#{base_url}/httpAuth/app/rest#{projectSegment}/buildTypes" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 buildTypes = JSON.parse(body).buildType unless err callback err, msg, buildTypes getBuilds = (msg, project, configuration, amount, callback) -> projectSegment = '' if project? projectSegment = "/projects/name:#{encodeURIComponent(project)}" url = "#{base_url}/httpAuth/app/rest#{projectSegment}/buildTypes/name:#{encodeURIComponent(configuration)}/builds" msg.http(url) .headers(getAuthHeader()) .query(locator: ["count:#{amount}","running:any"].join(",")) .get() (err, res, body) -> err = body unless res.statusCode == 200 builds = JSON.parse(body).build.splice(amount) unless err callback err, msg, builds mapNameToIdForBuildType = (msg, project, name, callback) -> execute = (buildTypes) -> buildType = _.find buildTypes, (bt) -> return bt.name == name and (not project? or bt.projectName == project) if buildType return buildType.id result = execute(buildTypes) if result callback(msg, result) return getBuildTypes msg, project, (err, msg, buildTypes) -> callback msg, execute(buildTypes) mapBuildToNameList = (build) -> id = build['buildTypeId'] msg = build['messengerBot'] url = "http://#{hostname}/httpAuth/app/rest/buildTypes/id:#{id}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode = 200 unless err buildName = JSON.parse(body).name baseMessage = "##{build.number} of #{buildName} #{build.webUrl}" if build.running status = if build.status == "SUCCESS" then "**Winning**" else "__FAILING__" message = "#{status} #{build.percentageComplete}% Complete :: #{baseMessage}" else status = if build.status == "SUCCESS" then "OK!" else "__FAILED__" message = "#{status} :: #{baseMessage}" msg.send message createAndPublishBuildMap = (builds, msg) -> for build in builds build['messengerBot'] = msg mapBuildToNameList(build) mapAndKillBuilds = (msg, name, id, project) -> comment = "killed by hubot" getCurrentBuilds msg, (err, builds, msg) -> if typeof(builds)=='string' builds=JSON.parse(builds) if builds['count']==0 msg.send "No builds are currently running" return mapNameToIdForBuildType msg, project, name, (msg, buildType) -> buildName = buildType for build in builds['build'] if name == 'all' or (build['id'] == parseInt(id) and id?) or (build['buildTypeId'] == buildName and buildName? and !id?) url = "#{base_url}/ajax.html?comment=#{comment}&submit=Stop&buildId=#{build['id']}&kill" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 if err msg.send "Fail! Something went wrong. Couldn't stop the build for some reason" else msg.send "The requested builds have been killed" robot.respond /show me builds/i, (msg) -> getCurrentBuilds msg, (err, builds, msg) -> if typeof(builds)=='string' builds=JSON.parse(builds) if builds['count']==0 msg.send "No builds are currently running" return createAndPublishBuildMap(builds['build'], msg) robot.respond /tc build start (.*)/i, (msg) -> configuration = buildName = msg.match[1] project = null buildTypeRE = /(.*?) of (.*)/i buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] mapNameToIdForBuildType msg, project, configuration, (msg, buildType) -> if not buildType msg.send "Build type #{buildName} was not found" return url = "#{base_url}/httpAuth/action.html?add2Queue=#{buildType}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 if err msg.send "Fail! Something went wrong. Couldn't start the build for some reason" else msg.send "Dropped a build in the queue for #{buildName}. Run `tc list builds of #{buildName}` to check the status" robot.respond /tc list (projects|buildTypes|builds) ?(.*)?/i, (msg) -> type = msg.match[1] option = msg.match[2] switch type when "projects" getProjects msg, (err, msg, projects) -> message = "" for project in projects message += project.name + "\n" msg.send message when "buildTypes" project = null if option? projectRE = /^\s*of (.*)/i matches = option.match(projectRE) if matches? and matches.length > 1 project = matches[1] getBuildTypes msg, project, (err, msg, buildTypes) -> message = "" for buildType in buildTypes message += "#{buildType.name} of #{buildType.projectName}\n" msg.send message when "builds" configuration = option project = null buildTypeRE = /^\s*of (.*?) of (.+) (\d+)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] amount = parseInt(buildTypeMatches[3]) else buildTypeRE = /^\s*of (.+) (\d+)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] amount = parseInt(buildTypeMatches[2]) project = null else amount = 5 buildTypeRE = /^\s*of (.*?) of (.*)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] else buildTypeRE = /^\s*of (.*)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = null getBuilds msg, project, configuration, amount, (err, msg, builds) -> if not builds msg.send "Could not find builds for #{option}" return createAndPublishBuildMap(builds, msg) robot.respond /tc build stop all (.*)/i, (msg) -> getCurrentBuilds msg, (err, builds, msg) -> if typeof(builds)=='string' builds=JSON.parse(builds) if builds['count']==0 msg.send "No builds are currently running" return configuration = buildName = msg.match[1] project = null id = null buildTypeRE = /(.*) if (.*) of (.*)/i buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] id = buildTypeMatches[2] project = buildTypeMatches[3] else buildTypeRE = /(.*) of (.*)/i buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] else buildTypeRE = /(.*) id (.*)/ buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] id = buildTypeMatches[2] else buildTypeRE= /(.*)/ buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] mapAndKillBuilds(msg, configuration, id, project)
49652
# Description: # wrapper for TeamCity REST API # # Dependencies: # "underscore": "1.3.3" # # Configuration: # HUBOT_TEAMCITY_USERNAME = <user name> # HUBOT_TEAMCITY_PASSWORD = <<PASSWORD>> # HUBOT_TEAMCITY_HOSTNAME = <host : port> # HUBOT_TEAMCITY_SCHEME = <http || https> defaults to http if not set. # # Commands: # hubot show me builds - Show status of currently running builds # hubot tc list projects - Show all available projects # hubot tc list buildTypes - Show all available build types # hubot tc list buildTypes of <project> - Show all available build types for the specified project # hubot tc list builds <buildType> <number> - Show the status of the last <number> builds. Number defaults to five. # hubot tc list builds of <buildType> of <project> <number>- Show the status of the last <number> builds of the specified build type of the specified project. Number can only follow the last variable, so if project is not passed, number must follow buildType directly. <number> Defaults to 5 # hubot tc build start <buildType> - Adds a build to the queue for the specified build type # hubot tc build start <buildType> of <project> - Adds a build to the queue for the specified build type of the specified project # hubot tc build stop all <buildType> id <buildId> of <project> - Stops all currently running builds of a given buildType. Project parameter is optional. Please note that the special 'all' keyword will kill all currently running builds ignoring all further parameters. hubot tc build stop all all # # Author: # <NAME> and <NAME> #Contributor: # <NAME> util = require 'util' _ = require 'underscore' module.exports = (robot) -> username = process.env.HUBOT_TEAMCITY_USERNAME password = process.env.HUBOT_TEAMCITY_PASSWORD hostname = process.env.HUBOT_TEAMCITY_HOSTNAME scheme = process.env.HUBOT_TEAMCITY_SCHEME || "http" base_url = "#{scheme}://#{hostname}" buildTypes = [] getAuthHeader = -> return Authorization: "Basic #{new Buffer("#{username}:#{password}").toString("base64")}", Accept: "application/json" getBuildType = (msg, type, callback) -> url = "#{base_url}/httpAuth/app/rest/buildTypes/#{type}" console.log "sending request to #{url}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getCurrentBuilds = (msg, type, callback) -> if (arguments.length == 2) if (Object.prototype.toString.call(type) == "[object Function]") callback = type url = "http://#{hostname}/httpAuth/app/rest/builds/?locator=running:true" else url = "http://#{hostname}/httpAuth/app/rest/builds/?locator=buildType:#{type},running:true" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getProjects = (msg, callback) -> url = "#{base_url}/httpAuth/app/rest/projects" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 projects = JSON.parse(body).project unless err callback err, msg, projects getBuildTypes = (msg, project, callback) -> projectSegment = '' if project? projectSegment = '/projects/name:' + encodeURIComponent project url = "#{base_url}/httpAuth/app/rest#{projectSegment}/buildTypes" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 buildTypes = JSON.parse(body).buildType unless err callback err, msg, buildTypes getBuilds = (msg, project, configuration, amount, callback) -> projectSegment = '' if project? projectSegment = "/projects/name:#{encodeURIComponent(project)}" url = "#{base_url}/httpAuth/app/rest#{projectSegment}/buildTypes/name:#{encodeURIComponent(configuration)}/builds" msg.http(url) .headers(getAuthHeader()) .query(locator: ["count:#{amount}","running:any"].join(",")) .get() (err, res, body) -> err = body unless res.statusCode == 200 builds = JSON.parse(body).build.splice(amount) unless err callback err, msg, builds mapNameToIdForBuildType = (msg, project, name, callback) -> execute = (buildTypes) -> buildType = _.find buildTypes, (bt) -> return bt.name == name and (not project? or bt.projectName == project) if buildType return buildType.id result = execute(buildTypes) if result callback(msg, result) return getBuildTypes msg, project, (err, msg, buildTypes) -> callback msg, execute(buildTypes) mapBuildToNameList = (build) -> id = build['buildTypeId'] msg = build['messengerBot'] url = "http://#{hostname}/httpAuth/app/rest/buildTypes/id:#{id}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode = 200 unless err buildName = JSON.parse(body).name baseMessage = "##{build.number} of #{buildName} #{build.webUrl}" if build.running status = if build.status == "SUCCESS" then "**Winning**" else "__FAILING__" message = "#{status} #{build.percentageComplete}% Complete :: #{baseMessage}" else status = if build.status == "SUCCESS" then "OK!" else "__FAILED__" message = "#{status} :: #{baseMessage}" msg.send message createAndPublishBuildMap = (builds, msg) -> for build in builds build['messengerBot'] = msg mapBuildToNameList(build) mapAndKillBuilds = (msg, name, id, project) -> comment = "killed by hubot" getCurrentBuilds msg, (err, builds, msg) -> if typeof(builds)=='string' builds=JSON.parse(builds) if builds['count']==0 msg.send "No builds are currently running" return mapNameToIdForBuildType msg, project, name, (msg, buildType) -> buildName = buildType for build in builds['build'] if name == 'all' or (build['id'] == parseInt(id) and id?) or (build['buildTypeId'] == buildName and buildName? and !id?) url = "#{base_url}/ajax.html?comment=#{comment}&submit=Stop&buildId=#{build['id']}&kill" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 if err msg.send "Fail! Something went wrong. Couldn't stop the build for some reason" else msg.send "The requested builds have been killed" robot.respond /show me builds/i, (msg) -> getCurrentBuilds msg, (err, builds, msg) -> if typeof(builds)=='string' builds=JSON.parse(builds) if builds['count']==0 msg.send "No builds are currently running" return createAndPublishBuildMap(builds['build'], msg) robot.respond /tc build start (.*)/i, (msg) -> configuration = buildName = msg.match[1] project = null buildTypeRE = /(.*?) of (.*)/i buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] mapNameToIdForBuildType msg, project, configuration, (msg, buildType) -> if not buildType msg.send "Build type #{buildName} was not found" return url = "#{base_url}/httpAuth/action.html?add2Queue=#{buildType}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 if err msg.send "Fail! Something went wrong. Couldn't start the build for some reason" else msg.send "Dropped a build in the queue for #{buildName}. Run `tc list builds of #{buildName}` to check the status" robot.respond /tc list (projects|buildTypes|builds) ?(.*)?/i, (msg) -> type = msg.match[1] option = msg.match[2] switch type when "projects" getProjects msg, (err, msg, projects) -> message = "" for project in projects message += project.name + "\n" msg.send message when "buildTypes" project = null if option? projectRE = /^\s*of (.*)/i matches = option.match(projectRE) if matches? and matches.length > 1 project = matches[1] getBuildTypes msg, project, (err, msg, buildTypes) -> message = "" for buildType in buildTypes message += "#{buildType.name} of #{buildType.projectName}\n" msg.send message when "builds" configuration = option project = null buildTypeRE = /^\s*of (.*?) of (.+) (\d+)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] amount = parseInt(buildTypeMatches[3]) else buildTypeRE = /^\s*of (.+) (\d+)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] amount = parseInt(buildTypeMatches[2]) project = null else amount = 5 buildTypeRE = /^\s*of (.*?) of (.*)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] else buildTypeRE = /^\s*of (.*)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = null getBuilds msg, project, configuration, amount, (err, msg, builds) -> if not builds msg.send "Could not find builds for #{option}" return createAndPublishBuildMap(builds, msg) robot.respond /tc build stop all (.*)/i, (msg) -> getCurrentBuilds msg, (err, builds, msg) -> if typeof(builds)=='string' builds=JSON.parse(builds) if builds['count']==0 msg.send "No builds are currently running" return configuration = buildName = msg.match[1] project = null id = null buildTypeRE = /(.*) if (.*) of (.*)/i buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] id = buildTypeMatches[2] project = buildTypeMatches[3] else buildTypeRE = /(.*) of (.*)/i buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] else buildTypeRE = /(.*) id (.*)/ buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] id = buildTypeMatches[2] else buildTypeRE= /(.*)/ buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] mapAndKillBuilds(msg, configuration, id, project)
true
# Description: # wrapper for TeamCity REST API # # Dependencies: # "underscore": "1.3.3" # # Configuration: # HUBOT_TEAMCITY_USERNAME = <user name> # HUBOT_TEAMCITY_PASSWORD = <PI:PASSWORD:<PASSWORD>END_PI> # HUBOT_TEAMCITY_HOSTNAME = <host : port> # HUBOT_TEAMCITY_SCHEME = <http || https> defaults to http if not set. # # Commands: # hubot show me builds - Show status of currently running builds # hubot tc list projects - Show all available projects # hubot tc list buildTypes - Show all available build types # hubot tc list buildTypes of <project> - Show all available build types for the specified project # hubot tc list builds <buildType> <number> - Show the status of the last <number> builds. Number defaults to five. # hubot tc list builds of <buildType> of <project> <number>- Show the status of the last <number> builds of the specified build type of the specified project. Number can only follow the last variable, so if project is not passed, number must follow buildType directly. <number> Defaults to 5 # hubot tc build start <buildType> - Adds a build to the queue for the specified build type # hubot tc build start <buildType> of <project> - Adds a build to the queue for the specified build type of the specified project # hubot tc build stop all <buildType> id <buildId> of <project> - Stops all currently running builds of a given buildType. Project parameter is optional. Please note that the special 'all' keyword will kill all currently running builds ignoring all further parameters. hubot tc build stop all all # # Author: # PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI #Contributor: # PI:NAME:<NAME>END_PI util = require 'util' _ = require 'underscore' module.exports = (robot) -> username = process.env.HUBOT_TEAMCITY_USERNAME password = process.env.HUBOT_TEAMCITY_PASSWORD hostname = process.env.HUBOT_TEAMCITY_HOSTNAME scheme = process.env.HUBOT_TEAMCITY_SCHEME || "http" base_url = "#{scheme}://#{hostname}" buildTypes = [] getAuthHeader = -> return Authorization: "Basic #{new Buffer("#{username}:#{password}").toString("base64")}", Accept: "application/json" getBuildType = (msg, type, callback) -> url = "#{base_url}/httpAuth/app/rest/buildTypes/#{type}" console.log "sending request to #{url}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getCurrentBuilds = (msg, type, callback) -> if (arguments.length == 2) if (Object.prototype.toString.call(type) == "[object Function]") callback = type url = "http://#{hostname}/httpAuth/app/rest/builds/?locator=running:true" else url = "http://#{hostname}/httpAuth/app/rest/builds/?locator=buildType:#{type},running:true" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getProjects = (msg, callback) -> url = "#{base_url}/httpAuth/app/rest/projects" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 projects = JSON.parse(body).project unless err callback err, msg, projects getBuildTypes = (msg, project, callback) -> projectSegment = '' if project? projectSegment = '/projects/name:' + encodeURIComponent project url = "#{base_url}/httpAuth/app/rest#{projectSegment}/buildTypes" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 buildTypes = JSON.parse(body).buildType unless err callback err, msg, buildTypes getBuilds = (msg, project, configuration, amount, callback) -> projectSegment = '' if project? projectSegment = "/projects/name:#{encodeURIComponent(project)}" url = "#{base_url}/httpAuth/app/rest#{projectSegment}/buildTypes/name:#{encodeURIComponent(configuration)}/builds" msg.http(url) .headers(getAuthHeader()) .query(locator: ["count:#{amount}","running:any"].join(",")) .get() (err, res, body) -> err = body unless res.statusCode == 200 builds = JSON.parse(body).build.splice(amount) unless err callback err, msg, builds mapNameToIdForBuildType = (msg, project, name, callback) -> execute = (buildTypes) -> buildType = _.find buildTypes, (bt) -> return bt.name == name and (not project? or bt.projectName == project) if buildType return buildType.id result = execute(buildTypes) if result callback(msg, result) return getBuildTypes msg, project, (err, msg, buildTypes) -> callback msg, execute(buildTypes) mapBuildToNameList = (build) -> id = build['buildTypeId'] msg = build['messengerBot'] url = "http://#{hostname}/httpAuth/app/rest/buildTypes/id:#{id}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode = 200 unless err buildName = JSON.parse(body).name baseMessage = "##{build.number} of #{buildName} #{build.webUrl}" if build.running status = if build.status == "SUCCESS" then "**Winning**" else "__FAILING__" message = "#{status} #{build.percentageComplete}% Complete :: #{baseMessage}" else status = if build.status == "SUCCESS" then "OK!" else "__FAILED__" message = "#{status} :: #{baseMessage}" msg.send message createAndPublishBuildMap = (builds, msg) -> for build in builds build['messengerBot'] = msg mapBuildToNameList(build) mapAndKillBuilds = (msg, name, id, project) -> comment = "killed by hubot" getCurrentBuilds msg, (err, builds, msg) -> if typeof(builds)=='string' builds=JSON.parse(builds) if builds['count']==0 msg.send "No builds are currently running" return mapNameToIdForBuildType msg, project, name, (msg, buildType) -> buildName = buildType for build in builds['build'] if name == 'all' or (build['id'] == parseInt(id) and id?) or (build['buildTypeId'] == buildName and buildName? and !id?) url = "#{base_url}/ajax.html?comment=#{comment}&submit=Stop&buildId=#{build['id']}&kill" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 if err msg.send "Fail! Something went wrong. Couldn't stop the build for some reason" else msg.send "The requested builds have been killed" robot.respond /show me builds/i, (msg) -> getCurrentBuilds msg, (err, builds, msg) -> if typeof(builds)=='string' builds=JSON.parse(builds) if builds['count']==0 msg.send "No builds are currently running" return createAndPublishBuildMap(builds['build'], msg) robot.respond /tc build start (.*)/i, (msg) -> configuration = buildName = msg.match[1] project = null buildTypeRE = /(.*?) of (.*)/i buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] mapNameToIdForBuildType msg, project, configuration, (msg, buildType) -> if not buildType msg.send "Build type #{buildName} was not found" return url = "#{base_url}/httpAuth/action.html?add2Queue=#{buildType}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 if err msg.send "Fail! Something went wrong. Couldn't start the build for some reason" else msg.send "Dropped a build in the queue for #{buildName}. Run `tc list builds of #{buildName}` to check the status" robot.respond /tc list (projects|buildTypes|builds) ?(.*)?/i, (msg) -> type = msg.match[1] option = msg.match[2] switch type when "projects" getProjects msg, (err, msg, projects) -> message = "" for project in projects message += project.name + "\n" msg.send message when "buildTypes" project = null if option? projectRE = /^\s*of (.*)/i matches = option.match(projectRE) if matches? and matches.length > 1 project = matches[1] getBuildTypes msg, project, (err, msg, buildTypes) -> message = "" for buildType in buildTypes message += "#{buildType.name} of #{buildType.projectName}\n" msg.send message when "builds" configuration = option project = null buildTypeRE = /^\s*of (.*?) of (.+) (\d+)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] amount = parseInt(buildTypeMatches[3]) else buildTypeRE = /^\s*of (.+) (\d+)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] amount = parseInt(buildTypeMatches[2]) project = null else amount = 5 buildTypeRE = /^\s*of (.*?) of (.*)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] else buildTypeRE = /^\s*of (.*)/i buildTypeMatches = option.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = null getBuilds msg, project, configuration, amount, (err, msg, builds) -> if not builds msg.send "Could not find builds for #{option}" return createAndPublishBuildMap(builds, msg) robot.respond /tc build stop all (.*)/i, (msg) -> getCurrentBuilds msg, (err, builds, msg) -> if typeof(builds)=='string' builds=JSON.parse(builds) if builds['count']==0 msg.send "No builds are currently running" return configuration = buildName = msg.match[1] project = null id = null buildTypeRE = /(.*) if (.*) of (.*)/i buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] id = buildTypeMatches[2] project = buildTypeMatches[3] else buildTypeRE = /(.*) of (.*)/i buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] project = buildTypeMatches[2] else buildTypeRE = /(.*) id (.*)/ buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] id = buildTypeMatches[2] else buildTypeRE= /(.*)/ buildTypeMatches = buildName.match buildTypeRE if buildTypeMatches? configuration = buildTypeMatches[1] mapAndKillBuilds(msg, configuration, id, project)
[ { "context": "_NAME = 'autocomplete-robot-framework'\nCFG_KEY = 'autocomplete-robot-framework'\n\nTIMEOUT=5000 #ms\nSEP = pathUtils.sep\n\n# Credits", "end": 384, "score": 0.9983376264572144, "start": 356, "tag": "KEY", "value": "autocomplete-robot-framework" } ]
spec/robot-framework-keywords-autocomplete-spec.coffee
gliviu/autocomplete-robot-framework
7
robotParser = require('../lib/parse-robot') libdocParser = require('../lib/parse-libdoc') libRepo = require('../lib/library-repo') libManager = require('../lib/library-manager') keywordsRepo = require('../lib/keywords') common = require('../lib/common') fs = require 'fs' pathUtils = require 'path' PACKAGE_NAME = 'autocomplete-robot-framework' CFG_KEY = 'autocomplete-robot-framework' TIMEOUT=5000 #ms SEP = pathUtils.sep # Credits - https://raw.githubusercontent.com/atom/autocomplete-atom-api/master/spec/provider-spec.coffee getCompletions = (editor, provider)-> cursor = editor.getLastCursor() start = cursor.getBeginningOfCurrentWordBufferPosition() end = cursor.getBufferPosition() prefix = editor.getTextInRange([start, end]) request = editor: editor bufferPosition: end scopeDescriptor: cursor.getScopeDescriptor() prefix: prefix provider.getSuggestions(request) describe 'Robot Framework keywords autocompletions', -> [editor, provider] = [] beforeEach -> waitsFor -> return !libManager.loading() , 'Provider should finish loading', TIMEOUT runs -> process.env.PYTHONPATH=pathUtils.join(__dirname, '../fixtures/libraries') libRepo.reset() libManager.reset() keywordsRepo.reset() waitsForPromise -> atom.packages.activatePackage(PACKAGE_NAME) runs -> provider = atom.packages.getActivePackage(PACKAGE_NAME).mainModule.getAutocompletePlusProvider() waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_keywords.rOBOt') waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor = atom.workspace.getActiveTextEditor() describe 'Keywords autocomplete', -> it 'suggests standard keywords', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' callm') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Call Method') it 'suggests keywords in current editor', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program') it 'shows documentation in suggestions', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(3) expect(suggestions[0]?.displayText).toEqual('With documentation') expect(suggestions[0]?.description).toEqual('documentation. Arguments: arg1, arg2, arg3') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withdoc2') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('With documentation 2') expect(suggestions[0]?.description).toEqual('documentation. Arguments: arg1, arg2, arg3') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withoutdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('Without documentation') expect(suggestions[0]?.description).toEqual(' Arguments: arg1, arg2, arg3') it 'shows arguments in suggestions', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' witharg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('With arguments') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withoutarg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('Without arguments') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withdefarg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].displayText).toEqual('With default value arguments') expect(suggestions[0].description).toEqual(' Arguments: arg1=default value ${VARIABLE1}, arg2, arg3, arg4, arg5=default value, arg6=${VARIABLE1} and ${VARIABLE2}') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withemb') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('With embedded ${arg1} arguments ${arg2}') it 'shows suggestions from current editor first', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' run') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0]?.displayText).toEqual('Run Program') it 'does not show keywords private to other files', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' privatek') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'shows keywords visible only inside current file', -> waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' privatek') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Private keyword') it 'matches beginning of word', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' dp') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0]?.displayText).toEqual('Dot.punctuation keyword') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' dot') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0]?.displayText).toEqual('Dot.punctuation keyword') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' punct') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Dot.punctuation keyword') it 'supports mixed case', -> waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' CALLME') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') it 'suggests nothing for empty prefix', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' ') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'supports multi-word suggestions', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' with def val arg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' with args with def val arg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' withdef valarg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' w d v a') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' there should be no keyword') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'is able to disable arguments suggestions', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log ${1:message}') runs -> atom.config.set("#{CFG_KEY}.suggestArguments", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log') it 'is able to hide optional arguments', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log ${1:message}') runs -> atom.config.set("#{CFG_KEY}.includeDefaultArguments", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log ${1:message} ${2:level=INFO} ${3:html=False} ${4:console=False} ${5:repr=False}') it 'supports changing argument separator', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' runkeyword') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Run Keyword ${1:name} ${2:*args}') runs -> atom.config.set("#{CFG_KEY}.argumentSeparator", ' | ') waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runkeyword') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Run Keyword | ${1:name} | ${2:*args}') it 'supports unicode characters in keyword names and arguments', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' thé') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('The é char is here') expect(suggestions[0].description).toEqual(' Arguments: é1=é1 val, é2=${é3} val') describe 'Keywords autocomplete in *Settings* section', -> beforeEach -> console.log (editor.getText()) console.log (editor.getPath()) waitsForPromise -> atom.workspace.open('autocomplete/settings.robot') runs -> editor = atom.workspace.getActiveTextEditor() it 'autocompletes keywords in test/suite setup', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText('\nTest Setup runkeys') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('Run Keywords') it 'suggests library names', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText('\nLibrary built') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('BuiltIn') it 'suggests resource names', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText('\nResource filepref') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('FilePrefix') describe 'BDD autocomplete', -> beforeEach -> waitsForPromise -> atom.workspace.open('autocomplete/bdd.robot') runs -> editor = atom.workspace.getActiveTextEditor() it 'suggests keywords using BDD notation', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' given welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' when welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' then welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' and welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' but welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') describe 'Library management', -> beforeEach -> waitsForPromise -> atom.workspace.open('autocomplete/Test_Libraries.robot') runs -> editor = atom.workspace.getActiveTextEditor() it 'should import modules', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' testmod') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].displayText).toEqual('TestModule') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].displayText).toEqual('Test Module Keyword') expect(suggestions[1].description).toEqual('Test module documentation. Arguments: param1, param2') it 'should import classes', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' testclas1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Test Class Keyword 1') expect(suggestions[0].description).toEqual('Test class documentation. Arguments: param1') it 'should handle classes with import parameters', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' testclparam') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Test Class Keyword Params') it 'should import Robot Framework builtin libraries', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' appefi') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Append To File') it 'should import Robot Framework builtin libraries when python environment is not available', -> runs -> atom.config.set("#{CFG_KEY}.pythonExecutable", 'invalid_python_executable') waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' appefi') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Append To File') expect(pathUtils.normalize(suggestions[0].keyword.resource.path)).toContain(pathUtils.normalize('fallback-libraries/OperatingSystem.xml')) it 'should not suggest private keywords', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' package.modules.TestModule.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) it 'should import libraries that are not in pythonpath and reside along with robot files', -> waitsForPromise -> atom.workspace.open('autocomplete/a/utils.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' interk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Internal Python Kw') describe 'Scope modifiers', -> describe 'Default scope modifiers', -> it 'limits suggestions to current imports', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' k') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestedUnits = new Set() for suggestion in suggestions when suggestion.type is 'keyword' suggestedUnits.add(suggestion.rightLabel) expect(['Test_Autocomplete_Libdoc', 'FileSizeLimit.robot', 'BuiltIn', 'Test_Autocomplete_Keywords.rOBOt', 'TestModule'].sort()).toEqual(Array.from(suggestedUnits).sort()) it 'suggests all keywords from resources having the same name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utility') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].snippet).toEqual('utility 2') waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utility') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1 text') describe 'File scope modifiers', -> it 'supports file scope modifier with libraries containing dot in their name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' HttpLibrary.HTTP.d') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('DELETE') it 'supports file scope modifier with resources', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' fileprefix.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('File keyword 1') expect(suggestions[1]?.displayText).toEqual('File keyword 2') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0]?.displayText).not.toEqual('BuiltIn') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('BuiltIn') it 'suggests all keywords from resources having the same name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utils.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(3) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].snippet).toEqual('utility 1 text') expect(suggestions[2].type).toEqual('keyword') expect(suggestions[2].snippet).toEqual('utility 2') it 'does not suggests keywords if resource/library name is incomplete', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' FilePrefi.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' FilePrefix2.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' package.modules.TestModul.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' package.modules.TestModule2.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) it 'suggests library names that are imported in other robot files', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' operatings') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('OperatingSystem') it 'does not not suggest library names that are not imported in any robot file', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' screensho') # Builtin screenshot library waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'suggests BuiltIn library even if it is not imported in any robot file', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin') # Builtin screenshot library waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') it 'supports mixed case for library name suggestions', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' BUILT') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' bUilTi') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') it 'suggests libraries by their short name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' TestModule') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('package.modules.TestModule') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' TestClass') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('package.classes.TestClass') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' RobotFile') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('namespace.separated.RobotFile') it 'suggests libraries by their full name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' package') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(3) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('package.classes.TestClass') expect(suggestions[1].type).toEqual('import') expect(suggestions[1].text).toEqual('package.classes.TestClassParams') expect(suggestions[2].type).toEqual('import') expect(suggestions[2].text).toEqual('package.modules.TestModule') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' namespace') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('namespace.separated.RobotFile') it 'supports file scope modifier with mixed case', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' BUILTIN.CALLME') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') it 'reacts on removeDotNotation configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('builtin.callme') runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('callme') describe 'Global scope modifiers', -> it 'supports global scope modifier', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .appendfil') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Append To File') it 'suggests all keywords from resources having the same name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .utility') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].snippet).toEqual('utility 2') describe 'Internal scope modifiers', -> it 'supports internal scope modifier', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' this.k') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(5) expect(suggestions[0]?.displayText).toEqual('Test keyword') expect(suggestions[1]?.displayText).toEqual('priv.keyword') expect(suggestions[2]?.displayText).toEqual('Priv test keyword') expect(suggestions[3]?.displayText).toEqual('Duplicated keyword') expect(suggestions[4]?.displayText).toEqual('Dot.punctuation keyword') describe 'Unknown scope modifiers', -> it 'has same suggestions as default scope modifier', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' UnkwnownLibrary.k') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestedUnits = new Set() for suggestion in suggestions when suggestion.type is 'keyword' suggestedUnits.add(suggestion.rightLabel) expect(['Test_Autocomplete_Libdoc', 'FileSizeLimit.robot', 'BuiltIn', 'Test_Autocomplete_Keywords.rOBOt', 'TestModule'].sort()).toEqual(Array.from(suggestedUnits).sort()) it 'is not affected by removeDotNotation configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' UnknownLibrary.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('callme') runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' UnknownLibrary.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('callme') describe 'Invalid scope modifiers', -> it 'suggests nothing', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' this is an invalid modifier.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) describe 'Autocomplete configuration', -> it 'react on showArguments configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.showArguments", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program - args') runs -> atom.config.set("#{CFG_KEY}.showArguments", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program') it 'react on excludeDirectories configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.excludeDirectories", []) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .utility1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('utility 1') expect(suggestions[1]?.displayText).toEqual('utility 1 text') runs -> atom.config.set("#{CFG_KEY}.excludeDirectories", ['auto*']) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) runs -> atom.config.set("#{CFG_KEY}.excludeDirectories", ['*.robot']) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .utility1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('utility 1 text') it 'react on processLibdocFiles configuration changes', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' autocompletelibdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Autocomplete libdoc test " \' < > &') runs -> atom.config.set("#{CFG_KEY}.processLibdocFiles", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' autocompletelibdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'react on maxFileSize configuration changes', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' limitfilesize') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Limit File Size Keyword') runs -> atom.config.set("#{CFG_KEY}.maxFileSize", 39) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' limitfilesize') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'react on showLibrarySuggestions configuration changes', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' built') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') runs -> atom.config.set("#{CFG_KEY}.showLibrarySuggestions", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' built') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) describe 'Ambiguous keywords', -> it 'resolves keyword found in diffrent resources using default scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' ak') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].snippet).toEqual('utils2.abk1') expect(suggestions[1].snippet).toEqual('utils3.abk1') it 'resolves keyword found in diffrent libraries using default scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' delete') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].snippet.startsWith('FtpLibrary.Delete')).toBeTruthy() expect(suggestions[1].snippet.startsWith('RequestsLibrary.Delete')).toBeTruthy() it 'resolves keyword found in diffrent resources using global scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .ak') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].snippet).toEqual('utils2.abk1') expect(suggestions[1].snippet).toEqual('utils3.abk1') it 'resolves keyword found in diffrent resources using file scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utils2.abk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('utils2.abk1') runs -> editor.insertText(' utils3.abk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('utils3.abk1') it 'resolves keyword found in diffrent resources using internal scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/a/utils2.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' this.abk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].snippet).toEqual('utils2.abk1') describe 'Imported resource path resolver', -> it 'resolves resource by resource name in the same directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr1k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr1.robot")).toBeTruthy() it 'resolves resource by resource name in different directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr6') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr6ka') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr6.robot")).toBeTruthy() it 'resolves resource by relative resource path in the same directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr2') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr2k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr2.robot")).toBeTruthy() it 'resolves resource by relative resource path in different directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr3') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr3ka') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr3.robot")).toBeTruthy() runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr4') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr4ka') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr4.robot")).toBeTruthy() it 'suggests keywords from all resources with same name when import path is computed', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr5') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('pr5k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr5.robot")).toBeTruthy() expect(suggestions[1]?.displayText).toEqual('pr5ka') expect(suggestions[1]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr5.robot")).toBeTruthy() it 'suggests keywords from all resources with same name when import path is wrong', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr7') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('pr7k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr7.robot")).toBeTruthy() expect(suggestions[1]?.displayText).toEqual('pr7ka') expect(suggestions[1]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr7.robot")).toBeTruthy() it 'resolves external resources', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' prex') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('prext') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}external-resource.robot")).toBeTruthy()
109611
robotParser = require('../lib/parse-robot') libdocParser = require('../lib/parse-libdoc') libRepo = require('../lib/library-repo') libManager = require('../lib/library-manager') keywordsRepo = require('../lib/keywords') common = require('../lib/common') fs = require 'fs' pathUtils = require 'path' PACKAGE_NAME = 'autocomplete-robot-framework' CFG_KEY = '<KEY>' TIMEOUT=5000 #ms SEP = pathUtils.sep # Credits - https://raw.githubusercontent.com/atom/autocomplete-atom-api/master/spec/provider-spec.coffee getCompletions = (editor, provider)-> cursor = editor.getLastCursor() start = cursor.getBeginningOfCurrentWordBufferPosition() end = cursor.getBufferPosition() prefix = editor.getTextInRange([start, end]) request = editor: editor bufferPosition: end scopeDescriptor: cursor.getScopeDescriptor() prefix: prefix provider.getSuggestions(request) describe 'Robot Framework keywords autocompletions', -> [editor, provider] = [] beforeEach -> waitsFor -> return !libManager.loading() , 'Provider should finish loading', TIMEOUT runs -> process.env.PYTHONPATH=pathUtils.join(__dirname, '../fixtures/libraries') libRepo.reset() libManager.reset() keywordsRepo.reset() waitsForPromise -> atom.packages.activatePackage(PACKAGE_NAME) runs -> provider = atom.packages.getActivePackage(PACKAGE_NAME).mainModule.getAutocompletePlusProvider() waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_keywords.rOBOt') waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor = atom.workspace.getActiveTextEditor() describe 'Keywords autocomplete', -> it 'suggests standard keywords', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' callm') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Call Method') it 'suggests keywords in current editor', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program') it 'shows documentation in suggestions', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(3) expect(suggestions[0]?.displayText).toEqual('With documentation') expect(suggestions[0]?.description).toEqual('documentation. Arguments: arg1, arg2, arg3') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withdoc2') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('With documentation 2') expect(suggestions[0]?.description).toEqual('documentation. Arguments: arg1, arg2, arg3') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withoutdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('Without documentation') expect(suggestions[0]?.description).toEqual(' Arguments: arg1, arg2, arg3') it 'shows arguments in suggestions', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' witharg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('With arguments') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withoutarg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('Without arguments') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withdefarg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].displayText).toEqual('With default value arguments') expect(suggestions[0].description).toEqual(' Arguments: arg1=default value ${VARIABLE1}, arg2, arg3, arg4, arg5=default value, arg6=${VARIABLE1} and ${VARIABLE2}') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withemb') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('With embedded ${arg1} arguments ${arg2}') it 'shows suggestions from current editor first', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' run') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0]?.displayText).toEqual('Run Program') it 'does not show keywords private to other files', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' privatek') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'shows keywords visible only inside current file', -> waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' privatek') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Private keyword') it 'matches beginning of word', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' dp') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0]?.displayText).toEqual('Dot.punctuation keyword') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' dot') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0]?.displayText).toEqual('Dot.punctuation keyword') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' punct') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Dot.punctuation keyword') it 'supports mixed case', -> waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' CALLME') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') it 'suggests nothing for empty prefix', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' ') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'supports multi-word suggestions', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' with def val arg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' with args with def val arg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' withdef valarg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' w d v a') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' there should be no keyword') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'is able to disable arguments suggestions', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log ${1:message}') runs -> atom.config.set("#{CFG_KEY}.suggestArguments", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log') it 'is able to hide optional arguments', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log ${1:message}') runs -> atom.config.set("#{CFG_KEY}.includeDefaultArguments", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log ${1:message} ${2:level=INFO} ${3:html=False} ${4:console=False} ${5:repr=False}') it 'supports changing argument separator', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' runkeyword') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Run Keyword ${1:name} ${2:*args}') runs -> atom.config.set("#{CFG_KEY}.argumentSeparator", ' | ') waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runkeyword') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Run Keyword | ${1:name} | ${2:*args}') it 'supports unicode characters in keyword names and arguments', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' thé') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('The é char is here') expect(suggestions[0].description).toEqual(' Arguments: é1=é1 val, é2=${é3} val') describe 'Keywords autocomplete in *Settings* section', -> beforeEach -> console.log (editor.getText()) console.log (editor.getPath()) waitsForPromise -> atom.workspace.open('autocomplete/settings.robot') runs -> editor = atom.workspace.getActiveTextEditor() it 'autocompletes keywords in test/suite setup', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText('\nTest Setup runkeys') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('Run Keywords') it 'suggests library names', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText('\nLibrary built') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('BuiltIn') it 'suggests resource names', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText('\nResource filepref') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('FilePrefix') describe 'BDD autocomplete', -> beforeEach -> waitsForPromise -> atom.workspace.open('autocomplete/bdd.robot') runs -> editor = atom.workspace.getActiveTextEditor() it 'suggests keywords using BDD notation', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' given welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' when welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' then welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' and welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' but welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') describe 'Library management', -> beforeEach -> waitsForPromise -> atom.workspace.open('autocomplete/Test_Libraries.robot') runs -> editor = atom.workspace.getActiveTextEditor() it 'should import modules', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' testmod') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].displayText).toEqual('TestModule') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].displayText).toEqual('Test Module Keyword') expect(suggestions[1].description).toEqual('Test module documentation. Arguments: param1, param2') it 'should import classes', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' testclas1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Test Class Keyword 1') expect(suggestions[0].description).toEqual('Test class documentation. Arguments: param1') it 'should handle classes with import parameters', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' testclparam') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Test Class Keyword Params') it 'should import Robot Framework builtin libraries', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' appefi') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Append To File') it 'should import Robot Framework builtin libraries when python environment is not available', -> runs -> atom.config.set("#{CFG_KEY}.pythonExecutable", 'invalid_python_executable') waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' appefi') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Append To File') expect(pathUtils.normalize(suggestions[0].keyword.resource.path)).toContain(pathUtils.normalize('fallback-libraries/OperatingSystem.xml')) it 'should not suggest private keywords', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' package.modules.TestModule.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) it 'should import libraries that are not in pythonpath and reside along with robot files', -> waitsForPromise -> atom.workspace.open('autocomplete/a/utils.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' interk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Internal Python Kw') describe 'Scope modifiers', -> describe 'Default scope modifiers', -> it 'limits suggestions to current imports', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' k') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestedUnits = new Set() for suggestion in suggestions when suggestion.type is 'keyword' suggestedUnits.add(suggestion.rightLabel) expect(['Test_Autocomplete_Libdoc', 'FileSizeLimit.robot', 'BuiltIn', 'Test_Autocomplete_Keywords.rOBOt', 'TestModule'].sort()).toEqual(Array.from(suggestedUnits).sort()) it 'suggests all keywords from resources having the same name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utility') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].snippet).toEqual('utility 2') waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utility') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1 text') describe 'File scope modifiers', -> it 'supports file scope modifier with libraries containing dot in their name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' HttpLibrary.HTTP.d') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('DELETE') it 'supports file scope modifier with resources', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' fileprefix.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('File keyword 1') expect(suggestions[1]?.displayText).toEqual('File keyword 2') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0]?.displayText).not.toEqual('BuiltIn') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('BuiltIn') it 'suggests all keywords from resources having the same name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utils.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(3) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].snippet).toEqual('utility 1 text') expect(suggestions[2].type).toEqual('keyword') expect(suggestions[2].snippet).toEqual('utility 2') it 'does not suggests keywords if resource/library name is incomplete', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' FilePrefi.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' FilePrefix2.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' package.modules.TestModul.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' package.modules.TestModule2.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) it 'suggests library names that are imported in other robot files', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' operatings') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('OperatingSystem') it 'does not not suggest library names that are not imported in any robot file', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' screensho') # Builtin screenshot library waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'suggests BuiltIn library even if it is not imported in any robot file', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin') # Builtin screenshot library waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') it 'supports mixed case for library name suggestions', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' BUILT') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' bUilTi') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') it 'suggests libraries by their short name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' TestModule') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('package.modules.TestModule') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' TestClass') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('package.classes.TestClass') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' RobotFile') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('namespace.separated.RobotFile') it 'suggests libraries by their full name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' package') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(3) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('package.classes.TestClass') expect(suggestions[1].type).toEqual('import') expect(suggestions[1].text).toEqual('package.classes.TestClassParams') expect(suggestions[2].type).toEqual('import') expect(suggestions[2].text).toEqual('package.modules.TestModule') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' namespace') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('namespace.separated.RobotFile') it 'supports file scope modifier with mixed case', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' BUILTIN.CALLME') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') it 'reacts on removeDotNotation configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('builtin.callme') runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('callme') describe 'Global scope modifiers', -> it 'supports global scope modifier', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .appendfil') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Append To File') it 'suggests all keywords from resources having the same name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .utility') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].snippet).toEqual('utility 2') describe 'Internal scope modifiers', -> it 'supports internal scope modifier', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' this.k') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(5) expect(suggestions[0]?.displayText).toEqual('Test keyword') expect(suggestions[1]?.displayText).toEqual('priv.keyword') expect(suggestions[2]?.displayText).toEqual('Priv test keyword') expect(suggestions[3]?.displayText).toEqual('Duplicated keyword') expect(suggestions[4]?.displayText).toEqual('Dot.punctuation keyword') describe 'Unknown scope modifiers', -> it 'has same suggestions as default scope modifier', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' UnkwnownLibrary.k') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestedUnits = new Set() for suggestion in suggestions when suggestion.type is 'keyword' suggestedUnits.add(suggestion.rightLabel) expect(['Test_Autocomplete_Libdoc', 'FileSizeLimit.robot', 'BuiltIn', 'Test_Autocomplete_Keywords.rOBOt', 'TestModule'].sort()).toEqual(Array.from(suggestedUnits).sort()) it 'is not affected by removeDotNotation configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' UnknownLibrary.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('callme') runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' UnknownLibrary.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('callme') describe 'Invalid scope modifiers', -> it 'suggests nothing', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' this is an invalid modifier.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) describe 'Autocomplete configuration', -> it 'react on showArguments configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.showArguments", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program - args') runs -> atom.config.set("#{CFG_KEY}.showArguments", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program') it 'react on excludeDirectories configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.excludeDirectories", []) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .utility1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('utility 1') expect(suggestions[1]?.displayText).toEqual('utility 1 text') runs -> atom.config.set("#{CFG_KEY}.excludeDirectories", ['auto*']) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) runs -> atom.config.set("#{CFG_KEY}.excludeDirectories", ['*.robot']) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .utility1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('utility 1 text') it 'react on processLibdocFiles configuration changes', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' autocompletelibdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Autocomplete libdoc test " \' < > &') runs -> atom.config.set("#{CFG_KEY}.processLibdocFiles", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' autocompletelibdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'react on maxFileSize configuration changes', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' limitfilesize') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Limit File Size Keyword') runs -> atom.config.set("#{CFG_KEY}.maxFileSize", 39) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' limitfilesize') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'react on showLibrarySuggestions configuration changes', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' built') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') runs -> atom.config.set("#{CFG_KEY}.showLibrarySuggestions", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' built') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) describe 'Ambiguous keywords', -> it 'resolves keyword found in diffrent resources using default scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' ak') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].snippet).toEqual('utils2.abk1') expect(suggestions[1].snippet).toEqual('utils3.abk1') it 'resolves keyword found in diffrent libraries using default scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' delete') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].snippet.startsWith('FtpLibrary.Delete')).toBeTruthy() expect(suggestions[1].snippet.startsWith('RequestsLibrary.Delete')).toBeTruthy() it 'resolves keyword found in diffrent resources using global scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .ak') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].snippet).toEqual('utils2.abk1') expect(suggestions[1].snippet).toEqual('utils3.abk1') it 'resolves keyword found in diffrent resources using file scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utils2.abk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('utils2.abk1') runs -> editor.insertText(' utils3.abk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('utils3.abk1') it 'resolves keyword found in diffrent resources using internal scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/a/utils2.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' this.abk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].snippet).toEqual('utils2.abk1') describe 'Imported resource path resolver', -> it 'resolves resource by resource name in the same directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr1k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr1.robot")).toBeTruthy() it 'resolves resource by resource name in different directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr6') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr6ka') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr6.robot")).toBeTruthy() it 'resolves resource by relative resource path in the same directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr2') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr2k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr2.robot")).toBeTruthy() it 'resolves resource by relative resource path in different directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr3') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr3ka') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr3.robot")).toBeTruthy() runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr4') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr4ka') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr4.robot")).toBeTruthy() it 'suggests keywords from all resources with same name when import path is computed', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr5') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('pr5k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr5.robot")).toBeTruthy() expect(suggestions[1]?.displayText).toEqual('pr5ka') expect(suggestions[1]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr5.robot")).toBeTruthy() it 'suggests keywords from all resources with same name when import path is wrong', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr7') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('pr7k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr7.robot")).toBeTruthy() expect(suggestions[1]?.displayText).toEqual('pr7ka') expect(suggestions[1]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr7.robot")).toBeTruthy() it 'resolves external resources', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' prex') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('prext') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}external-resource.robot")).toBeTruthy()
true
robotParser = require('../lib/parse-robot') libdocParser = require('../lib/parse-libdoc') libRepo = require('../lib/library-repo') libManager = require('../lib/library-manager') keywordsRepo = require('../lib/keywords') common = require('../lib/common') fs = require 'fs' pathUtils = require 'path' PACKAGE_NAME = 'autocomplete-robot-framework' CFG_KEY = 'PI:KEY:<KEY>END_PI' TIMEOUT=5000 #ms SEP = pathUtils.sep # Credits - https://raw.githubusercontent.com/atom/autocomplete-atom-api/master/spec/provider-spec.coffee getCompletions = (editor, provider)-> cursor = editor.getLastCursor() start = cursor.getBeginningOfCurrentWordBufferPosition() end = cursor.getBufferPosition() prefix = editor.getTextInRange([start, end]) request = editor: editor bufferPosition: end scopeDescriptor: cursor.getScopeDescriptor() prefix: prefix provider.getSuggestions(request) describe 'Robot Framework keywords autocompletions', -> [editor, provider] = [] beforeEach -> waitsFor -> return !libManager.loading() , 'Provider should finish loading', TIMEOUT runs -> process.env.PYTHONPATH=pathUtils.join(__dirname, '../fixtures/libraries') libRepo.reset() libManager.reset() keywordsRepo.reset() waitsForPromise -> atom.packages.activatePackage(PACKAGE_NAME) runs -> provider = atom.packages.getActivePackage(PACKAGE_NAME).mainModule.getAutocompletePlusProvider() waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_keywords.rOBOt') waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor = atom.workspace.getActiveTextEditor() describe 'Keywords autocomplete', -> it 'suggests standard keywords', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' callm') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Call Method') it 'suggests keywords in current editor', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program') it 'shows documentation in suggestions', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(3) expect(suggestions[0]?.displayText).toEqual('With documentation') expect(suggestions[0]?.description).toEqual('documentation. Arguments: arg1, arg2, arg3') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withdoc2') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('With documentation 2') expect(suggestions[0]?.description).toEqual('documentation. Arguments: arg1, arg2, arg3') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withoutdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('Without documentation') expect(suggestions[0]?.description).toEqual(' Arguments: arg1, arg2, arg3') it 'shows arguments in suggestions', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' witharg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('With arguments') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withoutarg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('Without arguments') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withdefarg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].displayText).toEqual('With default value arguments') expect(suggestions[0].description).toEqual(' Arguments: arg1=default value ${VARIABLE1}, arg2, arg3, arg4, arg5=default value, arg6=${VARIABLE1} and ${VARIABLE2}') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' withemb') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('With embedded ${arg1} arguments ${arg2}') it 'shows suggestions from current editor first', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' run') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0]?.displayText).toEqual('Run Program') it 'does not show keywords private to other files', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' privatek') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'shows keywords visible only inside current file', -> waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' privatek') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Private keyword') it 'matches beginning of word', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' dp') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0]?.displayText).toEqual('Dot.punctuation keyword') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' dot') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0]?.displayText).toEqual('Dot.punctuation keyword') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' punct') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Dot.punctuation keyword') it 'supports mixed case', -> waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' CALLME') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') it 'suggests nothing for empty prefix', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' ') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'supports multi-word suggestions', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' with def val arg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' with args with def val arg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' withdef valarg') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' w d v a') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('With default value arguments') runs -> editor.insertText(' there should be no keyword') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'is able to disable arguments suggestions', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log ${1:message}') runs -> atom.config.set("#{CFG_KEY}.suggestArguments", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log') it 'is able to hide optional arguments', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log ${1:message}') runs -> atom.config.set("#{CFG_KEY}.includeDefaultArguments", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' log') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Log ${1:message} ${2:level=INFO} ${3:html=False} ${4:console=False} ${5:repr=False}') it 'supports changing argument separator', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' runkeyword') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Run Keyword ${1:name} ${2:*args}') runs -> atom.config.set("#{CFG_KEY}.argumentSeparator", ' | ') waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runkeyword') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('Run Keyword | ${1:name} | ${2:*args}') it 'supports unicode characters in keyword names and arguments', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' thé') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('The é char is here') expect(suggestions[0].description).toEqual(' Arguments: é1=é1 val, é2=${é3} val') describe 'Keywords autocomplete in *Settings* section', -> beforeEach -> console.log (editor.getText()) console.log (editor.getPath()) waitsForPromise -> atom.workspace.open('autocomplete/settings.robot') runs -> editor = atom.workspace.getActiveTextEditor() it 'autocompletes keywords in test/suite setup', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText('\nTest Setup runkeys') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('Run Keywords') it 'suggests library names', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText('\nLibrary built') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('BuiltIn') it 'suggests resource names', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText('\nResource filepref') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('FilePrefix') describe 'BDD autocomplete', -> beforeEach -> waitsForPromise -> atom.workspace.open('autocomplete/bdd.robot') runs -> editor = atom.workspace.getActiveTextEditor() it 'suggests keywords using BDD notation', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' given welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' when welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' then welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' and welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') runs -> editor.insertText(' but welc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('welcome page should be open') describe 'Library management', -> beforeEach -> waitsForPromise -> atom.workspace.open('autocomplete/Test_Libraries.robot') runs -> editor = atom.workspace.getActiveTextEditor() it 'should import modules', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' testmod') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].displayText).toEqual('TestModule') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].displayText).toEqual('Test Module Keyword') expect(suggestions[1].description).toEqual('Test module documentation. Arguments: param1, param2') it 'should import classes', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' testclas1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Test Class Keyword 1') expect(suggestions[0].description).toEqual('Test class documentation. Arguments: param1') it 'should handle classes with import parameters', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' testclparam') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Test Class Keyword Params') it 'should import Robot Framework builtin libraries', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' appefi') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Append To File') it 'should import Robot Framework builtin libraries when python environment is not available', -> runs -> atom.config.set("#{CFG_KEY}.pythonExecutable", 'invalid_python_executable') waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' appefi') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Append To File') expect(pathUtils.normalize(suggestions[0].keyword.resource.path)).toContain(pathUtils.normalize('fallback-libraries/OperatingSystem.xml')) it 'should not suggest private keywords', -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.setText(' package.modules.TestModule.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) it 'should import libraries that are not in pythonpath and reside along with robot files', -> waitsForPromise -> atom.workspace.open('autocomplete/a/utils.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' interk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Internal Python Kw') describe 'Scope modifiers', -> describe 'Default scope modifiers', -> it 'limits suggestions to current imports', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' k') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestedUnits = new Set() for suggestion in suggestions when suggestion.type is 'keyword' suggestedUnits.add(suggestion.rightLabel) expect(['Test_Autocomplete_Libdoc', 'FileSizeLimit.robot', 'BuiltIn', 'Test_Autocomplete_Keywords.rOBOt', 'TestModule'].sort()).toEqual(Array.from(suggestedUnits).sort()) it 'suggests all keywords from resources having the same name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utility') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].snippet).toEqual('utility 2') waitsForPromise -> atom.workspace.open('autocomplete/test_autocomplete_testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utility') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1 text') describe 'File scope modifiers', -> it 'supports file scope modifier with libraries containing dot in their name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' HttpLibrary.HTTP.d') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0]?.displayText).toEqual('DELETE') it 'supports file scope modifier with resources', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' fileprefix.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('File keyword 1') expect(suggestions[1]?.displayText).toEqual('File keyword 2') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0]?.displayText).not.toEqual('BuiltIn') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('BuiltIn') it 'suggests all keywords from resources having the same name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utils.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(3) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].snippet).toEqual('utility 1 text') expect(suggestions[2].type).toEqual('keyword') expect(suggestions[2].snippet).toEqual('utility 2') it 'does not suggests keywords if resource/library name is incomplete', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' FilePrefi.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' FilePrefix2.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' package.modules.TestModul.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' package.modules.TestModule2.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(10) it 'suggests library names that are imported in other robot files', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' operatings') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('OperatingSystem') it 'does not not suggest library names that are not imported in any robot file', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' screensho') # Builtin screenshot library waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'suggests BuiltIn library even if it is not imported in any robot file', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin') # Builtin screenshot library waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') it 'supports mixed case for library name suggestions', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' BUILT') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' bUilTi') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') it 'suggests libraries by their short name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' TestModule') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('package.modules.TestModule') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' TestClass') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('package.classes.TestClass') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' RobotFile') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('namespace.separated.RobotFile') it 'suggests libraries by their full name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' package') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(3) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('package.classes.TestClass') expect(suggestions[1].type).toEqual('import') expect(suggestions[1].text).toEqual('package.classes.TestClassParams') expect(suggestions[2].type).toEqual('import') expect(suggestions[2].text).toEqual('package.modules.TestModule') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' namespace') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].type).toEqual('import') expect(suggestions[0].text).toEqual('namespace.separated.RobotFile') it 'supports file scope modifier with mixed case', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' BUILTIN.CALLME') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') it 'reacts on removeDotNotation configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('builtin.callme') runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' builtin.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('callme') describe 'Global scope modifiers', -> it 'supports global scope modifier', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .appendfil') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Append To File') it 'suggests all keywords from resources having the same name', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .utility') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].type).toEqual('keyword') expect(suggestions[0].snippet).toEqual('utility 1') expect(suggestions[1].type).toEqual('keyword') expect(suggestions[1].snippet).toEqual('utility 2') describe 'Internal scope modifiers', -> it 'supports internal scope modifier', -> runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' this.k') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(5) expect(suggestions[0]?.displayText).toEqual('Test keyword') expect(suggestions[1]?.displayText).toEqual('priv.keyword') expect(suggestions[2]?.displayText).toEqual('Priv test keyword') expect(suggestions[3]?.displayText).toEqual('Duplicated keyword') expect(suggestions[4]?.displayText).toEqual('Dot.punctuation keyword') describe 'Unknown scope modifiers', -> it 'has same suggestions as default scope modifier', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' UnkwnownLibrary.k') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestedUnits = new Set() for suggestion in suggestions when suggestion.type is 'keyword' suggestedUnits.add(suggestion.rightLabel) expect(['Test_Autocomplete_Libdoc', 'FileSizeLimit.robot', 'BuiltIn', 'Test_Autocomplete_Keywords.rOBOt', 'TestModule'].sort()).toEqual(Array.from(suggestedUnits).sort()) it 'is not affected by removeDotNotation configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' UnknownLibrary.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('callme') runs -> atom.config.set("#{CFG_KEY}.removeDotNotation", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' UnknownLibrary.callme') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Call Method') expect(suggestions[0]?.replacementPrefix).toEqual('callme') describe 'Invalid scope modifiers', -> it 'suggests nothing', -> editor.setCursorBufferPosition([Infinity, Infinity]) runs -> editor.insertText(' this is an invalid modifier.') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) describe 'Autocomplete configuration', -> it 'react on showArguments configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.showArguments", true) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program - args') runs -> atom.config.set("#{CFG_KEY}.showArguments", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program') it 'react on excludeDirectories configuration changes', -> runs -> atom.config.set("#{CFG_KEY}.excludeDirectories", []) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('Run Program') runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .utility1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('utility 1') expect(suggestions[1]?.displayText).toEqual('utility 1 text') runs -> atom.config.set("#{CFG_KEY}.excludeDirectories", ['auto*']) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' runprog') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) runs -> atom.config.set("#{CFG_KEY}.excludeDirectories", ['*.robot']) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .utility1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('utility 1 text') it 'react on processLibdocFiles configuration changes', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' autocompletelibdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Autocomplete libdoc test " \' < > &') runs -> atom.config.set("#{CFG_KEY}.processLibdocFiles", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' autocompletelibdoc') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'react on maxFileSize configuration changes', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' limitfilesize') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('Limit File Size Keyword') runs -> atom.config.set("#{CFG_KEY}.maxFileSize", 39) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' limitfilesize') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) it 'react on showLibrarySuggestions configuration changes', -> runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' built') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].displayText).toEqual('BuiltIn') runs -> atom.config.set("#{CFG_KEY}.showLibrarySuggestions", false) waitsFor -> return !provider.loading , 'Provider should finish loading', TIMEOUT runs -> editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' built') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(0) describe 'Ambiguous keywords', -> it 'resolves keyword found in diffrent resources using default scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' ak') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].snippet).toEqual('utils2.abk1') expect(suggestions[1].snippet).toEqual('utils3.abk1') it 'resolves keyword found in diffrent libraries using default scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' delete') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].snippet.startsWith('FtpLibrary.Delete')).toBeTruthy() expect(suggestions[1].snippet.startsWith('RequestsLibrary.Delete')).toBeTruthy() it 'resolves keyword found in diffrent resources using global scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' .ak') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(2) expect(suggestions[0].snippet).toEqual('utils2.abk1') expect(suggestions[1].snippet).toEqual('utils3.abk1') it 'resolves keyword found in diffrent resources using file scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/test_kw_import1.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' utils2.abk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('utils2.abk1') runs -> editor.insertText(' utils3.abk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toBeGreaterThan(0) expect(suggestions[0].snippet).toEqual('utils3.abk1') it 'resolves keyword found in diffrent resources using internal scope modifier', -> waitsForPromise -> atom.workspace.open('autocomplete/a/utils2.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' this.abk') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> expect(suggestions.length).toEqual(1) expect(suggestions[0].snippet).toEqual('utils2.abk1') describe 'Imported resource path resolver', -> it 'resolves resource by resource name in the same directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr1') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr1k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr1.robot")).toBeTruthy() it 'resolves resource by resource name in different directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr6') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr6ka') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr6.robot")).toBeTruthy() it 'resolves resource by relative resource path in the same directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr2') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr2k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr2.robot")).toBeTruthy() it 'resolves resource by relative resource path in different directory', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr3') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr3ka') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr3.robot")).toBeTruthy() runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr4') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('pr4ka') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr4.robot")).toBeTruthy() it 'suggests keywords from all resources with same name when import path is computed', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr5') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('pr5k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr5.robot")).toBeTruthy() expect(suggestions[1]?.displayText).toEqual('pr5ka') expect(suggestions[1]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr5.robot")).toBeTruthy() it 'suggests keywords from all resources with same name when import path is wrong', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' pr7') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(2) expect(suggestions[0]?.displayText).toEqual('pr7k') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}pr7.robot")).toBeTruthy() expect(suggestions[1]?.displayText).toEqual('pr7ka') expect(suggestions[1]?.resourceKey.endsWith("path-resolver#{SEP}a#{SEP}pr7.robot")).toBeTruthy() it 'resolves external resources', -> waitsForPromise -> atom.workspace.open('path-resolver/path-resolver.robot') runs -> editor = atom.workspace.getActiveTextEditor() editor.setCursorBufferPosition([Infinity, Infinity]) editor.insertText(' prex') waitsForPromise -> getCompletions(editor, provider).then (suggestions) -> suggestions = suggestions.filter (suggestion) -> suggestion.type=='keyword' expect(suggestions.length).toEqual(1) expect(suggestions[0]?.displayText).toEqual('prext') expect(suggestions[0]?.resourceKey.endsWith("path-resolver#{SEP}external-resource.robot")).toBeTruthy()
[ { "context": "icates are created like this\n# https://github.com/argon/node-apn/wiki/Preparing-Certificates\n\ncert = path", "end": 321, "score": 0.9967823028564453, "start": 316, "tag": "USERNAME", "value": "argon" }, { "context": "is 'production' then return\n token = device.token...
src/services/apn.coffee
abhan00/mygitrepopractice
0
path = require 'path' apn = require 'apn' CERTS_PATH = process.env.CERTS_PATH or 'push-notification-service-data' delete process.env.CERTS_PATH # nobody else needs to know ENV = 'development' ENV = 'production' if process.env.NODE_ENV is 'production' # APN certificates are created like this # https://github.com/argon/node-apn/wiki/Preparing-Certificates cert = path.join(CERTS_PATH, 'apn', ENV, 'cert.pem') key = path.join(CERTS_PATH, 'apn', ENV, 'key.pem') options = cert: cert key: key production: ENV is 'production' batchFeedback: true interval: 60 invalidateToken = -> # Handle feedback, tells us when devicetokens are invalid feedback = new apn.Feedback(options) feedback.on 'feedback', (devices) -> deviceTokensToDelete = (item.device.token.toString("hex") for item in devices) console.log "APN Service Feedback Invalid tokens", deviceTokensToDelete if deviceTokensToDelete.length > 0 invalidateToken(token) for token in deviceTokensToDelete # Create the main service service = new apn.Connection(options) # log all events service.on 'connected', -> console.log 'APN Service is not connected' service.on 'socketError', (e) -> console.log 'APN Service Socket error', e service.on 'error', (e) -> console.log 'APN Service Error', e service.on 'timeout', (e) -> console.log 'APN Service connection timed out' service.on 'transmitted', (notification, device) -> if ENV is 'production' then return token = device.token.toString('hex') console.log "APN Service Notification transmitted to: #{token}" service.on 'transmissionError', (errCode, notification, token) -> console.log "APN Service Notification to #{token} failed with #{errCode}", token, notification service.on 'cacheTooSmall', (sizeDifference) -> console.log "APN Service Error: CacheTooSmall (size difference: #{sizeDifference})" # exported api module.exports.send = send = (notification={}, tokens=[]) -> ret = { result: 'ok' } # we have no specific payload to return note = new apn.Notification() # expiry oneHour = Math.floor(Date.now() / 1000) + 3600 fiveHours = oneHour * 5 aMinute = Math.floor(Date.now() / 1000) + 60 note.expry = aMinute # badge increment # TODO: figure out how to do autoincrementinb badge note.badge = notification.badge or "" # the message to be shown to the user note.alert = notification.alert or notification.message or "" # additional application-specific payload note.payload = notification.payload || {} # tell the ios application this notification may be parsed in the background # See. 'Using Push Notifications to Initiate a Download' at # https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW1 note.contentAvailable = 1 if process.env.TEST_MODE in ["1", "true"] console.log "Would send APN push notification", note, tokens return ret service.pushNotification(note, tokens) ret module.exports.setInvalidTokenCallback = (cb) -> invalidateToken = cb # TODO: setup feedback service # Do we actually need feedback service if we already have 'transmissionError' event ? # cli test usage if not module.parent # create and send message token = process.argv[2] message = process.argv[3] || "io non sono te" send({message}, [token]) console.log "=> #{token}: #{message}"
157887
path = require 'path' apn = require 'apn' CERTS_PATH = process.env.CERTS_PATH or 'push-notification-service-data' delete process.env.CERTS_PATH # nobody else needs to know ENV = 'development' ENV = 'production' if process.env.NODE_ENV is 'production' # APN certificates are created like this # https://github.com/argon/node-apn/wiki/Preparing-Certificates cert = path.join(CERTS_PATH, 'apn', ENV, 'cert.pem') key = path.join(CERTS_PATH, 'apn', ENV, 'key.pem') options = cert: cert key: key production: ENV is 'production' batchFeedback: true interval: 60 invalidateToken = -> # Handle feedback, tells us when devicetokens are invalid feedback = new apn.Feedback(options) feedback.on 'feedback', (devices) -> deviceTokensToDelete = (item.device.token.toString("hex") for item in devices) console.log "APN Service Feedback Invalid tokens", deviceTokensToDelete if deviceTokensToDelete.length > 0 invalidateToken(token) for token in deviceTokensToDelete # Create the main service service = new apn.Connection(options) # log all events service.on 'connected', -> console.log 'APN Service is not connected' service.on 'socketError', (e) -> console.log 'APN Service Socket error', e service.on 'error', (e) -> console.log 'APN Service Error', e service.on 'timeout', (e) -> console.log 'APN Service connection timed out' service.on 'transmitted', (notification, device) -> if ENV is 'production' then return token = device.token.<KEY>('<KEY>') console.log "APN Service Notification transmitted to: #{token}" service.on 'transmissionError', (errCode, notification, token) -> console.log "APN Service Notification to #{token} failed with #{errCode}", token, notification service.on 'cacheTooSmall', (sizeDifference) -> console.log "APN Service Error: CacheTooSmall (size difference: #{sizeDifference})" # exported api module.exports.send = send = (notification={}, tokens=[]) -> ret = { result: 'ok' } # we have no specific payload to return note = new apn.Notification() # expiry oneHour = Math.floor(Date.now() / 1000) + 3600 fiveHours = oneHour * 5 aMinute = Math.floor(Date.now() / 1000) + 60 note.expry = aMinute # badge increment # TODO: figure out how to do autoincrementinb badge note.badge = notification.badge or "" # the message to be shown to the user note.alert = notification.alert or notification.message or "" # additional application-specific payload note.payload = notification.payload || {} # tell the ios application this notification may be parsed in the background # See. 'Using Push Notifications to Initiate a Download' at # https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW1 note.contentAvailable = 1 if process.env.TEST_MODE in ["1", "true"] console.log "Would send APN push notification", note, tokens return ret service.pushNotification(note, tokens) ret module.exports.setInvalidTokenCallback = (cb) -> invalidateToken = cb # TODO: setup feedback service # Do we actually need feedback service if we already have 'transmissionError' event ? # cli test usage if not module.parent # create and send message token = process.argv[2] message = process.argv[3] || "io non sono te" send({message}, [token]) console.log "=> #{token}: #{message}"
true
path = require 'path' apn = require 'apn' CERTS_PATH = process.env.CERTS_PATH or 'push-notification-service-data' delete process.env.CERTS_PATH # nobody else needs to know ENV = 'development' ENV = 'production' if process.env.NODE_ENV is 'production' # APN certificates are created like this # https://github.com/argon/node-apn/wiki/Preparing-Certificates cert = path.join(CERTS_PATH, 'apn', ENV, 'cert.pem') key = path.join(CERTS_PATH, 'apn', ENV, 'key.pem') options = cert: cert key: key production: ENV is 'production' batchFeedback: true interval: 60 invalidateToken = -> # Handle feedback, tells us when devicetokens are invalid feedback = new apn.Feedback(options) feedback.on 'feedback', (devices) -> deviceTokensToDelete = (item.device.token.toString("hex") for item in devices) console.log "APN Service Feedback Invalid tokens", deviceTokensToDelete if deviceTokensToDelete.length > 0 invalidateToken(token) for token in deviceTokensToDelete # Create the main service service = new apn.Connection(options) # log all events service.on 'connected', -> console.log 'APN Service is not connected' service.on 'socketError', (e) -> console.log 'APN Service Socket error', e service.on 'error', (e) -> console.log 'APN Service Error', e service.on 'timeout', (e) -> console.log 'APN Service connection timed out' service.on 'transmitted', (notification, device) -> if ENV is 'production' then return token = device.token.PI:KEY:<KEY>END_PI('PI:KEY:<KEY>END_PI') console.log "APN Service Notification transmitted to: #{token}" service.on 'transmissionError', (errCode, notification, token) -> console.log "APN Service Notification to #{token} failed with #{errCode}", token, notification service.on 'cacheTooSmall', (sizeDifference) -> console.log "APN Service Error: CacheTooSmall (size difference: #{sizeDifference})" # exported api module.exports.send = send = (notification={}, tokens=[]) -> ret = { result: 'ok' } # we have no specific payload to return note = new apn.Notification() # expiry oneHour = Math.floor(Date.now() / 1000) + 3600 fiveHours = oneHour * 5 aMinute = Math.floor(Date.now() / 1000) + 60 note.expry = aMinute # badge increment # TODO: figure out how to do autoincrementinb badge note.badge = notification.badge or "" # the message to be shown to the user note.alert = notification.alert or notification.message or "" # additional application-specific payload note.payload = notification.payload || {} # tell the ios application this notification may be parsed in the background # See. 'Using Push Notifications to Initiate a Download' at # https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW1 note.contentAvailable = 1 if process.env.TEST_MODE in ["1", "true"] console.log "Would send APN push notification", note, tokens return ret service.pushNotification(note, tokens) ret module.exports.setInvalidTokenCallback = (cb) -> invalidateToken = cb # TODO: setup feedback service # Do we actually need feedback service if we already have 'transmissionError' event ? # cli test usage if not module.parent # create and send message token = process.argv[2] message = process.argv[3] || "io non sono te" send({message}, [token]) console.log "=> #{token}: #{message}"
[ { "context": " Big Sick'\n\tyear: 2017\n\t}\n\t{\n\trating: 92\n\ttitle: 'Wonder Woman'\n\tyear: 2017\n\t}\n\t{\n\trating: 92\n\ttitle:", "end": 3134, "score": 0.6056333184242249, "start": 3133, "tag": "NAME", "value": "W" }, { "context": "der Woman'\n\tyear: 2017\n\t}\n\t{\n\trating...
prototypes/scrollingCards.framer/app.coffee
davo/FramerNYCMeetup
7
# Requirements { chroma } = require 'npm' Canvas.backgroundColor = 'black' textColor = (toneOne, toneTwo) -> vsWhite = chroma.contrast(toneOne, toneTwo) if vsWhite < 4.5 return '#FFF' else chroma(toneOne).saturate(0.6).hex() # Colors colors = [ { 'color1': '#FFFFFF' 'color2': '#6284FF' 'color3': '#FF0000' } { 'color1': '#52ACFF' 'color2': '#FFE32C' } { 'color1': '#FFE53B' 'color2': '#FF2525' } { 'color1': '#FAACA8' 'color2': '#DDD6F3' } { 'color1': '#21D4FD' 'color2': '#B721FF' } { 'color1': '#08AEEA' 'color2': '#2AF598' } { 'color1': '#FEE140' 'color2': '#FA709A' } { 'color1': '#8EC5FC' 'color2': '#E0C3FC' } { 'color1': '#FBAB7E' 'color2': '#F7CE68' } { 'color1': '#FF3CAC' 'color2': '#784BA0' 'color3': '#2B86C5' } { 'color1': '#D9AFD9' 'color2': '#97D9E1' } { 'color1': '#00DBDE' 'color2': '#FC00FF' } { 'color1': '#F4D03F' 'color2': '#16A085' } { 'color1': '#0093E9' 'color2': '#80D0C7' } { 'color1': '#74EBD5' 'color2': '#9FACE6' } { 'color1': '#FAD961' 'color2': '#F76B1C' } { 'color1': '#FA8BFF' 'color2': '#2BD2FF' 'color3': '#2BFF88' } { 'color1': '#FBDA61' 'color2': '#FF5ACD' } { 'color1': '#8BC6EC' 'color2': '#9599E2' } { 'color1': '#A9C9FF' 'color2': '#FFBBEC' } { 'color1': '#3EECAC' 'color2': '#EE74E1' } { 'color1': '#4158D0' 'color2': '#C850C0' 'color3': '#FFCC70' } { 'color1': '#85FFBD' 'color2': '#FFFB7D' } { 'color1': '#FFDEE9' 'color2': '#B5FFFC' } { 'color1': '#FF9A8B' 'color2': '#FF6A88' 'color3': '#FF99AC' } ] duotone = [ { 'toneOne': '#00ff36' 'blendOne': 'multiply' 'toneTwo': '#23278a' 'blendTwo': 'lighten' greyscale: 100 contrast: 100 } { 'toneOne': '#e41c2d' 'blendOne': 'multiply' 'toneTwo': '#1d3162' 'blendTwo': 'lighten' greyscale: 100 contrast: 140 } { 'toneOne': '#FCA300' 'blendOne': 'darken' 'toneTwo': '#e23241' 'blendTwo': 'lighten' greyscale: 100 contrast: 120 } { 'toneOne': '#FCA300' 'blendOne': 'darken' 'toneTwo': '#282581' 'blendTwo': 'lighten' greyscale: 100 contrast: 120 } ] # urlShot = 'https://api.dribbble.com/v1/shots/'+shotID+'?access_token='+access_token # # fetch(urlShot, method: 'get').then((response) -> # response.json() # .then (data) -> # movieTitle = null queryOMDB = 'http://www.omdbapi.com/?t='+movieTitle+'&apikey=86718c42' getMovie = (movieTitle) -> fetch(queryOMDB, method: 'get').then((response) -> response.json() .then (data) -> print data ) # .retro # background-color: #f1e3a0 # img # mix-blend-mode: darken # -webkit-filter: grayscale(100%) contrast(2) # filter: grayscale(100%) contrast(2) # &::after # background: linear-gradient(180deg, #f430a9, #f2e782) # mix-blend-mode: lighten # Data # Top Rated Movies on IMDB http://www.imdb.com/chart/top?sort=ir,desc&mode=simple&page=1 # Data # Movies from https://www.lists.design/ best = [ { rating: 99 title: 'Get Out' year: 2017 } { rating: 98 title: 'The Big Sick' year: 2017 } { rating: 92 title: 'Wonder Woman' year: 2017 } { rating: 92 title: 'Dunkirk' year: 2017 } { rating: 100 title: 'Lady Bird' year: 2017 } { rating: 93 title: 'Logan' year: 2017 } { rating: 93 title: 'Baby Driver' year: 2017 } { rating: 93 title: 'War for the Planet of the Apes' year: 2017 } { rating: 92 title: 'Thor: Ragnarok' year: 2017 } { rating: 92 title: 'Spider-Man: Homecoming' year: 2017 } { rating: 98 title: 'I Am Not Your Negro' year: 2017 } { rating: 97 title: 'Coco' year: 2017 } { rating: 98 title: 'Call Me by Your Name' year: 2017 } { rating: 95 title: 'The Florida Project' year: 2017 } { rating: 93 title: 'Logan Lucky' year: 2017 } { rating: 92 title: 'Hidden Figures' year: 2017 } { rating: 96 title: 'The Salesman (Forushande)' year: 2017 } { rating: 91 title: 'The Lego Batman Movie' year: 2017 } { rating: 94 title: 'Three Billboards Outside Ebbing, Missouri' year: 2017 } { rating: 98 title: 'My Life as a Zucchini (Ma vie de courgette)' year: 2017 } { rating: 99 title: 'God\'s Own Country' year: 2017 } { rating: 87 title: 'Blade Runner 2049' year: 2017 } { rating: 100 title: 'Faces Places (Visages, villages)' year: 2017 } { rating: 99 title: 'City of Ghosts' year: 2017 } { rating: 100 title: 'Truman' year: 2017 } { rating: 98 title: 'Kedi' year: 2017 } { rating: 96 title: 'Mudbound' year: 2017 } { rating: 97 title: 'After the Storm (Umi yori mo mada fukaku)' year: 2017 } { rating: 99 title: 'Jane' year: 2017 } { rating: 99 title: 'Whose Streets?' year: 2017 } { rating: 98 title: 'Lucky' year: 2017 } { rating: 100 title: 'Bright Lights: Starring Carrie Fisher and Debbie Reynolds' year: 2017 } { rating: 100 title: 'The Happiest Day in the Life of Olli Mäki (Hymyilevä mies)' year: 2017 } { rating: 95 title: 'The Red Turtle (La tortue rouge)' year: 2017 } { rating: 96 title: 'Stronger' year: 2017 } { rating: 100 title: 'The Work' year: 2017 } { rating: 100 title: 'Dawson City: Frozen Time' year: 2017 } { rating: 97 title: 'Your Name. (Kimi No Na Wa.)' year: 2017 } { rating: 96 title: 'The Disaster Artist' year: 2017 } { rating: 98 title: 'BPM (Beats Per Minute) (120 battements par minute)' year: 2017 } { rating: 95 title: 'Graduation (Bacalaureat)' year: 2017 } { rating: 93 title: 'I, Daniel Blake' year: 2017 } { rating: 98 title: 'In This Corner of the World (Kono sekai no katasumi ni)' year: 2017 } { rating: 97 title: 'Columbus' year: 2017 } { rating: 95 title: 'The Shape of Water' year: 2017 } { rating: 90 title: 'A Ghost Story' year: 2017 } { rating: 90 title: 'John Wick: Chapter 2' year: 2017 } { rating: 98 title: 'Dina' year: 2017 } { rating: 98 title: 'Trophy' year: 2017 } { rating: 93 title: 'The Meyerowitz Stories (New and Selected)' year: 2017 } ] movies = [ { 'title': 'Pulp Fiction' } { 'title': 'Fight Club' } { 'title': 'The Shawshank Redemption' } { 'title': 'The Dark Knight' } { 'title': 'Inglourious Basterds' } { 'title': 'Inception' } { 'title': 'The Matrix' } { 'title': 'The Empire Strikes Back' } { 'title': 'The Lord of the Rings: The Fellowship of the Ring' } { 'title': 'Toy Story' } { 'title': 'The Big Lebowski' } { 'title': 'Django Unchained' } { 'title': 'The Lord of the Rings: The Return of the King' } { 'title': 'The Departed' } { 'title': 'Memento' } { 'title': 'The Godfather' } { 'title': 'Reservoir Dogs' } { 'title': 'Saving Private Ryan' } { 'title': 'Forrest Gump' } { 'title': 'Monty Python and the Holy Grail' } { 'title': 'Se7en' } { 'title': 'Back to the Future' } { 'title': 'Goodfellas' } { 'title': 'The Prestige' } { 'title': 'Shaun of the Dead' } { 'title': 'Alien' } { 'title': 'The Silence of the Lambs' } { 'title': 'The Lord of the Rings: The Two Towers' } { 'title': 'Spirited Away' } { 'title': 'The Good, the Bad and the Ugly' } { 'title': 'Eternal Sunshine of the Spotless Mind' } { 'title': 'Raiders of the Lost Ark' } { 'title': '2001: A Space Odyssey' } { 'title': 'Dr. Strangelove Or: How I Learned to Stop Worrying and Love the Bomb' } { 'title': 'Blade Runner' } { 'title': 'The Lion King' } { 'title': 'One Flew Over the Cuckoo\'s Nest' } { 'title': 'There Will Be Blood' } { 'title': 'The Shining' } { 'title': 'The Truman Show' } { 'title': 'A Clockwork Orange' } { 'title': 'Star Wars' } { 'title': 'District 9' } { 'title': 'Up' } { 'title': 'Office Space' } { 'title': '12 Angry Men' } { 'title': 'Pan\'s Labyrinth' } { 'title': 'The Usual Suspects' } { 'title': 'Jurassic Park' } { 'title': 'V for Vendetta' } { 'title': 'The Princess Bride' } { 'title': 'No Country for Old Men' } { 'title': 'Full Metal Jacket' } { 'title': 'Schindler\'s List' } { 'title': 'Good Will Hunting' } { 'title': 'Children of Men' } { 'title': 'Kill Bill: Vol. 1' } { 'title': 'WALL·E' } { 'title': 'American History X' } { 'title': 'Die Hard' } { 'title': 'Drive' } { 'title': 'Moon' } { 'title': 'Groundhog Day' } { 'title': 'Batman Begins' } { 'title': 'Fargo' } { 'title': 'The Incredibles' } { 'title': 'O Brother, Where Art Thou' } { 'title': 'Gladiator' } { 'title': 'Airplane!' } { 'title': 'Apocalypse Now' } { 'title': 'American Beauty' } { 'title': 'Terminator 2: Judgment Day' } { 'title': 'Léon' } { 'title': 'Toy Story 3' } { 'title': 'Snatch' } { 'title': 'American Psycho' } { 'title': 'The Social Network' } { 'title': 'Oldboy' } { 'title': 'Ferris Bueller\'s Day Off' } { 'title': 'Princess Mononoke' } { 'title': 'In Bruges' } { 'title': 'Donnie Darko' } { 'title': 'Casablanca' } { 'title': 'City of God' } { 'title': 'Psycho' } { 'title': 'The Fifth Element' } { 'title': 'Seven Samurai' } { 'title': 'Taxi Driver' } { 'title': 'Monsters, Inc.' } { 'title': '28 Days Later' } { 'title': 'Requiem for a Dream' } { 'title': 'The Godfather: Part II' } { 'title': 'Hot Fuzz' } { 'title': 'Trainspotting' } { 'title': 'Amélie' } { 'title': 'Twelve Monkeys' } { 'title': 'Aliens' } { 'title': 'The Dark Knight Rises' } { 'title': 'Kiss Kiss Bang Bang' } { 'title': 'Lost in Translation' } { 'title': 'Chinatown' } { 'title': 'The Royal Tennenbaums' } { 'title': 'Rear Window' } { 'title': 'Jaws' } { 'title': 'Ocean\'s Eleven' } { 'title': 'Howl\'s Moving Castle' } { 'title': 'The Green Mile' } { 'title': 'Black Swan' } { 'title': 'Citizen Kane' } { 'title': 'Moonrise Kingdom' } { 'title': 'Looper' } { 'title': 'The Thing' } { 'title': 'The Breakfast Club' } { 'title': 'The Cabin in the Woods' } { 'title': 'L.A. Confidential' } { 'title': 'Scott Pilgrim Vs. the World' } { 'title': 'Finding Nemo' } { 'title': 'Boogie Nights' } { 'title': 'Superbad' } { 'title': 'Sin City' } { 'title': 'Fear and Loathing in Las Vegas' } { 'title': 'Indiana Jones and the Last Crusade' } { 'title': 'Gattaca' } { 'title': 'To Kill a Mockingbird' } { 'title': 'Lawrence of Arabia' } { 'title': 'Being John Malkovich' } { 'title': 'The Pianist' } { 'title': 'Annie Hall' } { 'title': 'Anchorman: The Legend of Ron Burgundy' } { 'title': 'Argo' } { 'title': 'Raging Bull' } { 'title': 'Vertigo' } { 'title': 'Little Miss Sunshine' } { 'title': 'The Avengers' } { 'title': 'Butch Cassidy and the Sundance Kid' } { 'title': 'Dazed and Confused' } { 'title': 'Days of Summer' } { 'title': 'Willy Wonka & the Chocolate Factory' } { 'title': 'Unforgiven' } { 'title': 'Fantastic Mr. Fox' } { 'title': 'Brazil' } { 'title': 'The Iron Giant' } { 'title': 'Akira' } { 'title': 'The Terminator' } { 'title': 'Ghost Busters' } { 'title': 'This Is Spinal Tap' } { 'title': 'Gran Torino' } { 'title': 'Adaptation.' } { 'title': 'A Fistful of Dollars' } { 'title': 'Stand by Me' } { 'title': 'Apollo 13' } { 'title': 'Blazing Saddles' } { 'title': 'Amadeus' } { 'title': 'Kick-Ass' } { 'title': 'Rushmore' } { 'title': 'Life of Brian' } { 'title': 'Almost Famous' } { 'title': 'Network' } { 'title': 'Mulholland Drive' } { 'title': 'Star Trek' } { 'title': 'It\'s a Wonderful Life' } { 'title': 'Singin\' in the Rain' } { 'title': 'The Graduate' } { 'title': 'Cool Hand Luke' } { 'title': 'The Nightmare Before Christmas' } { 'title': 'Metropolis' } { 'title': 'Casino Royale' } { 'title': 'Zodiac' } { 'title': 'Crouching Tiger, Hidden Dragon' } { 'title': 'True Grit' } { 'title': 'Braveheart' } { 'title': 'Yojimbo' } { 'title': 'The Thin Red Line' } { 'title': 'Warrior' } { 'title': 'Blue Velvet' } { 'title': 'Primer' } { 'title': 'The Life Aquatic With Steve Zissou' } { 'title': 'Big Fish' } { 'title': 'Mr. Smith Goes to Washington' } { 'title': 'Clerks' } { 'title': 'Rashomon' } { 'title': 'Once Upon a Time in the West' } { 'title': 'The Rocky Horror Picture Show' } { 'title': 'North by Northwest' } { 'title': 'Gangs of New York' } { 'title': 'Duck Soup' } { 'title': 'Grave of the Fireflies' } { 'title': 'M' } { 'title': 'E.T. the Extra-Terrestrial' } { 'title': 'The Blues Brothers' } { 'title': 'The Great Dictator' } { 'title': 'Galaxy Quest' } { 'title': 'Hotel Rwanda' } { 'title': 'Brick' } { 'title': 'The Assassination of Jesse James by the Coward Robert Ford' } { 'title': 'Zoolander' } { 'title': 'The Deer Hunter' } { 'title': '8 1/2' } { 'title': 'The Third Man' } { 'title': 'The Bridge on the River Kwai' } { 'title': 'The Lives of Others' } { 'title': 'Heat' } { 'title': 'The Seventh Seal' } { 'title': 'Kill Bill: Vol. 2' } { 'title': 'Synecdoche, New York' } { 'title': 'Stranger Than Fiction' } { 'title': 'Double Indemnity' } { 'title': 'On the Waterfront' } { 'title': 'Predator' } { 'title': 'Lucky Number Slevin' } { 'title': 'Catch Me If You Can' } { 'title': 'Dredd' } { 'title': 'Battle Royale' } { 'title': 'Robocop' } { 'title': 'How to Train Your Dragon' } { 'title': 'Dog Day Afternoon' } { 'title': 'Planet of the Apes' } { 'title': 'Nausicaä of the Valley of the Wind' } { 'title': 'Master and Commander: The Far Side of the World' } { 'title': 'City Lights' } { 'title': 'Paths of Glory' } { 'title': 'Brokeback Mountain' } { 'title': 'The Hobbit: An Unexpected Journey' } { 'title': 'The Wizard of Oz' } { 'title': 'Close Encounters of the Third Kind' } { 'title': 'The Wrestler' } { 'title': 'The Jerk' } { 'title': 'Slumdog Millionaire' } { 'title': 'Silver Linings Playbook' } { 'title': 'Glengarry Glen Ross' } { 'title': 'Sunset Boulevard' } { 'title': 'Return of the Jedi' } { 'title': 'Ran' } { 'title': 'Collateral' } { 'title': 'Let the Right One in' } { 'title': 'The Sting' } { 'title': 'Tucker and Dale Vs. Evil' } { 'title': 'Some Like It Hot' } { 'title': 'Shutter Island' } { 'title': 'The Maltese Falcon' } { 'title': 'The Treasure of the Sierra Madre' } { 'title': 'Sunshine' } { 'title': 'Punch-Drunk Love' } { 'title': 'Magnolia' } { 'title': 'Thank You for Smoking' } { 'title': 'Ghost in the Shell' } { 'title': 'Barry Lyndon' } { 'title': 'Ikiru' } { 'title': 'Dawn of the Dead' } { 'title': 'The Hurt Locker' } ] # Snapshots from omdbapi pf = 'Title': 'Pulp Fiction' 'Year': '1994' 'Rated': 'R' 'Released': '14 Oct 1994' 'Runtime': '154 min' 'Genre': 'Crime, Drama' 'Director': 'Quentin Tarantino' 'Writer': 'Quentin Tarantino (stories), Roger Avary (stories), Quentin Tarantino' 'Actors': 'Tim Roth, Amanda Plummer, Laura Lovelace, John Travolta' 'Plot': 'The lives of two mob hit men, a boxer, a gangster\'s wife, and a pair of diner bandits intertwine in four tales of violence and redemption.' 'Language': 'English, Spanish, French' 'Country': 'USA' 'Awards': 'Won 1 Oscar. Another 60 wins & 68 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/c_mfit,q_auto:best,w_1280/v1512202426/pulpFiction.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '8.9/10' } { 'Source': 'Rotten Tomatoes' 'Value': '94%' } { 'Source': 'Metacritic' 'Value': '94/100' } ] 'Metascore': '94' 'imdbRating': '8.9' 'imdbVotes': '1,471,678' 'imdbID': 'tt0110912' 'Type': 'movie' 'DVD': '19 May 1998' 'BoxOffice': 'N/A' 'Production': 'Miramax Films' 'Website': 'N/A' 'Response': 'True' fc = 'Title': 'Fight Club' 'Year': '1999' 'Rated': 'R' 'Released': '15 Oct 1999' 'Runtime': '139 min' 'Genre': 'Drama' 'Director': 'David Fincher' 'Writer': 'Chuck Palahniuk (novel), Jim Uhls (screenplay)' 'Actors': 'Edward Norton, Brad Pitt, Meat Loaf, Zach Grenier' 'Plot': 'An insomniac office worker, looking for a way to change his life, crosses paths with a devil-may-care soap maker, forming an underground fight club that evolves into something much, much more.' 'Language': 'English' 'Country': 'USA, Germany' 'Awards': 'Nominated for 1 Oscar. Another 10 wins & 32 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/s--bD7uo-Gy--/c_imagga_scale,q_auto:best,w_1280/v1512202141/Fight-Club_ksipx1.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '8.8/10' } { 'Source': 'Rotten Tomatoes' 'Value': '79%' } { 'Source': 'Metacritic' 'Value': '66/100' } ] 'Metascore': '66' 'imdbRating': '8.8' 'imdbVotes': '1,508,138' 'imdbID': 'tt0137523' 'Type': 'movie' 'DVD': '06 Jun 2000' 'BoxOffice': 'N/A' 'Production': '20th Century Fox' 'Website': 'http://www.foxmovies.com/fightclub/' 'Response': 'True' tsr = 'Title': 'The Shawshank Redemption' 'Year': '1994' 'Rated': 'R' 'Released': '14 Oct 1994' 'Runtime': '142 min' 'Genre': 'Crime, Drama' 'Director': 'Frank Darabont' 'Writer': 'Stephen King (short story "Rita Hayworth and Shawshank Redemption"), Frank Darabont (screenplay)' 'Actors': 'Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler' 'Plot': 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.' 'Language': 'English' 'Country': 'USA' 'Awards': 'Nominated for 7 Oscars. Another 19 wins & 29 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/s--UQgrUWCP--/c_imagga_crop,h_720,q_jpegmini,w_1280/v1512201263/shawshankRedemption.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '9.3/10' } { 'Source': 'Rotten Tomatoes' 'Value': '91%' } { 'Source': 'Metacritic' 'Value': '80/100' } ] 'Metascore': '80' 'imdbRating': '9.3' 'imdbVotes': '1,874,788' 'imdbID': 'tt0111161' 'Type': 'movie' 'DVD': '27 Jan 1998' 'BoxOffice': 'N/A' 'Production': 'Columbia Pictures' 'Website': 'N/A' 'Response': 'True' tdk = 'Title': 'The Dark Knight' 'Year': '2008' 'Rated': 'PG-13' 'Released': '18 Jul 2008' 'Runtime': '152 min' 'Genre': 'Action, Crime, Drama' 'Director': 'Christopher Nolan' 'Writer': 'Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)' 'Actors': 'Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine' 'Plot': 'When the menace known as the Joker emerges from his mysterious past, he wreaks havoc and chaos on the people of Gotham, the Dark Knight must accept one of the greatest psychological and physical tests of his ability to fight injustice.' 'Language': 'English, Mandarin' 'Country': 'USA, UK' 'Awards': 'Won 2 Oscars. Another 151 wins & 154 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/c_lfill,h_720,q_auto:best,w_1280/v1512203105/theDarkKnight.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '9.0/10' } { 'Source': 'Rotten Tomatoes' 'Value': '94%' } { 'Source': 'Metacritic' 'Value': '82/100' } ] 'Metascore': '82' 'imdbRating': '9.0' 'imdbVotes': '1,848,050' 'imdbID': 'tt0468569' 'Type': 'movie' 'DVD': '09 Dec 2008' 'BoxOffice': '$533,316,061' 'Production': 'Warner Bros. Pictures/Legendary' 'Website': 'http://thedarkknight.warnerbros.com/' 'Response': 'True' ib = 'Title': 'Inglourious Basterds' 'Year': '2009' 'Rated': 'R' 'Released': '21 Aug 2009' 'Runtime': '153 min' 'Genre': 'Adventure, Drama, War' 'Director': 'Quentin Tarantino, Eli Roth' 'Writer': 'Quentin Tarantino' 'Actors': 'Brad Pitt, Mélanie Laurent, Christoph Waltz, Eli Roth' 'Plot': 'In Nazi-occupied France during World War II, a plan to assassinate Nazi leaders by a group of Jewish U.S. soldiers coincides with a theatre owner\'s vengeful plans for the same.' 'Language': 'English, German, French, Italian' 'Country': 'USA, Germany' 'Awards': 'Won 1 Oscar. Another 129 wins & 165 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/s--epexlNdl--/c_imagga_scale,h_720,q_auto:best,w_1280/v1512203671/inglouriousBasterds_koghsj.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '8.3/10' } { 'Source': 'Rotten Tomatoes' 'Value': '88%' } { 'Source': 'Metacritic' 'Value': '69/100' } ] 'Metascore': '69' 'imdbRating': '8.3' 'imdbVotes': '997,468' 'imdbID': 'tt0361748' 'Type': 'movie' 'DVD': '15 Dec 2009' 'BoxOffice': '$120,523,073' 'Production': 'The Weinstein Company' 'Website': 'http://www.inglouriousbasterds-movie.com/' 'Response': 'True' # Add Card Function numOfCards = 0 cards = [] cardSize = width: 355 height: 235 offset: 11 addCard = () -> tone = _.sample duotone card = new Layer width: cardSize.width height: cardSize.height x: Align.center midX: 0.5 y: numOfCards * (cardSize.height + cardSize.offset) name: 'card'+numOfCards parent: cardContainer borderRadius: 13 opacity: 0 scale: 0.8 blur: 12 backgroundColor: tone.toneOne poster = new Layer parent: card size: card.size blending: tone.blendOne opacity: 0.7 clip: true borderRadius: 13 grayscale: tone.greyscale contrast: tone.contrast after = new Layer parent: card size: card.size clip: true blending: tone.blendTwo backgroundColor: tone.toneTwo borderRadius: 13 if numOfCards is 0 poster.image = pf.Poster else if numOfCards is 1 poster.image = fc.Poster else if numOfCards is 2 poster.image = tsr.Poster else if numOfCards is 3 poster.image = tdk.Poster else next = numOfCards + 1 fetch = movies[next].title type = new TextLayer parent: card width: 209 fontSize: 32 x: Align.left +18 y: Align.top -24 color: 'white' fontFamily: '-apple-system' fontWeight: 700 text: movies[numOfCards].title opacity: 0 type.states = fadeIn: opacity: 1 y: Align.top +24 animationOptions: time: 0.15 delay: 0.05 numOfCards = numOfCards + 1 # http://www.omdbapi.com/?t=Pulp+Fiction&apikey=86718c42 cards.push(card) card.states = fadeIn: scale: 1 blur: 0 opacity: 1 y: card.y + 11 animationOptions: time: 0.5 card.animate('fadeIn') card.onAnimationEnd -> type.animate('fadeIn') # card.onTap -> # @.animate('done') # Force resize to match height with the contents of the container cardContainer.height = cardContainer.contentFrame().height + 90 * 2 if numOfCards > 4 flow.scroll.updateContent() flow.scroll.scrollToPoint(y: cardContainer.height, curve: Bezier.ease, time: 10) cardContainer = new Layer parent: scroll.content width: Screen.width height: Screen.height * 1.5 y: 140 backgroundColor: null # Flow Component flow = new FlowComponent backgroundColor: null parent: main index: -1 flow.showNext(cardContainer) flow.scroll.mouseWheelEnabled = true flow.scroll.contentInset = top: header.height flow.index = 2 offsetHeader = (point, withModifier) -> if withModifier is 'scroll' # print point header.y = Utils.modulate(point,[0,header.height],[point,-header.height],true) header.opacity = Utils.modulate(point,[0,70],[1,0],true) header.scale = Utils.modulate(point,[0,70],[1,0.9],true) else if withModifier is 'drag' # print point header.y = Utils.modulate(point,[140,0],[0,-header.height],true) header.opacity = Utils.modulate(point,[140,70],[1,0],true) header.scale = Utils.modulate(point,[140,70],[1,0.9],true) flow.scroll.on 'scroll', -> if flow.scroll.isDragging is false offsetHeader @.scrollPoint.y, 'scroll' else if flow.scroll.isDragging is true offsetHeader @.minY, 'drag' # Interactions button.placeBefore flow homebar.placeBefore flow button.states = over: opacity: 0.90 options: time: 0.50 curve: Spring out: opacity: 0.99 options: time: 0.50 curve: Spring # Button interactions button.y = Screen.height button.on 'mouseover', -> @.animate 'over' button.on 'mouseout', -> @.animate 'out' button.on 'tap', -> addCard() # Init i = null _.times 4, -> i += 1 Utils.delay 0.7 * i, -> addCard() if i > 3 Utils.delay 0.7 * i, -> button.animate y: Screen.height - (83+44) options: time: 0.50 curve: Spring
193944
# Requirements { chroma } = require 'npm' Canvas.backgroundColor = 'black' textColor = (toneOne, toneTwo) -> vsWhite = chroma.contrast(toneOne, toneTwo) if vsWhite < 4.5 return '#FFF' else chroma(toneOne).saturate(0.6).hex() # Colors colors = [ { 'color1': '#FFFFFF' 'color2': '#6284FF' 'color3': '#FF0000' } { 'color1': '#52ACFF' 'color2': '#FFE32C' } { 'color1': '#FFE53B' 'color2': '#FF2525' } { 'color1': '#FAACA8' 'color2': '#DDD6F3' } { 'color1': '#21D4FD' 'color2': '#B721FF' } { 'color1': '#08AEEA' 'color2': '#2AF598' } { 'color1': '#FEE140' 'color2': '#FA709A' } { 'color1': '#8EC5FC' 'color2': '#E0C3FC' } { 'color1': '#FBAB7E' 'color2': '#F7CE68' } { 'color1': '#FF3CAC' 'color2': '#784BA0' 'color3': '#2B86C5' } { 'color1': '#D9AFD9' 'color2': '#97D9E1' } { 'color1': '#00DBDE' 'color2': '#FC00FF' } { 'color1': '#F4D03F' 'color2': '#16A085' } { 'color1': '#0093E9' 'color2': '#80D0C7' } { 'color1': '#74EBD5' 'color2': '#9FACE6' } { 'color1': '#FAD961' 'color2': '#F76B1C' } { 'color1': '#FA8BFF' 'color2': '#2BD2FF' 'color3': '#2BFF88' } { 'color1': '#FBDA61' 'color2': '#FF5ACD' } { 'color1': '#8BC6EC' 'color2': '#9599E2' } { 'color1': '#A9C9FF' 'color2': '#FFBBEC' } { 'color1': '#3EECAC' 'color2': '#EE74E1' } { 'color1': '#4158D0' 'color2': '#C850C0' 'color3': '#FFCC70' } { 'color1': '#85FFBD' 'color2': '#FFFB7D' } { 'color1': '#FFDEE9' 'color2': '#B5FFFC' } { 'color1': '#FF9A8B' 'color2': '#FF6A88' 'color3': '#FF99AC' } ] duotone = [ { 'toneOne': '#00ff36' 'blendOne': 'multiply' 'toneTwo': '#23278a' 'blendTwo': 'lighten' greyscale: 100 contrast: 100 } { 'toneOne': '#e41c2d' 'blendOne': 'multiply' 'toneTwo': '#1d3162' 'blendTwo': 'lighten' greyscale: 100 contrast: 140 } { 'toneOne': '#FCA300' 'blendOne': 'darken' 'toneTwo': '#e23241' 'blendTwo': 'lighten' greyscale: 100 contrast: 120 } { 'toneOne': '#FCA300' 'blendOne': 'darken' 'toneTwo': '#282581' 'blendTwo': 'lighten' greyscale: 100 contrast: 120 } ] # urlShot = 'https://api.dribbble.com/v1/shots/'+shotID+'?access_token='+access_token # # fetch(urlShot, method: 'get').then((response) -> # response.json() # .then (data) -> # movieTitle = null queryOMDB = 'http://www.omdbapi.com/?t='+movieTitle+'&apikey=86718c42' getMovie = (movieTitle) -> fetch(queryOMDB, method: 'get').then((response) -> response.json() .then (data) -> print data ) # .retro # background-color: #f1e3a0 # img # mix-blend-mode: darken # -webkit-filter: grayscale(100%) contrast(2) # filter: grayscale(100%) contrast(2) # &::after # background: linear-gradient(180deg, #f430a9, #f2e782) # mix-blend-mode: lighten # Data # Top Rated Movies on IMDB http://www.imdb.com/chart/top?sort=ir,desc&mode=simple&page=1 # Data # Movies from https://www.lists.design/ best = [ { rating: 99 title: 'Get Out' year: 2017 } { rating: 98 title: 'The Big Sick' year: 2017 } { rating: 92 title: '<NAME>onder Woman' year: 2017 } { rating: 92 title: '<NAME>' year: 2017 } { rating: 100 title: '<NAME>' year: 2017 } { rating: 93 title: '<NAME>' year: 2017 } { rating: 93 title: '<NAME>' year: 2017 } { rating: 93 title: 'War for the Planet of the Apes' year: 2017 } { rating: 92 title: '<NAME>' year: 2017 } { rating: 92 title: 'Spider-Man: Homecoming' year: 2017 } { rating: 98 title: 'I Am Not Your Negro' year: 2017 } { rating: 97 title: '<NAME>' year: 2017 } { rating: 98 title: 'Call Me by Your Name' year: 2017 } { rating: 95 title: 'The Florida Project' year: 2017 } { rating: 93 title: '<NAME>' year: 2017 } { rating: 92 title: 'Hidden Figures' year: 2017 } { rating: 96 title: 'The Salesman (Forushande)' year: 2017 } { rating: 91 title: 'The Lego Batman Movie' year: 2017 } { rating: 94 title: 'Three Billboards Outside Ebbing, Missouri' year: 2017 } { rating: 98 title: 'My Life as a Zucchini (Ma vie de courgette)' year: 2017 } { rating: 99 title: 'God\'s Own Country' year: 2017 } { rating: 87 title: 'Blade Runner 2049' year: 2017 } { rating: 100 title: 'Faces Places (Visages, villages)' year: 2017 } { rating: 99 title: 'City of Ghosts' year: 2017 } { rating: 100 title: '<NAME>' year: 2017 } { rating: 98 title: '<NAME>' year: 2017 } { rating: 96 title: '<NAME>' year: 2017 } { rating: 97 title: 'After the Storm (Umi yori mo mada fukaku)' year: 2017 } { rating: 99 title: '<NAME>' year: 2017 } { rating: 99 title: 'Whose Streets?' year: 2017 } { rating: 98 title: 'Lucky' year: 2017 } { rating: 100 title: 'Bright Lights: Starring <NAME> and <NAME>' year: 2017 } { rating: 100 title: 'The Happiest Day in the Life of <NAME> (Hymyilevä mies)' year: 2017 } { rating: 95 title: 'The Red Turtle (La tortue rouge)' year: 2017 } { rating: 96 title: 'Stronger' year: 2017 } { rating: 100 title: 'The Work' year: 2017 } { rating: 100 title: 'Dawson City: Frozen Time' year: 2017 } { rating: 97 title: 'Your Name. (<NAME>.)' year: 2017 } { rating: 96 title: 'The Disaster Artist' year: 2017 } { rating: 98 title: 'BPM (Beats Per Minute) (120 battements par minute)' year: 2017 } { rating: 95 title: 'Graduation (Bacalaureat)' year: 2017 } { rating: 93 title: 'I, <NAME>' year: 2017 } { rating: 98 title: 'In This Corner of the World (Kono sekai no katasumi ni)' year: 2017 } { rating: 97 title: '<NAME>' year: 2017 } { rating: 95 title: 'The Shape of Water' year: 2017 } { rating: 90 title: 'A Ghost Story' year: 2017 } { rating: 90 title: '<NAME>: Chapter 2' year: 2017 } { rating: 98 title: '<NAME>' year: 2017 } { rating: 98 title: '<NAME>' year: 2017 } { rating: 93 title: 'The Meyerowitz Stories (New and Selected)' year: 2017 } ] movies = [ { 'title': 'Pulp Fiction' } { 'title': 'Fight Club' } { 'title': 'The Shawshank Redemption' } { 'title': 'The Dark Knight' } { 'title': 'Inglourious Basterds' } { 'title': 'Inception' } { 'title': 'The Matrix' } { 'title': 'The Empire Strikes Back' } { 'title': 'The Lord of the Rings: The Fellowship of the Ring' } { 'title': 'Toy Story' } { 'title': 'The Big Lebowski' } { 'title': 'Django Unchained' } { 'title': 'The Lord of the Rings: The Return of the King' } { 'title': 'The Departed' } { 'title': 'Memento' } { 'title': 'The Godfather' } { 'title': 'Reservoir Dogs' } { 'title': 'Saving Private Ryan' } { 'title': '<NAME>rest Gump' } { 'title': 'Monty Python and the Holy Grail' } { 'title': 'Se7en' } { 'title': 'Back to the Future' } { 'title': 'Goodfellas' } { 'title': 'The Prestige' } { 'title': 'Shaun of the Dead' } { 'title': 'Alien' } { 'title': 'The Silence of the Lambs' } { 'title': 'The Lord of the Rings: The Two Towers' } { 'title': 'Spirited Away' } { 'title': 'The Good, the Bad and the Ugly' } { 'title': 'Eternal Sunshine of the Spotless Mind' } { 'title': 'Raiders of the Lost Ark' } { 'title': '2001: A Space Odyssey' } { 'title': 'Dr. Strangelove Or: How I Learned to Stop Worrying and Love the Bomb' } { 'title': 'Blade Runner' } { 'title': 'The Lion King' } { 'title': 'One Flew Over the Cuckoo\'s Nest' } { 'title': 'There Will Be Blood' } { 'title': 'The Shining' } { 'title': 'The Truman Show' } { 'title': 'A Clockwork Orange' } { 'title': 'Star Wars' } { 'title': 'District 9' } { 'title': 'Up' } { 'title': 'Office Space' } { 'title': '12 Angry Men' } { 'title': 'Pan\'s Labyrinth' } { 'title': 'The Usual Suspects' } { 'title': 'Jurassic Park' } { 'title': 'V for Vendetta' } { 'title': 'The Princess Bride' } { 'title': 'No Country for Old Men' } { 'title': 'Full Metal Jacket' } { 'title': 'Schindler\'s List' } { 'title': 'Good Will Hunting' } { 'title': 'Children of Men' } { 'title': 'Kill Bill: Vol. 1' } { 'title': 'WALL·E' } { 'title': 'American History X' } { 'title': 'Die Hard' } { 'title': 'Drive' } { 'title': 'Moon' } { 'title': 'Groundhog Day' } { 'title': 'Batman Begins' } { 'title': 'Fargo' } { 'title': 'The Incredibles' } { 'title': 'O Brother, Where Art Thou' } { 'title': 'Gladiator' } { 'title': 'Airplane!' } { 'title': 'Apocalypse Now' } { 'title': 'American Beauty' } { 'title': 'Terminator 2: Judgment Day' } { 'title': '<NAME>' } { 'title': 'Toy Story 3' } { 'title': 'Snatch' } { 'title': 'American Psycho' } { 'title': 'The Social Network' } { 'title': 'Oldboy' } { 'title': '<NAME>\'<NAME> Day Off' } { 'title': '<NAME>' } { 'title': 'In Bruges' } { 'title': '<NAME>' } { 'title': 'Casablanca' } { 'title': 'City of God' } { 'title': 'Psycho' } { 'title': 'The Fifth Element' } { 'title': 'Seven Samurai' } { 'title': 'Taxi Driver' } { 'title': 'Monsters, Inc.' } { 'title': '28 Days Later' } { 'title': 'Requiem for a Dream' } { 'title': 'The Godfather: Part II' } { 'title': 'Hot Fuzz' } { 'title': 'Trainspotting' } { 'title': 'Amélie' } { 'title': 'Twelve Monkeys' } { 'title': 'Aliens' } { 'title': 'The Dark Knight Rises' } { 'title': 'Kiss Kiss Bang Bang' } { 'title': 'Lost in Translation' } { 'title': 'Chinatown' } { 'title': 'The Royal Tennenbaums' } { 'title': 'Rear Window' } { 'title': 'Jaws' } { 'title': 'Ocean\'s Eleven' } { 'title': 'Howl\'s Moving Castle' } { 'title': 'The Green Mile' } { 'title': 'Black Swan' } { 'title': 'Citizen Kane' } { 'title': 'Moonrise Kingdom' } { 'title': 'Looper' } { 'title': 'The Thing' } { 'title': 'The Breakfast Club' } { 'title': 'The Cabin in the Woods' } { 'title': 'L.A. Confidential' } { 'title': 'Scott Pilgrim Vs. the World' } { 'title': 'Finding Nemo' } { 'title': 'Boogie Nights' } { 'title': 'Superbad' } { 'title': 'Sin City' } { 'title': 'Fear and Loathing in Las Vegas' } { 'title': 'Indiana Jones and the Last Crusade' } { 'title': '<NAME>' } { 'title': 'To Kill a Mockingbird' } { 'title': 'Lawrence of Arabia' } { 'title': 'Being <NAME>' } { 'title': 'The Pianist' } { 'title': '<NAME>' } { 'title': 'Anchorman: The Legend of Ron <NAME>' } { 'title': '<NAME>' } { 'title': 'Raging Bull' } { 'title': 'Vertigo' } { 'title': 'Little Miss Sunshine' } { 'title': 'The Avengers' } { 'title': 'Butch Cassidy and the Sundance Kid' } { 'title': 'Dazed and Confused' } { 'title': 'Days of Summer' } { 'title': '<NAME> & the Chocolate Factory' } { 'title': 'Unforgiven' } { 'title': 'Fantastic Mr. Fox' } { 'title': 'Brazil' } { 'title': 'The Iron Giant' } { 'title': '<NAME>ira' } { 'title': 'The Terminator' } { 'title': 'Ghost Busters' } { 'title': 'This Is Spinal Tap' } { 'title': 'Gran Torino' } { 'title': 'Adaptation.' } { 'title': 'A Fistful of Dollars' } { 'title': 'Stand by Me' } { 'title': 'Apollo 13' } { 'title': 'Blazing Saddles' } { 'title': 'Amadeus' } { 'title': 'Kick-Ass' } { 'title': 'Rushmore' } { 'title': 'Life of Brian' } { 'title': 'Almost Famous' } { 'title': 'Network' } { 'title': 'Mulholland Drive' } { 'title': 'Star Trek' } { 'title': 'It\'s a Wonderful Life' } { 'title': 'Singin\' in the Rain' } { 'title': 'The Graduate' } { 'title': 'Cool Hand Luke' } { 'title': 'The Nightmare Before Christmas' } { 'title': 'Metropolis' } { 'title': '<NAME>' } { 'title': 'Zodiac' } { 'title': 'Crouching Tiger, Hidden Dragon' } { 'title': 'True Grit' } { 'title': 'Braveheart' } { 'title': 'Yo<NAME>' } { 'title': 'The Thin Red Line' } { 'title': 'Warrior' } { 'title': 'Blue Velvet' } { 'title': 'Primer' } { 'title': 'The Life Aquatic With <NAME>' } { 'title': 'Big Fish' } { 'title': 'Mr<NAME>. <NAME>es to Washington' } { 'title': 'Clerks' } { 'title': 'Rashomon' } { 'title': 'Once Upon a Time in the West' } { 'title': 'The Rocky Horror Picture Show' } { 'title': 'North by Northwest' } { 'title': 'Gangs of New York' } { 'title': 'Duck Soup' } { 'title': 'Grave of the Fireflies' } { 'title': 'M' } { 'title': 'E.T. the Extra-Terrestrial' } { 'title': 'The Blues Brothers' } { 'title': 'The Great Dictator' } { 'title': 'Galaxy Quest' } { 'title': 'Hotel Rwanda' } { 'title': 'Brick' } { 'title': 'The Assassination of <NAME> by the C<NAME>ard <NAME>' } { 'title': 'Z<NAME>' } { 'title': 'The Deer Hunter' } { 'title': '8 1/2' } { 'title': 'The Third Man' } { 'title': 'The Bridge on the River Kwai' } { 'title': 'The Lives of Others' } { 'title': 'Heat' } { 'title': 'The Seventh Seal' } { 'title': 'Kill Bill: Vol. 2' } { 'title': 'Synecdoche, New York' } { 'title': 'Stranger Than Fiction' } { 'title': 'Double Indemnity' } { 'title': 'On the Waterfront' } { 'title': 'Predator' } { 'title': 'Lucky Number Slevin' } { 'title': 'Catch Me If You Can' } { 'title': '<NAME>' } { 'title': 'Battle Royale' } { 'title': 'Robocop' } { 'title': 'How to Train Your Dragon' } { 'title': 'Dog Day Afternoon' } { 'title': 'Planet of the Apes' } { 'title': 'Nausicaä of the Valley of the Wind' } { 'title': 'Master and Commander: The Far Side of the World' } { 'title': 'City Lights' } { 'title': 'Paths of Glory' } { 'title': 'Brokeback Mountain' } { 'title': 'The Hobbit: An Unexpected Journey' } { 'title': 'The Wizard of Oz' } { 'title': 'Close Encounters of the Third Kind' } { 'title': 'The Wrestler' } { 'title': 'The Jerk' } { 'title': 'Slumdog Millionaire' } { 'title': 'Silver Linings Playbook' } { 'title': '<NAME>' } { 'title': 'Sunset Boulevard' } { 'title': 'Return of the Jedi' } { 'title': 'Ran' } { 'title': 'Collateral' } { 'title': 'Let the Right One in' } { 'title': 'The Sting' } { 'title': 'Tucker and Dale Vs. Evil' } { 'title': 'Some Like It Hot' } { 'title': 'Shutter Island' } { 'title': 'The Maltese Falcon' } { 'title': 'The Treasure of the Sierra Madre' } { 'title': 'Sunshine' } { 'title': 'Punch-Drunk Love' } { 'title': '<NAME>' } { 'title': 'Thank You for Smoking' } { 'title': 'Ghost in the Shell' } { 'title': '<NAME>' } { 'title': 'Ik<NAME>' } { 'title': 'Dawn of the Dead' } { 'title': 'The Hurt Locker' } ] # Snapshots from omdbapi pf = 'Title': 'Pulp Fiction' 'Year': '1994' 'Rated': 'R' 'Released': '14 Oct 1994' 'Runtime': '154 min' 'Genre': 'Crime, Drama' 'Director': '<NAME>' 'Writer': '<NAME> (stories), <NAME> (stories), <NAME>' 'Actors': '<NAME>, <NAME>, <NAME>, <NAME>' 'Plot': 'The lives of two mob hit men, a boxer, a gangster\'s wife, and a pair of diner bandits intertwine in four tales of violence and redemption.' 'Language': 'English, Spanish, French' 'Country': 'USA' 'Awards': 'Won 1 Oscar. Another 60 wins & 68 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/c_mfit,q_auto:best,w_1280/v1512202426/pulpFiction.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '8.9/10' } { 'Source': 'Rotten Tomatoes' 'Value': '94%' } { 'Source': 'Metacritic' 'Value': '94/100' } ] 'Metascore': '94' 'imdbRating': '8.9' 'imdbVotes': '1,471,678' 'imdbID': 'tt0110912' 'Type': 'movie' 'DVD': '19 May 1998' 'BoxOffice': 'N/A' 'Production': 'Miramax Films' 'Website': 'N/A' 'Response': 'True' fc = 'Title': 'Fight Club' 'Year': '1999' 'Rated': 'R' 'Released': '15 Oct 1999' 'Runtime': '139 min' 'Genre': 'Drama' 'Director': '<NAME>' 'Writer': '<NAME> (novel), <NAME> (screenplay)' 'Actors': '<NAME>, <NAME>, <NAME>, <NAME>' 'Plot': 'An insomniac office worker, looking for a way to change his life, crosses paths with a devil-may-care soap maker, forming an underground fight club that evolves into something much, much more.' 'Language': 'English' 'Country': 'USA, Germany' 'Awards': 'Nominated for 1 Oscar. Another 10 wins & 32 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/s--bD7uo-Gy--/c_imagga_scale,q_auto:best,w_1280/v1512202141/Fight-Club_ksipx1.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '8.8/10' } { 'Source': 'Rotten Tomatoes' 'Value': '79%' } { 'Source': 'Metacritic' 'Value': '66/100' } ] 'Metascore': '66' 'imdbRating': '8.8' 'imdbVotes': '1,508,138' 'imdbID': 'tt0137523' 'Type': 'movie' 'DVD': '06 Jun 2000' 'BoxOffice': 'N/A' 'Production': '20th Century Fox' 'Website': 'http://www.foxmovies.com/fightclub/' 'Response': 'True' tsr = 'Title': 'The Shawshank Redemption' 'Year': '1994' 'Rated': 'R' 'Released': '14 Oct 1994' 'Runtime': '142 min' 'Genre': 'Crime, Drama' 'Director': '<NAME>' 'Writer': '<NAME> (short story "<NAME> and <NAME>awsh<NAME> Rede<NAME>ion"), <NAME> (screenplay)' 'Actors': '<NAME>, <NAME>, <NAME>, <NAME>' 'Plot': 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.' 'Language': 'English' 'Country': 'USA' 'Awards': 'Nominated for 7 Oscars. Another 19 wins & 29 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/s--UQgrUWCP--/c_imagga_crop,h_720,q_jpegmini,w_1280/v1512201263/shawshankRedemption.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '9.3/10' } { 'Source': 'Rotten Tomatoes' 'Value': '91%' } { 'Source': 'Metacritic' 'Value': '80/100' } ] 'Metascore': '80' 'imdbRating': '9.3' 'imdbVotes': '1,874,788' 'imdbID': 'tt0111161' 'Type': 'movie' 'DVD': '27 Jan 1998' 'BoxOffice': 'N/A' 'Production': 'Columbia Pictures' 'Website': 'N/A' 'Response': 'True' tdk = 'Title': 'The Dark Knight' 'Year': '2008' 'Rated': 'PG-13' 'Released': '18 Jul 2008' 'Runtime': '152 min' 'Genre': 'Action, Crime, Drama' 'Director': '<NAME>' 'Writer': '<NAME> (screenplay), <NAME> (screenplay), <NAME> (story), <NAME> (story), <NAME> (characters)' 'Actors': '<NAME>, <NAME>, <NAME>, <NAME>' 'Plot': 'When the menace known as the Joker emerges from his mysterious past, he wreaks havoc and chaos on the people of Gotham, the Dark Knight must accept one of the greatest psychological and physical tests of his ability to fight injustice.' 'Language': 'English, Mandarin' 'Country': 'USA, UK' 'Awards': 'Won 2 Oscars. Another 151 wins & 154 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/c_lfill,h_720,q_auto:best,w_1280/v1512203105/theDarkKnight.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '9.0/10' } { 'Source': 'Rotten Tomatoes' 'Value': '94%' } { 'Source': 'Metacritic' 'Value': '82/100' } ] 'Metascore': '82' 'imdbRating': '9.0' 'imdbVotes': '1,848,050' 'imdbID': 'tt0468569' 'Type': 'movie' 'DVD': '09 Dec 2008' 'BoxOffice': '$533,316,061' 'Production': 'Warner Bros. Pictures/Legendary' 'Website': 'http://thedarkknight.warnerbros.com/' 'Response': 'True' ib = 'Title': 'Inglourious Basterds' 'Year': '2009' 'Rated': 'R' 'Released': '21 Aug 2009' 'Runtime': '153 min' 'Genre': 'Adventure, Drama, War' 'Director': '<NAME>, <NAME>' 'Writer': '<NAME>' 'Actors': '<NAME>, <NAME>, <NAME>, <NAME>' 'Plot': 'In Nazi-occupied France during World War II, a plan to assassinate Nazi leaders by a group of Jewish U.S. soldiers coincides with a theatre owner\'s vengeful plans for the same.' 'Language': 'English, German, French, Italian' 'Country': 'USA, Germany' 'Awards': 'Won 1 Oscar. Another 129 wins & 165 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/s--epexlNdl--/c_imagga_scale,h_720,q_auto:best,w_1280/v1512203671/inglouriousBasterds_koghsj.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '8.3/10' } { 'Source': 'Rotten Tomatoes' 'Value': '88%' } { 'Source': 'Metacritic' 'Value': '69/100' } ] 'Metascore': '69' 'imdbRating': '8.3' 'imdbVotes': '997,468' 'imdbID': 'tt0361748' 'Type': 'movie' 'DVD': '15 Dec 2009' 'BoxOffice': '$120,523,073' 'Production': 'The Weinstein Company' 'Website': 'http://www.inglouriousbasterds-movie.com/' 'Response': 'True' # Add Card Function numOfCards = 0 cards = [] cardSize = width: 355 height: 235 offset: 11 addCard = () -> tone = _.sample duotone card = new Layer width: cardSize.width height: cardSize.height x: Align.center midX: 0.5 y: numOfCards * (cardSize.height + cardSize.offset) name: 'card'+numOfCards parent: cardContainer borderRadius: 13 opacity: 0 scale: 0.8 blur: 12 backgroundColor: tone.toneOne poster = new Layer parent: card size: card.size blending: tone.blendOne opacity: 0.7 clip: true borderRadius: 13 grayscale: tone.greyscale contrast: tone.contrast after = new Layer parent: card size: card.size clip: true blending: tone.blendTwo backgroundColor: tone.toneTwo borderRadius: 13 if numOfCards is 0 poster.image = pf.Poster else if numOfCards is 1 poster.image = fc.Poster else if numOfCards is 2 poster.image = tsr.Poster else if numOfCards is 3 poster.image = tdk.Poster else next = numOfCards + 1 fetch = movies[next].title type = new TextLayer parent: card width: 209 fontSize: 32 x: Align.left +18 y: Align.top -24 color: 'white' fontFamily: '-apple-system' fontWeight: 700 text: movies[numOfCards].title opacity: 0 type.states = fadeIn: opacity: 1 y: Align.top +24 animationOptions: time: 0.15 delay: 0.05 numOfCards = numOfCards + 1 # http://www.omdbapi.com/?t=Pulp+Fiction&apikey=86718c42 cards.push(card) card.states = fadeIn: scale: 1 blur: 0 opacity: 1 y: card.y + 11 animationOptions: time: 0.5 card.animate('fadeIn') card.onAnimationEnd -> type.animate('fadeIn') # card.onTap -> # @.animate('done') # Force resize to match height with the contents of the container cardContainer.height = cardContainer.contentFrame().height + 90 * 2 if numOfCards > 4 flow.scroll.updateContent() flow.scroll.scrollToPoint(y: cardContainer.height, curve: Bezier.ease, time: 10) cardContainer = new Layer parent: scroll.content width: Screen.width height: Screen.height * 1.5 y: 140 backgroundColor: null # Flow Component flow = new FlowComponent backgroundColor: null parent: main index: -1 flow.showNext(cardContainer) flow.scroll.mouseWheelEnabled = true flow.scroll.contentInset = top: header.height flow.index = 2 offsetHeader = (point, withModifier) -> if withModifier is 'scroll' # print point header.y = Utils.modulate(point,[0,header.height],[point,-header.height],true) header.opacity = Utils.modulate(point,[0,70],[1,0],true) header.scale = Utils.modulate(point,[0,70],[1,0.9],true) else if withModifier is 'drag' # print point header.y = Utils.modulate(point,[140,0],[0,-header.height],true) header.opacity = Utils.modulate(point,[140,70],[1,0],true) header.scale = Utils.modulate(point,[140,70],[1,0.9],true) flow.scroll.on 'scroll', -> if flow.scroll.isDragging is false offsetHeader @.scrollPoint.y, 'scroll' else if flow.scroll.isDragging is true offsetHeader @.minY, 'drag' # Interactions button.placeBefore flow homebar.placeBefore flow button.states = over: opacity: 0.90 options: time: 0.50 curve: Spring out: opacity: 0.99 options: time: 0.50 curve: Spring # Button interactions button.y = Screen.height button.on 'mouseover', -> @.animate 'over' button.on 'mouseout', -> @.animate 'out' button.on 'tap', -> addCard() # Init i = null _.times 4, -> i += 1 Utils.delay 0.7 * i, -> addCard() if i > 3 Utils.delay 0.7 * i, -> button.animate y: Screen.height - (83+44) options: time: 0.50 curve: Spring
true
# Requirements { chroma } = require 'npm' Canvas.backgroundColor = 'black' textColor = (toneOne, toneTwo) -> vsWhite = chroma.contrast(toneOne, toneTwo) if vsWhite < 4.5 return '#FFF' else chroma(toneOne).saturate(0.6).hex() # Colors colors = [ { 'color1': '#FFFFFF' 'color2': '#6284FF' 'color3': '#FF0000' } { 'color1': '#52ACFF' 'color2': '#FFE32C' } { 'color1': '#FFE53B' 'color2': '#FF2525' } { 'color1': '#FAACA8' 'color2': '#DDD6F3' } { 'color1': '#21D4FD' 'color2': '#B721FF' } { 'color1': '#08AEEA' 'color2': '#2AF598' } { 'color1': '#FEE140' 'color2': '#FA709A' } { 'color1': '#8EC5FC' 'color2': '#E0C3FC' } { 'color1': '#FBAB7E' 'color2': '#F7CE68' } { 'color1': '#FF3CAC' 'color2': '#784BA0' 'color3': '#2B86C5' } { 'color1': '#D9AFD9' 'color2': '#97D9E1' } { 'color1': '#00DBDE' 'color2': '#FC00FF' } { 'color1': '#F4D03F' 'color2': '#16A085' } { 'color1': '#0093E9' 'color2': '#80D0C7' } { 'color1': '#74EBD5' 'color2': '#9FACE6' } { 'color1': '#FAD961' 'color2': '#F76B1C' } { 'color1': '#FA8BFF' 'color2': '#2BD2FF' 'color3': '#2BFF88' } { 'color1': '#FBDA61' 'color2': '#FF5ACD' } { 'color1': '#8BC6EC' 'color2': '#9599E2' } { 'color1': '#A9C9FF' 'color2': '#FFBBEC' } { 'color1': '#3EECAC' 'color2': '#EE74E1' } { 'color1': '#4158D0' 'color2': '#C850C0' 'color3': '#FFCC70' } { 'color1': '#85FFBD' 'color2': '#FFFB7D' } { 'color1': '#FFDEE9' 'color2': '#B5FFFC' } { 'color1': '#FF9A8B' 'color2': '#FF6A88' 'color3': '#FF99AC' } ] duotone = [ { 'toneOne': '#00ff36' 'blendOne': 'multiply' 'toneTwo': '#23278a' 'blendTwo': 'lighten' greyscale: 100 contrast: 100 } { 'toneOne': '#e41c2d' 'blendOne': 'multiply' 'toneTwo': '#1d3162' 'blendTwo': 'lighten' greyscale: 100 contrast: 140 } { 'toneOne': '#FCA300' 'blendOne': 'darken' 'toneTwo': '#e23241' 'blendTwo': 'lighten' greyscale: 100 contrast: 120 } { 'toneOne': '#FCA300' 'blendOne': 'darken' 'toneTwo': '#282581' 'blendTwo': 'lighten' greyscale: 100 contrast: 120 } ] # urlShot = 'https://api.dribbble.com/v1/shots/'+shotID+'?access_token='+access_token # # fetch(urlShot, method: 'get').then((response) -> # response.json() # .then (data) -> # movieTitle = null queryOMDB = 'http://www.omdbapi.com/?t='+movieTitle+'&apikey=86718c42' getMovie = (movieTitle) -> fetch(queryOMDB, method: 'get').then((response) -> response.json() .then (data) -> print data ) # .retro # background-color: #f1e3a0 # img # mix-blend-mode: darken # -webkit-filter: grayscale(100%) contrast(2) # filter: grayscale(100%) contrast(2) # &::after # background: linear-gradient(180deg, #f430a9, #f2e782) # mix-blend-mode: lighten # Data # Top Rated Movies on IMDB http://www.imdb.com/chart/top?sort=ir,desc&mode=simple&page=1 # Data # Movies from https://www.lists.design/ best = [ { rating: 99 title: 'Get Out' year: 2017 } { rating: 98 title: 'The Big Sick' year: 2017 } { rating: 92 title: 'PI:NAME:<NAME>END_PIonder Woman' year: 2017 } { rating: 92 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 100 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 93 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 93 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 93 title: 'War for the Planet of the Apes' year: 2017 } { rating: 92 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 92 title: 'Spider-Man: Homecoming' year: 2017 } { rating: 98 title: 'I Am Not Your Negro' year: 2017 } { rating: 97 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 98 title: 'Call Me by Your Name' year: 2017 } { rating: 95 title: 'The Florida Project' year: 2017 } { rating: 93 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 92 title: 'Hidden Figures' year: 2017 } { rating: 96 title: 'The Salesman (Forushande)' year: 2017 } { rating: 91 title: 'The Lego Batman Movie' year: 2017 } { rating: 94 title: 'Three Billboards Outside Ebbing, Missouri' year: 2017 } { rating: 98 title: 'My Life as a Zucchini (Ma vie de courgette)' year: 2017 } { rating: 99 title: 'God\'s Own Country' year: 2017 } { rating: 87 title: 'Blade Runner 2049' year: 2017 } { rating: 100 title: 'Faces Places (Visages, villages)' year: 2017 } { rating: 99 title: 'City of Ghosts' year: 2017 } { rating: 100 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 98 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 96 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 97 title: 'After the Storm (Umi yori mo mada fukaku)' year: 2017 } { rating: 99 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 99 title: 'Whose Streets?' year: 2017 } { rating: 98 title: 'Lucky' year: 2017 } { rating: 100 title: 'Bright Lights: Starring PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI' year: 2017 } { rating: 100 title: 'The Happiest Day in the Life of PI:NAME:<NAME>END_PI (Hymyilevä mies)' year: 2017 } { rating: 95 title: 'The Red Turtle (La tortue rouge)' year: 2017 } { rating: 96 title: 'Stronger' year: 2017 } { rating: 100 title: 'The Work' year: 2017 } { rating: 100 title: 'Dawson City: Frozen Time' year: 2017 } { rating: 97 title: 'Your Name. (PI:NAME:<NAME>END_PI.)' year: 2017 } { rating: 96 title: 'The Disaster Artist' year: 2017 } { rating: 98 title: 'BPM (Beats Per Minute) (120 battements par minute)' year: 2017 } { rating: 95 title: 'Graduation (Bacalaureat)' year: 2017 } { rating: 93 title: 'I, PI:NAME:<NAME>END_PI' year: 2017 } { rating: 98 title: 'In This Corner of the World (Kono sekai no katasumi ni)' year: 2017 } { rating: 97 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 95 title: 'The Shape of Water' year: 2017 } { rating: 90 title: 'A Ghost Story' year: 2017 } { rating: 90 title: 'PI:NAME:<NAME>END_PI: Chapter 2' year: 2017 } { rating: 98 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 98 title: 'PI:NAME:<NAME>END_PI' year: 2017 } { rating: 93 title: 'The Meyerowitz Stories (New and Selected)' year: 2017 } ] movies = [ { 'title': 'Pulp Fiction' } { 'title': 'Fight Club' } { 'title': 'The Shawshank Redemption' } { 'title': 'The Dark Knight' } { 'title': 'Inglourious Basterds' } { 'title': 'Inception' } { 'title': 'The Matrix' } { 'title': 'The Empire Strikes Back' } { 'title': 'The Lord of the Rings: The Fellowship of the Ring' } { 'title': 'Toy Story' } { 'title': 'The Big Lebowski' } { 'title': 'Django Unchained' } { 'title': 'The Lord of the Rings: The Return of the King' } { 'title': 'The Departed' } { 'title': 'Memento' } { 'title': 'The Godfather' } { 'title': 'Reservoir Dogs' } { 'title': 'Saving Private Ryan' } { 'title': 'PI:NAME:<NAME>END_PIrest Gump' } { 'title': 'Monty Python and the Holy Grail' } { 'title': 'Se7en' } { 'title': 'Back to the Future' } { 'title': 'Goodfellas' } { 'title': 'The Prestige' } { 'title': 'Shaun of the Dead' } { 'title': 'Alien' } { 'title': 'The Silence of the Lambs' } { 'title': 'The Lord of the Rings: The Two Towers' } { 'title': 'Spirited Away' } { 'title': 'The Good, the Bad and the Ugly' } { 'title': 'Eternal Sunshine of the Spotless Mind' } { 'title': 'Raiders of the Lost Ark' } { 'title': '2001: A Space Odyssey' } { 'title': 'Dr. Strangelove Or: How I Learned to Stop Worrying and Love the Bomb' } { 'title': 'Blade Runner' } { 'title': 'The Lion King' } { 'title': 'One Flew Over the Cuckoo\'s Nest' } { 'title': 'There Will Be Blood' } { 'title': 'The Shining' } { 'title': 'The Truman Show' } { 'title': 'A Clockwork Orange' } { 'title': 'Star Wars' } { 'title': 'District 9' } { 'title': 'Up' } { 'title': 'Office Space' } { 'title': '12 Angry Men' } { 'title': 'Pan\'s Labyrinth' } { 'title': 'The Usual Suspects' } { 'title': 'Jurassic Park' } { 'title': 'V for Vendetta' } { 'title': 'The Princess Bride' } { 'title': 'No Country for Old Men' } { 'title': 'Full Metal Jacket' } { 'title': 'Schindler\'s List' } { 'title': 'Good Will Hunting' } { 'title': 'Children of Men' } { 'title': 'Kill Bill: Vol. 1' } { 'title': 'WALL·E' } { 'title': 'American History X' } { 'title': 'Die Hard' } { 'title': 'Drive' } { 'title': 'Moon' } { 'title': 'Groundhog Day' } { 'title': 'Batman Begins' } { 'title': 'Fargo' } { 'title': 'The Incredibles' } { 'title': 'O Brother, Where Art Thou' } { 'title': 'Gladiator' } { 'title': 'Airplane!' } { 'title': 'Apocalypse Now' } { 'title': 'American Beauty' } { 'title': 'Terminator 2: Judgment Day' } { 'title': 'PI:NAME:<NAME>END_PI' } { 'title': 'Toy Story 3' } { 'title': 'Snatch' } { 'title': 'American Psycho' } { 'title': 'The Social Network' } { 'title': 'Oldboy' } { 'title': 'PI:NAME:<NAME>END_PI\'PI:NAME:<NAME>END_PI Day Off' } { 'title': 'PI:NAME:<NAME>END_PI' } { 'title': 'In Bruges' } { 'title': 'PI:NAME:<NAME>END_PI' } { 'title': 'Casablanca' } { 'title': 'City of God' } { 'title': 'Psycho' } { 'title': 'The Fifth Element' } { 'title': 'Seven Samurai' } { 'title': 'Taxi Driver' } { 'title': 'Monsters, Inc.' } { 'title': '28 Days Later' } { 'title': 'Requiem for a Dream' } { 'title': 'The Godfather: Part II' } { 'title': 'Hot Fuzz' } { 'title': 'Trainspotting' } { 'title': 'Amélie' } { 'title': 'Twelve Monkeys' } { 'title': 'Aliens' } { 'title': 'The Dark Knight Rises' } { 'title': 'Kiss Kiss Bang Bang' } { 'title': 'Lost in Translation' } { 'title': 'Chinatown' } { 'title': 'The Royal Tennenbaums' } { 'title': 'Rear Window' } { 'title': 'Jaws' } { 'title': 'Ocean\'s Eleven' } { 'title': 'Howl\'s Moving Castle' } { 'title': 'The Green Mile' } { 'title': 'Black Swan' } { 'title': 'Citizen Kane' } { 'title': 'Moonrise Kingdom' } { 'title': 'Looper' } { 'title': 'The Thing' } { 'title': 'The Breakfast Club' } { 'title': 'The Cabin in the Woods' } { 'title': 'L.A. Confidential' } { 'title': 'Scott Pilgrim Vs. the World' } { 'title': 'Finding Nemo' } { 'title': 'Boogie Nights' } { 'title': 'Superbad' } { 'title': 'Sin City' } { 'title': 'Fear and Loathing in Las Vegas' } { 'title': 'Indiana Jones and the Last Crusade' } { 'title': 'PI:NAME:<NAME>END_PI' } { 'title': 'To Kill a Mockingbird' } { 'title': 'Lawrence of Arabia' } { 'title': 'Being PI:NAME:<NAME>END_PI' } { 'title': 'The Pianist' } { 'title': 'PI:NAME:<NAME>END_PI' } { 'title': 'Anchorman: The Legend of Ron PI:NAME:<NAME>END_PI' } { 'title': 'PI:NAME:<NAME>END_PI' } { 'title': 'Raging Bull' } { 'title': 'Vertigo' } { 'title': 'Little Miss Sunshine' } { 'title': 'The Avengers' } { 'title': 'Butch Cassidy and the Sundance Kid' } { 'title': 'Dazed and Confused' } { 'title': 'Days of Summer' } { 'title': 'PI:NAME:<NAME>END_PI & the Chocolate Factory' } { 'title': 'Unforgiven' } { 'title': 'Fantastic Mr. Fox' } { 'title': 'Brazil' } { 'title': 'The Iron Giant' } { 'title': 'PI:NAME:<NAME>END_PIira' } { 'title': 'The Terminator' } { 'title': 'Ghost Busters' } { 'title': 'This Is Spinal Tap' } { 'title': 'Gran Torino' } { 'title': 'Adaptation.' } { 'title': 'A Fistful of Dollars' } { 'title': 'Stand by Me' } { 'title': 'Apollo 13' } { 'title': 'Blazing Saddles' } { 'title': 'Amadeus' } { 'title': 'Kick-Ass' } { 'title': 'Rushmore' } { 'title': 'Life of Brian' } { 'title': 'Almost Famous' } { 'title': 'Network' } { 'title': 'Mulholland Drive' } { 'title': 'Star Trek' } { 'title': 'It\'s a Wonderful Life' } { 'title': 'Singin\' in the Rain' } { 'title': 'The Graduate' } { 'title': 'Cool Hand Luke' } { 'title': 'The Nightmare Before Christmas' } { 'title': 'Metropolis' } { 'title': 'PI:NAME:<NAME>END_PI' } { 'title': 'Zodiac' } { 'title': 'Crouching Tiger, Hidden Dragon' } { 'title': 'True Grit' } { 'title': 'Braveheart' } { 'title': 'YoPI:NAME:<NAME>END_PI' } { 'title': 'The Thin Red Line' } { 'title': 'Warrior' } { 'title': 'Blue Velvet' } { 'title': 'Primer' } { 'title': 'The Life Aquatic With PI:NAME:<NAME>END_PI' } { 'title': 'Big Fish' } { 'title': 'MrPI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PIes to Washington' } { 'title': 'Clerks' } { 'title': 'Rashomon' } { 'title': 'Once Upon a Time in the West' } { 'title': 'The Rocky Horror Picture Show' } { 'title': 'North by Northwest' } { 'title': 'Gangs of New York' } { 'title': 'Duck Soup' } { 'title': 'Grave of the Fireflies' } { 'title': 'M' } { 'title': 'E.T. the Extra-Terrestrial' } { 'title': 'The Blues Brothers' } { 'title': 'The Great Dictator' } { 'title': 'Galaxy Quest' } { 'title': 'Hotel Rwanda' } { 'title': 'Brick' } { 'title': 'The Assassination of PI:NAME:<NAME>END_PI by the CPI:NAME:<NAME>END_PIard PI:NAME:<NAME>END_PI' } { 'title': 'ZPI:NAME:<NAME>END_PI' } { 'title': 'The Deer Hunter' } { 'title': '8 1/2' } { 'title': 'The Third Man' } { 'title': 'The Bridge on the River Kwai' } { 'title': 'The Lives of Others' } { 'title': 'Heat' } { 'title': 'The Seventh Seal' } { 'title': 'Kill Bill: Vol. 2' } { 'title': 'Synecdoche, New York' } { 'title': 'Stranger Than Fiction' } { 'title': 'Double Indemnity' } { 'title': 'On the Waterfront' } { 'title': 'Predator' } { 'title': 'Lucky Number Slevin' } { 'title': 'Catch Me If You Can' } { 'title': 'PI:NAME:<NAME>END_PI' } { 'title': 'Battle Royale' } { 'title': 'Robocop' } { 'title': 'How to Train Your Dragon' } { 'title': 'Dog Day Afternoon' } { 'title': 'Planet of the Apes' } { 'title': 'Nausicaä of the Valley of the Wind' } { 'title': 'Master and Commander: The Far Side of the World' } { 'title': 'City Lights' } { 'title': 'Paths of Glory' } { 'title': 'Brokeback Mountain' } { 'title': 'The Hobbit: An Unexpected Journey' } { 'title': 'The Wizard of Oz' } { 'title': 'Close Encounters of the Third Kind' } { 'title': 'The Wrestler' } { 'title': 'The Jerk' } { 'title': 'Slumdog Millionaire' } { 'title': 'Silver Linings Playbook' } { 'title': 'PI:NAME:<NAME>END_PI' } { 'title': 'Sunset Boulevard' } { 'title': 'Return of the Jedi' } { 'title': 'Ran' } { 'title': 'Collateral' } { 'title': 'Let the Right One in' } { 'title': 'The Sting' } { 'title': 'Tucker and Dale Vs. Evil' } { 'title': 'Some Like It Hot' } { 'title': 'Shutter Island' } { 'title': 'The Maltese Falcon' } { 'title': 'The Treasure of the Sierra Madre' } { 'title': 'Sunshine' } { 'title': 'Punch-Drunk Love' } { 'title': 'PI:NAME:<NAME>END_PI' } { 'title': 'Thank You for Smoking' } { 'title': 'Ghost in the Shell' } { 'title': 'PI:NAME:<NAME>END_PI' } { 'title': 'IkPI:NAME:<NAME>END_PI' } { 'title': 'Dawn of the Dead' } { 'title': 'The Hurt Locker' } ] # Snapshots from omdbapi pf = 'Title': 'Pulp Fiction' 'Year': '1994' 'Rated': 'R' 'Released': '14 Oct 1994' 'Runtime': '154 min' 'Genre': 'Crime, Drama' 'Director': 'PI:NAME:<NAME>END_PI' 'Writer': 'PI:NAME:<NAME>END_PI (stories), PI:NAME:<NAME>END_PI (stories), PI:NAME:<NAME>END_PI' 'Actors': 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI' 'Plot': 'The lives of two mob hit men, a boxer, a gangster\'s wife, and a pair of diner bandits intertwine in four tales of violence and redemption.' 'Language': 'English, Spanish, French' 'Country': 'USA' 'Awards': 'Won 1 Oscar. Another 60 wins & 68 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/c_mfit,q_auto:best,w_1280/v1512202426/pulpFiction.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '8.9/10' } { 'Source': 'Rotten Tomatoes' 'Value': '94%' } { 'Source': 'Metacritic' 'Value': '94/100' } ] 'Metascore': '94' 'imdbRating': '8.9' 'imdbVotes': '1,471,678' 'imdbID': 'tt0110912' 'Type': 'movie' 'DVD': '19 May 1998' 'BoxOffice': 'N/A' 'Production': 'Miramax Films' 'Website': 'N/A' 'Response': 'True' fc = 'Title': 'Fight Club' 'Year': '1999' 'Rated': 'R' 'Released': '15 Oct 1999' 'Runtime': '139 min' 'Genre': 'Drama' 'Director': 'PI:NAME:<NAME>END_PI' 'Writer': 'PI:NAME:<NAME>END_PI (novel), PI:NAME:<NAME>END_PI (screenplay)' 'Actors': 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI' 'Plot': 'An insomniac office worker, looking for a way to change his life, crosses paths with a devil-may-care soap maker, forming an underground fight club that evolves into something much, much more.' 'Language': 'English' 'Country': 'USA, Germany' 'Awards': 'Nominated for 1 Oscar. Another 10 wins & 32 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/s--bD7uo-Gy--/c_imagga_scale,q_auto:best,w_1280/v1512202141/Fight-Club_ksipx1.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '8.8/10' } { 'Source': 'Rotten Tomatoes' 'Value': '79%' } { 'Source': 'Metacritic' 'Value': '66/100' } ] 'Metascore': '66' 'imdbRating': '8.8' 'imdbVotes': '1,508,138' 'imdbID': 'tt0137523' 'Type': 'movie' 'DVD': '06 Jun 2000' 'BoxOffice': 'N/A' 'Production': '20th Century Fox' 'Website': 'http://www.foxmovies.com/fightclub/' 'Response': 'True' tsr = 'Title': 'The Shawshank Redemption' 'Year': '1994' 'Rated': 'R' 'Released': '14 Oct 1994' 'Runtime': '142 min' 'Genre': 'Crime, Drama' 'Director': 'PI:NAME:<NAME>END_PI' 'Writer': 'PI:NAME:<NAME>END_PI (short story "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PIawshPI:NAME:<NAME>END_PI RedePI:NAME:<NAME>END_PIion"), PI:NAME:<NAME>END_PI (screenplay)' 'Actors': 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI' 'Plot': 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.' 'Language': 'English' 'Country': 'USA' 'Awards': 'Nominated for 7 Oscars. Another 19 wins & 29 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/s--UQgrUWCP--/c_imagga_crop,h_720,q_jpegmini,w_1280/v1512201263/shawshankRedemption.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '9.3/10' } { 'Source': 'Rotten Tomatoes' 'Value': '91%' } { 'Source': 'Metacritic' 'Value': '80/100' } ] 'Metascore': '80' 'imdbRating': '9.3' 'imdbVotes': '1,874,788' 'imdbID': 'tt0111161' 'Type': 'movie' 'DVD': '27 Jan 1998' 'BoxOffice': 'N/A' 'Production': 'Columbia Pictures' 'Website': 'N/A' 'Response': 'True' tdk = 'Title': 'The Dark Knight' 'Year': '2008' 'Rated': 'PG-13' 'Released': '18 Jul 2008' 'Runtime': '152 min' 'Genre': 'Action, Crime, Drama' 'Director': 'PI:NAME:<NAME>END_PI' 'Writer': 'PI:NAME:<NAME>END_PI (screenplay), PI:NAME:<NAME>END_PI (screenplay), PI:NAME:<NAME>END_PI (story), PI:NAME:<NAME>END_PI (story), PI:NAME:<NAME>END_PI (characters)' 'Actors': 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI' 'Plot': 'When the menace known as the Joker emerges from his mysterious past, he wreaks havoc and chaos on the people of Gotham, the Dark Knight must accept one of the greatest psychological and physical tests of his ability to fight injustice.' 'Language': 'English, Mandarin' 'Country': 'USA, UK' 'Awards': 'Won 2 Oscars. Another 151 wins & 154 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/c_lfill,h_720,q_auto:best,w_1280/v1512203105/theDarkKnight.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '9.0/10' } { 'Source': 'Rotten Tomatoes' 'Value': '94%' } { 'Source': 'Metacritic' 'Value': '82/100' } ] 'Metascore': '82' 'imdbRating': '9.0' 'imdbVotes': '1,848,050' 'imdbID': 'tt0468569' 'Type': 'movie' 'DVD': '09 Dec 2008' 'BoxOffice': '$533,316,061' 'Production': 'Warner Bros. Pictures/Legendary' 'Website': 'http://thedarkknight.warnerbros.com/' 'Response': 'True' ib = 'Title': 'Inglourious Basterds' 'Year': '2009' 'Rated': 'R' 'Released': '21 Aug 2009' 'Runtime': '153 min' 'Genre': 'Adventure, Drama, War' 'Director': 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI' 'Writer': 'PI:NAME:<NAME>END_PI' 'Actors': 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI' 'Plot': 'In Nazi-occupied France during World War II, a plan to assassinate Nazi leaders by a group of Jewish U.S. soldiers coincides with a theatre owner\'s vengeful plans for the same.' 'Language': 'English, German, French, Italian' 'Country': 'USA, Germany' 'Awards': 'Won 1 Oscar. Another 129 wins & 165 nominations.' 'Poster': 'http://res.cloudinary.com/pixelbeat/image/upload/s--epexlNdl--/c_imagga_scale,h_720,q_auto:best,w_1280/v1512203671/inglouriousBasterds_koghsj.jpg' 'Ratings': [ { 'Source': 'Internet Movie Database' 'Value': '8.3/10' } { 'Source': 'Rotten Tomatoes' 'Value': '88%' } { 'Source': 'Metacritic' 'Value': '69/100' } ] 'Metascore': '69' 'imdbRating': '8.3' 'imdbVotes': '997,468' 'imdbID': 'tt0361748' 'Type': 'movie' 'DVD': '15 Dec 2009' 'BoxOffice': '$120,523,073' 'Production': 'The Weinstein Company' 'Website': 'http://www.inglouriousbasterds-movie.com/' 'Response': 'True' # Add Card Function numOfCards = 0 cards = [] cardSize = width: 355 height: 235 offset: 11 addCard = () -> tone = _.sample duotone card = new Layer width: cardSize.width height: cardSize.height x: Align.center midX: 0.5 y: numOfCards * (cardSize.height + cardSize.offset) name: 'card'+numOfCards parent: cardContainer borderRadius: 13 opacity: 0 scale: 0.8 blur: 12 backgroundColor: tone.toneOne poster = new Layer parent: card size: card.size blending: tone.blendOne opacity: 0.7 clip: true borderRadius: 13 grayscale: tone.greyscale contrast: tone.contrast after = new Layer parent: card size: card.size clip: true blending: tone.blendTwo backgroundColor: tone.toneTwo borderRadius: 13 if numOfCards is 0 poster.image = pf.Poster else if numOfCards is 1 poster.image = fc.Poster else if numOfCards is 2 poster.image = tsr.Poster else if numOfCards is 3 poster.image = tdk.Poster else next = numOfCards + 1 fetch = movies[next].title type = new TextLayer parent: card width: 209 fontSize: 32 x: Align.left +18 y: Align.top -24 color: 'white' fontFamily: '-apple-system' fontWeight: 700 text: movies[numOfCards].title opacity: 0 type.states = fadeIn: opacity: 1 y: Align.top +24 animationOptions: time: 0.15 delay: 0.05 numOfCards = numOfCards + 1 # http://www.omdbapi.com/?t=Pulp+Fiction&apikey=86718c42 cards.push(card) card.states = fadeIn: scale: 1 blur: 0 opacity: 1 y: card.y + 11 animationOptions: time: 0.5 card.animate('fadeIn') card.onAnimationEnd -> type.animate('fadeIn') # card.onTap -> # @.animate('done') # Force resize to match height with the contents of the container cardContainer.height = cardContainer.contentFrame().height + 90 * 2 if numOfCards > 4 flow.scroll.updateContent() flow.scroll.scrollToPoint(y: cardContainer.height, curve: Bezier.ease, time: 10) cardContainer = new Layer parent: scroll.content width: Screen.width height: Screen.height * 1.5 y: 140 backgroundColor: null # Flow Component flow = new FlowComponent backgroundColor: null parent: main index: -1 flow.showNext(cardContainer) flow.scroll.mouseWheelEnabled = true flow.scroll.contentInset = top: header.height flow.index = 2 offsetHeader = (point, withModifier) -> if withModifier is 'scroll' # print point header.y = Utils.modulate(point,[0,header.height],[point,-header.height],true) header.opacity = Utils.modulate(point,[0,70],[1,0],true) header.scale = Utils.modulate(point,[0,70],[1,0.9],true) else if withModifier is 'drag' # print point header.y = Utils.modulate(point,[140,0],[0,-header.height],true) header.opacity = Utils.modulate(point,[140,70],[1,0],true) header.scale = Utils.modulate(point,[140,70],[1,0.9],true) flow.scroll.on 'scroll', -> if flow.scroll.isDragging is false offsetHeader @.scrollPoint.y, 'scroll' else if flow.scroll.isDragging is true offsetHeader @.minY, 'drag' # Interactions button.placeBefore flow homebar.placeBefore flow button.states = over: opacity: 0.90 options: time: 0.50 curve: Spring out: opacity: 0.99 options: time: 0.50 curve: Spring # Button interactions button.y = Screen.height button.on 'mouseover', -> @.animate 'over' button.on 'mouseout', -> @.animate 'out' button.on 'tap', -> addCard() # Init i = null _.times 4, -> i += 1 Utils.delay 0.7 * i, -> addCard() if i > 3 Utils.delay 0.7 * i, -> button.animate y: Screen.height - (83+44) options: time: 0.50 curve: Spring
[ { "context": "email) ->\n doc =\n email: email\n password: '12345678'\n profile:\n first_name: faker.name.firstN", "end": 5231, "score": 0.9992924928665161, "start": 5223, "tag": "PASSWORD", "value": "12345678" }, { "context": "one, email) ->\n Meteor.loginWithPasswor...
app_tests/client/yield.app-tests.coffee
Phaze1D/SA-Units
0
faker = require 'faker' { chai, assert, expect } = require 'meteor/practicalmeteor:chai' { Meteor } = require 'meteor/meteor' { Accounts } = require 'meteor/accounts-base' { resetDatabase } = require 'meteor/xolvio:cleaner' { Random } = require 'meteor/random' { _ } = require 'meteor/underscore' UnitModule = require '../../imports/api/collections/units/units.coffee' YieldModule = require '../../imports/api/collections/yields/yields.coffee' OrganizationModule = require '../../imports/api/collections/organizations/organizations.coffee' UMethods = require '../../imports/api/collections/units/methods.coffee' OMethods = require '../../imports/api/collections/organizations/methods.coffee' IMethods = require '../../imports/api/collections/ingredients/methods.coffee' { inviteUser } = require '../../imports/api/collections/users/methods.coffee' { insert update } = require '../../imports/api/collections/yields/methods.coffee' organizationIDs = [] yieldIDS = [] ingredientIDS = [] subHandler = "" xdescribe 'Yield Full App Test Client', () -> before( (done) -> Meteor.logout( (err) -> done() ) ) describe "Yield Insert", -> it "login", (done) -> expect(Meteor.user()).to.not.exist createUser(done, faker.internet.email()) it 'create organization', (done) -> createOrgan(done, organizationIDs) it "create ingredient", (done) -> createIngredient(done, 0) it 'Subscribe to ', (done) -> callbacks = onStop: (err) -> onReady: () -> done() Meteor.subscribe("organizations", callbacks) it "Invalid Unit id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[0] organization_id: "nonn" organization_id = organizationIDs[0] insert.call { organization_id, yield_doc } , (err, res) -> expect(err).to.have.property('error', 'validation-error') done() it "Non exisent unit id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[0] unit_id: "andflskf" organization_id: "non" organization_id = organizationIDs[0] insert.call {organization_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it 'create organization', (done) -> createOrgan(done, organizationIDs) it 'Subscribe to ', (done) -> callbacks = onStop: (err) -> onReady: () -> done() subHandler = Meteor.subscribe('yields', organizationIDs[1], callbacks) unit1d = "" it "create unit", (done) -> unit_doc = name: faker.company.companyName() amount: 12 organization_id: organizationIDs[1] organization_id = organizationIDs[1] UMethods.insert.call {organization_id, unit_doc}, (err, res) -> unit1d = res done() it "Exisent but not in organization unit_id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[0] unit_id: unit1d organization_id: organizationIDs[0] organization_id = organizationIDs[0] insert.call {organization_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it "create ingredient", (done) -> createIngredient(done, 1) it "Valid insert", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[1] unit_id: unit1d organization_id: organizationIDs[1] organization_id = organizationIDs[1] insert.call {organization_id, yield_doc} , (err, res) -> expect(err).to.not.exist expect(YieldModule.Yields.findOne().amount).to.equal(0) yieldIDS.push res done() describe "Yield Update", -> it "Invalid organization id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 organization_id = "noo" yield_id = "NONO" update.call {organization_id, yield_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it "Valid yield id but not in organization", (done) -> yield_doc = name: faker.company.companyName() organization_id = organizationIDs[0] yield_id = yieldIDS[0] update.call {organization_id, yield_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it "Valid update", (done) -> passname = YieldModule.Yields.findOne().name yield_doc = name: faker.company.companyName() amount: 21.21 organization_id = organizationIDs[1] yield_id = yieldIDS[0] update.call {organization_id, yield_id, yield_doc} , (err, res) -> expect(YieldModule.Yields.findOne().name).to.not.equal(passname) expect(YieldModule.Yields.findOne().amount).to.equal(0) done() createUser = (done, email) -> doc = email: email password: '12345678' profile: first_name: faker.name.firstName() last_name: faker.name.lastName() Accounts.createUser doc, (error) -> expect(error).to.not.exist done() login = (done, email) -> Meteor.loginWithPassword email, '12345678', (err) -> done() logout = (done) -> Meteor.logout( (err) -> done() ) createOrgan = (done) -> organ_doc = name: faker.company.companyName() email: faker.internet.email() OMethods.insert.call organ_doc, (err, res) -> organizationIDs.push res expect(err).to.not.exist done() createIngredient = (done, i) -> ingredient_doc = name: faker.name.firstName() measurement_unit: 'kg' organization_id: organizationIDs[i] IMethods.insert.call {ingredient_doc}, (err, res) -> throw err if err? ingredientIDS.push res done() inviteUse = (done, email) -> invited_user_doc = emails: [ address: email ] profile: first_name: faker.name.firstName() organization_id = organizationID permission = owner: false viewer: false expenses_manager: false sells_manager: false units_manager: false inventories_manager: true users_manager: false inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) -> done()
92452
faker = require 'faker' { chai, assert, expect } = require 'meteor/practicalmeteor:chai' { Meteor } = require 'meteor/meteor' { Accounts } = require 'meteor/accounts-base' { resetDatabase } = require 'meteor/xolvio:cleaner' { Random } = require 'meteor/random' { _ } = require 'meteor/underscore' UnitModule = require '../../imports/api/collections/units/units.coffee' YieldModule = require '../../imports/api/collections/yields/yields.coffee' OrganizationModule = require '../../imports/api/collections/organizations/organizations.coffee' UMethods = require '../../imports/api/collections/units/methods.coffee' OMethods = require '../../imports/api/collections/organizations/methods.coffee' IMethods = require '../../imports/api/collections/ingredients/methods.coffee' { inviteUser } = require '../../imports/api/collections/users/methods.coffee' { insert update } = require '../../imports/api/collections/yields/methods.coffee' organizationIDs = [] yieldIDS = [] ingredientIDS = [] subHandler = "" xdescribe 'Yield Full App Test Client', () -> before( (done) -> Meteor.logout( (err) -> done() ) ) describe "Yield Insert", -> it "login", (done) -> expect(Meteor.user()).to.not.exist createUser(done, faker.internet.email()) it 'create organization', (done) -> createOrgan(done, organizationIDs) it "create ingredient", (done) -> createIngredient(done, 0) it 'Subscribe to ', (done) -> callbacks = onStop: (err) -> onReady: () -> done() Meteor.subscribe("organizations", callbacks) it "Invalid Unit id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[0] organization_id: "nonn" organization_id = organizationIDs[0] insert.call { organization_id, yield_doc } , (err, res) -> expect(err).to.have.property('error', 'validation-error') done() it "Non exisent unit id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[0] unit_id: "andflskf" organization_id: "non" organization_id = organizationIDs[0] insert.call {organization_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it 'create organization', (done) -> createOrgan(done, organizationIDs) it 'Subscribe to ', (done) -> callbacks = onStop: (err) -> onReady: () -> done() subHandler = Meteor.subscribe('yields', organizationIDs[1], callbacks) unit1d = "" it "create unit", (done) -> unit_doc = name: faker.company.companyName() amount: 12 organization_id: organizationIDs[1] organization_id = organizationIDs[1] UMethods.insert.call {organization_id, unit_doc}, (err, res) -> unit1d = res done() it "Exisent but not in organization unit_id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[0] unit_id: unit1d organization_id: organizationIDs[0] organization_id = organizationIDs[0] insert.call {organization_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it "create ingredient", (done) -> createIngredient(done, 1) it "Valid insert", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[1] unit_id: unit1d organization_id: organizationIDs[1] organization_id = organizationIDs[1] insert.call {organization_id, yield_doc} , (err, res) -> expect(err).to.not.exist expect(YieldModule.Yields.findOne().amount).to.equal(0) yieldIDS.push res done() describe "Yield Update", -> it "Invalid organization id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 organization_id = "noo" yield_id = "NONO" update.call {organization_id, yield_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it "Valid yield id but not in organization", (done) -> yield_doc = name: faker.company.companyName() organization_id = organizationIDs[0] yield_id = yieldIDS[0] update.call {organization_id, yield_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it "Valid update", (done) -> passname = YieldModule.Yields.findOne().name yield_doc = name: faker.company.companyName() amount: 21.21 organization_id = organizationIDs[1] yield_id = yieldIDS[0] update.call {organization_id, yield_id, yield_doc} , (err, res) -> expect(YieldModule.Yields.findOne().name).to.not.equal(passname) expect(YieldModule.Yields.findOne().amount).to.equal(0) done() createUser = (done, email) -> doc = email: email password: '<PASSWORD>' profile: first_name: faker.name.firstName() last_name: faker.name.lastName() Accounts.createUser doc, (error) -> expect(error).to.not.exist done() login = (done, email) -> Meteor.loginWithPassword email, '<PASSWORD>', (err) -> done() logout = (done) -> Meteor.logout( (err) -> done() ) createOrgan = (done) -> organ_doc = name: faker.company.companyName() email: faker.internet.email() OMethods.insert.call organ_doc, (err, res) -> organizationIDs.push res expect(err).to.not.exist done() createIngredient = (done, i) -> ingredient_doc = name: faker.name.firstName() measurement_unit: 'kg' organization_id: organizationIDs[i] IMethods.insert.call {ingredient_doc}, (err, res) -> throw err if err? ingredientIDS.push res done() inviteUse = (done, email) -> invited_user_doc = emails: [ address: email ] profile: first_name: faker.name.firstName() organization_id = organizationID permission = owner: false viewer: false expenses_manager: false sells_manager: false units_manager: false inventories_manager: true users_manager: false inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) -> done()
true
faker = require 'faker' { chai, assert, expect } = require 'meteor/practicalmeteor:chai' { Meteor } = require 'meteor/meteor' { Accounts } = require 'meteor/accounts-base' { resetDatabase } = require 'meteor/xolvio:cleaner' { Random } = require 'meteor/random' { _ } = require 'meteor/underscore' UnitModule = require '../../imports/api/collections/units/units.coffee' YieldModule = require '../../imports/api/collections/yields/yields.coffee' OrganizationModule = require '../../imports/api/collections/organizations/organizations.coffee' UMethods = require '../../imports/api/collections/units/methods.coffee' OMethods = require '../../imports/api/collections/organizations/methods.coffee' IMethods = require '../../imports/api/collections/ingredients/methods.coffee' { inviteUser } = require '../../imports/api/collections/users/methods.coffee' { insert update } = require '../../imports/api/collections/yields/methods.coffee' organizationIDs = [] yieldIDS = [] ingredientIDS = [] subHandler = "" xdescribe 'Yield Full App Test Client', () -> before( (done) -> Meteor.logout( (err) -> done() ) ) describe "Yield Insert", -> it "login", (done) -> expect(Meteor.user()).to.not.exist createUser(done, faker.internet.email()) it 'create organization', (done) -> createOrgan(done, organizationIDs) it "create ingredient", (done) -> createIngredient(done, 0) it 'Subscribe to ', (done) -> callbacks = onStop: (err) -> onReady: () -> done() Meteor.subscribe("organizations", callbacks) it "Invalid Unit id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[0] organization_id: "nonn" organization_id = organizationIDs[0] insert.call { organization_id, yield_doc } , (err, res) -> expect(err).to.have.property('error', 'validation-error') done() it "Non exisent unit id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[0] unit_id: "andflskf" organization_id: "non" organization_id = organizationIDs[0] insert.call {organization_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it 'create organization', (done) -> createOrgan(done, organizationIDs) it 'Subscribe to ', (done) -> callbacks = onStop: (err) -> onReady: () -> done() subHandler = Meteor.subscribe('yields', organizationIDs[1], callbacks) unit1d = "" it "create unit", (done) -> unit_doc = name: faker.company.companyName() amount: 12 organization_id: organizationIDs[1] organization_id = organizationIDs[1] UMethods.insert.call {organization_id, unit_doc}, (err, res) -> unit1d = res done() it "Exisent but not in organization unit_id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[0] unit_id: unit1d organization_id: organizationIDs[0] organization_id = organizationIDs[0] insert.call {organization_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it "create ingredient", (done) -> createIngredient(done, 1) it "Valid insert", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 ingredient_id: ingredientIDS[1] unit_id: unit1d organization_id: organizationIDs[1] organization_id = organizationIDs[1] insert.call {organization_id, yield_doc} , (err, res) -> expect(err).to.not.exist expect(YieldModule.Yields.findOne().amount).to.equal(0) yieldIDS.push res done() describe "Yield Update", -> it "Invalid organization id", (done) -> yield_doc = name: faker.company.companyName() amount: 21.21 organization_id = "noo" yield_id = "NONO" update.call {organization_id, yield_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it "Valid yield id but not in organization", (done) -> yield_doc = name: faker.company.companyName() organization_id = organizationIDs[0] yield_id = yieldIDS[0] update.call {organization_id, yield_id, yield_doc} , (err, res) -> expect(err).to.have.property('error', 'notAuthorized') done() it "Valid update", (done) -> passname = YieldModule.Yields.findOne().name yield_doc = name: faker.company.companyName() amount: 21.21 organization_id = organizationIDs[1] yield_id = yieldIDS[0] update.call {organization_id, yield_id, yield_doc} , (err, res) -> expect(YieldModule.Yields.findOne().name).to.not.equal(passname) expect(YieldModule.Yields.findOne().amount).to.equal(0) done() createUser = (done, email) -> doc = email: email password: 'PI:PASSWORD:<PASSWORD>END_PI' profile: first_name: faker.name.firstName() last_name: faker.name.lastName() Accounts.createUser doc, (error) -> expect(error).to.not.exist done() login = (done, email) -> Meteor.loginWithPassword email, 'PI:PASSWORD:<PASSWORD>END_PI', (err) -> done() logout = (done) -> Meteor.logout( (err) -> done() ) createOrgan = (done) -> organ_doc = name: faker.company.companyName() email: faker.internet.email() OMethods.insert.call organ_doc, (err, res) -> organizationIDs.push res expect(err).to.not.exist done() createIngredient = (done, i) -> ingredient_doc = name: faker.name.firstName() measurement_unit: 'kg' organization_id: organizationIDs[i] IMethods.insert.call {ingredient_doc}, (err, res) -> throw err if err? ingredientIDS.push res done() inviteUse = (done, email) -> invited_user_doc = emails: [ address: email ] profile: first_name: faker.name.firstName() organization_id = organizationID permission = owner: false viewer: false expenses_manager: false sells_manager: false units_manager: false inventories_manager: true users_manager: false inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) -> done()
[ { "context": "pName: 'awesomeApp'\n\t\t\tcommit: 'abcdef'\n\t\t\tname: 'awesomeDevice'\n\t\t\tversion: 'v1.0.0'\n\t\t\tdeviceType: 'raspberry-p", "end": 1016, "score": 0.7219251394271851, "start": 1003, "tag": "USERNAME", "value": "awesomeDevice" }, { "context": "eId: 1,\n\t\t\t\tser...
test/04-service.spec.coffee
XevoInc/balena-supervisor
0
{ assert, expect } = require './lib/chai-config' _ = require 'lodash' { Service } = require '../src/compose/service' configs = { simple: { compose: require('./data/docker-states/simple/compose.json') imageInfo: require('./data/docker-states/simple/imageInfo.json') inspect: require('./data/docker-states/simple/inspect.json') } entrypoint: { compose: require('./data/docker-states/entrypoint/compose.json') imageInfo: require('./data/docker-states/entrypoint/imageInfo.json') inspect: require('./data/docker-states/entrypoint/inspect.json') }, networkModeService: { compose: require('./data/docker-states/network-mode-service/compose.json') imageInfo: require('./data/docker-states/network-mode-service/imageInfo.json') inspect: require('./data/docker-states/network-mode-service/inspect.json') } } describe 'compose/service', -> it 'extends environment variables properly', -> extendEnvVarsOpts = { uuid: '1234' appName: 'awesomeApp' commit: 'abcdef' name: 'awesomeDevice' version: 'v1.0.0' deviceType: 'raspberry-pi' osVersion: 'Resin OS 2.0.2' } service = { appId: '23' releaseId: 2 serviceId: 3 imageId: 4 serviceName: 'serviceName' environment: FOO: 'bar' A_VARIABLE: 'ITS_VALUE' } s = Service.fromComposeObject(service, extendEnvVarsOpts) expect(s.config.environment).to.deep.equal({ FOO: 'bar' A_VARIABLE: 'ITS_VALUE' RESIN_APP_ID: '23' RESIN_APP_NAME: 'awesomeApp' RESIN_DEVICE_UUID: '1234' RESIN_DEVICE_TYPE: 'raspberry-pi' RESIN_HOST_OS_VERSION: 'Resin OS 2.0.2' RESIN_SERVICE_NAME: 'serviceName' RESIN_SUPERVISOR_VERSION: 'v1.0.0' RESIN_APP_LOCK_PATH: '/tmp/balena/updates.lock' RESIN_SERVICE_KILL_ME_PATH: '/tmp/balena/handover-complete' RESIN: '1' BALENA_APP_ID: '23' BALENA_APP_NAME: 'awesomeApp' BALENA_DEVICE_UUID: '1234' BALENA_DEVICE_TYPE: 'raspberry-pi' BALENA_HOST_OS_VERSION: 'Resin OS 2.0.2' BALENA_SERVICE_NAME: 'serviceName' BALENA_SUPERVISOR_VERSION: 'v1.0.0' BALENA_APP_LOCK_PATH: '/tmp/balena/updates.lock' BALENA_SERVICE_HANDOVER_COMPLETE_PATH: '/tmp/balena/handover-complete' BALENA: '1' USER: 'root' }) it 'returns the correct default bind mounts', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 }, { appName: 'foo' }) binds = Service.defaultBinds(s.appId, s.serviceName) expect(binds).to.deep.equal([ '/tmp/balena-supervisor/services/1234/foo:/tmp/resin' '/tmp/balena-supervisor/services/1234/foo:/tmp/balena' ]) it 'produces the correct port bindings and exposed ports', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 expose: [ 1000, '243/udp' ], ports: [ '2344' '2345:2354' '2346:2367/udp' ] }, { imageInfo: Config: { ExposedPorts: { '53/tcp': {} '53/udp': {} '2354/tcp': {} } } }) ports = s.generateExposeAndPorts() expect(ports.portBindings).to.deep.equal({ '2344/tcp': [{ HostIp: '', HostPort: '2344' }], '2354/tcp': [{ HostIp: '', HostPort: '2345' }], '2367/udp': [{ HostIp: '', HostPort: '2346' }] }) expect(ports.exposedPorts).to.deep.equal({ '1000/tcp': {} '243/udp': {} '2344/tcp': {} '2354/tcp': {} '2367/udp': {} '53/tcp': {} '53/udp': {} }) it 'correctly handles port ranges', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 expose: [ 1000, '243/udp' ], ports: [ '1000-1003:2000-2003' ] }, { appName: 'test' }) ports = s.generateExposeAndPorts() expect(ports.portBindings).to.deep.equal({ '2000/tcp': [ HostIp: '' HostPort: '1000' ], '2001/tcp': [ HostIp: '' HostPort: '1001' ], '2002/tcp': [ HostIp: '' HostPort: '1002' ], '2003/tcp': [ HostIp: '' HostPort: '1003' ] }) expect(ports.exposedPorts).to.deep.equal({ '1000/tcp': {} '2000/tcp': {} '2001/tcp': {} '2002/tcp': {} '2003/tcp': {} '243/udp': {} }) it 'should correctly handle large port ranges', -> @timeout(60000) s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 ports: [ '5-65536:5-65536/tcp' '5-65536:5-65536/udp' ] }, { appName: 'test' }) expect(s.generateExposeAndPorts()).to.not.throw it 'should correctly report implied exposed ports from portMappings', -> service = Service.fromComposeObject({ appId: 123456, serviceId: 123456, serviceName: 'test', ports: [ '80:80' '100:100' ] }, { appName: 'test' }) expect(service.config).to.have.property('expose').that.deep.equals(['80/tcp', '100/tcp']) describe 'Ordered array parameters', -> it 'Should correctly compare ordered array parameters', -> svc1 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', dns: [ '1.1.1.1', '8.8.8.8', ] }, { appName: 'test' }) assert(!svc1.isEqualConfig(svc2)) it 'should correctly compare non-ordered array parameters', -> svc1 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'abcdef', 'ghijk', ] }, { appName: 'test' }) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'abcdef', 'ghijk', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'ghijk', 'abcdef', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) it 'should correctly compare both ordered and non-ordered array parameters', -> svc1 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'abcdef', 'ghijk', ], dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'ghijk', 'abcdef', ], dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) describe 'parseMemoryNumber()', -> makeComposeServiceWithLimit = (memLimit) -> Service.fromComposeObject({ appId: 123456 serviceId: 123456 serviceName: 'foobar' mem_limit: memLimit }, { appName: 'test' }) it 'should correctly parse memory number strings without a unit', -> expect(makeComposeServiceWithLimit('64').config.memLimit).to.equal(64) it 'should correctly apply the default value', -> expect(makeComposeServiceWithLimit(undefined).config.memLimit).to.equal(0) it 'should correctly support parsing numbers as memory limits', -> expect(makeComposeServiceWithLimit(64).config.memLimit).to.equal(64) it 'should correctly parse memory number strings that use a byte unit', -> expect(makeComposeServiceWithLimit('64b').config.memLimit).to.equal(64) expect(makeComposeServiceWithLimit('64B').config.memLimit).to.equal(64) it 'should correctly parse memory number strings that use a kilobyte unit', -> expect(makeComposeServiceWithLimit('64k').config.memLimit).to.equal(65536) expect(makeComposeServiceWithLimit('64K').config.memLimit).to.equal(65536) expect(makeComposeServiceWithLimit('64kb').config.memLimit).to.equal(65536) expect(makeComposeServiceWithLimit('64Kb').config.memLimit).to.equal(65536) it 'should correctly parse memory number strings that use a megabyte unit', -> expect(makeComposeServiceWithLimit('64m').config.memLimit).to.equal(67108864) expect(makeComposeServiceWithLimit('64M').config.memLimit).to.equal(67108864) expect(makeComposeServiceWithLimit('64mb').config.memLimit).to.equal(67108864) expect(makeComposeServiceWithLimit('64Mb').config.memLimit).to.equal(67108864) it 'should correctly parse memory number strings that use a gigabyte unit', -> expect(makeComposeServiceWithLimit('64g').config.memLimit).to.equal(68719476736) expect(makeComposeServiceWithLimit('64G').config.memLimit).to.equal(68719476736) expect(makeComposeServiceWithLimit('64gb').config.memLimit).to.equal(68719476736) expect(makeComposeServiceWithLimit('64Gb').config.memLimit).to.equal(68719476736) describe 'getWorkingDir', -> makeComposeServiceWithWorkdir = (workdir) -> Service.fromComposeObject({ appId: 123456, serviceId: 123456, serviceName: 'foobar' workingDir: workdir }, { appName: 'test' }) it 'should remove a trailing slash', -> expect(makeComposeServiceWithWorkdir('/usr/src/app/').config.workingDir).to.equal('/usr/src/app') expect(makeComposeServiceWithWorkdir('/').config.workingDir).to.equal('/') expect(makeComposeServiceWithWorkdir('/usr/src/app').config.workingDir).to.equal('/usr/src/app') expect(makeComposeServiceWithWorkdir('').config.workingDir).to.equal('') describe 'Docker <-> Compose config', -> omitConfigForComparison = (config) -> return _.omit(config, ['running', 'networks']) it 'should be identical when converting a simple service', -> composeSvc = Service.fromComposeObject(configs.simple.compose, configs.simple.imageInfo) dockerSvc = Service.fromDockerContainer(configs.simple.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig(composeSvc)).to.be.true it 'should correct convert formats with a null entrypoint', -> composeSvc = Service.fromComposeObject(configs.entrypoint.compose, configs.entrypoint.imageInfo) dockerSvc = Service.fromDockerContainer(configs.entrypoint.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig(composeSvc)).to.equals(true) describe 'Networks', -> it 'should correctly convert networks from compose to docker format', -> makeComposeServiceWithNetwork = (networks) -> Service.fromComposeObject({ appId: 123456, serviceId: 123456, serviceName: 'test', networks }, { appName: 'test' }) expect(makeComposeServiceWithNetwork({ 'balena': { 'ipv4Address': '1.2.3.4' } }).toDockerContainer({ deviceName: 'foo' }).NetworkingConfig).to.deep.equal({ EndpointsConfig: { '123456_balena': { IPAMConfig: { IPv4Address: '1.2.3.4' }, Aliases: [ 'test' ] } } }) expect(makeComposeServiceWithNetwork({ balena: { aliases: [ 'test', '1123'] ipv4Address: '1.2.3.4' ipv6Address: '5.6.7.8' linkLocalIps: [ '123.123.123' ] } }).toDockerContainer({ deviceName: 'foo' }).NetworkingConfig).to.deep.equal({ EndpointsConfig: { '123456_balena': { IPAMConfig: { IPv4Address: '1.2.3.4' IPv6Address: '5.6.7.8' LinkLocalIPs: [ '123.123.123' ] } Aliases: [ 'test', '1123' ] } } }) it 'should correctly convert Docker format to service format', -> dockerCfg = require('./data/docker-states/simple/inspect.json') makeServiceFromDockerWithNetwork = (networks) -> Service.fromDockerContainer( newConfig = _.cloneDeep(dockerCfg) newConfig.NetworkSettings = { Networks: networks } ) expect(makeServiceFromDockerWithNetwork({ '123456_balena': { IPAMConfig: { IPv4Address: '1.2.3.4' }, Aliases: [] } }).config.networks).to.deep.equal({ '123456_balena': { 'ipv4Address': '1.2.3.4' } }) expect(makeServiceFromDockerWithNetwork({ '123456_balena': { IPAMConfig: { IPv4Address: '1.2.3.4' IPv6Address: '5.6.7.8' LinkLocalIps: [ '123.123.123' ] } Aliases: [ 'test', '1123' ] } }).config.networks).to.deep.equal({ '123456_balena': { ipv4Address: '1.2.3.4' ipv6Address: '5.6.7.8' linkLocalIps: [ '123.123.123' ] aliases: [ 'test', '1123' ] } }) describe 'Network mode=service:', -> it 'should correctly add a depends_on entry for the service', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 network_mode: 'service: test' }, { appName: 'test' }) expect(s.dependsOn).to.deep.equal(['test']) s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 depends_on: [ 'another_service' ] network_mode: 'service: test' }, { appName: 'test' }) expect(s.dependsOn).to.deep.equal([ 'another_service', 'test' ]) it 'should correctly convert a network_mode service: to a container:', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 network_mode: 'service: test' }, { appName: 'test' }) expect(s.toDockerContainer({ deviceName: '', containerIds: { test: 'abcdef' } })) .to.have.property('HostConfig') .that.has.property('NetworkMode') .that.equals('container:abcdef') it 'should not cause a container restart if a service: container has not changed', -> composeSvc = Service.fromComposeObject(configs.networkModeService.compose, configs.networkModeService.imageInfo) dockerSvc = Service.fromDockerContainer(configs.networkModeService.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.not.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig( composeSvc, { test: 'abcdef' } )).to.be.true it 'should restart a container when its dependent network mode container changes', -> composeSvc = Service.fromComposeObject(configs.networkModeService.compose, configs.networkModeService.imageInfo) dockerSvc = Service.fromDockerContainer(configs.networkModeService.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.not.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig( composeSvc, { test: 'qwerty' } )).to.be.false
83781
{ assert, expect } = require './lib/chai-config' _ = require 'lodash' { Service } = require '../src/compose/service' configs = { simple: { compose: require('./data/docker-states/simple/compose.json') imageInfo: require('./data/docker-states/simple/imageInfo.json') inspect: require('./data/docker-states/simple/inspect.json') } entrypoint: { compose: require('./data/docker-states/entrypoint/compose.json') imageInfo: require('./data/docker-states/entrypoint/imageInfo.json') inspect: require('./data/docker-states/entrypoint/inspect.json') }, networkModeService: { compose: require('./data/docker-states/network-mode-service/compose.json') imageInfo: require('./data/docker-states/network-mode-service/imageInfo.json') inspect: require('./data/docker-states/network-mode-service/inspect.json') } } describe 'compose/service', -> it 'extends environment variables properly', -> extendEnvVarsOpts = { uuid: '1234' appName: 'awesomeApp' commit: 'abcdef' name: 'awesomeDevice' version: 'v1.0.0' deviceType: 'raspberry-pi' osVersion: 'Resin OS 2.0.2' } service = { appId: '23' releaseId: 2 serviceId: 3 imageId: 4 serviceName: 'serviceName' environment: FOO: 'bar' A_VARIABLE: 'ITS_VALUE' } s = Service.fromComposeObject(service, extendEnvVarsOpts) expect(s.config.environment).to.deep.equal({ FOO: 'bar' A_VARIABLE: 'ITS_VALUE' RESIN_APP_ID: '23' RESIN_APP_NAME: 'awesomeApp' RESIN_DEVICE_UUID: '1234' RESIN_DEVICE_TYPE: 'raspberry-pi' RESIN_HOST_OS_VERSION: 'Resin OS 2.0.2' RESIN_SERVICE_NAME: 'serviceName' RESIN_SUPERVISOR_VERSION: 'v1.0.0' RESIN_APP_LOCK_PATH: '/tmp/balena/updates.lock' RESIN_SERVICE_KILL_ME_PATH: '/tmp/balena/handover-complete' RESIN: '1' BALENA_APP_ID: '23' BALENA_APP_NAME: 'awesomeApp' BALENA_DEVICE_UUID: '1234' BALENA_DEVICE_TYPE: 'raspberry-pi' BALENA_HOST_OS_VERSION: 'Resin OS 2.0.2' BALENA_SERVICE_NAME: 'serviceName' BALENA_SUPERVISOR_VERSION: 'v1.0.0' BALENA_APP_LOCK_PATH: '/tmp/balena/updates.lock' BALENA_SERVICE_HANDOVER_COMPLETE_PATH: '/tmp/balena/handover-complete' BALENA: '1' USER: 'root' }) it 'returns the correct default bind mounts', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 }, { appName: 'foo' }) binds = Service.defaultBinds(s.appId, s.serviceName) expect(binds).to.deep.equal([ '/tmp/balena-supervisor/services/1234/foo:/tmp/resin' '/tmp/balena-supervisor/services/1234/foo:/tmp/balena' ]) it 'produces the correct port bindings and exposed ports', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 expose: [ 1000, '243/udp' ], ports: [ '2344' '2345:2354' '2346:2367/udp' ] }, { imageInfo: Config: { ExposedPorts: { '53/tcp': {} '53/udp': {} '2354/tcp': {} } } }) ports = s.generateExposeAndPorts() expect(ports.portBindings).to.deep.equal({ '2344/tcp': [{ HostIp: '', HostPort: '2344' }], '2354/tcp': [{ HostIp: '', HostPort: '2345' }], '2367/udp': [{ HostIp: '', HostPort: '2346' }] }) expect(ports.exposedPorts).to.deep.equal({ '1000/tcp': {} '243/udp': {} '2344/tcp': {} '2354/tcp': {} '2367/udp': {} '53/tcp': {} '53/udp': {} }) it 'correctly handles port ranges', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 expose: [ 1000, '243/udp' ], ports: [ '1000-1003:2000-2003' ] }, { appName: 'test' }) ports = s.generateExposeAndPorts() expect(ports.portBindings).to.deep.equal({ '2000/tcp': [ HostIp: '' HostPort: '1000' ], '2001/tcp': [ HostIp: '' HostPort: '1001' ], '2002/tcp': [ HostIp: '' HostPort: '1002' ], '2003/tcp': [ HostIp: '' HostPort: '1003' ] }) expect(ports.exposedPorts).to.deep.equal({ '1000/tcp': {} '2000/tcp': {} '2001/tcp': {} '2002/tcp': {} '2003/tcp': {} '243/udp': {} }) it 'should correctly handle large port ranges', -> @timeout(60000) s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 ports: [ '5-65536:5-65536/tcp' '5-65536:5-65536/udp' ] }, { appName: 'test' }) expect(s.generateExposeAndPorts()).to.not.throw it 'should correctly report implied exposed ports from portMappings', -> service = Service.fromComposeObject({ appId: 123456, serviceId: 123456, serviceName: 'test', ports: [ '80:80' '100:100' ] }, { appName: 'test' }) expect(service.config).to.have.property('expose').that.deep.equals(['80/tcp', '100/tcp']) describe 'Ordered array parameters', -> it 'Should correctly compare ordered array parameters', -> svc1 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', dns: [ '1.1.1.1', '8.8.8.8', ] }, { appName: 'test' }) assert(!svc1.isEqualConfig(svc2)) it 'should correctly compare non-ordered array parameters', -> svc1 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'abcdef', 'ghijk', ] }, { appName: 'test' }) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'abcdef', 'ghijk', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'ghijk', 'abcdef', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) it 'should correctly compare both ordered and non-ordered array parameters', -> svc1 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'abcdef', 'ghijk', ], dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'ghijk', 'abcdef', ], dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) describe 'parseMemoryNumber()', -> makeComposeServiceWithLimit = (memLimit) -> Service.fromComposeObject({ appId: 123456 serviceId: 123456 serviceName: 'foobar' mem_limit: memLimit }, { appName: 'test' }) it 'should correctly parse memory number strings without a unit', -> expect(makeComposeServiceWithLimit('64').config.memLimit).to.equal(64) it 'should correctly apply the default value', -> expect(makeComposeServiceWithLimit(undefined).config.memLimit).to.equal(0) it 'should correctly support parsing numbers as memory limits', -> expect(makeComposeServiceWithLimit(64).config.memLimit).to.equal(64) it 'should correctly parse memory number strings that use a byte unit', -> expect(makeComposeServiceWithLimit('64b').config.memLimit).to.equal(64) expect(makeComposeServiceWithLimit('64B').config.memLimit).to.equal(64) it 'should correctly parse memory number strings that use a kilobyte unit', -> expect(makeComposeServiceWithLimit('64k').config.memLimit).to.equal(65536) expect(makeComposeServiceWithLimit('64K').config.memLimit).to.equal(65536) expect(makeComposeServiceWithLimit('64kb').config.memLimit).to.equal(65536) expect(makeComposeServiceWithLimit('64Kb').config.memLimit).to.equal(65536) it 'should correctly parse memory number strings that use a megabyte unit', -> expect(makeComposeServiceWithLimit('64m').config.memLimit).to.equal(67108864) expect(makeComposeServiceWithLimit('64M').config.memLimit).to.equal(67108864) expect(makeComposeServiceWithLimit('64mb').config.memLimit).to.equal(67108864) expect(makeComposeServiceWithLimit('64Mb').config.memLimit).to.equal(67108864) it 'should correctly parse memory number strings that use a gigabyte unit', -> expect(makeComposeServiceWithLimit('64g').config.memLimit).to.equal(68719476736) expect(makeComposeServiceWithLimit('64G').config.memLimit).to.equal(68719476736) expect(makeComposeServiceWithLimit('64gb').config.memLimit).to.equal(68719476736) expect(makeComposeServiceWithLimit('64Gb').config.memLimit).to.equal(68719476736) describe 'getWorkingDir', -> makeComposeServiceWithWorkdir = (workdir) -> Service.fromComposeObject({ appId: 123456, serviceId: 123456, serviceName: 'foobar' workingDir: workdir }, { appName: 'test' }) it 'should remove a trailing slash', -> expect(makeComposeServiceWithWorkdir('/usr/src/app/').config.workingDir).to.equal('/usr/src/app') expect(makeComposeServiceWithWorkdir('/').config.workingDir).to.equal('/') expect(makeComposeServiceWithWorkdir('/usr/src/app').config.workingDir).to.equal('/usr/src/app') expect(makeComposeServiceWithWorkdir('').config.workingDir).to.equal('') describe 'Docker <-> Compose config', -> omitConfigForComparison = (config) -> return _.omit(config, ['running', 'networks']) it 'should be identical when converting a simple service', -> composeSvc = Service.fromComposeObject(configs.simple.compose, configs.simple.imageInfo) dockerSvc = Service.fromDockerContainer(configs.simple.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig(composeSvc)).to.be.true it 'should correct convert formats with a null entrypoint', -> composeSvc = Service.fromComposeObject(configs.entrypoint.compose, configs.entrypoint.imageInfo) dockerSvc = Service.fromDockerContainer(configs.entrypoint.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig(composeSvc)).to.equals(true) describe 'Networks', -> it 'should correctly convert networks from compose to docker format', -> makeComposeServiceWithNetwork = (networks) -> Service.fromComposeObject({ appId: 123456, serviceId: 123456, serviceName: 'test', networks }, { appName: 'test' }) expect(makeComposeServiceWithNetwork({ 'balena': { 'ipv4Address': '1.2.3.4' } }).toDockerContainer({ deviceName: 'foo' }).NetworkingConfig).to.deep.equal({ EndpointsConfig: { '123456_balena': { IPAMConfig: { IPv4Address: '172.16.17.32' }, Aliases: [ 'test' ] } } }) expect(makeComposeServiceWithNetwork({ balena: { aliases: [ 'test', '1123'] ipv4Address: '1.2.3.4' ipv6Address: '5.6.7.8' linkLocalIps: [ '123.123.123' ] } }).toDockerContainer({ deviceName: 'foo' }).NetworkingConfig).to.deep.equal({ EndpointsConfig: { '123456_balena': { IPAMConfig: { IPv4Address: '1.2.3.4' IPv6Address: '5.6.7.8' LinkLocalIPs: [ '123.123.123' ] } Aliases: [ 'test', '1123' ] } } }) it 'should correctly convert Docker format to service format', -> dockerCfg = require('./data/docker-states/simple/inspect.json') makeServiceFromDockerWithNetwork = (networks) -> Service.fromDockerContainer( newConfig = _.cloneDeep(dockerCfg) newConfig.NetworkSettings = { Networks: networks } ) expect(makeServiceFromDockerWithNetwork({ '123456_balena': { IPAMConfig: { IPv4Address: '1.2.3.4' }, Aliases: [] } }).config.networks).to.deep.equal({ '123456_balena': { 'ipv4Address': '1.2.3.4' } }) expect(makeServiceFromDockerWithNetwork({ '123456_balena': { IPAMConfig: { IPv4Address: '1.2.3.4' IPv6Address: '5.6.7.8' LinkLocalIps: [ '123.123.123' ] } Aliases: [ 'test', '1123' ] } }).config.networks).to.deep.equal({ '123456_balena': { ipv4Address: '1.2.3.4' ipv6Address: '5.6.7.8' linkLocalIps: [ '123.123.123' ] aliases: [ 'test', '1123' ] } }) describe 'Network mode=service:', -> it 'should correctly add a depends_on entry for the service', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 network_mode: 'service: test' }, { appName: 'test' }) expect(s.dependsOn).to.deep.equal(['test']) s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 depends_on: [ 'another_service' ] network_mode: 'service: test' }, { appName: 'test' }) expect(s.dependsOn).to.deep.equal([ 'another_service', 'test' ]) it 'should correctly convert a network_mode service: to a container:', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 network_mode: 'service: test' }, { appName: 'test' }) expect(s.toDockerContainer({ deviceName: '', containerIds: { test: 'abcdef' } })) .to.have.property('HostConfig') .that.has.property('NetworkMode') .that.equals('container:abcdef') it 'should not cause a container restart if a service: container has not changed', -> composeSvc = Service.fromComposeObject(configs.networkModeService.compose, configs.networkModeService.imageInfo) dockerSvc = Service.fromDockerContainer(configs.networkModeService.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.not.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig( composeSvc, { test: 'abcdef' } )).to.be.true it 'should restart a container when its dependent network mode container changes', -> composeSvc = Service.fromComposeObject(configs.networkModeService.compose, configs.networkModeService.imageInfo) dockerSvc = Service.fromDockerContainer(configs.networkModeService.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.not.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig( composeSvc, { test: 'qwerty' } )).to.be.false
true
{ assert, expect } = require './lib/chai-config' _ = require 'lodash' { Service } = require '../src/compose/service' configs = { simple: { compose: require('./data/docker-states/simple/compose.json') imageInfo: require('./data/docker-states/simple/imageInfo.json') inspect: require('./data/docker-states/simple/inspect.json') } entrypoint: { compose: require('./data/docker-states/entrypoint/compose.json') imageInfo: require('./data/docker-states/entrypoint/imageInfo.json') inspect: require('./data/docker-states/entrypoint/inspect.json') }, networkModeService: { compose: require('./data/docker-states/network-mode-service/compose.json') imageInfo: require('./data/docker-states/network-mode-service/imageInfo.json') inspect: require('./data/docker-states/network-mode-service/inspect.json') } } describe 'compose/service', -> it 'extends environment variables properly', -> extendEnvVarsOpts = { uuid: '1234' appName: 'awesomeApp' commit: 'abcdef' name: 'awesomeDevice' version: 'v1.0.0' deviceType: 'raspberry-pi' osVersion: 'Resin OS 2.0.2' } service = { appId: '23' releaseId: 2 serviceId: 3 imageId: 4 serviceName: 'serviceName' environment: FOO: 'bar' A_VARIABLE: 'ITS_VALUE' } s = Service.fromComposeObject(service, extendEnvVarsOpts) expect(s.config.environment).to.deep.equal({ FOO: 'bar' A_VARIABLE: 'ITS_VALUE' RESIN_APP_ID: '23' RESIN_APP_NAME: 'awesomeApp' RESIN_DEVICE_UUID: '1234' RESIN_DEVICE_TYPE: 'raspberry-pi' RESIN_HOST_OS_VERSION: 'Resin OS 2.0.2' RESIN_SERVICE_NAME: 'serviceName' RESIN_SUPERVISOR_VERSION: 'v1.0.0' RESIN_APP_LOCK_PATH: '/tmp/balena/updates.lock' RESIN_SERVICE_KILL_ME_PATH: '/tmp/balena/handover-complete' RESIN: '1' BALENA_APP_ID: '23' BALENA_APP_NAME: 'awesomeApp' BALENA_DEVICE_UUID: '1234' BALENA_DEVICE_TYPE: 'raspberry-pi' BALENA_HOST_OS_VERSION: 'Resin OS 2.0.2' BALENA_SERVICE_NAME: 'serviceName' BALENA_SUPERVISOR_VERSION: 'v1.0.0' BALENA_APP_LOCK_PATH: '/tmp/balena/updates.lock' BALENA_SERVICE_HANDOVER_COMPLETE_PATH: '/tmp/balena/handover-complete' BALENA: '1' USER: 'root' }) it 'returns the correct default bind mounts', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 }, { appName: 'foo' }) binds = Service.defaultBinds(s.appId, s.serviceName) expect(binds).to.deep.equal([ '/tmp/balena-supervisor/services/1234/foo:/tmp/resin' '/tmp/balena-supervisor/services/1234/foo:/tmp/balena' ]) it 'produces the correct port bindings and exposed ports', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 expose: [ 1000, '243/udp' ], ports: [ '2344' '2345:2354' '2346:2367/udp' ] }, { imageInfo: Config: { ExposedPorts: { '53/tcp': {} '53/udp': {} '2354/tcp': {} } } }) ports = s.generateExposeAndPorts() expect(ports.portBindings).to.deep.equal({ '2344/tcp': [{ HostIp: '', HostPort: '2344' }], '2354/tcp': [{ HostIp: '', HostPort: '2345' }], '2367/udp': [{ HostIp: '', HostPort: '2346' }] }) expect(ports.exposedPorts).to.deep.equal({ '1000/tcp': {} '243/udp': {} '2344/tcp': {} '2354/tcp': {} '2367/udp': {} '53/tcp': {} '53/udp': {} }) it 'correctly handles port ranges', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 expose: [ 1000, '243/udp' ], ports: [ '1000-1003:2000-2003' ] }, { appName: 'test' }) ports = s.generateExposeAndPorts() expect(ports.portBindings).to.deep.equal({ '2000/tcp': [ HostIp: '' HostPort: '1000' ], '2001/tcp': [ HostIp: '' HostPort: '1001' ], '2002/tcp': [ HostIp: '' HostPort: '1002' ], '2003/tcp': [ HostIp: '' HostPort: '1003' ] }) expect(ports.exposedPorts).to.deep.equal({ '1000/tcp': {} '2000/tcp': {} '2001/tcp': {} '2002/tcp': {} '2003/tcp': {} '243/udp': {} }) it 'should correctly handle large port ranges', -> @timeout(60000) s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 ports: [ '5-65536:5-65536/tcp' '5-65536:5-65536/udp' ] }, { appName: 'test' }) expect(s.generateExposeAndPorts()).to.not.throw it 'should correctly report implied exposed ports from portMappings', -> service = Service.fromComposeObject({ appId: 123456, serviceId: 123456, serviceName: 'test', ports: [ '80:80' '100:100' ] }, { appName: 'test' }) expect(service.config).to.have.property('expose').that.deep.equals(['80/tcp', '100/tcp']) describe 'Ordered array parameters', -> it 'Should correctly compare ordered array parameters', -> svc1 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', dns: [ '1.1.1.1', '8.8.8.8', ] }, { appName: 'test' }) assert(!svc1.isEqualConfig(svc2)) it 'should correctly compare non-ordered array parameters', -> svc1 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'abcdef', 'ghijk', ] }, { appName: 'test' }) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'abcdef', 'ghijk', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'ghijk', 'abcdef', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) it 'should correctly compare both ordered and non-ordered array parameters', -> svc1 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'abcdef', 'ghijk', ], dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) svc2 = Service.fromComposeObject({ appId: 1, serviceId: 1, serviceName: 'test', volumes: [ 'ghijk', 'abcdef', ], dns: [ '8.8.8.8', '1.1.1.1', ] }, { appName: 'test' }) assert(svc1.isEqualConfig(svc2)) describe 'parseMemoryNumber()', -> makeComposeServiceWithLimit = (memLimit) -> Service.fromComposeObject({ appId: 123456 serviceId: 123456 serviceName: 'foobar' mem_limit: memLimit }, { appName: 'test' }) it 'should correctly parse memory number strings without a unit', -> expect(makeComposeServiceWithLimit('64').config.memLimit).to.equal(64) it 'should correctly apply the default value', -> expect(makeComposeServiceWithLimit(undefined).config.memLimit).to.equal(0) it 'should correctly support parsing numbers as memory limits', -> expect(makeComposeServiceWithLimit(64).config.memLimit).to.equal(64) it 'should correctly parse memory number strings that use a byte unit', -> expect(makeComposeServiceWithLimit('64b').config.memLimit).to.equal(64) expect(makeComposeServiceWithLimit('64B').config.memLimit).to.equal(64) it 'should correctly parse memory number strings that use a kilobyte unit', -> expect(makeComposeServiceWithLimit('64k').config.memLimit).to.equal(65536) expect(makeComposeServiceWithLimit('64K').config.memLimit).to.equal(65536) expect(makeComposeServiceWithLimit('64kb').config.memLimit).to.equal(65536) expect(makeComposeServiceWithLimit('64Kb').config.memLimit).to.equal(65536) it 'should correctly parse memory number strings that use a megabyte unit', -> expect(makeComposeServiceWithLimit('64m').config.memLimit).to.equal(67108864) expect(makeComposeServiceWithLimit('64M').config.memLimit).to.equal(67108864) expect(makeComposeServiceWithLimit('64mb').config.memLimit).to.equal(67108864) expect(makeComposeServiceWithLimit('64Mb').config.memLimit).to.equal(67108864) it 'should correctly parse memory number strings that use a gigabyte unit', -> expect(makeComposeServiceWithLimit('64g').config.memLimit).to.equal(68719476736) expect(makeComposeServiceWithLimit('64G').config.memLimit).to.equal(68719476736) expect(makeComposeServiceWithLimit('64gb').config.memLimit).to.equal(68719476736) expect(makeComposeServiceWithLimit('64Gb').config.memLimit).to.equal(68719476736) describe 'getWorkingDir', -> makeComposeServiceWithWorkdir = (workdir) -> Service.fromComposeObject({ appId: 123456, serviceId: 123456, serviceName: 'foobar' workingDir: workdir }, { appName: 'test' }) it 'should remove a trailing slash', -> expect(makeComposeServiceWithWorkdir('/usr/src/app/').config.workingDir).to.equal('/usr/src/app') expect(makeComposeServiceWithWorkdir('/').config.workingDir).to.equal('/') expect(makeComposeServiceWithWorkdir('/usr/src/app').config.workingDir).to.equal('/usr/src/app') expect(makeComposeServiceWithWorkdir('').config.workingDir).to.equal('') describe 'Docker <-> Compose config', -> omitConfigForComparison = (config) -> return _.omit(config, ['running', 'networks']) it 'should be identical when converting a simple service', -> composeSvc = Service.fromComposeObject(configs.simple.compose, configs.simple.imageInfo) dockerSvc = Service.fromDockerContainer(configs.simple.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig(composeSvc)).to.be.true it 'should correct convert formats with a null entrypoint', -> composeSvc = Service.fromComposeObject(configs.entrypoint.compose, configs.entrypoint.imageInfo) dockerSvc = Service.fromDockerContainer(configs.entrypoint.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig(composeSvc)).to.equals(true) describe 'Networks', -> it 'should correctly convert networks from compose to docker format', -> makeComposeServiceWithNetwork = (networks) -> Service.fromComposeObject({ appId: 123456, serviceId: 123456, serviceName: 'test', networks }, { appName: 'test' }) expect(makeComposeServiceWithNetwork({ 'balena': { 'ipv4Address': '1.2.3.4' } }).toDockerContainer({ deviceName: 'foo' }).NetworkingConfig).to.deep.equal({ EndpointsConfig: { '123456_balena': { IPAMConfig: { IPv4Address: 'PI:IP_ADDRESS:172.16.17.32END_PI' }, Aliases: [ 'test' ] } } }) expect(makeComposeServiceWithNetwork({ balena: { aliases: [ 'test', '1123'] ipv4Address: '1.2.3.4' ipv6Address: '5.6.7.8' linkLocalIps: [ '123.123.123' ] } }).toDockerContainer({ deviceName: 'foo' }).NetworkingConfig).to.deep.equal({ EndpointsConfig: { '123456_balena': { IPAMConfig: { IPv4Address: '1.2.3.4' IPv6Address: '5.6.7.8' LinkLocalIPs: [ '123.123.123' ] } Aliases: [ 'test', '1123' ] } } }) it 'should correctly convert Docker format to service format', -> dockerCfg = require('./data/docker-states/simple/inspect.json') makeServiceFromDockerWithNetwork = (networks) -> Service.fromDockerContainer( newConfig = _.cloneDeep(dockerCfg) newConfig.NetworkSettings = { Networks: networks } ) expect(makeServiceFromDockerWithNetwork({ '123456_balena': { IPAMConfig: { IPv4Address: '1.2.3.4' }, Aliases: [] } }).config.networks).to.deep.equal({ '123456_balena': { 'ipv4Address': '1.2.3.4' } }) expect(makeServiceFromDockerWithNetwork({ '123456_balena': { IPAMConfig: { IPv4Address: '1.2.3.4' IPv6Address: '5.6.7.8' LinkLocalIps: [ '123.123.123' ] } Aliases: [ 'test', '1123' ] } }).config.networks).to.deep.equal({ '123456_balena': { ipv4Address: '1.2.3.4' ipv6Address: '5.6.7.8' linkLocalIps: [ '123.123.123' ] aliases: [ 'test', '1123' ] } }) describe 'Network mode=service:', -> it 'should correctly add a depends_on entry for the service', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 network_mode: 'service: test' }, { appName: 'test' }) expect(s.dependsOn).to.deep.equal(['test']) s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 depends_on: [ 'another_service' ] network_mode: 'service: test' }, { appName: 'test' }) expect(s.dependsOn).to.deep.equal([ 'another_service', 'test' ]) it 'should correctly convert a network_mode service: to a container:', -> s = Service.fromComposeObject({ appId: '1234' serviceName: 'foo' releaseId: 2 serviceId: 3 imageId: 4 network_mode: 'service: test' }, { appName: 'test' }) expect(s.toDockerContainer({ deviceName: '', containerIds: { test: 'abcdef' } })) .to.have.property('HostConfig') .that.has.property('NetworkMode') .that.equals('container:abcdef') it 'should not cause a container restart if a service: container has not changed', -> composeSvc = Service.fromComposeObject(configs.networkModeService.compose, configs.networkModeService.imageInfo) dockerSvc = Service.fromDockerContainer(configs.networkModeService.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.not.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig( composeSvc, { test: 'abcdef' } )).to.be.true it 'should restart a container when its dependent network mode container changes', -> composeSvc = Service.fromComposeObject(configs.networkModeService.compose, configs.networkModeService.imageInfo) dockerSvc = Service.fromDockerContainer(configs.networkModeService.inspect) composeConfig = omitConfigForComparison(composeSvc.config) dockerConfig = omitConfigForComparison(dockerSvc.config) expect(composeConfig).to.not.deep.equal(dockerConfig) expect(dockerSvc.isEqualConfig( composeSvc, { test: 'qwerty' } )).to.be.false
[ { "context": "5'\n account1 = generateDummyAccount '123', 'qwertyuser'\n account2 = generateDummyAccount '", "end": 629, "score": 0.5789495706558228, "start": 627, "tag": "PASSWORD", "value": "qw" }, { "context": "\n account1 = generateDummyAccount '123', 'qwertyuse...
client/home/lib/virtualmachines/test/stores/sharingsearchstore.test.coffee
ezgikaysi/koding
1
actions = require 'home/virtualmachines/flux/search/actiontypes' expect = require 'expect' Reactor = require 'app/flux/base/reactor' SharingSearchStore = require 'home/virtualmachines/flux/search/stores/sharingsearchstore' generateDummyAccount = require 'app/util/generateDummyAccount' describe 'VirtualMachinesSharingSearchStore', -> beforeEach -> @reactor = new Reactor @reactor.registerStores [SharingSearchStore] describe '#setSearchItems', -> it 'sets search items for machineId', -> machineId = '12345' account1 = generateDummyAccount '123', 'qwertyuser' account2 = generateDummyAccount '456', 'testuser' items = [ account1, account2 ] @reactor.dispatch actions.SET_VIRTUAL_MACHINES_SHARING_SEARCH_ITEMS, { machineId, items } storeState = @reactor.evaluateToJS [SharingSearchStore.getterPath] expect(storeState[machineId][0]).toEqual account1 expect(storeState[machineId][1]).toEqual account2 describe '#resetSearchItems', -> it 'deleted search items for machineId', -> machineId = '12345' account1 = generateDummyAccount '123', 'qwertyuser' account2 = generateDummyAccount '456', 'testuser' items = [ account1, account2 ] @reactor.dispatch actions.SET_VIRTUAL_MACHINES_SHARING_SEARCH_ITEMS, { machineId, items } storeState = @reactor.evaluateToJS [SharingSearchStore.getterPath] expect(storeState[machineId]).toExist() @reactor.dispatch actions.RESET_VIRTUAL_MACHINES_SHARING_SEARCH_ITEMS, { machineId } storeState = @reactor.evaluateToJS [SharingSearchStore.getterPath] expect(storeState[machineId]).toNotExist()
59831
actions = require 'home/virtualmachines/flux/search/actiontypes' expect = require 'expect' Reactor = require 'app/flux/base/reactor' SharingSearchStore = require 'home/virtualmachines/flux/search/stores/sharingsearchstore' generateDummyAccount = require 'app/util/generateDummyAccount' describe 'VirtualMachinesSharingSearchStore', -> beforeEach -> @reactor = new Reactor @reactor.registerStores [SharingSearchStore] describe '#setSearchItems', -> it 'sets search items for machineId', -> machineId = '12345' account1 = generateDummyAccount '123', '<PASSWORD> <KEY>user' account2 = generateDummyAccount '456', '<PASSWORD>' items = [ account1, account2 ] @reactor.dispatch actions.SET_VIRTUAL_MACHINES_SHARING_SEARCH_ITEMS, { machineId, items } storeState = @reactor.evaluateToJS [SharingSearchStore.getterPath] expect(storeState[machineId][0]).toEqual account1 expect(storeState[machineId][1]).toEqual account2 describe '#resetSearchItems', -> it 'deleted search items for machineId', -> machineId = '12345' account1 = generateDummyAccount '123', '<PASSWORD>ertyuser' account2 = generateDummyAccount '456', '<PASSWORD>' items = [ account1, account2 ] @reactor.dispatch actions.SET_VIRTUAL_MACHINES_SHARING_SEARCH_ITEMS, { machineId, items } storeState = @reactor.evaluateToJS [SharingSearchStore.getterPath] expect(storeState[machineId]).toExist() @reactor.dispatch actions.RESET_VIRTUAL_MACHINES_SHARING_SEARCH_ITEMS, { machineId } storeState = @reactor.evaluateToJS [SharingSearchStore.getterPath] expect(storeState[machineId]).toNotExist()
true
actions = require 'home/virtualmachines/flux/search/actiontypes' expect = require 'expect' Reactor = require 'app/flux/base/reactor' SharingSearchStore = require 'home/virtualmachines/flux/search/stores/sharingsearchstore' generateDummyAccount = require 'app/util/generateDummyAccount' describe 'VirtualMachinesSharingSearchStore', -> beforeEach -> @reactor = new Reactor @reactor.registerStores [SharingSearchStore] describe '#setSearchItems', -> it 'sets search items for machineId', -> machineId = '12345' account1 = generateDummyAccount '123', 'PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PIuser' account2 = generateDummyAccount '456', 'PI:PASSWORD:<PASSWORD>END_PI' items = [ account1, account2 ] @reactor.dispatch actions.SET_VIRTUAL_MACHINES_SHARING_SEARCH_ITEMS, { machineId, items } storeState = @reactor.evaluateToJS [SharingSearchStore.getterPath] expect(storeState[machineId][0]).toEqual account1 expect(storeState[machineId][1]).toEqual account2 describe '#resetSearchItems', -> it 'deleted search items for machineId', -> machineId = '12345' account1 = generateDummyAccount '123', 'PI:PASSWORD:<PASSWORD>END_PIertyuser' account2 = generateDummyAccount '456', 'PI:PASSWORD:<PASSWORD>END_PI' items = [ account1, account2 ] @reactor.dispatch actions.SET_VIRTUAL_MACHINES_SHARING_SEARCH_ITEMS, { machineId, items } storeState = @reactor.evaluateToJS [SharingSearchStore.getterPath] expect(storeState[machineId]).toExist() @reactor.dispatch actions.RESET_VIRTUAL_MACHINES_SHARING_SEARCH_ITEMS, { machineId } storeState = @reactor.evaluateToJS [SharingSearchStore.getterPath] expect(storeState[machineId]).toNotExist()
[ { "context": ">\n token = new OneTimeToken\n _id: 'misused'\n ttl: 3600\n use: 'wrong'\n s", "end": 1288, "score": 0.5825185179710388, "start": 1284, "tag": "USERNAME", "value": "used" }, { "context": "r\n token = new OneTimeToken\n _id: '...
test/unit/oidc/verifyEmail.coffee
LorianeE/connect
331
chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect chai.use sinonChai chai.should() {verifyEmail} = require '../../../oidc' OneTimeToken = require '../../../models/OneTimeToken' User = require '../../../models/User' describe 'Verify Email', -> {req,res,next} = {} describe 'with missing token', -> before -> req = query: {} res = render: sinon.spy() next = sinon.spy() verifyEmail req, res, next it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with invalid or expired token', -> before -> req = query: token: 'invalid' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, null) verifyEmail req, res, next after -> OneTimeToken.consume.restore() it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with wrong token type', -> before -> token = new OneTimeToken _id: 'misused' ttl: 3600 use: 'wrong' sub: 'nomatter' req = query: token: 'misused' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) verifyEmail req, res, next after -> OneTimeToken.consume.restore() it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with unknown user', -> before -> token = new OneTimeToken _id: 'misused' ttl: 3600 use: 'emailVerification' sub: 'unknown' req = query: token: 'valid' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) sinon.stub(User, 'patch').callsArgWith(2, null, null) verifyEmail req, res, next after -> OneTimeToken.consume.restore() User.patch.restore() it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with valid token', -> before -> user = new User token = new OneTimeToken _id: 'misused' ttl: 3600 use: 'emailVerification' sub: 'uuid' req = query: token: 'valid' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) sinon.stub(User, 'patch').callsArgWith(2, null, user) verifyEmail req, res, next after -> OneTimeToken.consume.restore() User.patch.restore() it 'should render a response with null signin', -> res.render.should.have.been.calledWith 'verifyEmail' res.render.should.not.have.been.calledWith( 'verifyEmail', sinon.match.object ) describe 'with valid token and client redirect', -> before -> user = new User token = new OneTimeToken _id: 'misused' ttl: 3600 use: 'emailVerification' sub: 'uuid' req = query: token: 'valid' client: {} connectParams: redirect_uri: 'https://example.com/callback' client_id: 'client-uuid' response_type: 'id_token token' scope: 'openid profile' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) sinon.stub(User, 'patch').callsArgWith(2, null, user) verifyEmail req, res, next after -> OneTimeToken.consume.restore() User.patch.restore() it 'should render a response with url', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ signin: { url: sinon.match.string } }) it 'should render a response with client', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ signin: { url: sinon.match.string } })
27377
chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect chai.use sinonChai chai.should() {verifyEmail} = require '../../../oidc' OneTimeToken = require '../../../models/OneTimeToken' User = require '../../../models/User' describe 'Verify Email', -> {req,res,next} = {} describe 'with missing token', -> before -> req = query: {} res = render: sinon.spy() next = sinon.spy() verifyEmail req, res, next it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with invalid or expired token', -> before -> req = query: token: 'invalid' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, null) verifyEmail req, res, next after -> OneTimeToken.consume.restore() it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with wrong token type', -> before -> token = new OneTimeToken _id: 'misused' ttl: 3600 use: 'wrong' sub: 'nomatter' req = query: token: 'misused' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) verifyEmail req, res, next after -> OneTimeToken.consume.restore() it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with unknown user', -> before -> token = new OneTimeToken _id: 'misused' ttl: 3600 use: 'emailVerification' sub: 'unknown' req = query: token: 'valid' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) sinon.stub(User, 'patch').callsArgWith(2, null, null) verifyEmail req, res, next after -> OneTimeToken.consume.restore() User.patch.restore() it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with valid token', -> before -> user = new User token = new OneTimeToken _id: 'misused' ttl: 3600 use: 'emailVerification' sub: 'uuid' req = query: token: 'valid' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) sinon.stub(User, 'patch').callsArgWith(2, null, user) verifyEmail req, res, next after -> OneTimeToken.consume.restore() User.patch.restore() it 'should render a response with null signin', -> res.render.should.have.been.calledWith 'verifyEmail' res.render.should.not.have.been.calledWith( 'verifyEmail', sinon.match.object ) describe 'with valid token and client redirect', -> before -> user = new User token = new OneTimeToken _id: 'mis<PASSWORD>' ttl: 3600 use: 'emailVerification' sub: 'uuid' req = query: token: 'valid' client: {} connectParams: redirect_uri: 'https://example.com/callback' client_id: 'client-uuid' response_type: 'id_token token' scope: 'openid profile' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) sinon.stub(User, 'patch').callsArgWith(2, null, user) verifyEmail req, res, next after -> OneTimeToken.consume.restore() User.patch.restore() it 'should render a response with url', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ signin: { url: sinon.match.string } }) it 'should render a response with client', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ signin: { url: sinon.match.string } })
true
chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect chai.use sinonChai chai.should() {verifyEmail} = require '../../../oidc' OneTimeToken = require '../../../models/OneTimeToken' User = require '../../../models/User' describe 'Verify Email', -> {req,res,next} = {} describe 'with missing token', -> before -> req = query: {} res = render: sinon.spy() next = sinon.spy() verifyEmail req, res, next it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with invalid or expired token', -> before -> req = query: token: 'invalid' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, null) verifyEmail req, res, next after -> OneTimeToken.consume.restore() it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with wrong token type', -> before -> token = new OneTimeToken _id: 'misused' ttl: 3600 use: 'wrong' sub: 'nomatter' req = query: token: 'misused' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) verifyEmail req, res, next after -> OneTimeToken.consume.restore() it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with unknown user', -> before -> token = new OneTimeToken _id: 'misused' ttl: 3600 use: 'emailVerification' sub: 'unknown' req = query: token: 'valid' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) sinon.stub(User, 'patch').callsArgWith(2, null, null) verifyEmail req, res, next after -> OneTimeToken.consume.restore() User.patch.restore() it 'should render an error', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ error: sinon.match.string }) describe 'with valid token', -> before -> user = new User token = new OneTimeToken _id: 'misused' ttl: 3600 use: 'emailVerification' sub: 'uuid' req = query: token: 'valid' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) sinon.stub(User, 'patch').callsArgWith(2, null, user) verifyEmail req, res, next after -> OneTimeToken.consume.restore() User.patch.restore() it 'should render a response with null signin', -> res.render.should.have.been.calledWith 'verifyEmail' res.render.should.not.have.been.calledWith( 'verifyEmail', sinon.match.object ) describe 'with valid token and client redirect', -> before -> user = new User token = new OneTimeToken _id: 'misPI:PASSWORD:<PASSWORD>END_PI' ttl: 3600 use: 'emailVerification' sub: 'uuid' req = query: token: 'valid' client: {} connectParams: redirect_uri: 'https://example.com/callback' client_id: 'client-uuid' response_type: 'id_token token' scope: 'openid profile' res = render: sinon.spy() next = sinon.spy() sinon.stub(OneTimeToken, 'consume').callsArgWith(1, null, token) sinon.stub(User, 'patch').callsArgWith(2, null, user) verifyEmail req, res, next after -> OneTimeToken.consume.restore() User.patch.restore() it 'should render a response with url', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ signin: { url: sinon.match.string } }) it 'should render a response with client', -> res.render.should.have.been .calledWith 'verifyEmail', sinon.match({ signin: { url: sinon.match.string } })
[ { "context": "ser.coffee: Github user class\n#\n# Copyright © 2011 Pavan Kumar Sunkara. All rights reserved\n#\n\n# Requiring modules\nBase ", "end": 75, "score": 0.9998731017112732, "start": 56, "tag": "NAME", "value": "Pavan Kumar Sunkara" }, { "context": "\n @[e] = data[e]\n\...
src/octonode/user.coffee
Palem1988/octonode
933
# # user.coffee: Github user class # # Copyright © 2011 Pavan Kumar Sunkara. All rights reserved # # Requiring modules Base = require './base' # Initiate class class User extends Base constructor: (@login, @client) -> profile: (data) -> Object.keys(data).forEach (e) => @[e] = data[e] # Get a user # '/users/pkumar' GET info: (cb) -> @client.get "/users/#{@login}", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User info error')) else cb null, b, h # Get the followers of a user # '/users/pkumar/followers' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] followers: (params..., cb) -> @client.get "/users/#{@login}/followers", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User followers error')) else cb null, b, h # Get the followings of a user # '/users/pkumar/following' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] following: (params..., cb) -> @client.get "/users/#{@login}/following", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User following error')) else cb null, b, h # Get the repos of a user # '/users/pkumar/repos' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] repos: (params..., cb) -> @client.get "/users/#{@login}/repos", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User repos error')) else cb null, b, h # Get events performed by a user # '/users/pksunkara/events' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] events: (params..., events, cb) -> if !cb and typeof events == 'function' cb = events events = null else if events? if typeof events == 'number' and params.length > 0 params[1] = events events = null else if !Array.isArray events events = [events] @client.get "/users/#{@login}/events", params..., (err, s, b, h) -> return cb(err) if err return cb(new Error('User events error')) if s isnt 200 if events? b = b.filter (event) -> return events.indexOf(event.type) != -1 cb null, b, h # Get a list of organizations a user belongs to and has publicized membership. # '/users/pksunkara/orgs' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] orgs: (params..., cb) -> @client.get "/users/#{@login}/orgs", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User organizations error')) else cb null, b, h # Export module module.exports = User
68092
# # user.coffee: Github user class # # Copyright © 2011 <NAME>. All rights reserved # # Requiring modules Base = require './base' # Initiate class class User extends Base constructor: (@login, @client) -> profile: (data) -> Object.keys(data).forEach (e) => @[e] = data[e] # Get a user # '/users/pkumar' GET info: (cb) -> @client.get "/users/#{@login}", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User info error')) else cb null, b, h # Get the followers of a user # '/users/pkumar/followers' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] followers: (params..., cb) -> @client.get "/users/#{@login}/followers", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User followers error')) else cb null, b, h # Get the followings of a user # '/users/pkumar/following' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] following: (params..., cb) -> @client.get "/users/#{@login}/following", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User following error')) else cb null, b, h # Get the repos of a user # '/users/pkumar/repos' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] repos: (params..., cb) -> @client.get "/users/#{@login}/repos", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User repos error')) else cb null, b, h # Get events performed by a user # '/users/pksunkara/events' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] events: (params..., events, cb) -> if !cb and typeof events == 'function' cb = events events = null else if events? if typeof events == 'number' and params.length > 0 params[1] = events events = null else if !Array.isArray events events = [events] @client.get "/users/#{@login}/events", params..., (err, s, b, h) -> return cb(err) if err return cb(new Error('User events error')) if s isnt 200 if events? b = b.filter (event) -> return events.indexOf(event.type) != -1 cb null, b, h # Get a list of organizations a user belongs to and has publicized membership. # '/users/pksunkara/orgs' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] orgs: (params..., cb) -> @client.get "/users/#{@login}/orgs", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User organizations error')) else cb null, b, h # Export module module.exports = User
true
# # user.coffee: Github user class # # Copyright © 2011 PI:NAME:<NAME>END_PI. All rights reserved # # Requiring modules Base = require './base' # Initiate class class User extends Base constructor: (@login, @client) -> profile: (data) -> Object.keys(data).forEach (e) => @[e] = data[e] # Get a user # '/users/pkumar' GET info: (cb) -> @client.get "/users/#{@login}", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User info error')) else cb null, b, h # Get the followers of a user # '/users/pkumar/followers' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] followers: (params..., cb) -> @client.get "/users/#{@login}/followers", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User followers error')) else cb null, b, h # Get the followings of a user # '/users/pkumar/following' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] following: (params..., cb) -> @client.get "/users/#{@login}/following", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User following error')) else cb null, b, h # Get the repos of a user # '/users/pkumar/repos' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] repos: (params..., cb) -> @client.get "/users/#{@login}/repos", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User repos error')) else cb null, b, h # Get events performed by a user # '/users/pksunkara/events' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] events: (params..., events, cb) -> if !cb and typeof events == 'function' cb = events events = null else if events? if typeof events == 'number' and params.length > 0 params[1] = events events = null else if !Array.isArray events events = [events] @client.get "/users/#{@login}/events", params..., (err, s, b, h) -> return cb(err) if err return cb(new Error('User events error')) if s isnt 200 if events? b = b.filter (event) -> return events.indexOf(event.type) != -1 cb null, b, h # Get a list of organizations a user belongs to and has publicized membership. # '/users/pksunkara/orgs' GET # - page or query object, optional - params[0] # - per_page, optional - params[1] orgs: (params..., cb) -> @client.get "/users/#{@login}/orgs", params..., (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error('User organizations error')) else cb null, b, h # Export module module.exports = User